From dd5de2eb513727bbe1f13653def8c4219c447fb4 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 20:46:13 +0100 Subject: [PATCH 1/6] 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 489f3bf8fb..64d680a55a 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -2115,6 +2115,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 a80d84b7ab2650b4535c6814743e527804365a0a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 24 Nov 2026 22:13:17 +0100 Subject: [PATCH 2/6] 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 9a7f3d9f086b91ee1c66b13ff6136a9a5b8f1bed Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 11:26:33 +0100 Subject: [PATCH 3/6] 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 b103921c17d537c9fe949796224d71253869a99c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 11:42:31 +0100 Subject: [PATCH 4/6] 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 2e70d4d5052abdd109330f5374c584663d8b0fc0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 12:04:53 +0100 Subject: [PATCH 5/6] 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 521a8d7beb11766ff365122100d09ea231e09689 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 12:23:51 +0100 Subject: [PATCH 6/6] 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(