From 18ff6d0ae5df69ad8e985c1091baaf2966aa7a6d Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 20:46:13 +0100 Subject: [PATCH 01/23] fix: reuse a spark send's key across retries Derive each Spark send's idempotency key from the seed, the payment hash and an attempt number, so a retry reuses its attempt's key and Spark never pays an invoice twice. The attempt moves on only past keys Spark lists as failed. A short balance under a reused key keeps the send held, as it can hide the transfer an earlier attempt committed. The refusal while Spark's list can't be read now applies only to an invoice an older build sent under a random key. Verified: just compile, just test, just lint --- .../main/java/to/bitkit/data/CacheStore.kt | 18 +++ .../java/to/bitkit/repositories/SparkRepo.kt | 51 +++++++-- .../java/to/bitkit/services/SparkSendKey.kt | 52 +++++++++ .../java/to/bitkit/services/SparkService.kt | 14 +++ .../bitkit/repositories/LightningRepoTest.kt | 1 + .../to/bitkit/repositories/SparkRepoTest.kt | 103 +++++++++++++++++- .../to/bitkit/services/SparkSendKeyTest.kt | 45 ++++++++ changelog.d/next/2019.fixed.md | 1 + 8 files changed, 270 insertions(+), 15 deletions(-) create mode 100644 app/src/main/java/to/bitkit/services/SparkSendKey.kt create mode 100644 app/src/test/java/to/bitkit/services/SparkSendKeyTest.kt create mode 100644 changelog.d/next/2019.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 296fc3798f..ea1008572e 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -200,6 +200,18 @@ class CacheStore internal constructor( } } + /** + * Keeps [attempt] as the latest attempt at paying the invoice with [paymentHash], which expires at [expiresAt], + * and drops the attempts of invoices expired before [now], both in epoch seconds. + */ + suspend fun setSparkSendAttempt(paymentHash: String, attempt: Int, expiresAt: Long, now: Long) { + val hash = paymentHash.lowercase() + store.updateData { + val live = it.sparkSendAttempts.filterValues { kept -> kept.expiresAt >= now } + it.copy(sparkSendAttempts = live + (hash to SparkSendAttempt(attempt, expiresAt))) + } + } + suspend fun addSparkUnsavedOwnFailure(paymentId: String) { if (paymentId in store.data.first().sparkUnsavedOwnFailures) return store.updateData { it.copy(sparkUnsavedOwnFailures = it.sparkUnsavedOwnFailures + paymentId) } @@ -413,6 +425,8 @@ data class AppCacheData( * only its own outcome settles it. A hold without one waits for a paid attempt or its invoice's expiry. */ val sparkSendAttemptIds: Map = mapOf(), + /** The latest attempt at each invoice Spark sent, by hash, whose number picks the attempt's idempotency key. */ + val sparkSendAttempts: Map = mapOf(), /** * Payment ids of Spark send attempts whose own failure a failed Activity write still has to save over an earlier * attempt's row, kept across a restart until it saves. @@ -463,6 +477,10 @@ data class AppCacheData( fun invalidateReceiveOnchainAddress() = copy(bip21 = "", onchainAddress = "") } +/** An attempt at paying an invoice through Spark, the [attempt]th, of an invoice that expires at [expiresAt]. */ +@Serializable +data class SparkSendAttempt(val attempt: Int, val expiresAt: Long) + @Serializable data class CachedUsdtBalance( val address: String, diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 2bbeb986b4..7d2382ef92 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -530,7 +530,8 @@ class SparkRepo @Inject constructor( /** * Pays [bolt11] and returns its payment hash, the id ldk-node payments use, so the send flow can match it. * Fails with [SparkError.SendRefused] when nothing left the wallet: Spark was not connected, could not prepare the - * payment or list its payments, or its fee was over [maxTotalFeeMsat]; with [SparkError.InvoiceExpired], a + * payment, could not list its payments while an older build's send of the invoice is kept, or its fee was over + * [maxTotalFeeMsat]; with [SparkError.InvoiceExpired], a * [SparkError.SendRefused], 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 @@ -587,12 +588,11 @@ class SparkRepo @Inject constructor( isFailedUnsent = canList, ) } - // A list that can't be read may hide a payment of the invoice, which Spark would pay again under a new - // key. It is read again here: the local one before Spark's first sync, else the synced one. + // Spark's local list picks the attempt's key and, before Spark's first sync, shows the invoice's earlier + // sends, as the synced list did above. + val local = runSuspendCatching { listPayments() }.getOrNull() if (earlier == SparkLightningSend.Unavailable) { - val local = runSuspendCatching { listPayments() }.getOrNull() - ?: throw SparkError.SendRefused("Spark could not list its payments to check the invoice") - when (local.latestSend(paymentHash)?.status) { + when (local?.latestSend(paymentHash)?.status) { PaymentStatus.COMPLETED -> { Logger.info("Skipped Spark send of '$paymentHash', already paid", context = TAG) return@runSuspendCatching paymentHash @@ -600,6 +600,11 @@ class SparkRepo @Inject constructor( PaymentStatus.PENDING -> throw PaymentPendingException(paymentHash) else -> Unit } + // A retry reuses its attempt's key, so Spark never pays an invoice twice under it, but an older + // build sent under a random key, which a list that can't be read may hide. + if (local == null && hasUnkeyedSend(paymentHash)) { + throw SparkError.SendRefused("Spark could not list its payments to check the invoice") + } } // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. if (!onBeforeSend()) throw PaymentAbortedBeforeSend() @@ -609,11 +614,21 @@ class SparkRepo @Inject constructor( if (!isEntered) throw PaymentPendingException(paymentHash) // Kept in flight until its result is handled, so a sync meanwhile never takes back its saved hold. try { - // Spark keeps the key as this attempt's payment id, so only its own outcome settles the send. - val attemptId = UUID.randomUUID().toString() + // Spark keeps the key as this attempt's payment id, so only its own outcome settles the send. A retry + // keeps the latest attempt's key, so Spark returns that attempt's payment instead of paying again, and + // moves past each attempt Spark's list shows failed, as a failed key can't send again. + val attempt = nextSendAttempt(paymentHash, local) + val attemptId = sparkService.sendKey(paymentHash, attempt) + val isReusedKey = cacheStore.data.first().sparkSendAttempts[paymentHash.lowercase()]?.attempt == attempt val sent = run { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) + cacheStore.setSparkSendAttempt( + paymentHash, + attempt, + expiresAt.toEpochSeconds(), + clock.now().epochSeconds, + ) spending { // Kept until the call returns, so a send cut off by process death or cancellation stays held. cacheStore.addSparkUncertainSend(paymentHash, clock.now().epochSeconds, attemptId) @@ -638,8 +653,9 @@ class SparkRepo @Inject constructor( throw SparkError.InvoiceExpired(it) } // Spark selects the leaves to spend before anything goes to the operators, so a short balance left - // nothing, for instance when an earlier send spent it after the balance was read. - if (it is SdkException.InsufficientFunds) { + // nothing, for instance when an earlier send spent it after the balance was read. Under a key an + // earlier attempt used, it can hide the transfer that attempt committed, so that send stays held. + if (it is SdkException.InsufficientFunds && !isReusedKey) { cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) throw SparkError.SendRefused("Spark balance can't cover the payment", it) @@ -676,6 +692,21 @@ class SparkRepo @Inject constructor( } } + private suspend fun nextSendAttempt(paymentHash: String, listing: List?): Int { + var attempt = cacheStore.data.first().sparkSendAttempts[paymentHash.lowercase()]?.attempt ?: 0 + val failed = listing?.filter { it.status == PaymentStatus.FAILED }?.mapTo(HashSet()) { it.id } + ?: return attempt + while (sparkService.sendKey(paymentHash, attempt) in failed) attempt++ + return attempt + } + + private suspend fun hasUnkeyedSend(paymentHash: String): Boolean { + val hash = paymentHash.lowercase() + val cache = cacheStore.data.first() + if (hash in cache.sparkSendAttempts) return false + return hash in cache.sparkSendHashes || hash in cache.sparkUncertainSends + } + private suspend fun settleUncertainSend(paymentHash: String, expiresAt: ULong, attemptId: String) { val failedAt = clock.now().epochSeconds val startedAt = cacheStore.data.first().sparkUncertainSends[paymentHash.lowercase()] ?: failedAt diff --git a/app/src/main/java/to/bitkit/services/SparkSendKey.kt b/app/src/main/java/to/bitkit/services/SparkSendKey.kt new file mode 100644 index 0000000000..bd9911cbe5 --- /dev/null +++ b/app/src/main/java/to/bitkit/services/SparkSendKey.kt @@ -0,0 +1,52 @@ +package to.bitkit.services + +import to.bitkit.ext.fromHex +import java.nio.ByteBuffer +import java.security.MessageDigest +import java.util.UUID +import javax.crypto.Mac +import javax.crypto.spec.SecretKeySpec + +/** + * The idempotency key of a Spark send of an invoice. Spark makes one transfer per key, so a retry under the same key + * never pays the invoice twice: it gets back the transfer an earlier try committed, or sends when none did. A key + * whose payment failed can't send again, so the next attempt takes the next key. + * + * Keys derive from the wallet seed, the payment hash and the attempt number, so a restored wallet derives the same + * keys, no other wallet can, and the operators can't link a transfer to its invoice. iOS derives the same keys. + */ +object SparkSendKey { + private val NAMESPACE = UUID.fromString("794acd96-39bc-4fd1-a09f-02b269a4a34d") + private val LABEL = "bitkit spark send key".encodeToByteArray() + private const val HMAC = "HmacSHA256" + private const val UUID_BYTES = 16 + + /** The secret all send keys derive from: an HMAC-SHA256 of a fixed label, keyed with the BIP39 [seed]. */ + fun secret(seed: ByteArray): ByteArray = Mac.getInstance(HMAC).run { + init(SecretKeySpec(seed, HMAC)) + doFinal(LABEL) + } + + /** + * The key of attempt [attempt] at paying the invoice with [paymentHash]: a UUIDv5 of [secret], the hash's 32 bytes + * and [attempt] as 4 bytes big-endian. + */ + fun key(secret: ByteArray, paymentHash: String, attempt: Int): String { + require(attempt >= 0) { "Attempt '$attempt' is negative" } + val name = secret + paymentHash.fromHex() + ByteBuffer.allocate(Int.SIZE_BYTES) + .putInt(attempt) + .array() + val namespace = ByteBuffer.allocate(UUID_BYTES) + .putLong(NAMESPACE.mostSignificantBits) + .putLong(NAMESPACE.leastSignificantBits) + .array() + val hash = MessageDigest.getInstance("SHA-1").run { + update(namespace) + digest(name) + } + hash[6] = (hash[6].toInt() and 0x0f or 0x50).toByte() + hash[8] = (hash[8].toInt() and 0x3f or 0x80).toByte() + val bytes = ByteBuffer.wrap(hash, 0, UUID_BYTES) + return UUID(bytes.long, bytes.long).toString() + } +} diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 0ac2092c48..7cd4b3d935 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -44,6 +44,7 @@ import breez_sdk_spark.SendPaymentRequest import breez_sdk_spark.SyncWalletRequest import breez_sdk_spark.defaultConfig import breez_sdk_spark.parseSparkConfig +import com.synonym.bitkitcore.mnemonicToSeed import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asSharedFlow @@ -156,6 +157,10 @@ class SparkService @Inject constructor( private var sdk: BreezSdk? = null private var listenerId: String? = null + /** The connected wallet's [SparkSendKey.secret], derived once at connect. */ + @Volatile + private var sendKeySecret: ByteArray? = null + private val _events = MutableSharedFlow(extraBufferCapacity = 64) val events: SharedFlow = _events.asSharedFlow() @@ -190,6 +195,7 @@ class SparkService @Inject constructor( val network = sparkNetwork() ?: throw SparkError.Unsupported() val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) ?: throw ServiceError.MnemonicNotFound() val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name) + val secret = SparkSendKey.secret(mnemonicToSeed(mnemonic, passphrase)) val config = configure(defaultConfig(network), Env.breezApiKey, isExiting) val storageDir = File(Env.sparkStoragePath(walletIndex)).apply { mkdirs() }.path val apiType = configureLocalSpark(config, Env.localSparkSettings) @@ -209,6 +215,7 @@ class SparkService @Inject constructor( }, ) sdk = connected + sendKeySecret = secret val chain = chainServiceUrl ?: "default" Logger.info("Connected Spark wallet on '$network' with chain '$chain' and exit '$isExiting'", context = TAG) true @@ -223,6 +230,7 @@ class SparkService @Inject constructor( } finally { sdk = null listenerId = null + sendKeySecret = null } } @@ -278,6 +286,12 @@ class SparkService @Inject constructor( ), ) + /** The idempotency key of attempt [attempt] at paying the invoice with [paymentHash], see [SparkSendKey]. */ + fun sendKey(paymentHash: String, attempt: Int): String { + val secret = checkNotNull(sendKeySecret) { "Spark is not connected" } + return SparkSendKey.key(secret, paymentHash, attempt) + } + /** Sends [prepared]; Spark makes one payment per [idempotencyKey], a UUID that becomes the payment's id. */ suspend fun send(prepared: PrepareSendPaymentResponse, idempotencyKey: String? = null): Payment { val options = when (prepared.paymentMethod) { diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 018e16b1bf..6f43ef6a4c 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -2143,6 +2143,7 @@ class LightningRepoTest : BaseUnitTest() { val sparkService = mock() whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.sendKey(any(), any())).thenReturn("key") val details = mock { on { paymentHash } doReturn "hash" } val prepared = PrepareSendPaymentResponse( paymentMethod = SendPaymentMethod.Bolt11Invoice(details, null, 1uL), diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index fc2beaaaab..15276edbe4 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -80,6 +80,7 @@ import to.bitkit.data.MAX_SPARK_SEND_HASHES import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.data.SparkPayoutChain +import to.bitkit.data.SparkSendAttempt import to.bitkit.env.Env import to.bitkit.ext.create import to.bitkit.ext.scopedActivityId @@ -172,6 +173,9 @@ class SparkRepoTest : BaseUnitTest() { whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.success(Unit)) whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.networkName).thenReturn("regtest") + whenever(sparkService.sendKey(any(), any())).thenAnswer { + "${it.getArgument(0)}-${it.getArgument(1)}" + } whenever { sparkService.lightningSendStatus(any()) }.thenAnswer { sendStatus() } whenever { cacheStore.update(any()) }.thenAnswer { val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) @@ -4337,7 +4341,8 @@ class SparkRepoTest : BaseUnitTest() { argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } ) assertNull(sut.earlierLightningSend("lnbc1", "hash")) - whenever(sparkService.send(any(), anyOrNull())).thenReturn(sentPayment(fees = 0)) + val sent = sentPayment(fees = 0) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(sent) sut.payInvoice("lnbc1", 100uL) verify(sparkService, times(2)).send(any(), anyOrNull()) } @@ -5059,8 +5064,9 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `a spark send is refused before it goes out while spark's synced list can't be read`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + fun `an older build's spark send refuses a retry while spark's synced list can't be read`() = test { + // An older build sent the invoice under a random key, which a retry's key can't match. + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkSendHashes = listOf("hash"))), clock) whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) @@ -5080,14 +5086,15 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `a spark send is refused before spark's first sync while its list can't be read`() = test { + fun `an older build's spark send refuses a retry before the first sync while the list can't be read`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkSendHashes = listOf("hash"))), clock) whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) // No wallet sync has succeeded yet, and Spark's local list can't be read either. whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = null)) val prepared = unexpiredPrepared() whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - val sut = createSut() + val sut = createSut(store) sut.start(0).getOrThrow() advanceUntilIdle() whenever(sparkService.listPayments()).thenAnswer { throw SdkException.Generic("storage") } @@ -5114,6 +5121,92 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any(), anyOrNull()) } + @Test + fun `a spark send goes out under its first attempt's key while spark's list can't be read`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + // No wallet sync has succeeded yet, as right after a restore, and Spark's local list can't be read either. + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = null)) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val sent = sentPayment(fees = 0) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(sent) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + whenever(sparkService.listPayments()).thenAnswer { throw SdkException.Generic("storage") } + + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + + // A payment an earlier attempt committed under this key comes back from Spark instead of paying again. + assertEquals("hash-0", sentKey()) + assertEquals(0, store.data.first().sparkSendAttempts["hash"]?.attempt) + } + + @Test + fun `a spark retry reuses its attempt's key until spark lists that attempt failed`() = test { + val kept = AppCacheData(sparkSendAttempts = mapOf("hash" to SparkSendAttempt(1, now.epochSeconds + 3_600))) + val store = CacheStore(InMemoryDataStore(kept), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val sent = sentPayment(fees = 0) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(sent) + // The first attempt failed; the second one's outcome isn't listed. + val failed = sentPayment(fees = 0).copy(id = "hash-0", status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + sut.payInvoice("lnbc1", 100uL).getOrThrow() + + assertEquals("hash-1", sentKey()) + assertEquals(1, store.data.first().sparkSendAttempts["hash"]?.attempt) + } + + @Test + fun `a spark retry takes the next attempt's key once spark lists its attempt failed`() = test { + val kept = AppCacheData(sparkSendAttempts = mapOf("hash" to SparkSendAttempt(0, now.epochSeconds + 3_600))) + val store = CacheStore(InMemoryDataStore(kept), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val sent = sentPayment(fees = 0) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(sent) + val failed = sentPayment(fees = 0).copy(id = "hash-0", status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + sut.payInvoice("lnbc1", 100uL).getOrThrow() + + // A failed key can't send again, so the retry takes a new one. + assertEquals("hash-1", sentKey()) + assertEquals(1, store.data.first().sparkSendAttempts["hash"]?.attempt) + } + + @Test + fun `a short balance under a reused spark key keeps the send held`() = test { + val kept = AppCacheData(sparkSendAttempts = mapOf("hash" to SparkSendAttempt(0, now.epochSeconds + 3_600))) + val store = CacheStore(InMemoryDataStore(kept), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + // Spark picks leaves before the operators see the key, so the earlier attempt's transfer can't come back. + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.InsufficientFunds(null) } + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + assertEquals("hash-0", sentKey()) + assertTrue("hash" in store.data.first().sparkSendHashes, "the node could pay the invoice again") + assertTrue("hash" in store.data.first().sparkUncertainSends) + } + @Test fun `a held spark send spark never recorded reports its failure at expiry after a restart`() = test { val sentAt = now.epochSeconds diff --git a/app/src/test/java/to/bitkit/services/SparkSendKeyTest.kt b/app/src/test/java/to/bitkit/services/SparkSendKeyTest.kt new file mode 100644 index 0000000000..b3abfdc089 --- /dev/null +++ b/app/src/test/java/to/bitkit/services/SparkSendKeyTest.kt @@ -0,0 +1,45 @@ +package to.bitkit.services + +import org.junit.Test +import to.bitkit.ext.fromHex +import to.bitkit.ext.toHex +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals + +class SparkSendKeyTest { + private companion object { + /** The BIP39 seed of `abandon … about` with passphrase `TREZOR`, from the BIP39 test vectors. */ + const val SEED = "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e534955" + + "31f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04" + + /** Bytes 0 to 31. */ + const val PAYMENT_HASH = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + } + + // iOS's SparkSendKeyTests asserts the same vector, so a wallet restored on the other app derives the same keys. + @Test + fun `derives the shared test vector`() { + val secret = SparkSendKey.secret(SEED.fromHex()) + + assertEquals("577ceb10411255cef07e3f49bd7e5239de07586c7457f65ee72ee53737361a98", secret.toHex()) + assertEquals("8d92d8bf-76f3-56fe-8958-8e440acb64fc", SparkSendKey.key(secret, PAYMENT_HASH, 0)) + assertEquals("712dea1f-8268-5e52-a280-aac86bc60b59", SparkSendKey.key(secret, PAYMENT_HASH, 1)) + } + + @Test + fun `reads the payment hash in either case`() { + val secret = SparkSendKey.secret(SEED.fromHex()) + + assertEquals( + SparkSendKey.key(secret, PAYMENT_HASH, 0), + SparkSendKey.key(secret, PAYMENT_HASH.uppercase(), 0), + ) + } + + @Test + fun `another seed derives other keys`() { + val other = SparkSendKey.secret(ByteArray(64)) + + assertNotEquals("8d92d8bf-76f3-56fe-8958-8e440acb64fc", SparkSendKey.key(other, PAYMENT_HASH, 0)) + } +} diff --git a/changelog.d/next/2019.fixed.md b/changelog.d/next/2019.fixed.md new file mode 100644 index 0000000000..6c57301c0c --- /dev/null +++ b/changelog.d/next/2019.fixed.md @@ -0,0 +1 @@ +Fixed a Lightning invoice paid through Spark being paid twice when the app retried it after an interrupted send. From 66fc8b3487fcb328a2f868e18c533b97d2c91f0b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 24 Nov 2026 22:13:17 +0100 Subject: [PATCH 02/23] fix: retry a spark send spark can't select leaves for Verified: just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 44 ++++++++++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 59 +++++++++++++++++++ changelog.d/next/2019.fixed.md | 2 +- 3 files changed, 99 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 7d2382ef92..49eb41b62f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -132,6 +132,11 @@ class SparkRepo @Inject constructor( private val SETTLE_RETRY_INTERVAL = 30.seconds + /** Sends again under the same key while Spark can't select the leaves, as after a move to Spark lands. */ + private const val LEAF_SELECTION_RETRIES = 3 + + private val LEAF_SELECTION_RETRY_DELAY = 2.seconds + /** 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 } @@ -642,7 +647,7 @@ class SparkRepo @Inject constructor( cacheStore.removeSparkSendHash(paymentHash) throw it } - runSuspendCatching { sparkService.send(prepared, attemptId) } + sendRetryingLeafSelection(prepared, attemptId, paymentDeadlineAt) } } val payment = sent.getOrElse { @@ -652,10 +657,11 @@ class SparkRepo @Inject constructor( cacheStore.removeSparkSendHash(paymentHash) throw SparkError.InvoiceExpired(it) } - // Spark selects the leaves to spend before anything goes to the operators, so a short balance left - // nothing, for instance when an earlier send spent it after the balance was read. Under a key an - // earlier attempt used, it can hide the transfer that attempt committed, so that send stays held. - if (it is SdkException.InsufficientFunds && !isReusedKey) { + // Spark selects the leaves to spend before anything goes to the operators, so a short balance or + // leaves it can't select left nothing, for instance when an earlier send spent the balance after + // it was read. Under a key an earlier attempt used, it can hide the transfer that attempt + // committed, so that send stays held. + if ((it is SdkException.InsufficientFunds || it.isLeafSelectionFailure()) && !isReusedKey) { cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) throw SparkError.SendRefused("Spark balance can't cover the payment", it) @@ -692,6 +698,26 @@ class SparkRepo @Inject constructor( } } + private suspend fun sendRetryingLeafSelection( + prepared: PrepareSendPaymentResponse, + attemptId: String, + paymentDeadlineAt: Instant?, + ): Result { + var result = runSuspendCatching { sparkService.send(prepared, attemptId) } + repeat(LEAF_SELECTION_RETRIES) { + if (result.exceptionOrNull()?.isLeafSelectionFailure() != true) return result + Logger.info("Retrying Spark send '$attemptId' as Spark could not select its leaves", context = TAG) + delay(LEAF_SELECTION_RETRY_DELAY) + val canRetry = runCatching { + ensurePaymentDeadline(paymentDeadlineAt) + ensureNotExiting() + }.isSuccess + if (!canRetry) return result + result = runSuspendCatching { sparkService.send(prepared, attemptId) } + } + return result + } + private suspend fun nextSendAttempt(paymentHash: String, listing: List?): Int { var attempt = cacheStore.data.first().sparkSendAttempts[paymentHash.lowercase()]?.attempt ?: 0 val failed = listing?.filter { it.status == PaymentStatus.FAILED }?.mapTo(HashSet()) { it.id } @@ -2686,6 +2712,14 @@ internal fun SdkException.InvalidInput.isBelowMinimum(): Boolean = internal fun Throwable.isWithdrawalFeeRise(): Boolean = this is SdkException.InvalidInput && v1.contains("onchain fee rose to", ignoreCase = true) +/** + * Spark fails a send with this error when it holds the balance but can't select leaves to spend, for instance right + * after a move to Spark lands, before anything reaches the operators (`select_leaves_with_retry` in the 0.28.3 SDK's + * `spark-wallet/src/wallet.rs`). + */ +internal fun Throwable.isLeafSelectionFailure(): Boolean = + this is SdkException.SparkException && v1.contains("Failed to select leaves after all retries", ignoreCase = true) + /** Spark refuses an expired Lightning invoice with this input error, at prepare and again at send. */ internal fun Throwable.isInvoiceExpired(): Boolean = this is SdkException.InvalidInput && v1.contains("invoice has expired", ignoreCase = true) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 15276edbe4..5a7f29ba8d 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5207,6 +5207,62 @@ class SparkRepoTest : BaseUnitTest() { assertTrue("hash" in store.data.first().sparkUncertainSends) } + @Test + fun `a spark send retries under its key while spark can't select its leaves`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val sent = sentPayment(fees = 0) + var sends = 0 + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { + if (++sends == 1) throw leafSelectionFailure() else sent + } + val sut = createSut() + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + + val keys = argumentCaptor().apply { verify(sparkService, times(2)).send(any(), capture()) }.allValues + assertEquals(listOf("hash-0", "hash-0"), keys) + } + + @Test + fun `a spark send whose leaves spark can't select is refused under a new key`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw leafSelectionFailure() } + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + verify(sparkService, times(4)).send(any(), anyOrNull()) + assertFalse("hash" in store.data.first().sparkSendHashes) + assertFalse("hash" in store.data.first().sparkUncertainSends) + } + + @Test + fun `leaves spark can't select under a reused spark key keep the send held`() = test { + val kept = AppCacheData(sparkSendAttempts = mapOf("hash" to SparkSendAttempt(0, now.epochSeconds + 3_600))) + val store = CacheStore(InMemoryDataStore(kept), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw leafSelectionFailure() } + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + assertTrue("hash" in store.data.first().sparkSendHashes, "the node could pay the invoice again") + assertTrue("hash" in store.data.first().sparkUncertainSends) + } + @Test fun `a held spark send spark never recorded reports its failure at expiry after a restart`() = test { val sentAt = now.epochSeconds @@ -5600,6 +5656,9 @@ class SparkRepoTest : BaseUnitTest() { } /** The idempotency key of the latest Spark send, which Spark keeps as that attempt's payment id. */ + private fun leafSelectionFailure() = + SdkException.SparkException("Tree service error: generic error: Failed to select leaves after all retries") + private suspend fun sentKey(): String = argumentCaptor().apply { verify(sparkService, atLeastOnce()).send(any(), capture()) }.lastValue diff --git a/changelog.d/next/2019.fixed.md b/changelog.d/next/2019.fixed.md index 6c57301c0c..e306939073 100644 --- a/changelog.d/next/2019.fixed.md +++ b/changelog.d/next/2019.fixed.md @@ -1 +1 @@ -Fixed a Lightning invoice paid through Spark being paid twice when the app retried it after an interrupted send. +Fixed a Lightning invoice paid through Spark being paid twice when the app retried it after an interrupted send, and a payment made right after moving funds to Spark staying pending. From 5d47da0576c7e68806045fdaee8e0c2c8ff84981 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 11:26:33 +0100 Subject: [PATCH 03/23] fix: retry a refused spark send under a new key A send refused before anything reached Spark's operators (a short balance or leaves Spark can't select under a never-used key, an expired invoice, a deadline or exit) kept its attempt as the invoice's latest, so a retry counted that unused key as reused and held the invoice pending until it expired. The refusal now puts back the attempt kept before it. Verified: just compile, just test, just lint (after the last edit: lint and test) --- app/src/main/java/to/bitkit/data/CacheStore.kt | 9 +++++++++ .../java/to/bitkit/repositories/SparkRepo.kt | 12 +++++++++++- .../to/bitkit/repositories/SparkRepoTest.kt | 18 ++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index ea1008572e..6fe9a1aded 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -212,6 +212,15 @@ class CacheStore internal constructor( } } + /** Puts back [previous], the attempt kept before a send whose key never reached Spark, or drops the invoice's. */ + suspend fun restoreSparkSendAttempt(paymentHash: String, previous: SparkSendAttempt?) { + val hash = paymentHash.lowercase() + store.updateData { + val attempts = it.sparkSendAttempts - hash + it.copy(sparkSendAttempts = if (previous == null) attempts else attempts + (hash to previous)) + } + } + suspend fun addSparkUnsavedOwnFailure(paymentId: String) { if (paymentId in store.data.first().sparkUnsavedOwnFailures) return store.updateData { it.copy(sparkUnsavedOwnFailures = it.sparkUnsavedOwnFailures + paymentId) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 49eb41b62f..fbf8c8834e 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -624,7 +624,14 @@ class SparkRepo @Inject constructor( // moves past each attempt Spark's list shows failed, as a failed key can't send again. val attempt = nextSendAttempt(paymentHash, local) val attemptId = sparkService.sendKey(paymentHash, attempt) - val isReusedKey = cacheStore.data.first().sparkSendAttempts[paymentHash.lowercase()]?.attempt == attempt + val previousAttempt = cacheStore.data.first().sparkSendAttempts[paymentHash.lowercase()] + val isReusedKey = previousAttempt?.attempt == attempt + + // A send refused before anything reached Spark's operators leaves its key unused, so a retry refuses + // the same way. + suspend fun forgetUnusedAttempt() { + if (!isReusedKey) cacheStore.restoreSparkSendAttempt(paymentHash, previousAttempt) + } val sent = run { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) @@ -645,6 +652,7 @@ class SparkRepo @Inject constructor( }.onFailure { cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) + forgetUnusedAttempt() throw it } sendRetryingLeafSelection(prepared, attemptId, paymentDeadlineAt) @@ -655,6 +663,7 @@ class SparkRepo @Inject constructor( if (it.isInvoiceExpired()) { cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) + forgetUnusedAttempt() throw SparkError.InvoiceExpired(it) } // Spark selects the leaves to spend before anything goes to the operators, so a short balance or @@ -664,6 +673,7 @@ class SparkRepo @Inject constructor( if ((it is SdkException.InsufficientFunds || it.isLeafSelectionFailure()) && !isReusedKey) { cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) + forgetUnusedAttempt() throw SparkError.SendRefused("Spark balance can't cover the payment", it) } Logger.warn("Failed to learn the outcome of Spark send '$paymentHash'", it, context = TAG) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 5a7f29ba8d..0b5b15af1c 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5245,6 +5245,24 @@ class SparkRepoTest : BaseUnitTest() { assertFalse("hash" in store.data.first().sparkUncertainSends) } + @Test + fun `a spark send refused before reaching spark is refused again on retry`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw leafSelectionFailure() } + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + assertFalse("hash" in store.data.first().sparkSendAttempts) + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + assertFalse("hash" in store.data.first().sparkUncertainSends) + } + @Test fun `leaves spark can't select under a reused spark key keep the send held`() = test { val kept = AppCacheData(sparkSendAttempts = mapOf("hash" to SparkSendAttempt(0, now.epochSeconds + 3_600))) From 15abcb75907ff77f0752929d9e72efcd296cb65d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 11:42:31 +0100 Subject: [PATCH 04/23] fix: report a spark send failure a retry gets back A retry under a key whose failure this process already reported, as when Spark's list couldn't be read to move past it, got the failure back with no event, leaving the send screen waiting; it is now refused. A send that lost Spark's key secret is refused instead of throwing, the leaf-selection refusal says so, and the restored cache log leaves out send attempts. Verified: just compile, just test, just lint --- .../java/to/bitkit/repositories/BackupRepo.kt | 1 + .../java/to/bitkit/repositories/SparkRepo.kt | 18 +++++++++++++---- .../to/bitkit/repositories/SparkRepoTest.kt | 20 ++++++++++++++++++- 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 14acac1874..474c4cdd56 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1341,6 +1341,7 @@ class BackupRepo @Inject constructor( cachedRates = emptyList(), moveToSparkHashes = emptyList(), sparkSendAttemptIds = emptyMap(), + sparkSendAttempts = emptyMap(), sparkUnsavedOwnFailures = emptySet(), ) Logger.debug("Restored caches: ${jsonLogOf(logged)}", TAG) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index fbf8c8834e..e672881322 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -622,8 +622,10 @@ class SparkRepo @Inject constructor( // Spark keeps the key as this attempt's payment id, so only its own outcome settles the send. A retry // keeps the latest attempt's key, so Spark returns that attempt's payment instead of paying again, and // moves past each attempt Spark's list shows failed, as a failed key can't send again. - val attempt = nextSendAttempt(paymentHash, local) - val attemptId = sparkService.sendKey(paymentHash, attempt) + // The key's secret comes with Spark's connection, so a send that lost it is refused before it goes. + val (attempt, attemptId) = runSuspendCatching { + nextSendAttempt(paymentHash, local).let { it to sparkService.sendKey(paymentHash, it) } + }.getOrElse { throw SparkError.SendRefused("Spark is not connected", it) } val previousAttempt = cacheStore.data.first().sparkSendAttempts[paymentHash.lowercase()] val isReusedKey = previousAttempt?.attempt == attempt @@ -674,7 +676,12 @@ class SparkRepo @Inject constructor( cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) forgetUnusedAttempt() - throw SparkError.SendRefused("Spark balance can't cover the payment", it) + val reason = if (it.isLeafSelectionFailure()) { + "Spark could not select leaves for the payment" + } else { + "Spark balance can't cover the payment" + } + throw SparkError.SendRefused(reason, it) } Logger.warn("Failed to learn the outcome of Spark send '$paymentHash'", it, context = TAG) settleUncertainSend(paymentHash, expiresAt, attemptId) @@ -690,7 +697,10 @@ class SparkRepo @Inject constructor( // Spark's failure event during its send call was left to this result, so the result reports it. if (payment.status == PaymentStatus.FAILED) { recordActivity(payment, isOwnAttempt = true) - if (reportedSendIds.add(payment.id)) payment.toNodeEvent()?.let { _nodeEvents.emit(it) } + // A retry under a key whose failure was already reported, as when Spark's list couldn't be read to + // move past it, gets that failure back and no event, so the result reports it. + if (!reportedSendIds.add(payment.id)) throw SparkError.SendRefused("Spark send failed earlier") + payment.toNodeEvent()?.let { _nodeEvents.emit(it) } } Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) paymentHash diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 0b5b15af1c..33e78d60d5 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5143,6 +5143,24 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(0, store.data.first().sparkSendAttempts["hash"]?.attempt) } + @Test + fun `a spark retry that gets back a failure already reported is refused`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = null)) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val failed = sentPayment(fees = 0).copy(id = "hash-0", status = PaymentStatus.FAILED) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(failed) + val sut = createSut() + sut.start(0).getOrThrow() + advanceUntilIdle() + whenever(sparkService.listPayments()).thenAnswer { throw SdkException.Generic("storage") } + sut.payInvoice("lnbc1", 100uL) + + // Spark's list still can't be read, so the retry keeps the failed attempt's key and gets its failure back. + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + } + @Test fun `a spark retry reuses its attempt's key until spark lists that attempt failed`() = test { val kept = AppCacheData(sparkSendAttempts = mapOf("hash" to SparkSendAttempt(1, now.epochSeconds + 3_600))) @@ -5673,10 +5691,10 @@ class SparkRepoTest : BaseUnitTest() { ) } - /** The idempotency key of the latest Spark send, which Spark keeps as that attempt's payment id. */ private fun leafSelectionFailure() = SdkException.SparkException("Tree service error: generic error: Failed to select leaves after all retries") + /** The idempotency key of the latest Spark send, which Spark keeps as that attempt's payment id. */ private suspend fun sentKey(): String = argumentCaptor().apply { verify(sparkService, atLeastOnce()).send(any(), capture()) }.lastValue From 363241b0302dec7eb0d71f490be4581957ad142f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 12:04:53 +0100 Subject: [PATCH 05/23] fix: release a failed spark send's invoice A send whose own result came back failed kept the invoice's send hash, so a retry while Spark's list couldn't be read showed it pending; the failed attempt paid nothing, so the hash goes, as when its outcome settles. The leaf-selection retry checks the deadline and exit before it waits, and a connection keeps the send key's secret before it reports connected. Verified: just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 16 ++++++++----- .../java/to/bitkit/services/SparkService.kt | 3 ++- .../to/bitkit/repositories/SparkRepoTest.kt | 23 ++++++++++++++++++- 3 files changed, 34 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index e672881322..f46fc3debf 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -696,6 +696,8 @@ class SparkRepo @Inject constructor( } // Spark's failure event during its send call was left to this result, so the result reports it. if (payment.status == PaymentStatus.FAILED) { + // This attempt paid nothing, as when its outcome settles, so a retry isn't held as pending. + cacheStore.removeSparkSendHash(paymentHash) recordActivity(payment, isOwnAttempt = true) // A retry under a key whose failure was already reported, as when Spark's list couldn't be read to // move past it, gets that failure back and no event, so the result reports it. @@ -724,15 +726,17 @@ class SparkRepo @Inject constructor( paymentDeadlineAt: Instant?, ): Result { var result = runSuspendCatching { sparkService.send(prepared, attemptId) } - repeat(LEAF_SELECTION_RETRIES) { - if (result.exceptionOrNull()?.isLeafSelectionFailure() != true) return result - Logger.info("Retrying Spark send '$attemptId' as Spark could not select its leaves", context = TAG) - delay(LEAF_SELECTION_RETRY_DELAY) - val canRetry = runCatching { + val canRetry = suspend { + runCatching { ensurePaymentDeadline(paymentDeadlineAt) ensureNotExiting() }.isSuccess - if (!canRetry) return result + } + repeat(LEAF_SELECTION_RETRIES) { + if (result.exceptionOrNull()?.isLeafSelectionFailure() != true || !canRetry()) return result + Logger.info("Retrying Spark send '$attemptId' as Spark could not select its leaves", context = TAG) + delay(LEAF_SELECTION_RETRY_DELAY) + if (!canRetry()) return result result = runSuspendCatching { sparkService.send(prepared, attemptId) } } return result diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 7cd4b3d935..31cdaa216b 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -214,8 +214,9 @@ class SparkService @Inject constructor( } }, ) - sdk = connected + // The secret comes first, so a send that sees the wallet connected can derive its key. sendKeySecret = secret + sdk = connected val chain = chainServiceUrl ?: "default" Logger.info("Connected Spark wallet on '$network' with chain '$chain' and exit '$isExiting'", context = TAG) true diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 33e78d60d5..0cb91e1b48 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5151,7 +5151,8 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) val failed = sentPayment(fees = 0).copy(id = "hash-0", status = PaymentStatus.FAILED) whenever(sparkService.send(any(), anyOrNull())).thenReturn(failed) - val sut = createSut() + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) sut.start(0).getOrThrow() advanceUntilIdle() whenever(sparkService.listPayments()).thenAnswer { throw SdkException.Generic("storage") } @@ -5281,6 +5282,26 @@ class SparkRepoTest : BaseUnitTest() { assertFalse("hash" in store.data.first().sparkUncertainSends) } + @Test + fun `a refused spark retry keeps the attempt spark listed failed before it`() = test { + val kept = AppCacheData(sparkSendAttempts = mapOf("hash" to SparkSendAttempt(0, now.epochSeconds + 3_600))) + val store = CacheStore(InMemoryDataStore(kept), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val firstFailed = sentPayment(fees = 0).copy(id = "hash-0", status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(firstFailed)) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw leafSelectionFailure() } + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + assertEquals("hash-1", sentKey()) + assertEquals(0, store.data.first().sparkSendAttempts["hash"]?.attempt) + } + @Test fun `leaves spark can't select under a reused spark key keep the send held`() = test { val kept = AppCacheData(sparkSendAttempts = mapOf("hash" to SparkSendAttempt(0, now.epochSeconds + 3_600))) From 188bf74a6f36b885aaeb964f44ec8bd98b584988 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 12:23:51 +0100 Subject: [PATCH 06/23] test: cover spark send attempt pruning and restore Also publishes Spark's connection to other threads with the send key's secret already set, and drops a needless suspend from the retry check. Verified: just compile, just test, just lint --- .../main/java/to/bitkit/repositories/SparkRepo.kt | 2 +- .../main/java/to/bitkit/services/SparkService.kt | 2 ++ .../test/java/to/bitkit/data/CacheStoreTest.kt | 15 +++++++++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index f46fc3debf..6e0337e9e4 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -726,7 +726,7 @@ class SparkRepo @Inject constructor( paymentDeadlineAt: Instant?, ): Result { var result = runSuspendCatching { sparkService.send(prepared, attemptId) } - val canRetry = suspend { + val canRetry = { runCatching { ensurePaymentDeadline(paymentDeadlineAt) ensureNotExiting() diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 31cdaa216b..21564fa141 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -154,6 +154,8 @@ class SparkService @Inject constructor( } private val mutex = Mutex() + + @Volatile private var sdk: BreezSdk? = null private var listenerId: String? = null diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index a80c36f49c..619d6b0df5 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -32,6 +32,21 @@ class CacheStoreTest : BaseUnitTest() { @After fun tearDown() = runBlocking { sut.reset() } + @Test + fun `a spark send attempt drops expired ones and restores the earlier one`() = test { + sut.setSparkSendAttempt("OLD", attempt = 2, expiresAt = 1_500, now = 1_000) + sut.setSparkSendAttempt("hash", attempt = 0, expiresAt = 3_000, now = 1_000) + sut.setSparkSendAttempt("hash", attempt = 1, expiresAt = 3_000, now = 2_000) + + assertEquals(mapOf("hash" to SparkSendAttempt(1, 3_000)), sut.data.first().sparkSendAttempts) + + sut.restoreSparkSendAttempt("HASH", SparkSendAttempt(0, 3_000)) + assertEquals(0, sut.data.first().sparkSendAttempts["hash"]?.attempt) + + sut.restoreSparkSendAttempt("hash", null) + assertFalse("hash" in sut.data.first().sparkSendAttempts) + } + @Test fun `invalidateReceiveLightningInvoice preserves a replacement invoice`() = test { val replacement = AppCacheData( From 2095114109c086c278caf4b1d8bb30c5595b0535 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 13:09:18 +0100 Subject: [PATCH 07/23] fix: keep the node off a refused spark send until spark syncs The SDK selects leaves again when it retries a failed submission, so a short balance or leaves it can't select under a new key can follow a transfer it committed. Such a refusal now notes when it happened, and the node holds off the invoice until Spark has synced since, so Spark's list shows any transfer the send committed. A retry over Spark isn't held, as one under the same key can't pay twice. Verified: just compile, just test, just lint --- .../main/java/to/bitkit/data/CacheStore.kt | 24 +++++++++++++ .../java/to/bitkit/repositories/BackupRepo.kt | 1 + .../java/to/bitkit/repositories/SparkRepo.kt | 27 +++++++++++++-- .../java/to/bitkit/data/CacheStoreTest.kt | 15 ++++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 34 +++++++++++++++++-- 5 files changed, 97 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 6fe9a1aded..5d68fca657 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -166,6 +166,24 @@ class CacheStore internal constructor( } } + /** Drops the refusals whose invoice expired by [refusedAt], which the node can no longer pay. */ + suspend fun addSparkRefusedSend(paymentHash: String, refusedAt: Long, expiresAt: Long) { + val hash = paymentHash.lowercase() + store.updateData { + val unexpired = it.sparkRefusedSends.filterValues { send -> send.expiresAt > refusedAt } + it.copy(sparkRefusedSends = unexpired + (hash to SparkRefusedSend(refusedAt, expiresAt))) + } + } + + /** Drops the refusal of [paymentHash] made at [refusedAt] only, as a later one waits for its own sync. */ + suspend fun removeSparkRefusedSend(paymentHash: String, refusedAt: Long) { + val hash = paymentHash.lowercase() + store.updateData { + val isSame = it.sparkRefusedSends[hash]?.refusedAt == refusedAt + if (isSame) it.copy(sparkRefusedSends = it.sparkRefusedSends - hash) else it + } + } + suspend fun removeSparkSendHash(paymentHash: String) { val hash = paymentHash.lowercase() if (hash !in store.data.first().sparkSendHashes) return @@ -436,6 +454,8 @@ data class AppCacheData( val sparkSendAttemptIds: Map = mapOf(), /** The latest attempt at each invoice Spark sent, by hash, whose number picks the attempt's idempotency key. */ val sparkSendAttempts: Map = mapOf(), + /** Spark sends refused after they may have reached the operators: the node stays off each until Spark syncs. */ + val sparkRefusedSends: Map = mapOf(), /** * Payment ids of Spark send attempts whose own failure a failed Activity write still has to save over an earlier * attempt's row, kept across a restart until it saves. @@ -490,6 +510,10 @@ data class AppCacheData( @Serializable data class SparkSendAttempt(val attempt: Int, val expiresAt: Long) +/** When a Spark send was refused and when its invoice expires, in epoch seconds. */ +@Serializable +data class SparkRefusedSend(val refusedAt: Long, val expiresAt: Long) + @Serializable data class CachedUsdtBalance( val address: String, diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 474c4cdd56..643a703262 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1342,6 +1342,7 @@ class BackupRepo @Inject constructor( moveToSparkHashes = emptyList(), sparkSendAttemptIds = emptyMap(), sparkSendAttempts = emptyMap(), + sparkRefusedSends = emptyMap(), sparkUnsavedOwnFailures = emptySet(), ) Logger.debug("Restored caches: ${jsonLogOf(logged)}", TAG) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 6e0337e9e4..14e7fd9a28 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -629,8 +629,8 @@ class SparkRepo @Inject constructor( val previousAttempt = cacheStore.data.first().sparkSendAttempts[paymentHash.lowercase()] val isReusedKey = previousAttempt?.attempt == attempt - // A send refused before anything reached Spark's operators leaves its key unused, so a retry refuses - // the same way. + // A refused send is taken as not having used its key, so a retry refuses the same way; a retry + // under the same key can't pay twice either way. suspend fun forgetUnusedAttempt() { if (!isReusedKey) cacheStore.restoreSparkSendAttempt(paymentHash, previousAttempt) } @@ -673,6 +673,14 @@ class SparkRepo @Inject constructor( // it was read. Under a key an earlier attempt used, it can hide the transfer that attempt // committed, so that send stays held. if ((it is SdkException.InsufficientFunds || it.isLeafSelectionFailure()) && !isReusedKey) { + // After an operator error the SDK can select leaves again, so this error can still follow a + // committed transfer: the node stays off the invoice until Spark syncs and lists it. Kept + // before the holds go, so no stop in between frees the invoice. + cacheStore.addSparkRefusedSend( + paymentHash, + refusedAt = clock.now().epochSeconds, + expiresAt = expiresAt.toEpochSeconds(), + ) cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) forgetUnusedAttempt() @@ -1819,6 +1827,15 @@ class SparkRepo @Inject constructor( send.value.equals(bolt11, ignoreCase = true) || send.key == paymentHash?.lowercase() } sendsInFlight.entries.firstOrNull(isOfInvoice)?.let { return@withContext EarlierSend.Pending(it.key) } + // A Spark send refused after it may have reached the operators holds the invoice until Spark syncs since. + val refused = paymentHash?.lowercase()?.let { hash -> + cacheStore.data.first().sparkRefusedSends[hash] + ?.takeIf { it.expiresAt > clock.now().epochSeconds } + ?.let { hash to it.refusedAt } + } + if (refused != null && !hasSyncedSince(refused.second.toULong())) { + return@withContext EarlierSend.Pending(refused.first) + } // A retry started, or recorded, while the listing below is read may still be pending, as may a send whose // outcome Spark didn't report until a sync settles it. val retried = { @@ -1837,6 +1854,7 @@ class SparkRepo @Inject constructor( null } if (payments == null) { + refused?.let { return@withContext EarlierSend.Pending(it.first) } startedSend(paymentHash)?.let { return@withContext EarlierSend.Pending(it) } refuseUnverifiedRestoredInvoice(bolt11, invoiceCreatedAt, invoiceExpiresAt) return@withContext null @@ -1847,6 +1865,11 @@ class SparkRepo @Inject constructor( it.invoice.equals(bolt11, ignoreCase = true) || it.htlcDetails.paymentHash.equals(paymentHash, ignoreCase = true) } + // Spark synced since the refusal, so this list shows any transfer that send committed, which keeps the + // refusal to hold the invoice when Spark can't list. + if (send == null || send.status == PaymentStatus.FAILED) { + refused?.let { cacheStore.removeSparkRefusedSend(it.first, it.second) } + } if (send == null) { (retried() ?: paymentHash?.lowercase()?.takeIf { it in unlisted }) ?.let { return@withContext EarlierSend.Pending(it) } diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index 619d6b0df5..f71408275d 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -47,6 +47,21 @@ class CacheStoreTest : BaseUnitTest() { assertFalse("hash" in sut.data.first().sparkSendAttempts) } + @Test + fun `a refused spark send drops expired ones and keeps a later refusal`() = test { + sut.addSparkRefusedSend("OLD", refusedAt = 1_000, expiresAt = 1_500) + sut.addSparkRefusedSend("HASH", refusedAt = 2_000, expiresAt = 3_000) + + assertEquals(mapOf("hash" to SparkRefusedSend(2_000, 3_000)), sut.data.first().sparkRefusedSends) + + sut.addSparkRefusedSend("hash", refusedAt = 2_500, expiresAt = 3_000) + sut.removeSparkRefusedSend("HASH", refusedAt = 2_000) + assertEquals(2_500, sut.data.first().sparkRefusedSends["hash"]?.refusedAt) + + sut.removeSparkRefusedSend("hash", refusedAt = 2_500) + assertFalse("hash" in sut.data.first().sparkRefusedSends) + } + @Test fun `invalidateReceiveLightningInvoice preserves a replacement invoice`() = test { val replacement = AppCacheData( diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 0cb91e1b48..b726edfae3 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4045,7 +4045,8 @@ class SparkRepoTest : BaseUnitTest() { assertTrue(inFlightAtClear.isNotEmpty() && inFlightAtClear.all { it }, "a sync could take back the hold") assertFalse(sut.isSendInFlight("hash")) - assertNull(sut.earlierLightningSend("lnbc1", "hash")) + // The node stays off the invoice until Spark syncs and shows no transfer for it. + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) } @Test @@ -5260,13 +5261,42 @@ class SparkRepoTest : BaseUnitTest() { assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) verify(sparkService, times(4)).send(any(), anyOrNull()) - assertFalse("hash" in store.data.first().sparkSendHashes) assertFalse("hash" in store.data.first().sparkUncertainSends) } + @Test + fun `a spark send refused after a leaf failure keeps the node off its invoice until spark syncs`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = null)) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw leafSelectionFailure() } + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) + sut.start(0).getOrThrow() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + // The SDK may have selected leaves again after a committed transfer, which Spark shows only once it syncs. + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) + + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1u)) + whenever(sparkService.listPayments()).thenReturn(emptyList()) + sut.start(0).getOrThrow() + advanceUntilIdle() + whenever(sparkService.listPayments()).thenAnswer { throw IllegalStateException("spark list") } + // Synced, but a list Spark can't read shows nothing of the transfer. + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) + + doReturn(emptyList()).whenever(sparkService).listPayments() + assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) + assertFalse("hash" in store.data.first().sparkRefusedSends) + } + @Test fun `a spark send refused before reaching spark is refused again on retry`() = test { whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) val prepared = unexpiredPrepared() whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw leafSelectionFailure() } From a3b2d6025101e83e248dbe0cdd25f89a205bba1d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 14:17:31 +0100 Subject: [PATCH 08/23] fix: leave payment details out of the restore log The restore log's copy of the app cache drops every address, invoice, payment hash, payment and activity id, transaction id and comment, as support requests attach the log. Closes #2024 Verified: detekt, compileDevDebugKotlin, BackupRepoTest and SparkRepoTest --- .../java/to/bitkit/repositories/BackupRepo.kt | 44 ++++++++++++++----- .../to/bitkit/repositories/BackupRepoTest.kt | 31 +++++++++++++ 2 files changed, 65 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 643a703262..757cb2ab4f 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -42,6 +42,7 @@ import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import to.bitkit.R import to.bitkit.async.appScope +import to.bitkit.data.AppCacheData import to.bitkit.data.AppDb import to.bitkit.data.CacheStore import to.bitkit.data.HwWalletStore @@ -1336,16 +1337,7 @@ class BackupRepo @Inject constructor( } runCatching { restoreSparkExitEarlierAddresses(parsed.sparkExitEarlierAddresses) } .onFailure { Logger.warn("Failed to restore the earlier Spark exit addresses", it, context = TAG) } - // Payment history and Spark attempt ids stay out of the log, as support requests attach it. - val logged = parsed.cache.copy( - cachedRates = emptyList(), - moveToSparkHashes = emptyList(), - sparkSendAttemptIds = emptyMap(), - sparkSendAttempts = emptyMap(), - sparkRefusedSends = emptyMap(), - sparkUnsavedOwnFailures = emptySet(), - ) - Logger.debug("Restored caches: ${jsonLogOf(logged)}", TAG) + Logger.debug("Restored caches: ${jsonLogOf(parsed.cache.withoutPaymentDetails())}", TAG) onCacheRestored() val persisted = preActivityMetadataRepo.upsertPreActivityMetadata(parsed.tagMetadata) .onFailure { Logger.warn("Failed to restore pre-activity metadata", it, context = TAG) } @@ -1722,3 +1714,35 @@ internal fun Throwable.isTemporaryBackupFailure(): Boolean = isPaykitTemporarily -> true else -> false } + +/** + * The cache as the restore log shows it: without the addresses, invoices, payment hashes, payment and activity ids, + * transaction ids and comments that identify a payment, as support requests attach the log. + */ +internal fun AppCacheData.withoutPaymentDetails() = copy( + cachedRates = emptyList(), + onchainAddress = "", + bolt11 = "", + bolt11PaymentHash = "", + bip21 = "", + deletedActivities = emptyList(), + detachedActivityContacts = emptySet(), + pendingBoostActivities = emptyList(), + backgroundReceive = null, + quickPayLedger = quickPayLedger?.copy(records = emptyList()), + pendingLightningMessages = emptyMap(), + pendingSparkWithdrawal = null, + sentSparkWithdrawals = emptyList(), + unfinishedPubkySwaps = emptyList(), + pubkySwapHoldHashes = emptyMap(), + sparkSendHashes = emptyList(), + sparkSendExpiries = emptyMap(), + sparkUncertainSends = emptyMap(), + sparkSendAttemptIds = emptyMap(), + sparkSendAttempts = emptyMap(), + sparkRefusedSends = emptyMap(), + sparkUnsavedOwnFailures = emptySet(), + moveToSparkHashes = emptyList(), + ldkSendHashes = emptyList(), + ldkSendExpiries = emptyMap(), +) diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 8ebe2f287b..f76491b486 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -58,6 +58,8 @@ import to.bitkit.data.PrivatePaykitReservationData import to.bitkit.data.PrivatePaykitReservationStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore +import to.bitkit.data.SparkRefusedSend +import to.bitkit.data.SparkSendAttempt import to.bitkit.data.WalletConnectionRecovery import to.bitkit.data.WatchOnlyAccountAllocationState import to.bitkit.data.WatchOnlyAccountBackupSnapshot @@ -101,6 +103,7 @@ import to.bitkit.services.SparkError import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture import to.bitkit.utils.AppError +import to.bitkit.utils.jsonLogOf import java.io.File import java.security.MessageDigest import java.util.concurrent.CountDownLatch @@ -3866,6 +3869,34 @@ class BackupRepoTest : BaseUnitTest() { connectionRecovery = connectionRecoveryFixture(settingsStore, keychain), ) + @Test + fun `the restore log leaves out every payment detail`() { + val id = "PAYMENT_DETAIL" + val cache = AppCacheData( + onchainAddress = id, + bolt11 = id, + bolt11PaymentHash = id, + bip21 = id, + deletedActivities = listOf(id), + detachedActivityContacts = setOf(id), + pendingLightningMessages = mapOf(id to id), + unfinishedPubkySwaps = listOf(id), + pubkySwapHoldHashes = mapOf(id to id), + sparkSendHashes = listOf(id), + sparkSendExpiries = mapOf(id to 1), + sparkUncertainSends = mapOf(id to 1), + sparkSendAttemptIds = mapOf(id to id), + sparkSendAttempts = mapOf(id to SparkSendAttempt(0, 1)), + sparkRefusedSends = mapOf(id to SparkRefusedSend(1, 2)), + sparkUnsavedOwnFailures = setOf(id), + moveToSparkHashes = listOf(id), + ldkSendHashes = listOf(id), + ldkSendExpiries = mapOf(id to 1), + ) + + assertFalse(id in jsonLogOf(cache.withoutPaymentDetails())) + } + private class BackupRepoTestError(message: String) : AppError(message) private companion object { From 2e951c31ea928ed2450e65942aadb835a165b2b4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 14:17:32 +0100 Subject: [PATCH 09/23] fix: keep a paid spark send paid after a storage error Cache writes on the Spark send's settlement path are best-effort: a storage error is logged and never turns a completed send into a failure. Closes #2025 Verified: detekt, compileDevDebugKotlin, BackupRepoTest and SparkRepoTest --- .../java/to/bitkit/repositories/SparkRepo.kt | 18 +++++++++++++++--- .../to/bitkit/repositories/SparkRepoTest.kt | 15 +++++++++++++++ 2 files changed, 30 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 14e7fd9a28..48a7b54d8c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -700,12 +700,16 @@ class SparkRepo @Inject constructor( if (payment.status == PaymentStatus.PENDING) { settleUncertainSend(paymentHash, expiresAt, attemptId) } else { - cacheStore.removeSparkUncertainSend(paymentHash) + bestEffort("end the hold of Spark send '$paymentHash'") { + cacheStore.removeSparkUncertainSend(paymentHash) + } } // Spark's failure event during its send call was left to this result, so the result reports it. if (payment.status == PaymentStatus.FAILED) { // This attempt paid nothing, as when its outcome settles, so a retry isn't held as pending. - cacheStore.removeSparkSendHash(paymentHash) + bestEffort("drop the hash of Spark send '$paymentHash'") { + cacheStore.removeSparkSendHash(paymentHash) + } recordActivity(payment, isOwnAttempt = true) // A retry under a key whose failure was already reported, as when Spark's list couldn't be read to // move past it, gets that failure back and no event, so the result reports it. @@ -750,6 +754,11 @@ class SparkRepo @Inject constructor( return result } + /** Logs a failed cache write on a send's settlement path, so a storage error never changes the send's outcome. */ + private suspend fun bestEffort(what: String, write: suspend () -> Unit) { + runSuspendCatching { write() }.onFailure { Logger.warn("Failed to $what", it, context = TAG) } + } + private suspend fun nextSendAttempt(paymentHash: String, listing: List?): Int { var attempt = cacheStore.data.first().sparkSendAttempts[paymentHash.lowercase()]?.attempt ?: 0 val failed = listing?.filter { it.status == PaymentStatus.FAILED }?.mapTo(HashSet()) { it.id } @@ -769,7 +778,10 @@ class SparkRepo @Inject constructor( val failedAt = clock.now().epochSeconds val startedAt = cacheStore.data.first().sparkUncertainSends[paymentHash.lowercase()] ?: failedAt uncertainSends[paymentHash.lowercase()] = UncertainSend(attemptId, failedAt.toULong(), expiresAt) - cacheStore.addSparkUncertainSend(paymentHash, startedAt, attemptId) + // Held in memory meanwhile, and the hash kept before the send still holds the invoice after a restart. + bestEffort("keep the hold of Spark send '$paymentHash'") { + cacheStore.addSparkUncertainSend(paymentHash, startedAt, attemptId) + } scope.launch { // The send screen tracks the hash as pending only once the send returns, and resolves tracked ones. withTimeoutOrNull(PENDING_TRACK_WAIT) { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index b726edfae3..5f1eea1b25 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5293,6 +5293,21 @@ class SparkRepoTest : BaseUnitTest() { assertFalse("hash" in store.data.first().sparkRefusedSends) } + @Test + fun `a paid spark send stays paid when its hold can't be removed from storage`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(sentPayment(fees = 0)) + whenever(cacheStore.removeSparkUncertainSend(any())).thenAnswer { throw IOException("disk full") } + val sut = createSut() + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + } + @Test fun `a spark send refused before reaching spark is refused again on retry`() = test { whenever(sparkService.isConnected).thenReturn(true) From 9647c19d19fb3338329426fb04d1e6ecd2f19d0b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 14:22:56 +0100 Subject: [PATCH 10/23] test: cover the refusal of a spark send that may have reached spark Verified: detekt and SparkRepoTest --- .../to/bitkit/repositories/SparkRepoTest.kt | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 5f1eea1b25..b48921aecd 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5247,6 +5247,57 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(listOf("hash-0", "hash-0"), keys) } + @Test + fun `a spark send stops retrying its leaves once its deadline passes`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val deadline = now + 1.minutes + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { + now = deadline + 1.minutes + throw leafSelectionFailure() + } + val sut = createSut(CacheStore(InMemoryDataStore(AppCacheData()), clock)) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", 100uL, paymentDeadlineAt = deadline).exceptionOrNull()) + + verify(sparkService, times(1)).send(any(), anyOrNull()) + } + + @Test + fun `a refused spark send spark lists completed keeps the node off while spark can't list until it expires`() = + test { + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = null)) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw leafSelectionFailure() } + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) + sut.start(0).getOrThrow() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1u)) + var isListReadable = true + whenever(sparkService.listPayments()).thenAnswer { + check(isListReadable) { "spark list" } + listOf(sentPayment(fees = 0)) + } + sut.start(0).getOrThrow() + advanceUntilIdle() + assertNotNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) + + // The transfer the refused send committed keeps its refusal, so a list Spark can't read still holds it. + isListReadable = false + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) + + // Once the invoice expired, no node send can pay it. + now += 2.hours + assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) + } + @Test fun `a spark send whose leaves spark can't select is refused under a new key`() = test { whenever(sparkService.isConnected).thenReturn(true) From 7c7023cbd37b950c1bf55959859c76daa158392a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 14:37:46 +0100 Subject: [PATCH 11/23] fix: keep spark settlement writes best-effort and the usdt address out of the restore log Verified: detekt, lint and the unit suite --- .../main/java/to/bitkit/repositories/BackupRepo.kt | 1 + .../main/java/to/bitkit/repositories/SparkRepo.kt | 12 ++++++++---- .../java/to/bitkit/repositories/BackupRepoTest.kt | 2 ++ 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 757cb2ab4f..7af42af66b 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1725,6 +1725,7 @@ internal fun AppCacheData.withoutPaymentDetails() = copy( bolt11 = "", bolt11PaymentHash = "", bip21 = "", + usdtDisplayBalance = null, deletedActivities = emptyList(), detachedActivityContacts = emptySet(), pendingBoostActivities = emptyList(), diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 48a7b54d8c..150a2f3af0 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -909,8 +909,10 @@ class SparkRepo @Inject constructor( // finds it settled. return holdRestoreMutex.withLock { if (!uncertainSends.remove(key, uncertain)) return@withLock null - cacheStore.removeSparkUncertainSend(paymentHash) - if (isFailed && !sendsInFlight.containsKey(key)) cacheStore.removeSparkSendHash(paymentHash) + bestEffort("end the hold of Spark send '$paymentHash'") { cacheStore.removeSparkUncertainSend(paymentHash) } + if (isFailed && !sendsInFlight.containsKey(key)) { + bestEffort("drop the hash of Spark send '$paymentHash'") { cacheStore.removeSparkSendHash(paymentHash) } + } key !in restoredAtStart } } @@ -2247,8 +2249,10 @@ class SparkRepo @Inject constructor( if (isFailed && isHeldFrom(payment)) return@withLock true uncertainSends.remove(hash.lowercase()) if (restoredAtStart.remove(hash.lowercase())) reportedSendIds.add(payment.id) - cacheStore.removeSparkUncertainSend(hash) - if (isReleased) cacheStore.removeSparkSendHash(hash) + bestEffort("end the hold of Spark send '$hash'") { cacheStore.removeSparkUncertainSend(hash) } + if (isReleased) { + bestEffort("drop the hash of Spark send '$hash'") { cacheStore.removeSparkSendHash(hash) } + } false } } ?: false diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index f76491b486..d0a15a1142 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -51,6 +51,7 @@ import to.bitkit.R import to.bitkit.data.AppCacheData import to.bitkit.data.AppDb import to.bitkit.data.CacheStore +import to.bitkit.data.CachedUsdtBalance import to.bitkit.data.HwWalletData import to.bitkit.data.HwWalletStore import to.bitkit.data.PaykitOutboundDeliveryStore @@ -3877,6 +3878,7 @@ class BackupRepoTest : BaseUnitTest() { bolt11 = id, bolt11PaymentHash = id, bip21 = id, + usdtDisplayBalance = CachedUsdtBalance(address = id, network = "regtest", balance = 1u), deletedActivities = listOf(id), detachedActivityContacts = setOf(id), pendingLightningMessages = mapOf(id to id), From e888aa6b4ca3fc126139585c1f35d725d00ff117 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 15:48:04 +0100 Subject: [PATCH 12/23] fix: keep the node off a refused spark send until its invoice expires A transfer the refused send committed can stay unlisted after a sync and still go out, as an unknown send's can, so the refusal holds the node until the invoice expires. A failed result Spark returns is reported as a failure, as the caller subscribes to events only once the send returns. Verified: detekt, SparkRepoTest and CacheStoreTest --- .../main/java/to/bitkit/data/CacheStore.kt | 11 +---- .../java/to/bitkit/repositories/SparkRepo.kt | 30 +++++-------- .../java/to/bitkit/data/CacheStoreTest.kt | 6 +-- .../to/bitkit/repositories/SparkRepoTest.kt | 45 +++---------------- 4 files changed, 18 insertions(+), 74 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 5d68fca657..edd9b3270c 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -175,15 +175,6 @@ class CacheStore internal constructor( } } - /** Drops the refusal of [paymentHash] made at [refusedAt] only, as a later one waits for its own sync. */ - suspend fun removeSparkRefusedSend(paymentHash: String, refusedAt: Long) { - val hash = paymentHash.lowercase() - store.updateData { - val isSame = it.sparkRefusedSends[hash]?.refusedAt == refusedAt - if (isSame) it.copy(sparkRefusedSends = it.sparkRefusedSends - hash) else it - } - } - suspend fun removeSparkSendHash(paymentHash: String) { val hash = paymentHash.lowercase() if (hash !in store.data.first().sparkSendHashes) return @@ -454,7 +445,7 @@ data class AppCacheData( val sparkSendAttemptIds: Map = mapOf(), /** The latest attempt at each invoice Spark sent, by hash, whose number picks the attempt's idempotency key. */ val sparkSendAttempts: Map = mapOf(), - /** Spark sends refused after they may have reached the operators: the node stays off each until Spark syncs. */ + /** Spark sends refused after they may have reached the operators: the node stays off each until it expires. */ val sparkRefusedSends: Map = mapOf(), /** * Payment ids of Spark send attempts whose own failure a failed Activity write still has to save over an earlier diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 150a2f3af0..97e877f632 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -711,10 +711,11 @@ class SparkRepo @Inject constructor( cacheStore.removeSparkSendHash(paymentHash) } recordActivity(payment, isOwnAttempt = true) - // A retry under a key whose failure was already reported, as when Spark's list couldn't be read to - // move past it, gets that failure back and no event, so the result reports it. - if (!reportedSendIds.add(payment.id)) throw SparkError.SendRefused("Spark send failed earlier") - payment.toNodeEvent()?.let { _nodeEvents.emit(it) } + // The caller subscribes to events only once this returns, so the result reports the failure too. A + // retry under a key whose failure was already reported, as when Spark's list couldn't be read to + // move past it, gets that failure back and no event. + if (reportedSendIds.add(payment.id)) payment.toNodeEvent()?.let { _nodeEvents.emit(it) } + throw SparkError.SendRefused("Spark send failed") } Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) paymentHash @@ -1841,15 +1842,12 @@ class SparkRepo @Inject constructor( send.value.equals(bolt11, ignoreCase = true) || send.key == paymentHash?.lowercase() } sendsInFlight.entries.firstOrNull(isOfInvoice)?.let { return@withContext EarlierSend.Pending(it.key) } - // A Spark send refused after it may have reached the operators holds the invoice until Spark syncs since. - val refused = paymentHash?.lowercase()?.let { hash -> - cacheStore.data.first().sparkRefusedSends[hash] - ?.takeIf { it.expiresAt > clock.now().epochSeconds } - ?.let { hash to it.refusedAt } - } - if (refused != null && !hasSyncedSince(refused.second.toULong())) { - return@withContext EarlierSend.Pending(refused.first) - } + // A Spark send refused after it may have reached the operators holds the invoice until it expires: a + // transfer it committed can stay unlisted after a sync and still go out, as an unknown send's can. + val refusals = cacheStore.data.first().sparkRefusedSends + paymentHash?.lowercase() + ?.takeIf { hash -> refusals[hash]?.let { it.expiresAt > clock.now().epochSeconds } == true } + ?.let { return@withContext EarlierSend.Pending(it) } // A retry started, or recorded, while the listing below is read may still be pending, as may a send whose // outcome Spark didn't report until a sync settles it. val retried = { @@ -1868,7 +1866,6 @@ class SparkRepo @Inject constructor( null } if (payments == null) { - refused?.let { return@withContext EarlierSend.Pending(it.first) } startedSend(paymentHash)?.let { return@withContext EarlierSend.Pending(it) } refuseUnverifiedRestoredInvoice(bolt11, invoiceCreatedAt, invoiceExpiresAt) return@withContext null @@ -1879,11 +1876,6 @@ class SparkRepo @Inject constructor( it.invoice.equals(bolt11, ignoreCase = true) || it.htlcDetails.paymentHash.equals(paymentHash, ignoreCase = true) } - // Spark synced since the refusal, so this list shows any transfer that send committed, which keeps the - // refusal to hold the invoice when Spark can't list. - if (send == null || send.status == PaymentStatus.FAILED) { - refused?.let { cacheStore.removeSparkRefusedSend(it.first, it.second) } - } if (send == null) { (retried() ?: paymentHash?.lowercase()?.takeIf { it in unlisted }) ?.let { return@withContext EarlierSend.Pending(it) } diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index f71408275d..dff04054cf 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -48,18 +48,14 @@ class CacheStoreTest : BaseUnitTest() { } @Test - fun `a refused spark send drops expired ones and keeps a later refusal`() = test { + fun `a refused spark send drops expired ones and keeps the latest refusal`() = test { sut.addSparkRefusedSend("OLD", refusedAt = 1_000, expiresAt = 1_500) sut.addSparkRefusedSend("HASH", refusedAt = 2_000, expiresAt = 3_000) assertEquals(mapOf("hash" to SparkRefusedSend(2_000, 3_000)), sut.data.first().sparkRefusedSends) sut.addSparkRefusedSend("hash", refusedAt = 2_500, expiresAt = 3_000) - sut.removeSparkRefusedSend("HASH", refusedAt = 2_000) assertEquals(2_500, sut.data.first().sparkRefusedSends["hash"]?.refusedAt) - - sut.removeSparkRefusedSend("hash", refusedAt = 2_500) - assertFalse("hash" in sut.data.first().sparkRefusedSends) } @Test diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index b48921aecd..f993e812b2 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4442,7 +4442,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(earlier) val sut = createSut(store) sut.start(0).getOrThrow() - sut.payInvoice("lnbc1", 100uL).getOrThrow() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) whenever { sparkService.listPayments() }.thenReturn(listOf(earlier)) advanceUntilIdle() @@ -5266,38 +5266,6 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, times(1)).send(any(), anyOrNull()) } - @Test - fun `a refused spark send spark lists completed keeps the node off while spark can't list until it expires`() = - test { - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = null)) - val prepared = unexpiredPrepared() - whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw leafSelectionFailure() } - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - val sut = createSut(store) - sut.start(0).getOrThrow() - assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) - - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1u)) - var isListReadable = true - whenever(sparkService.listPayments()).thenAnswer { - check(isListReadable) { "spark list" } - listOf(sentPayment(fees = 0)) - } - sut.start(0).getOrThrow() - advanceUntilIdle() - assertNotNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) - - // The transfer the refused send committed keeps its refusal, so a list Spark can't read still holds it. - isListReadable = false - assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) - - // Once the invoice expired, no node send can pay it. - now += 2.hours - assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) - } - @Test fun `a spark send whose leaves spark can't select is refused under a new key`() = test { whenever(sparkService.isConnected).thenReturn(true) @@ -5316,7 +5284,7 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `a spark send refused after a leaf failure keeps the node off its invoice until spark syncs`() = test { + fun `a spark send refused after a leaf failure keeps the node off its invoice until it expires`() = test { whenever(sparkService.isConnected).thenReturn(true) whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = null)) val prepared = unexpiredPrepared() @@ -5327,21 +5295,18 @@ class SparkRepoTest : BaseUnitTest() { sut.start(0).getOrThrow() assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) - - // The SDK may have selected leaves again after a committed transfer, which Spark shows only once it syncs. assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) + // The SDK may have selected leaves again after a committed transfer, which can stay unlisted after a sync. whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1u)) whenever(sparkService.listPayments()).thenReturn(emptyList()) sut.start(0).getOrThrow() advanceUntilIdle() - whenever(sparkService.listPayments()).thenAnswer { throw IllegalStateException("spark list") } - // Synced, but a list Spark can't read shows nothing of the transfer. assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) - doReturn(emptyList()).whenever(sparkService).listPayments() + // Once the invoice expired, no node send can pay it. + now += 2.hours assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) - assertFalse("hash" in store.data.first().sparkRefusedSends) } @Test From 04194a0112debfc114a50a127c0bf9b72f9f44e1 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 16:10:40 +0100 Subject: [PATCH 13/23] fix: treat a spark send refused after a leaf failure as uncertain A refusal that may follow a committed transfer keeps the Paykit proof, the allowance attempt and the QuickPay charge open. A node send of its invoice is refused instead of held pending, and each leaf-selection retry rechecks that the payment is still allowed. Verified: SparkRepoTest, QuickPayRepoTest, PaykitPaymentProofRepoTest, LightningRepoTest --- .../repositories/PaykitPaymentProofRepo.kt | 2 ++ .../to/bitkit/repositories/QuickPayRepo.kt | 7 ++-- .../java/to/bitkit/repositories/SparkRepo.kt | 31 +++++++++++------- .../java/to/bitkit/services/SparkService.kt | 9 ++++-- .../java/to/bitkit/viewmodels/AppViewModel.kt | 5 ++- .../PaykitPaymentProofRepoTest.kt | 12 +++++++ .../bitkit/repositories/QuickPayRepoTest.kt | 7 ++++ .../to/bitkit/repositories/SparkRepoTest.kt | 32 ++++++++++++++++--- 8 files changed, 82 insertions(+), 23 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index b8fe69b490..a08d766db2 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -938,6 +938,8 @@ class PaykitPaymentProofRepo @Inject constructor( val error = generateSequence(submissionError) { it.cause } .firstOrNull { it is ServiceError.PaymentDeadlineExpired || it is SparkError.SendRefused } ?: submissionError.asNodeException() ?: submissionError + // A refused Spark send that may have committed a transfer can still settle, so its proof is kept. + if (error is SparkError.SendRefused && error.mayHaveReachedSpark) return false when (error) { is SparkError.SendRefused, is NodeNotRunningError, diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index e6ff629b86..a7db9bb620 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -1081,9 +1081,10 @@ internal data class SpendSnapshot( ) internal fun classifyDispatchError(error: Throwable): QuickPayDispatchClass { - // Spark refuses only before anything leaves the wallet, as PaykitPaymentProofRepo reads it. - if (generateSequence(error) { it.cause }.any { it is SparkError.SendRefused }) { - return QuickPayDispatchClass.PRE_DISPATCH_REJECTION + // Spark refuses before anything leaves the wallet, as PaykitPaymentProofRepo reads it, unless the refusal may + // follow a transfer Spark committed. + generateSequence(error) { it.cause }.filterIsInstance().firstOrNull()?.let { + return if (it.mayHaveReachedSpark) QuickPayDispatchClass.AMBIGUOUS else QuickPayDispatchClass.PRE_DISPATCH_REJECTION } return when (error.asNodeException()) { is NodeException.InvalidInvoice, diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 97e877f632..29f7e65fa4 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -657,7 +657,7 @@ class SparkRepo @Inject constructor( forgetUnusedAttempt() throw it } - sendRetryingLeafSelection(prepared, attemptId, paymentDeadlineAt) + sendRetryingLeafSelection(prepared, attemptId, paymentDeadlineAt, onBeforeSend) } } val payment = sent.getOrElse { @@ -689,7 +689,7 @@ class SparkRepo @Inject constructor( } else { "Spark balance can't cover the payment" } - throw SparkError.SendRefused(reason, it) + throw SparkError.SendRefused(reason, it, mayHaveReachedSpark = true) } Logger.warn("Failed to learn the outcome of Spark send '$paymentHash'", it, context = TAG) settleUncertainSend(paymentHash, expiresAt, attemptId) @@ -737,6 +737,7 @@ class SparkRepo @Inject constructor( prepared: PrepareSendPaymentResponse, attemptId: String, paymentDeadlineAt: Instant?, + onBeforeSend: suspend () -> Boolean, ): Result { var result = runSuspendCatching { sparkService.send(prepared, attemptId) } val canRetry = { @@ -749,7 +750,8 @@ class SparkRepo @Inject constructor( if (result.exceptionOrNull()?.isLeafSelectionFailure() != true || !canRetry()) return result Logger.info("Retrying Spark send '$attemptId' as Spark could not select its leaves", context = TAG) delay(LEAF_SELECTION_RETRY_DELAY) - if (!canRetry()) return result + // A cancel, block or identity change can land during the delay, so each resend is checked again. + if (!canRetry() || !onBeforeSend()) return result result = runSuspendCatching { sparkService.send(prepared, attemptId) } } return result @@ -1842,12 +1844,17 @@ class SparkRepo @Inject constructor( send.value.equals(bolt11, ignoreCase = true) || send.key == paymentHash?.lowercase() } sendsInFlight.entries.firstOrNull(isOfInvoice)?.let { return@withContext EarlierSend.Pending(it.key) } - // A Spark send refused after it may have reached the operators holds the invoice until it expires: a - // transfer it committed can stay unlisted after a sync and still go out, as an unknown send's can. - val refusals = cacheStore.data.first().sparkRefusedSends - paymentHash?.lowercase() - ?.takeIf { hash -> refusals[hash]?.let { it.expiresAt > clock.now().epochSeconds } == true } - ?.let { return@withContext EarlierSend.Pending(it) } + // A Spark send refused after it may have reached the operators keeps the node off the invoice until it + // expires: a transfer it committed can stay unlisted after a sync and still go out, as an unknown send's + // can. Unless an earlier send reads pending or paid, the node send is refused, not held pending, as no + // event would resolve a pending screen. + val refusal = cacheStore.data.first().sparkRefusedSends[paymentHash?.lowercase()] + val noEarlierSend = { + if (refusal != null && refusal.expiresAt > clock.now().epochSeconds) { + throw SparkError.SendRefused("Spark may still send this invoice", mayHaveReachedSpark = true) + } + null + } // A retry started, or recorded, while the listing below is read may still be pending, as may a send whose // outcome Spark didn't report until a sync settles it. val retried = { @@ -1868,7 +1875,7 @@ class SparkRepo @Inject constructor( if (payments == null) { startedSend(paymentHash)?.let { return@withContext EarlierSend.Pending(it) } refuseUnverifiedRestoredInvoice(bolt11, invoiceCreatedAt, invoiceExpiresAt) - return@withContext null + return@withContext noEarlierSend() } seedSendHashes(payments) val send = payments @@ -1880,7 +1887,7 @@ class SparkRepo @Inject constructor( (retried() ?: paymentHash?.lowercase()?.takeIf { it in unlisted }) ?.let { return@withContext EarlierSend.Pending(it) } refuseUnverifiedRestoredInvoice(bolt11, invoiceCreatedAt, invoiceExpiresAt) - return@withContext null + return@withContext noEarlierSend() } if (send.status == PaymentStatus.FAILED) { retried()?.let { return@withContext EarlierSend.Pending(it) } @@ -1890,7 +1897,7 @@ class SparkRepo @Inject constructor( when (send.status) { PaymentStatus.PENDING -> EarlierSend.Pending(hash) PaymentStatus.COMPLETED -> EarlierSend.Paid(hash) - PaymentStatus.FAILED -> null + PaymentStatus.FAILED -> noEarlierSend() } } diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 21564fa141..cc131d2385 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -420,9 +420,14 @@ 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; 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. + * sends yet. A Paykit request or allowance attempt can then end as failed, unless [mayHaveReachedSpark]: Spark + * refused it after a transfer it may have committed, which can still go out until the invoice expires. */ - open class SendRefused(message: String, cause: Throwable? = null) : SparkError(message, cause) + open class SendRefused( + message: String, + cause: Throwable? = null, + val mayHaveReachedSpark: Boolean = false, + ) : SparkError(message, cause) /** 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) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 645ee70721..20c5a0d1a2 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -8208,7 +8208,10 @@ class AppViewModel @Inject constructor( } releasePrivatePaymentListIfNeeded(contactPaymentContext) cancelPaymentProofPreparation(proofRequest) - finishManualAllowancePayment(allowanceAttemptId, succeeded = false) + // A refused Spark send that may have committed a transfer can still settle, and its event settles the + // allowance attempt then. + val mayHaveSent = (error as? SparkError.SendRefused)?.mayHaveReachedSpark == true + finishManualAllowancePayment(allowanceAttemptId, succeeded = if (mayHaveSent) null else false) createdMetadataPaymentId?.let { preActivityMetadataRepo.deletePreActivityMetadata(it) } lnurlComment?.let { activityRepo.clearPendingLightningMessage(paymentHash) } if (error is MoveToSparkError.UpdateFeeUnseen) { diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index eaefc24e54..023e508372 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -1501,6 +1501,18 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { } } + @Test + fun `a spark refusal that may follow a committed transfer keeps the proof`() = test { + val request = paymentRequest(MethodId.Bolt11.rawValue) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.Bolt11.rawValue, "bitkit", PaykitPaymentProofKind.Lightning).getOrThrow() + repo.associateLightningPayment(request, PAYMENT_HASH, MethodId.Bolt11.rawValue, "bitkit").getOrThrow() + val refusal = SparkError.SendRefused("Spark could not select leaves", mayHaveReachedSpark = true) + + assertFalse(repo.failLightningPayment(PAYMENT_HASH, refusal)) + assertFalse(storedProofs.isEmpty()) + } + @Test fun `onchain proof uses selected endpoint and transaction id`() = test { val txid = "ab".repeat(32) diff --git a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt index af3c71bde8..3684a6d6ab 100644 --- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt @@ -806,6 +806,13 @@ class QuickPayRepoTest : BaseUnitTest() { assertEquals(QuickPayDispatchClass.PRE_DISPATCH_REJECTION, classifyDispatchError(SparkError.InvoiceExpired())) } + @Test + fun `a spark refusal that may follow a committed transfer is ambiguous`() { + val refusal = SparkError.SendRefused("Spark could not select leaves", mayHaveReachedSpark = true) + + assertEquals(QuickPayDispatchClass.AMBIGUOUS, classifyDispatchError(to.bitkit.utils.AppError(refusal))) + } + @Test fun `classifies wrapped and unwrapped ldk errors`() { assertEquals( diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index f993e812b2..b6fb57f217 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4045,8 +4045,9 @@ class SparkRepoTest : BaseUnitTest() { assertTrue(inFlightAtClear.isNotEmpty() && inFlightAtClear.all { it }, "a sync could take back the hold") assertFalse(sut.isSendInFlight("hash")) - // The node stays off the invoice until Spark syncs and shows no transfer for it. - assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + // The node stays off the invoice until it expires. + val nodeRefusal = runCatching { sut.earlierLightningSend("lnbc1", "hash") }.exceptionOrNull() + assertTrue(assertIs(nodeRefusal).mayHaveReachedSpark) } @Test @@ -5266,6 +5267,24 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, times(1)).send(any(), anyOrNull()) } + @Test + fun `a spark send stops retrying its leaves once the payment is no longer allowed`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw leafSelectionFailure() } + val sut = createSut(CacheStore(InMemoryDataStore(AppCacheData()), clock)) + sut.start(0).getOrThrow() + advanceUntilIdle() + var checks = 0 + + val result = sut.payInvoice("lnbc1", 100uL, onBeforeSend = { ++checks == 1 }) + + assertIs(result.exceptionOrNull()) + verify(sparkService, times(1)).send(any(), anyOrNull()) + assertEquals(2, checks) + } + @Test fun `a spark send whose leaves spark can't select is refused under a new key`() = test { whenever(sparkService.isConnected).thenReturn(true) @@ -5294,15 +5313,18 @@ class SparkRepoTest : BaseUnitTest() { val sut = createSut(store) sut.start(0).getOrThrow() - assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) - assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) + val refusal = assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + assertTrue(refusal.mayHaveReachedSpark) + val nodeRefusal = runCatching { sut.earlierLightningSend("lnbc1280n1send", "hash") }.exceptionOrNull() + assertTrue(assertIs(nodeRefusal).mayHaveReachedSpark) // The SDK may have selected leaves again after a committed transfer, which can stay unlisted after a sync. whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1u)) whenever(sparkService.listPayments()).thenReturn(emptyList()) sut.start(0).getOrThrow() advanceUntilIdle() - assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) + val laterRefusal = runCatching { sut.earlierLightningSend("lnbc1280n1send", "hash") }.exceptionOrNull() + assertIs(laterRefusal) // Once the invoice expired, no node send can pay it. now += 2.hours From 4038326ad27ad98e26fcfc0cac631c4511d53b9d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 16:16:43 +0100 Subject: [PATCH 14/23] fix: keep a spark send refused after a leaf failure open where it may settle A Spark retry of leaves it couldn't select keeps its rail admission and rechecks only the payment's authorization. A Pubky swap's hold payment waits on its claim, a Paykit request shows failed but keeps its proof and private list, and QuickPay shows failed but keeps its charge. The hold read on the uncertain path is best-effort. Verified: SparkRepoTest, QuickPayRepoTest, PaykitPaymentProofRepoTest, LightningRepoTest --- .../to/bitkit/repositories/LightningRepo.kt | 7 +++++- .../to/bitkit/repositories/QuickPayRepo.kt | 14 +++++++++++- .../java/to/bitkit/repositories/SparkRepo.kt | 6 +++-- .../java/to/bitkit/viewmodels/AppViewModel.kt | 22 ++++++++++++------- .../bitkit/repositories/LightningRepoTest.kt | 19 ++++++++++++++++ .../bitkit/repositories/QuickPayRepoTest.kt | 4 ++-- 6 files changed, 58 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 7c7a9f88d5..29c0e213fd 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1630,7 +1630,12 @@ class LightningRepo @Inject constructor( var isAdmitted = false var isRefused = false var railBefore: LightningRail? = null - val authorizeSend: suspend () -> Boolean = { + var isChecked = false + val authorizeSend: suspend () -> Boolean = authorize@{ + // Spark's retry of a send whose leaves it couldn't select keeps the send's admission and rechecks only + // that the payment is still allowed. + if (isChecked) return@authorize isAuthorizedAtSubmission?.invoke() ?: onBeforeSend() + isChecked = true val isAuthorized = onBeforeSend().also { if (it) requireWalletRestoreComplete() } if (isAuthorized) { isAdmitted = admitSend(key, LightningRail.Spark) { diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index a7db9bb620..22bd6bba12 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -577,6 +577,11 @@ class QuickPayRepo @Inject constructor( emitOutcomeLocked(invoiceHash, error, paymentRequest) } } + // Shown as failed, as nothing would resolve a pending screen if no transfer went out; the charge stays, as + // a transfer Spark may have committed can still settle. + QuickPayDispatchClass.REFUSED_AFTER_SPARK_SEND -> mutex.withLock { + emitOutcomeLocked(invoiceHash, error, paymentRequest) + } QuickPayDispatchClass.DUPLICATE_PAYMENT, QuickPayDispatchClass.AMBIGUOUS, -> { @@ -1084,7 +1089,11 @@ internal fun classifyDispatchError(error: Throwable): QuickPayDispatchClass { // Spark refuses before anything leaves the wallet, as PaykitPaymentProofRepo reads it, unless the refusal may // follow a transfer Spark committed. generateSequence(error) { it.cause }.filterIsInstance().firstOrNull()?.let { - return if (it.mayHaveReachedSpark) QuickPayDispatchClass.AMBIGUOUS else QuickPayDispatchClass.PRE_DISPATCH_REJECTION + return if (it.mayHaveReachedSpark) { + QuickPayDispatchClass.REFUSED_AFTER_SPARK_SEND + } else { + QuickPayDispatchClass.PRE_DISPATCH_REJECTION + } } return when (error.asNodeException()) { is NodeException.InvalidInvoice, @@ -1100,6 +1109,9 @@ internal fun classifyDispatchError(error: Throwable): QuickPayDispatchClass { enum class QuickPayDispatchClass { PRE_DISPATCH_REJECTION, + + /** Refused after a transfer Spark may have committed, which can still settle until its invoice expires. */ + REFUSED_AFTER_SPARK_SEND, DUPLICATE_PAYMENT, AMBIGUOUS, } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 29f7e65fa4..812bea4fca 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -674,7 +674,7 @@ class SparkRepo @Inject constructor( // committed, so that send stays held. if ((it is SdkException.InsufficientFunds || it.isLeafSelectionFailure()) && !isReusedKey) { // After an operator error the SDK can select leaves again, so this error can still follow a - // committed transfer: the node stays off the invoice until Spark syncs and lists it. Kept + // committed transfer: the node stays off the invoice until it expires. Kept // before the holds go, so no stop in between frees the invoice. cacheStore.addSparkRefusedSend( paymentHash, @@ -779,7 +779,9 @@ class SparkRepo @Inject constructor( private suspend fun settleUncertainSend(paymentHash: String, expiresAt: ULong, attemptId: String) { val failedAt = clock.now().epochSeconds - val startedAt = cacheStore.data.first().sparkUncertainSends[paymentHash.lowercase()] ?: failedAt + val startedAt = runSuspendCatching { cacheStore.data.first().sparkUncertainSends[paymentHash.lowercase()] } + .onFailure { Logger.warn("Failed to read the hold of Spark send '$paymentHash'", it, context = TAG) } + .getOrNull() ?: failedAt uncertainSends[paymentHash.lowercase()] = UncertainSend(attemptId, failedAt.toULong(), expiresAt) // Held in memory meanwhile, and the hash kept before the send still holds the invoice after a restart. bestEffort("keep the hold of Spark send '$paymentHash'") { diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 20c5a0d1a2..be5dab8279 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -7761,8 +7761,9 @@ class AppViewModel @Inject constructor( swapIdsByHoldHash[holdPaymentHash] = payment.swapId // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending. lightningRepo.payInvoice(payment.invoice).onFailure { - // Spark may have sent it, so an unknown outcome waits on the claim like a sent hold payment. - if (it is PaymentPendingException) return@onFailure + // Spark may have sent it, so an unknown outcome, or a refusal after a transfer Spark may have committed, + // waits on the claim like a sent hold payment. + if (it is PaymentPendingException || it.mayHaveReachedSpark()) return@onFailure holdFailure.cancel() swapIdsByHoldHash.remove(holdPaymentHash) pubkySwapsRouteRepo.dropFailedSwap(payment.swapId) @@ -8206,11 +8207,13 @@ class AppViewModel @Inject constructor( resolveSettledPendingSend(pendingHash) return@onFailure } - releasePrivatePaymentListIfNeeded(contactPaymentContext) - cancelPaymentProofPreparation(proofRequest) - // A refused Spark send that may have committed a transfer can still settle, and its event settles the - // allowance attempt then. - val mayHaveSent = (error as? SparkError.SendRefused)?.mayHaveReachedSpark == true + // A refused Spark send that may have committed a transfer can still settle, so it shows as failed but keeps + // its proof, private payment list and allowance attempt, which its event settles then. + val mayHaveSent = error.mayHaveReachedSpark() + if (!mayHaveSent) { + releasePrivatePaymentListIfNeeded(contactPaymentContext) + cancelPaymentProofPreparation(proofRequest) + } finishManualAllowancePayment(allowanceAttemptId, succeeded = if (mayHaveSent) null else false) createdMetadataPaymentId?.let { preActivityMetadataRepo.deletePreActivityMetadata(it) } lnurlComment?.let { activityRepo.clearPendingLightningMessage(paymentHash) } @@ -8342,7 +8345,7 @@ class AppViewModel @Inject constructor( updateFailed: Boolean, ): Boolean = when (error) { is PaymentPendingException -> false - else if !isPaymentRequest -> true + else if !isPaymentRequest || error.mayHaveReachedSpark() -> true // Any failed spending balance update happens before the invoice is paid, so nothing was sent. else if updateFailed || error is LightningPaymentFailedError -> { paykitPaymentProofRepo.failLightningPayment(paymentHash) @@ -11219,3 +11222,6 @@ internal fun allowanceOffersAcceptedDescription( else -> several.replace("{names}", formatNames(names)) } } + +/** A Spark send refused after a transfer it may have committed, which can still settle until its invoice expires. */ +private fun Throwable.mayHaveReachedSpark(): Boolean = (this as? SparkError.SendRefused)?.mayHaveReachedSpark == true diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 6f43ef6a4c..f016afbfd5 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1249,6 +1249,25 @@ class LightningRepoTest : BaseUnitTest() { verify(sparkRepo).payInvoice(eq("invoice"), eq(1_000uL), eq(deadline), eq(10_000uL), any()) } + @Test + fun `a spark retry rechecks only the payment's authorization`() = test { + startNodeForTesting() + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + val checks = mutableListOf() + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())).doSuspendableAnswer { + val authorize = it.getArgument Boolean>(4) + repeat(2) { checks += authorize() } + Result.success("hash") + } + var submissionChecks = 0 + + val result = sut.payInvoiceAuthorizedAtSubmission("invoice", 1_000uL, { ++submissionChecks > 0 }) { true } + + assertEquals("hash", result.getOrThrow()) + assertEquals(listOf(true, true), checks) + assertEquals(1, submissionChecks) + } + @Test fun `a node send checks its authorization again where it is submitted`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt index 3684a6d6ab..1d2c6a394c 100644 --- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt @@ -807,10 +807,10 @@ class QuickPayRepoTest : BaseUnitTest() { } @Test - fun `a spark refusal that may follow a committed transfer is ambiguous`() { + fun `a spark refusal that may follow a committed transfer keeps its charge`() { val refusal = SparkError.SendRefused("Spark could not select leaves", mayHaveReachedSpark = true) - assertEquals(QuickPayDispatchClass.AMBIGUOUS, classifyDispatchError(to.bitkit.utils.AppError(refusal))) + assertEquals(QuickPayDispatchClass.REFUSED_AFTER_SPARK_SEND, classifyDispatchError(AppError(refusal))) } @Test From e34b5e656927890dee8027d7fb8debc807591fc8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 16:42:05 +0100 Subject: [PATCH 15/23] fix: keep a spark send held when spark can't select its leaves Leaves Spark still can't select after its retries can follow a transfer the send committed, as the SDK selects them again after an operator error, so the send stays held under any key until Spark settles it or its invoice expires, as any other unknown outcome does. A short balance under a new key is refused, as on master. This replaces the refusal marker and the Paykit, QuickPay and swap handling of a refusal that may have reached Spark, as the hold already keeps the node off the invoice and the proof, allowance and charge pending. A leaf retry rechecks only the caller's side-effect-free check at submission. Verified: SparkRepoTest, LightningRepoTest, CacheStoreTest, BackupRepoTest --- .../main/java/to/bitkit/data/CacheStore.kt | 15 ------- .../java/to/bitkit/repositories/BackupRepo.kt | 1 - .../to/bitkit/repositories/LightningRepo.kt | 4 +- .../repositories/PaykitPaymentProofRepo.kt | 2 - .../to/bitkit/repositories/QuickPayRepo.kt | 19 ++------ .../java/to/bitkit/repositories/SparkRepo.kt | 44 +++++-------------- .../java/to/bitkit/services/SparkService.kt | 9 +--- .../java/to/bitkit/viewmodels/AppViewModel.kt | 21 +++------ .../java/to/bitkit/data/CacheStoreTest.kt | 11 ----- .../to/bitkit/repositories/BackupRepoTest.kt | 2 - .../PaykitPaymentProofRepoTest.kt | 12 ----- .../bitkit/repositories/QuickPayRepoTest.kt | 7 --- .../to/bitkit/repositories/SparkRepoTest.kt | 33 +++++--------- 13 files changed, 36 insertions(+), 144 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index edd9b3270c..6fe9a1aded 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -166,15 +166,6 @@ class CacheStore internal constructor( } } - /** Drops the refusals whose invoice expired by [refusedAt], which the node can no longer pay. */ - suspend fun addSparkRefusedSend(paymentHash: String, refusedAt: Long, expiresAt: Long) { - val hash = paymentHash.lowercase() - store.updateData { - val unexpired = it.sparkRefusedSends.filterValues { send -> send.expiresAt > refusedAt } - it.copy(sparkRefusedSends = unexpired + (hash to SparkRefusedSend(refusedAt, expiresAt))) - } - } - suspend fun removeSparkSendHash(paymentHash: String) { val hash = paymentHash.lowercase() if (hash !in store.data.first().sparkSendHashes) return @@ -445,8 +436,6 @@ data class AppCacheData( val sparkSendAttemptIds: Map = mapOf(), /** The latest attempt at each invoice Spark sent, by hash, whose number picks the attempt's idempotency key. */ val sparkSendAttempts: Map = mapOf(), - /** Spark sends refused after they may have reached the operators: the node stays off each until it expires. */ - val sparkRefusedSends: Map = mapOf(), /** * Payment ids of Spark send attempts whose own failure a failed Activity write still has to save over an earlier * attempt's row, kept across a restart until it saves. @@ -501,10 +490,6 @@ data class AppCacheData( @Serializable data class SparkSendAttempt(val attempt: Int, val expiresAt: Long) -/** When a Spark send was refused and when its invoice expires, in epoch seconds. */ -@Serializable -data class SparkRefusedSend(val refusedAt: Long, val expiresAt: Long) - @Serializable data class CachedUsdtBalance( val address: String, diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 7af42af66b..d65a80d3ec 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1741,7 +1741,6 @@ internal fun AppCacheData.withoutPaymentDetails() = copy( sparkUncertainSends = emptyMap(), sparkSendAttemptIds = emptyMap(), sparkSendAttempts = emptyMap(), - sparkRefusedSends = emptyMap(), sparkUnsavedOwnFailures = emptySet(), moveToSparkHashes = emptyList(), ldkSendHashes = emptyList(), diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 29c0e213fd..fccd22e2d6 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1633,8 +1633,8 @@ class LightningRepo @Inject constructor( var isChecked = false val authorizeSend: suspend () -> Boolean = authorize@{ // Spark's retry of a send whose leaves it couldn't select keeps the send's admission and rechecks only - // that the payment is still allowed. - if (isChecked) return@authorize isAuthorizedAtSubmission?.invoke() ?: onBeforeSend() + // the caller's check at submission, which has no side effects. + if (isChecked) return@authorize isAuthorizedAtSubmission?.invoke() ?: true isChecked = true val isAuthorized = onBeforeSend().also { if (it) requireWalletRestoreComplete() } if (isAuthorized) { diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index a08d766db2..b8fe69b490 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -938,8 +938,6 @@ class PaykitPaymentProofRepo @Inject constructor( val error = generateSequence(submissionError) { it.cause } .firstOrNull { it is ServiceError.PaymentDeadlineExpired || it is SparkError.SendRefused } ?: submissionError.asNodeException() ?: submissionError - // A refused Spark send that may have committed a transfer can still settle, so its proof is kept. - if (error is SparkError.SendRefused && error.mayHaveReachedSpark) return false when (error) { is SparkError.SendRefused, is NodeNotRunningError, diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index 22bd6bba12..e6ff629b86 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -577,11 +577,6 @@ class QuickPayRepo @Inject constructor( emitOutcomeLocked(invoiceHash, error, paymentRequest) } } - // Shown as failed, as nothing would resolve a pending screen if no transfer went out; the charge stays, as - // a transfer Spark may have committed can still settle. - QuickPayDispatchClass.REFUSED_AFTER_SPARK_SEND -> mutex.withLock { - emitOutcomeLocked(invoiceHash, error, paymentRequest) - } QuickPayDispatchClass.DUPLICATE_PAYMENT, QuickPayDispatchClass.AMBIGUOUS, -> { @@ -1086,14 +1081,9 @@ internal data class SpendSnapshot( ) internal fun classifyDispatchError(error: Throwable): QuickPayDispatchClass { - // Spark refuses before anything leaves the wallet, as PaykitPaymentProofRepo reads it, unless the refusal may - // follow a transfer Spark committed. - generateSequence(error) { it.cause }.filterIsInstance().firstOrNull()?.let { - return if (it.mayHaveReachedSpark) { - QuickPayDispatchClass.REFUSED_AFTER_SPARK_SEND - } else { - QuickPayDispatchClass.PRE_DISPATCH_REJECTION - } + // Spark refuses only before anything leaves the wallet, as PaykitPaymentProofRepo reads it. + if (generateSequence(error) { it.cause }.any { it is SparkError.SendRefused }) { + return QuickPayDispatchClass.PRE_DISPATCH_REJECTION } return when (error.asNodeException()) { is NodeException.InvalidInvoice, @@ -1109,9 +1099,6 @@ internal fun classifyDispatchError(error: Throwable): QuickPayDispatchClass { enum class QuickPayDispatchClass { PRE_DISPATCH_REJECTION, - - /** Refused after a transfer Spark may have committed, which can still settle until its invoice expires. */ - REFUSED_AFTER_SPARK_SEND, DUPLICATE_PAYMENT, AMBIGUOUS, } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 812bea4fca..1267889ad7 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -668,29 +668,18 @@ class SparkRepo @Inject constructor( forgetUnusedAttempt() throw SparkError.InvoiceExpired(it) } - // Spark selects the leaves to spend before anything goes to the operators, so a short balance or - // leaves it can't select left nothing, for instance when an earlier send spent the balance after - // it was read. Under a key an earlier attempt used, it can hide the transfer that attempt - // committed, so that send stays held. - if ((it is SdkException.InsufficientFunds || it.isLeafSelectionFailure()) && !isReusedKey) { - // After an operator error the SDK can select leaves again, so this error can still follow a - // committed transfer: the node stays off the invoice until it expires. Kept - // before the holds go, so no stop in between frees the invoice. - cacheStore.addSparkRefusedSend( - paymentHash, - refusedAt = clock.now().epochSeconds, - expiresAt = expiresAt.toEpochSeconds(), - ) + // Spark selects the leaves to spend before anything goes to the operators, so a short balance left + // nothing, for instance when an earlier send spent it after the balance was read. Under a key an + // earlier attempt used, it can hide the transfer that attempt committed, so that send stays held. + if (it is SdkException.InsufficientFunds && !isReusedKey) { cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) forgetUnusedAttempt() - val reason = if (it.isLeafSelectionFailure()) { - "Spark could not select leaves for the payment" - } else { - "Spark balance can't cover the payment" - } - throw SparkError.SendRefused(reason, it, mayHaveReachedSpark = true) + throw SparkError.SendRefused("Spark balance can't cover the payment", it) } + // Leaves Spark still can't select after its retries can follow a transfer it committed, as the SDK + // selects them again after an operator error, so that send stays held until Spark settles it or its + // invoice expires, as any other unknown outcome does. Logger.warn("Failed to learn the outcome of Spark send '$paymentHash'", it, context = TAG) settleUncertainSend(paymentHash, expiresAt, attemptId) throw PaymentPendingException(paymentHash) @@ -1846,17 +1835,6 @@ class SparkRepo @Inject constructor( send.value.equals(bolt11, ignoreCase = true) || send.key == paymentHash?.lowercase() } sendsInFlight.entries.firstOrNull(isOfInvoice)?.let { return@withContext EarlierSend.Pending(it.key) } - // A Spark send refused after it may have reached the operators keeps the node off the invoice until it - // expires: a transfer it committed can stay unlisted after a sync and still go out, as an unknown send's - // can. Unless an earlier send reads pending or paid, the node send is refused, not held pending, as no - // event would resolve a pending screen. - val refusal = cacheStore.data.first().sparkRefusedSends[paymentHash?.lowercase()] - val noEarlierSend = { - if (refusal != null && refusal.expiresAt > clock.now().epochSeconds) { - throw SparkError.SendRefused("Spark may still send this invoice", mayHaveReachedSpark = true) - } - null - } // A retry started, or recorded, while the listing below is read may still be pending, as may a send whose // outcome Spark didn't report until a sync settles it. val retried = { @@ -1877,7 +1855,7 @@ class SparkRepo @Inject constructor( if (payments == null) { startedSend(paymentHash)?.let { return@withContext EarlierSend.Pending(it) } refuseUnverifiedRestoredInvoice(bolt11, invoiceCreatedAt, invoiceExpiresAt) - return@withContext noEarlierSend() + return@withContext null } seedSendHashes(payments) val send = payments @@ -1889,7 +1867,7 @@ class SparkRepo @Inject constructor( (retried() ?: paymentHash?.lowercase()?.takeIf { it in unlisted }) ?.let { return@withContext EarlierSend.Pending(it) } refuseUnverifiedRestoredInvoice(bolt11, invoiceCreatedAt, invoiceExpiresAt) - return@withContext noEarlierSend() + return@withContext null } if (send.status == PaymentStatus.FAILED) { retried()?.let { return@withContext EarlierSend.Pending(it) } @@ -1899,7 +1877,7 @@ class SparkRepo @Inject constructor( when (send.status) { PaymentStatus.PENDING -> EarlierSend.Pending(hash) PaymentStatus.COMPLETED -> EarlierSend.Paid(hash) - PaymentStatus.FAILED -> noEarlierSend() + PaymentStatus.FAILED -> null } } diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index cc131d2385..21564fa141 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -420,14 +420,9 @@ 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; 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, unless [mayHaveReachedSpark]: Spark - * refused it after a transfer it may have committed, which can still go out until the invoice expires. + * sends yet. A Paykit request or allowance attempt can then end as failed. */ - open class SendRefused( - message: String, - cause: Throwable? = null, - val mayHaveReachedSpark: Boolean = false, - ) : SparkError(message, cause) + open class SendRefused(message: String, cause: Throwable? = null) : SparkError(message, cause) /** 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) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index be5dab8279..645ee70721 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -7761,9 +7761,8 @@ class AppViewModel @Inject constructor( swapIdsByHoldHash[holdPaymentHash] = payment.swapId // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending. lightningRepo.payInvoice(payment.invoice).onFailure { - // Spark may have sent it, so an unknown outcome, or a refusal after a transfer Spark may have committed, - // waits on the claim like a sent hold payment. - if (it is PaymentPendingException || it.mayHaveReachedSpark()) return@onFailure + // Spark may have sent it, so an unknown outcome waits on the claim like a sent hold payment. + if (it is PaymentPendingException) return@onFailure holdFailure.cancel() swapIdsByHoldHash.remove(holdPaymentHash) pubkySwapsRouteRepo.dropFailedSwap(payment.swapId) @@ -8207,14 +8206,9 @@ class AppViewModel @Inject constructor( resolveSettledPendingSend(pendingHash) return@onFailure } - // A refused Spark send that may have committed a transfer can still settle, so it shows as failed but keeps - // its proof, private payment list and allowance attempt, which its event settles then. - val mayHaveSent = error.mayHaveReachedSpark() - if (!mayHaveSent) { - releasePrivatePaymentListIfNeeded(contactPaymentContext) - cancelPaymentProofPreparation(proofRequest) - } - finishManualAllowancePayment(allowanceAttemptId, succeeded = if (mayHaveSent) null else false) + releasePrivatePaymentListIfNeeded(contactPaymentContext) + cancelPaymentProofPreparation(proofRequest) + finishManualAllowancePayment(allowanceAttemptId, succeeded = false) createdMetadataPaymentId?.let { preActivityMetadataRepo.deletePreActivityMetadata(it) } lnurlComment?.let { activityRepo.clearPendingLightningMessage(paymentHash) } if (error is MoveToSparkError.UpdateFeeUnseen) { @@ -8345,7 +8339,7 @@ class AppViewModel @Inject constructor( updateFailed: Boolean, ): Boolean = when (error) { is PaymentPendingException -> false - else if !isPaymentRequest || error.mayHaveReachedSpark() -> true + else if !isPaymentRequest -> true // Any failed spending balance update happens before the invoice is paid, so nothing was sent. else if updateFailed || error is LightningPaymentFailedError -> { paykitPaymentProofRepo.failLightningPayment(paymentHash) @@ -11222,6 +11216,3 @@ internal fun allowanceOffersAcceptedDescription( else -> several.replace("{names}", formatNames(names)) } } - -/** A Spark send refused after a transfer it may have committed, which can still settle until its invoice expires. */ -private fun Throwable.mayHaveReachedSpark(): Boolean = (this as? SparkError.SendRefused)?.mayHaveReachedSpark == true diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index dff04054cf..619d6b0df5 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -47,17 +47,6 @@ class CacheStoreTest : BaseUnitTest() { assertFalse("hash" in sut.data.first().sparkSendAttempts) } - @Test - fun `a refused spark send drops expired ones and keeps the latest refusal`() = test { - sut.addSparkRefusedSend("OLD", refusedAt = 1_000, expiresAt = 1_500) - sut.addSparkRefusedSend("HASH", refusedAt = 2_000, expiresAt = 3_000) - - assertEquals(mapOf("hash" to SparkRefusedSend(2_000, 3_000)), sut.data.first().sparkRefusedSends) - - sut.addSparkRefusedSend("hash", refusedAt = 2_500, expiresAt = 3_000) - assertEquals(2_500, sut.data.first().sparkRefusedSends["hash"]?.refusedAt) - } - @Test fun `invalidateReceiveLightningInvoice preserves a replacement invoice`() = test { val replacement = AppCacheData( diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index d0a15a1142..54c7b00ab5 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -59,7 +59,6 @@ import to.bitkit.data.PrivatePaykitReservationData import to.bitkit.data.PrivatePaykitReservationStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore -import to.bitkit.data.SparkRefusedSend import to.bitkit.data.SparkSendAttempt import to.bitkit.data.WalletConnectionRecovery import to.bitkit.data.WatchOnlyAccountAllocationState @@ -3889,7 +3888,6 @@ class BackupRepoTest : BaseUnitTest() { sparkUncertainSends = mapOf(id to 1), sparkSendAttemptIds = mapOf(id to id), sparkSendAttempts = mapOf(id to SparkSendAttempt(0, 1)), - sparkRefusedSends = mapOf(id to SparkRefusedSend(1, 2)), sparkUnsavedOwnFailures = setOf(id), moveToSparkHashes = listOf(id), ldkSendHashes = listOf(id), diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index 023e508372..eaefc24e54 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -1501,18 +1501,6 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { } } - @Test - fun `a spark refusal that may follow a committed transfer keeps the proof`() = test { - val request = paymentRequest(MethodId.Bolt11.rawValue) - val repo = paymentProofRepo() - repo.prepare(request, MethodId.Bolt11.rawValue, "bitkit", PaykitPaymentProofKind.Lightning).getOrThrow() - repo.associateLightningPayment(request, PAYMENT_HASH, MethodId.Bolt11.rawValue, "bitkit").getOrThrow() - val refusal = SparkError.SendRefused("Spark could not select leaves", mayHaveReachedSpark = true) - - assertFalse(repo.failLightningPayment(PAYMENT_HASH, refusal)) - assertFalse(storedProofs.isEmpty()) - } - @Test fun `onchain proof uses selected endpoint and transaction id`() = test { val txid = "ab".repeat(32) diff --git a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt index 1d2c6a394c..af3c71bde8 100644 --- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt @@ -806,13 +806,6 @@ class QuickPayRepoTest : BaseUnitTest() { assertEquals(QuickPayDispatchClass.PRE_DISPATCH_REJECTION, classifyDispatchError(SparkError.InvoiceExpired())) } - @Test - fun `a spark refusal that may follow a committed transfer keeps its charge`() { - val refusal = SparkError.SendRefused("Spark could not select leaves", mayHaveReachedSpark = true) - - assertEquals(QuickPayDispatchClass.REFUSED_AFTER_SPARK_SEND, classifyDispatchError(AppError(refusal))) - } - @Test fun `classifies wrapped and unwrapped ldk errors`() { assertEquals( diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index b6fb57f217..95655d57b4 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4045,9 +4045,7 @@ class SparkRepoTest : BaseUnitTest() { assertTrue(inFlightAtClear.isNotEmpty() && inFlightAtClear.all { it }, "a sync could take back the hold") assertFalse(sut.isSendInFlight("hash")) - // The node stays off the invoice until it expires. - val nodeRefusal = runCatching { sut.earlierLightningSend("lnbc1", "hash") }.exceptionOrNull() - assertTrue(assertIs(nodeRefusal).mayHaveReachedSpark) + assertNull(sut.earlierLightningSend("lnbc1", "hash")) } @Test @@ -5262,7 +5260,7 @@ class SparkRepoTest : BaseUnitTest() { sut.start(0).getOrThrow() advanceUntilIdle() - assertIs(sut.payInvoice("lnbc1", 100uL, paymentDeadlineAt = deadline).exceptionOrNull()) + assertIs(sut.payInvoice("lnbc1", 100uL, paymentDeadlineAt = deadline).exceptionOrNull()) verify(sparkService, times(1)).send(any(), anyOrNull()) } @@ -5280,13 +5278,13 @@ class SparkRepoTest : BaseUnitTest() { val result = sut.payInvoice("lnbc1", 100uL, onBeforeSend = { ++checks == 1 }) - assertIs(result.exceptionOrNull()) + assertIs(result.exceptionOrNull()) verify(sparkService, times(1)).send(any(), anyOrNull()) assertEquals(2, checks) } @Test - fun `a spark send whose leaves spark can't select is refused under a new key`() = test { + fun `a spark send whose leaves spark can't select is held under a new key`() = test { whenever(sparkService.isConnected).thenReturn(true) val prepared = unexpiredPrepared() whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) @@ -5296,14 +5294,14 @@ class SparkRepoTest : BaseUnitTest() { sut.start(0).getOrThrow() advanceUntilIdle() - assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) verify(sparkService, times(4)).send(any(), anyOrNull()) - assertFalse("hash" in store.data.first().sparkUncertainSends) + assertTrue("hash" in store.data.first().sparkUncertainSends) } @Test - fun `a spark send refused after a leaf failure keeps the node off its invoice until it expires`() = test { + fun `a spark send held after a leaf failure keeps the node off its invoice after a sync`() = test { whenever(sparkService.isConnected).thenReturn(true) whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = null)) val prepared = unexpiredPrepared() @@ -5313,22 +5311,15 @@ class SparkRepoTest : BaseUnitTest() { val sut = createSut(store) sut.start(0).getOrThrow() - val refusal = assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) - assertTrue(refusal.mayHaveReachedSpark) - val nodeRefusal = runCatching { sut.earlierLightningSend("lnbc1280n1send", "hash") }.exceptionOrNull() - assertTrue(assertIs(nodeRefusal).mayHaveReachedSpark) + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) // The SDK may have selected leaves again after a committed transfer, which can stay unlisted after a sync. whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1u)) whenever(sparkService.listPayments()).thenReturn(emptyList()) sut.start(0).getOrThrow() advanceUntilIdle() - val laterRefusal = runCatching { sut.earlierLightningSend("lnbc1280n1send", "hash") }.exceptionOrNull() - assertIs(laterRefusal) - - // Once the invoice expired, no node send can pay it. - now += 2.hours - assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) } @Test @@ -5352,7 +5343,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) val prepared = unexpiredPrepared() whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw leafSelectionFailure() } + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.InsufficientFunds(null) } val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) val sut = createSut(store) sut.start(0).getOrThrow() @@ -5374,7 +5365,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) val firstFailed = sentPayment(fees = 0).copy(id = "hash-0", status = PaymentStatus.FAILED) whenever(sparkService.listPayments()).thenReturn(listOf(firstFailed)) - whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw leafSelectionFailure() } + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.InsufficientFunds(null) } val sut = createSut(store) sut.start(0).getOrThrow() advanceUntilIdle() From 67e123aa5b0a49936d2aab0542efa7d8f97f6240 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 16:46:42 +0100 Subject: [PATCH 16/23] fix: let a spark retry of a held send go out under its key A send held in doubt under this build's key is sent again under that key, which can't pay twice, instead of refused as pending, and its result settles the hold. Verified: SparkRepoTest, LightningRepoTest --- .../java/to/bitkit/repositories/SparkRepo.kt | 15 +++++- .../to/bitkit/repositories/SparkRepoTest.kt | 48 +++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 1267889ad7..1cf76bd46a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -581,8 +581,10 @@ class SparkRepo @Inject constructor( Logger.info("Skipped Spark send of '$paymentHash', already paid", context = TAG) return@runSuspendCatching paymentHash } + // A send held in doubt under this build's key is sent again under that key, which can't pay twice: + // the operators return the transfer it committed, if any. is SparkLightningSend.Found if earlier.status == PaymentStatus.PENDING -> - throw PaymentPendingException(paymentHash) + if (!isKeyedHold(paymentHash)) throw PaymentPendingException(paymentHash) // Spark's list, synced or unreadable, can lack a send it made before the restore, as on the node's // path, so the operators decide. Before Spark syncs, its list can lack an earlier attempt they show // failed, so that one is refused too. @@ -689,6 +691,8 @@ class SparkRepo @Inject constructor( if (payment.status == PaymentStatus.PENDING) { settleUncertainSend(paymentHash, expiresAt, attemptId) } else { + // A retry of a send held in doubt settles that hold with its own result. + uncertainSends.remove(paymentHash.lowercase()) bestEffort("end the hold of Spark send '$paymentHash'") { cacheStore.removeSparkUncertainSend(paymentHash) } @@ -1785,6 +1789,15 @@ class SparkRepo @Inject constructor( if (isHeld) SparkLightningSend.Found(PaymentStatus.PENDING, null) else send } + /** Whether [paymentHash] is pending only by a hold on a send under this build's key, which a retry can reuse. */ + private suspend fun isKeyedHold(paymentHash: String): Boolean { + val hash = paymentHash.lowercase() + if (sendsInFlight.containsKey(hash) || sendHold(hash) == null) return false + if (hash !in cacheStore.data.first().sparkSendAttempts) return false + val listed = listedLightningSend(paymentHash) + return listed !is SparkLightningSend.Found || listed.status != PaymentStatus.PENDING + } + /** The hold on the send of [hash] whose outcome Spark didn't report, null when none. */ private suspend fun sendHold(hash: String): SendHold? { uncertainSends[hash]?.let { return SendHold(it.attemptId) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 95655d57b4..dfbf1a79b9 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5394,6 +5394,54 @@ class SparkRepoTest : BaseUnitTest() { assertTrue("hash" in store.data.first().sparkUncertainSends) } + @Test + fun `a spark send held after a leaf failure reports its failure at its invoice's expiry`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenAnswer { info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) } + whenever(sparkService.listPayments()).thenReturn(emptyList()) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw leafSelectionFailure() } + val sut = createSut(CacheStore(InMemoryDataStore(AppCacheData()), clock)) + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + sut.start(0).getOrThrow() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + assertTrue(events.none { it is Event.PaymentFailed }, "a transfer the send committed can still go out") + + now += 2.hours + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals("hash", assertIs(events.single()).paymentHash) + } + + @Test + fun `a spark retry of a send held after a leaf failure pays under its key`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenAnswer { info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) } + whenever(sparkService.listPayments()).thenReturn(emptyList()) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + var sends = 0 + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { + if (++sends <= 4) throw leafSelectionFailure() + sentPayment(fees = 0).copy(id = it.getArgument(1)) + } + val sut = createSut(CacheStore(InMemoryDataStore(AppCacheData()), clock)) + sut.start(0).getOrThrow() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + + val keys = argumentCaptor().apply { verify(sparkService, times(5)).send(any(), capture()) }.allValues + assertEquals(List(5) { "hash-0" }, keys) + } + @Test fun `a held spark send spark never recorded reports its failure at expiry after a restart`() = test { val sentAt = now.epochSeconds From a14a004ef65ae055b3d940476cca4ec2c413ba66 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 17:01:13 +0100 Subject: [PATCH 17/23] fix: keep a spark send held when a leaf retry reads as unsent A short balance or an expiry on a leaf retry can follow a transfer the failed try committed, so the send ends with the leaf failure and stays held. An expiry under a reused key keeps the send held too. A failed result Spark returns is reported once, by the refusal, not also by an event. Verified: SparkRepoTest, LightningRepoTest, QuickPayRepoTest --- .../java/to/bitkit/repositories/SparkRepo.kt | 18 ++++++--- .../to/bitkit/repositories/SparkRepoTest.kt | 39 +++++++++++++++---- 2 files changed, 44 insertions(+), 13 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 1cf76bd46a..ee03d82a9a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -664,7 +664,9 @@ class SparkRepo @Inject constructor( } val payment = sent.getOrElse { // The SDK checks the expiry again before anything goes out, so an expired invoice left nothing. - if (it.isInvoiceExpired()) { + // Under a key an earlier attempt used, that attempt may have committed a transfer before the + // expiry, so the send stays held. + if (it.isInvoiceExpired() && !isReusedKey) { cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) forgetUnusedAttempt() @@ -704,10 +706,9 @@ class SparkRepo @Inject constructor( cacheStore.removeSparkSendHash(paymentHash) } recordActivity(payment, isOwnAttempt = true) - // The caller subscribes to events only once this returns, so the result reports the failure too. A - // retry under a key whose failure was already reported, as when Spark's list couldn't be read to - // move past it, gets that failure back and no event. - if (reportedSendIds.add(payment.id)) payment.toNodeEvent()?.let { _nodeEvents.emit(it) } + // The caller subscribes to events only once this returns, so the result reports the failure, once: + // marked reported, Spark's event for it is not reported again, as a second error would be. + reportedSendIds.add(payment.id) throw SparkError.SendRefused("Spark send failed") } Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) @@ -745,7 +746,12 @@ class SparkRepo @Inject constructor( delay(LEAF_SELECTION_RETRY_DELAY) // A cancel, block or identity change can land during the delay, so each resend is checked again. if (!canRetry() || !onBeforeSend()) return result - result = runSuspendCatching { sparkService.send(prepared, attemptId) } + val retried = runSuspendCatching { sparkService.send(prepared, attemptId) } + // A failed try can have committed a transfer before Spark selected leaves again, so a short balance or an + // expiry on a retry, which would read as nothing sent, ends with the earlier leaf failure instead. + val error = retried.exceptionOrNull() + if (error is SdkException.InsufficientFunds || error?.isInvoiceExpired() == true) return result + result = retried } return result } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index dfbf1a79b9..f7aafd76ae 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4970,7 +4970,7 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `a spark send its call returns as failed reports its failure`() = test { + fun `a spark send its call returns as failed reports its failure once by its result`() = test { whenever(sparkService.isConnected).thenReturn(true) val prepared = unexpiredPrepared() whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) @@ -4987,10 +4987,11 @@ class SparkRepoTest : BaseUnitTest() { backgroundScope.launch { sut.nodeEvents.collect { events += it } } runCurrent() - sut.payInvoice("lnbc1", 100uL) + val result = sut.payInvoice("lnbc1", 100uL) advanceUntilIdle() - assertEquals(1, events.count { it is Event.PaymentFailed }, "quickpay never learned the send failed") + assertIs(result.exceptionOrNull()) + assertTrue(events.none { it is Event.PaymentFailed }, "the failure was reported twice") verify(activityRepo).upsertActivity( argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } ) @@ -5260,7 +5261,9 @@ class SparkRepoTest : BaseUnitTest() { sut.start(0).getOrThrow() advanceUntilIdle() - assertIs(sut.payInvoice("lnbc1", 100uL, paymentDeadlineAt = deadline).exceptionOrNull()) + val result = sut.payInvoice("lnbc1", 100uL, paymentDeadlineAt = deadline) + + assertIs(result.exceptionOrNull()) verify(sparkService, times(1)).send(any(), anyOrNull()) } @@ -5394,6 +5397,27 @@ class SparkRepoTest : BaseUnitTest() { assertTrue("hash" in store.data.first().sparkUncertainSends) } + @Test + fun `a short balance on a leaf retry keeps a new key's send held`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + var sends = 0 + // The first try may have committed a transfer that spent the leaves the retry then lacks. + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { + if (++sends == 1) throw leafSelectionFailure() + throw SdkException.InsufficientFunds(null) + } + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + assertTrue("hash" in store.data.first().sparkUncertainSends) + } + @Test fun `a spark send held after a leaf failure reports its failure at its invoice's expiry`() = test { whenever(sparkService.isSupported).thenReturn(true) @@ -5719,7 +5743,7 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `a spark send that returns failed reports it when keeping its unsaved failure fails too`() = test { + fun `a spark send that returns failed is refused when keeping its unsaved failure fails too`() = test { whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) @@ -5735,10 +5759,11 @@ class SparkRepoTest : BaseUnitTest() { backgroundScope.launch { sut.nodeEvents.collect { events += it } } sut.start(0).getOrThrow() - sut.payInvoice("lnbc1", 100uL) + val result = sut.payInvoice("lnbc1", 100uL) advanceUntilIdle() - assertEquals("hash", assertIs(events.single()).paymentHash) + assertIs(result.exceptionOrNull()) + assertTrue(events.none { it is Event.PaymentFailed }) } @Test From e22f2e7649479ec81d3e045197f0fad013370755 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 17:40:12 +0100 Subject: [PATCH 18/23] fix: keep a held spark send's hold when its retry never goes out A same-key retry of a held send that its deadline or an exit stops before it sends keeps the earlier attempt's hold, which may have committed a transfer. A new key's refusal also ends a hold an earlier, failed attempt left in memory, and a keyed retry reads Spark's local list for the send's outcome. Verified: SparkRepoTest passes. --- .../java/to/bitkit/repositories/SparkRepo.kt | 35 ++++++++++--------- .../to/bitkit/repositories/SparkRepoTest.kt | 30 ++++++++++++++++ 2 files changed, 49 insertions(+), 16 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index ee03d82a9a..d29cfa3fbf 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -598,7 +598,10 @@ class SparkRepo @Inject constructor( // Spark's local list picks the attempt's key and, before Spark's first sync, shows the invoice's earlier // sends, as the synced list did above. val local = runSuspendCatching { listPayments() }.getOrNull() - if (earlier == SparkLightningSend.Unavailable) { + // Past the checks above, a pending send is a held one this build's key retries, whose outcome Spark's local + // list may already show. + val isKeyedRetry = earlier is SparkLightningSend.Found && earlier.status == PaymentStatus.PENDING + if (earlier == SparkLightningSend.Unavailable || isKeyedRetry) { when (local?.latestSend(paymentHash)?.status) { PaymentStatus.COMPLETED -> { Logger.info("Skipped Spark send of '$paymentHash', already paid", context = TAG) @@ -609,7 +612,7 @@ class SparkRepo @Inject constructor( } // A retry reuses its attempt's key, so Spark never pays an invoice twice under it, but an older // build sent under a random key, which a list that can't be read may hide. - if (local == null && hasUnkeyedSend(paymentHash)) { + if (!isKeyedRetry && local == null && hasUnkeyedSend(paymentHash)) { throw SparkError.SendRefused("Spark could not list its payments to check the invoice") } } @@ -630,10 +633,16 @@ class SparkRepo @Inject constructor( }.getOrElse { throw SparkError.SendRefused("Spark is not connected", it) } val previousAttempt = cacheStore.data.first().sparkSendAttempts[paymentHash.lowercase()] val isReusedKey = previousAttempt?.attempt == attempt + val wasHeld = uncertainSends.containsKey(paymentHash.lowercase()) - // A refused send is taken as not having used its key, so a retry refuses the same way; a retry - // under the same key can't pay twice either way. - suspend fun forgetUnusedAttempt() { + // A send refused before anything went out is taken as not having used its key, so a retry refuses the + // same way. The hold of an earlier attempt under the same key stays, as it may have committed a + // transfer. Under a new key every earlier attempt failed, so a hold one of them left ends too. + suspend fun dropUnsentSend() { + if (isReusedKey && wasHeld) return + uncertainSends.remove(paymentHash.lowercase()) + cacheStore.removeSparkUncertainSend(paymentHash) + cacheStore.removeSparkSendHash(paymentHash) if (!isReusedKey) cacheStore.restoreSparkSendAttempt(paymentHash, previousAttempt) } val sent = run { @@ -654,9 +663,7 @@ class SparkRepo @Inject constructor( ensurePaymentDeadline(paymentDeadlineAt) ensureNotExiting() }.onFailure { - cacheStore.removeSparkUncertainSend(paymentHash) - cacheStore.removeSparkSendHash(paymentHash) - forgetUnusedAttempt() + dropUnsentSend() throw it } sendRetryingLeafSelection(prepared, attemptId, paymentDeadlineAt, onBeforeSend) @@ -667,18 +674,14 @@ class SparkRepo @Inject constructor( // Under a key an earlier attempt used, that attempt may have committed a transfer before the // expiry, so the send stays held. if (it.isInvoiceExpired() && !isReusedKey) { - cacheStore.removeSparkUncertainSend(paymentHash) - cacheStore.removeSparkSendHash(paymentHash) - forgetUnusedAttempt() + dropUnsentSend() throw SparkError.InvoiceExpired(it) } // Spark selects the leaves to spend before anything goes to the operators, so a short balance left // nothing, for instance when an earlier send spent it after the balance was read. Under a key an // earlier attempt used, it can hide the transfer that attempt committed, so that send stays held. if (it is SdkException.InsufficientFunds && !isReusedKey) { - cacheStore.removeSparkUncertainSend(paymentHash) - cacheStore.removeSparkSendHash(paymentHash) - forgetUnusedAttempt() + dropUnsentSend() throw SparkError.SendRefused("Spark balance can't cover the payment", it) } // Leaves Spark still can't select after its retries can follow a transfer it committed, as the SDK @@ -2775,8 +2778,8 @@ internal fun Throwable.isWithdrawalFeeRise(): Boolean = /** * Spark fails a send with this error when it holds the balance but can't select leaves to spend, for instance right - * after a move to Spark lands, before anything reaches the operators (`select_leaves_with_retry` in the 0.28.3 SDK's - * `spark-wallet/src/wallet.rs`). + * after a move to Spark lands (`select_leaves_with_retry` in the 0.28.3 SDK's `spark-wallet/src/wallet.rs`). The SDK + * selects leaves again after an operator error, so the error can follow a transfer the send committed. */ internal fun Throwable.isLeafSelectionFailure(): Boolean = this is SdkException.SparkException && v1.contains("Failed to select leaves after all retries", ignoreCase = true) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index f7aafd76ae..37aacf133b 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5466,6 +5466,36 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(List(5) { "hash-0" }, keys) } + @Test + fun `a spark retry of a held send stopped by its deadline keeps the send held`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenAnswer { info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) } + whenever(sparkService.listPayments()).thenReturn(emptyList()) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { throw leafSelectionFailure() } + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) + sut.start(0).getOrThrow() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + val retry = sut.payInvoice( + "lnbc1", + 100uL, + paymentDeadlineAt = now + 1.minutes, + onBeforeSend = { + // The deadline passes while the retry is checked, so it never goes out. + now += 2.minutes + true + }, + ) + + assertIs(retry.exceptionOrNull()) + assertTrue("hash" in store.data.first().sparkUncertainSends) + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + } + @Test fun `a held spark send spark never recorded reports its failure at expiry after a restart`() = test { val sentAt = now.epochSeconds From b09e44bace1802100735828b800a32b5def494d8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 17:53:11 +0100 Subject: [PATCH 19/23] fix: keep a saved spark hold through a retry that never goes out A same-key retry stopped before it sends keeps the earlier hold also when it is saved only on disk, as before Spark's first sync after a restart. A send held under a key whose earlier result was already reported reports its own outcome again, so its caller's Pending resolves. Verified: SparkRepoTest passes. --- .../java/to/bitkit/repositories/SparkRepo.kt | 4 +- .../to/bitkit/repositories/SparkRepoTest.kt | 39 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index d29cfa3fbf..346e544863 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -633,7 +633,7 @@ class SparkRepo @Inject constructor( }.getOrElse { throw SparkError.SendRefused("Spark is not connected", it) } val previousAttempt = cacheStore.data.first().sparkSendAttempts[paymentHash.lowercase()] val isReusedKey = previousAttempt?.attempt == attempt - val wasHeld = uncertainSends.containsKey(paymentHash.lowercase()) + val wasHeld = sendHold(paymentHash.lowercase()) != null // A send refused before anything went out is taken as not having used its key, so a retry refuses the // same way. The hold of an earlier attempt under the same key stays, as it may have committed a @@ -785,6 +785,8 @@ class SparkRepo @Inject constructor( .onFailure { Logger.warn("Failed to read the hold of Spark send '$paymentHash'", it, context = TAG) } .getOrNull() ?: failedAt uncertainSends[paymentHash.lowercase()] = UncertainSend(attemptId, failedAt.toULong(), expiresAt) + // Its caller now waits on the hold, so its outcome is reported, also when an earlier send under the key was. + reportedSendIds.remove(attemptId) // Held in memory meanwhile, and the hash kept before the send still holds the invoice after a restart. bestEffort("keep the hold of Spark send '$paymentHash'") { cacheStore.addSparkUncertainSend(paymentHash, startedAt, attemptId) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 37aacf133b..6fc1497d8a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5496,6 +5496,45 @@ class SparkRepoTest : BaseUnitTest() { assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) } + @Test + fun `a spark retry stopped by its deadline keeps a hold only saved before a restart`() = test { + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to now.epochSeconds + 3_600), + sparkUncertainSends = mapOf("hash" to now.epochSeconds), + sparkSendAttemptIds = mapOf("hash" to "hash-0"), + sparkSendAttempts = mapOf("hash" to SparkSendAttempt(0, now.epochSeconds + 3_600)), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenAnswer { info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) } + whenever(sparkService.listPayments()).thenReturn(emptyList()) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val sut = createSut(store) + sut.start(0).getOrThrow() + + val retry = sut.payInvoice( + "lnbc1", + 100uL, + paymentDeadlineAt = now + 1.minutes, + onBeforeSend = { + now += 2.minutes + true + }, + ) + + assertIs(retry.exceptionOrNull()) + verify(sparkService, never()).send(any(), anyOrNull()) + assertTrue("hash" in store.data.first().sparkUncertainSends) + assertTrue("hash" in store.data.first().sparkSendHashes) + } + @Test fun `a held spark send spark never recorded reports its failure at expiry after a restart`() = test { val sentAt = now.epochSeconds From 22a8c49200477205d6298ea928062c01fd010129 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 18:05:53 +0100 Subject: [PATCH 20/23] fix: settle a held spark send before a new key's retry A retry of a held send whose attempt Spark lists failed stays pending until the next listing settles the hold, so the send after it goes through the restore checks a new key needs. A hold is never settled under a retry in flight under its key, and a held send whose retry fails at once reports the failure to the callers waiting on it. Verified: SparkRepoTest passes. --- .../java/to/bitkit/repositories/SparkRepo.kt | 7 +++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 20 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 346e544863..2fe034a320 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -634,6 +634,9 @@ class SparkRepo @Inject constructor( val previousAttempt = cacheStore.data.first().sparkSendAttempts[paymentHash.lowercase()] val isReusedKey = previousAttempt?.attempt == attempt val wasHeld = sendHold(paymentHash.lowercase()) != null + // A held send whose attempt Spark lists failed is settled by the next listing, and a send after that + // goes through the restore checks above, as a new key's send must. + if (isKeyedRetry && !isReusedKey) throw PaymentPendingException(paymentHash) // A send refused before anything went out is taken as not having used its key, so a retry refuses the // same way. The hold of an earlier attempt under the same key stays, as it may have committed a @@ -712,6 +715,8 @@ class SparkRepo @Inject constructor( // The caller subscribes to events only once this returns, so the result reports the failure, once: // marked reported, Spark's event for it is not reported again, as a second error would be. reportedSendIds.add(payment.id) + // An earlier caller waiting on the held send learns its failure from the event. + if (wasHeld) payment.toNodeEvent()?.let { _nodeEvents.emit(it) } throw SparkError.SendRefused("Spark send failed") } Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) @@ -917,6 +922,8 @@ class SparkRepo @Inject constructor( // invoice again clears its marker under the same lock, so it either sees the hold and gets its report, or // finds it settled. return holdRestoreMutex.withLock { + // A retry in flight under the send's key settles the hold with its own outcome. + if (sendsInFlight.containsKey(key)) return@withLock null if (!uncertainSends.remove(key, uncertain)) return@withLock null bestEffort("end the hold of Spark send '$paymentHash'") { cacheStore.removeSparkUncertainSend(paymentHash) } if (isFailed && !sendsInFlight.containsKey(key)) { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 6fc1497d8a..0dee68714f 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5535,6 +5535,26 @@ class SparkRepoTest : BaseUnitTest() { assertTrue("hash" in store.data.first().sparkSendHashes) } + @Test + fun `a spark retry of a held send spark lists failed never takes a new key before the hold settles`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenAnswer { info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) } + whenever(sparkService.listPayments()).thenReturn(emptyList()) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { throw leafSelectionFailure() } + val sut = createSut(CacheStore(InMemoryDataStore(AppCacheData()), clock)) + sut.start(0).getOrThrow() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + val failed = sentPayment(fees = 0).copy(id = "hash-0", status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + verify(sparkService, never()).send(any(), eq("hash-1")) + } + @Test fun `a held spark send spark never recorded reports its failure at expiry after a restart`() = test { val sentAt = now.epochSeconds From d42fac2095c627d590bac3d9bd7dece09bddd7bd Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 18:25:55 +0100 Subject: [PATCH 21/23] fix: report a held spark send's result to its waiters A retry of a held send whose call returns it paid or failed reports that result as the send's event, as Spark may not report a transfer it returned for the key again, so callers still waiting on the held send resolve. A hold left to a retry in flight stays polled. Verified: SparkRepoTest and detekt pass. --- .../java/to/bitkit/repositories/SparkRepo.kt | 89 +++++++++++-------- .../to/bitkit/repositories/SparkRepoTest.kt | 5 ++ 2 files changed, 59 insertions(+), 35 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 2fe034a320..50bbfd2a6d 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -601,20 +601,10 @@ class SparkRepo @Inject constructor( // Past the checks above, a pending send is a held one this build's key retries, whose outcome Spark's local // list may already show. val isKeyedRetry = earlier is SparkLightningSend.Found && earlier.status == PaymentStatus.PENDING - if (earlier == SparkLightningSend.Unavailable || isKeyedRetry) { - when (local?.latestSend(paymentHash)?.status) { - PaymentStatus.COMPLETED -> { - Logger.info("Skipped Spark send of '$paymentHash', already paid", context = TAG) - return@runSuspendCatching paymentHash - } - PaymentStatus.PENDING -> throw PaymentPendingException(paymentHash) - else -> Unit - } - // A retry reuses its attempt's key, so Spark never pays an invoice twice under it, but an older - // build sent under a random key, which a list that can't be read may hide. - if (!isKeyedRetry && local == null && hasUnkeyedSend(paymentHash)) { - throw SparkError.SendRefused("Spark could not list its payments to check the invoice") - } + val readsLocally = earlier == SparkLightningSend.Unavailable || isKeyedRetry + if (readsLocally && isPaidLocally(paymentHash, local, isKeyedRetry)) { + Logger.info("Skipped Spark send of '$paymentHash', already paid", context = TAG) + return@runSuspendCatching paymentHash } // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. if (!onBeforeSend()) throw PaymentAbortedBeforeSend() @@ -699,25 +689,7 @@ class SparkRepo @Inject constructor( if (payment.status == PaymentStatus.PENDING) { settleUncertainSend(paymentHash, expiresAt, attemptId) } else { - // A retry of a send held in doubt settles that hold with its own result. - uncertainSends.remove(paymentHash.lowercase()) - bestEffort("end the hold of Spark send '$paymentHash'") { - cacheStore.removeSparkUncertainSend(paymentHash) - } - } - // Spark's failure event during its send call was left to this result, so the result reports it. - if (payment.status == PaymentStatus.FAILED) { - // This attempt paid nothing, as when its outcome settles, so a retry isn't held as pending. - bestEffort("drop the hash of Spark send '$paymentHash'") { - cacheStore.removeSparkSendHash(paymentHash) - } - recordActivity(payment, isOwnAttempt = true) - // The caller subscribes to events only once this returns, so the result reports the failure, once: - // marked reported, Spark's event for it is not reported again, as a second error would be. - reportedSendIds.add(payment.id) - // An earlier caller waiting on the held send learns its failure from the event. - if (wasHeld) payment.toNodeEvent()?.let { _nodeEvents.emit(it) } - throw SparkError.SendRefused("Spark send failed") + settleSentResult(paymentHash, payment, wasHeld) } Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) paymentHash @@ -735,6 +707,52 @@ class SparkRepo @Inject constructor( } } + /** + * Whether Spark's [local] list shows the send of [paymentHash] paid; throws while it shows the send pending, or, + * unless it is a [isKeyedRetry], while the list can't be read and an older build sent the invoice. + */ + private suspend fun isPaidLocally(paymentHash: String, local: List?, isKeyedRetry: Boolean): Boolean { + when (local?.latestSend(paymentHash)?.status) { + PaymentStatus.COMPLETED -> return true + PaymentStatus.PENDING -> throw PaymentPendingException(paymentHash) + else -> Unit + } + // A retry reuses its attempt's key, so Spark never pays an invoice twice under it, but an older build sent + // under a random key, which a list that can't be read may hide. + if (!isKeyedRetry && local == null && hasUnkeyedSend(paymentHash)) { + throw SparkError.SendRefused("Spark could not list its payments to check the invoice") + } + return false + } + + /** + * Ends the hold of a send whose call returned its settled [payment]: a retry of a send held in doubt settles that + * hold with its own result, which callers waiting on the held send learn from its event, as Spark may not report a + * transfer it returned for the key again. A failed one is refused. + */ + private suspend fun settleSentResult(paymentHash: String, payment: Payment, wasHeld: Boolean) { + uncertainSends.remove(paymentHash.lowercase()) + bestEffort("end the hold of Spark send '$paymentHash'") { + cacheStore.removeSparkUncertainSend(paymentHash) + } + if (wasHeld && reportedSendIds.add(payment.id)) { + recordActivity(payment, isOwnAttempt = true) + payment.toNodeEvent()?.let { _nodeEvents.emit(it) } + } + // Spark's failure event during its send call was left to this result, so the result reports it. + if (payment.status == PaymentStatus.FAILED) { + // This attempt paid nothing, as when its outcome settles, so a retry isn't held as pending. + bestEffort("drop the hash of Spark send '$paymentHash'") { + cacheStore.removeSparkSendHash(paymentHash) + } + if (!wasHeld) recordActivity(payment, isOwnAttempt = true) + // The caller subscribes to events only once this returns, so the result reports the failure, once: + // marked reported, Spark's event for it is not reported again, as a second error would be. + reportedSendIds.add(payment.id) + throw SparkError.SendRefused("Spark send failed") + } + } + private suspend fun sendRetryingLeafSelection( prepared: PrepareSendPaymentResponse, attemptId: String, @@ -848,7 +866,8 @@ class SparkRepo @Inject constructor( if (!isSettled) return false // A send Spark settled while the app was closed updates its row only, as nobody waits for it now. Its marker // stays until its payment is claimed, so Spark's event for it meanwhile claims it too. - val isReported = takeUncertainSend(paymentHash, uncertain, send) ?: return true + // A hold left to a retry in flight under its key stays polled, as the retry may leave it held. + val isReported = takeUncertainSend(paymentHash, uncertain, send) ?: return !sendsInFlight.containsKey(key) when (send) { // A send Spark never recorded settles only at its expiry, so it is reported, as a caller may wait for it. SparkLightningSend.NotFound -> { @@ -926,7 +945,7 @@ class SparkRepo @Inject constructor( if (sendsInFlight.containsKey(key)) return@withLock null if (!uncertainSends.remove(key, uncertain)) return@withLock null bestEffort("end the hold of Spark send '$paymentHash'") { cacheStore.removeSparkUncertainSend(paymentHash) } - if (isFailed && !sendsInFlight.containsKey(key)) { + if (isFailed) { bestEffort("drop the hash of Spark send '$paymentHash'") { cacheStore.removeSparkSendHash(paymentHash) } } key !in restoredAtStart diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 0dee68714f..502bdedfd5 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5457,13 +5457,18 @@ class SparkRepoTest : BaseUnitTest() { sentPayment(fees = 0).copy(id = it.getArgument(1)) } val sut = createSut(CacheStore(InMemoryDataStore(AppCacheData()), clock)) + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } sut.start(0).getOrThrow() assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + runCurrent() val keys = argumentCaptor().apply { verify(sparkService, times(5)).send(any(), capture()) }.allValues assertEquals(List(5) { "hash-0" }, keys) + // A caller still waiting on the held send learns it paid. + assertEquals(1, events.count { it is Event.PaymentSuccessful }) } @Test From 9468eda61dc969a5936782391cca26f3d5c2afcd Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 18:41:17 +0100 Subject: [PATCH 22/23] fix: keep polling a spark hold a retry left in place Verified: none (one-line poll condition; the gate runs next) --- app/src/main/java/to/bitkit/repositories/SparkRepo.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 50bbfd2a6d..e4bd8f53b8 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -867,7 +867,7 @@ class SparkRepo @Inject constructor( // A send Spark settled while the app was closed updates its row only, as nobody waits for it now. Its marker // stays until its payment is claimed, so Spark's event for it meanwhile claims it too. // A hold left to a retry in flight under its key stays polled, as the retry may leave it held. - val isReported = takeUncertainSend(paymentHash, uncertain, send) ?: return !sendsInFlight.containsKey(key) + val isReported = takeUncertainSend(paymentHash, uncertain, send) ?: return uncertainSends[key] !== uncertain when (send) { // A send Spark never recorded settles only at its expiry, so it is reported, as a caller may wait for it. SparkLightningSend.NotFound -> { From 868ab1902e62bc76a283b72a6a6cd220ea7c59cb Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 20:07:47 +0100 Subject: [PATCH 23/23] fix: poll a spark hold once when a retry holds it again Each poll of a held send stops once a later hold replaces it, so keyed retries that end held keep one Spark sync per interval. Verified: SparkRepoTest and detekt pass. --- .../java/to/bitkit/repositories/SparkRepo.kt | 10 +++++---- .../to/bitkit/repositories/SparkRepoTest.kt | 21 +++++++++++++++++++ 2 files changed, 27 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 e4bd8f53b8..5e2cb5ba80 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -807,7 +807,8 @@ class SparkRepo @Inject constructor( val startedAt = runSuspendCatching { cacheStore.data.first().sparkUncertainSends[paymentHash.lowercase()] } .onFailure { Logger.warn("Failed to read the hold of Spark send '$paymentHash'", it, context = TAG) } .getOrNull() ?: failedAt - uncertainSends[paymentHash.lowercase()] = UncertainSend(attemptId, failedAt.toULong(), expiresAt) + val hold = UncertainSend(attemptId, failedAt.toULong(), expiresAt) + uncertainSends[paymentHash.lowercase()] = hold // Its caller now waits on the hold, so its outcome is reported, also when an earlier send under the key was. reportedSendIds.remove(attemptId) // Held in memory meanwhile, and the hash kept before the send still holds the invoice after a restart. @@ -820,11 +821,12 @@ class SparkRepo @Inject constructor( pendingPaymentRepo.state.first { paymentHash in it.pendingPayments } } repeat(SETTLE_ATTEMPTS) { - // A send its own payment event settled meanwhile needs no sync. - if (!uncertainSends.containsKey(paymentHash.lowercase())) return@launch + // A send its own payment event settled meanwhile needs no sync, and a later hold of it polls on + // its own. + if (uncertainSends[paymentHash.lowercase()] !== hold) return@launch runSuspendCatching { sparkService.syncWallet() } .onFailure { Logger.warn("Failed to sync Spark after send '$paymentHash'", it, context = TAG) } - if (trySettleUncertainSend(paymentHash)) return@launch + if (trySettleUncertainSend(paymentHash, held = hold)) return@launch delay(SETTLE_RETRY_INTERVAL) } // Spark's next sync settles it, as a send it resumes then ends with its own payment event. diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 502bdedfd5..c89de7c0be 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5560,6 +5560,27 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any(), eq("hash-1")) } + @Test + fun `keyed retries of a held spark send keep one poll of spark per interval`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenAnswer { info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) } + whenever(sparkService.listPayments()).thenReturn(emptyList()) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { throw leafSelectionFailure() } + val sut = createSut(CacheStore(InMemoryDataStore(AppCacheData()), clock)) + sut.start(0).getOrThrow() + repeat(3) { assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) } + // Past the wait for the send screen to track the send, every poll started. + advanceTimeBy(11.seconds) + clearInvocations(sparkService) + + advanceTimeBy(30.seconds) + + verify(sparkService, times(1)).syncWallet() + } + @Test fun `a held spark send spark never recorded reports its failure at expiry after a restart`() = test { val sentAt = now.epochSeconds