From 4ec9ece5363594200d2cddfe0a2a98550483325a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 14:50:20 +0100 Subject: [PATCH 01/96] fix: keep a spark retry held past an older failure A late failure event of an earlier attempt no longer ends the hold of an uncertain retry of the same invoice. After a waiting early claim, the Instant claim poll stops quoting and only watches for the claim. Also rewords the spark send liveness comment. --- .../to/bitkit/repositories/LightningRepo.kt | 4 +- .../java/to/bitkit/repositories/SparkRepo.kt | 48 +++++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 99 ++++++++++++++++++- 3 files changed, 140 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 06aa0c4587..fd150fa52e 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1645,8 +1645,8 @@ class LightningRepo @Inject constructor( key: String, ldkRecordsBefore: Long, ): Result? { - // Read before the row too, so a send that ends while it is read still counts as live. The mark comes first, - // so a send it counts as recorded is already admitted or in flight when liveness is read. + // Read before the row too, so a send that ends while it is read still counts as live. The mark comes first, so + // a send it counts was admitted before liveness is read: still live then, or ended before the row is read. val sparkRecordsBefore = sparkRepo.sendRecordMark() val wasLive = isSendLive(paymentHash, key, ldkRecordsBefore) val send = sparkRepo.lightningSend(paymentHash) as? SparkLightningSend.Found ?: return null diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index b8b4698efa..81c82d8274 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -548,12 +548,13 @@ class SparkRepo @Inject constructor( if (sendsInFlight.putIfAbsent(paymentHash.lowercase(), bolt11) != null) { throw PaymentPendingException(paymentHash) } + val sentAt = clock.now().epochSeconds val sent = try { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) spending { // Kept until the call returns, so a send cut off by process death or cancellation stays held. - cacheStore.addSparkUncertainSend(paymentHash, clock.now().epochSeconds) + cacheStore.addSparkUncertainSend(paymentHash, sentAt) // The checks above and both writes suspend, so the deadline and an exit that started meanwhile // are checked last, before the send. runCatching { @@ -584,7 +585,7 @@ class SparkRepo @Inject constructor( 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) - settleUncertainSend(paymentHash, expiresAt) + settleUncertainSend(paymentHash, sentAt, expiresAt) throw PaymentPendingException(paymentHash) } cacheStore.removeSparkUncertainSend(paymentHash) @@ -599,9 +600,9 @@ class SparkRepo @Inject constructor( } } - private suspend fun settleUncertainSend(paymentHash: String, expiresAt: ULong) { + private suspend fun settleUncertainSend(paymentHash: String, sentAt: Long, expiresAt: ULong) { val failedAt = clock.now().epochSeconds - uncertainSends[paymentHash.lowercase()] = UncertainSend(failedAt.toULong(), expiresAt) + uncertainSends[paymentHash.lowercase()] = UncertainSend(failedAt.toULong(), expiresAt, sentAt.toULong()) cacheStore.addSparkUncertainSend(paymentHash, failedAt) scope.launch { // The send screen tracks the hash as pending only once the send returns, and resolves tracked ones. @@ -655,8 +656,11 @@ class SparkRepo @Inject constructor( return true } - /** A send whose outcome Spark didn't report: when it failed, and when its invoice expires, in epoch seconds. */ - private data class UncertainSend(val failedAt: ULong, val expiresAt: ULong) + /** + * A send whose outcome Spark didn't report: when it failed, when its invoice expires and when it started, in epoch + * seconds. Its start is unknown after a restart, which keeps one stored time. + */ + private data class UncertainSend(val failedAt: ULong, val expiresAt: ULong, val sentAt: ULong? = null) /** Takes back the sends whose outcome Spark didn't report before a restart, so a sync can still settle them. */ private suspend fun restoreUncertainSends() { @@ -747,6 +751,9 @@ class SparkRepo @Inject constructor( private suspend fun claimInstantly(txid: String, ceilingSats: ULong) { var isSeen = false + // Once Spark waits for the early claim, the fee cap stays on the deposit and Spark claims it by itself when the + // provider offers it, so the poll only watches for the claim and asks the provider nothing more. + var isWaiting = false repeat(CLAIM_POLL_ATTEMPTS) { runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark state", it, context = TAG) } @@ -754,7 +761,9 @@ class SparkRepo @Inject constructor( setDepositClaim(txid, SparkDepositClaim.Claimed) return } - if (_depositClaims.value[txid] != SparkDepositClaim.Adding) { + if (isWaiting && _depositClaims.value[txid] != SparkDepositClaim.Adding) { + if (isClaimStarted(txid)) setDepositClaim(txid, SparkDepositClaim.Adding) + } else if (_depositClaims.value[txid] != SparkDepositClaim.Adding) { val offer = depositClaimOffer(txid) .onFailure { Logger.warn("Failed to quote Spark deposit '$txid'", it, context = TAG) } .getOrNull() @@ -764,7 +773,9 @@ class SparkRepo @Inject constructor( SparkClaimStep.Adding -> SparkDepositClaim.Adding SparkClaimStep.Unavailable -> SparkDepositClaim.Unavailable is SparkClaimStep.Ask -> SparkDepositClaim.Repriced(step.offer) - is SparkClaimStep.ClaimEarly -> claimEarly(step.offer).getOrNull()?.toDepositClaim(step.offer) + is SparkClaimStep.ClaimEarly -> claimEarly(step.offer).getOrNull() + ?.also { isWaiting = it == SparkEarlyClaim.Waiting } + ?.toDepositClaim(step.offer) } if (claim != null) setDepositClaim(txid, claim) if (claim?.isFinal == true) return @@ -784,6 +795,11 @@ class SparkRepo @Inject constructor( _depositClaims.update { if (txid in it) it else it + (txid to SparkDepositClaim.Later) } } + /** Whether Spark no longer lists the deposit in [txid] as unclaimed, so its claim is under way. */ + private suspend fun isClaimStarted(txid: String): Boolean = runSuspendCatching { + sparkService.listUnclaimedDeposits().none { it.txid.equals(txid, ignoreCase = true) } + }.onFailure { Logger.warn("Failed to list unclaimed Spark deposits", it, context = TAG) }.getOrDefault(false) + private fun isClaimed(txid: String): Boolean = _state.value.deposits.any { it.isClaimed && it.txid.equals(txid, ignoreCase = true) } @@ -1722,6 +1738,16 @@ class SparkRepo @Inject constructor( private fun recordedSince(records: Long): Set = sendRecordedAt.filterValues { it > records }.keys /** The payment hash of this send, at [status] when given. */ + /** + * Whether this failed send started before the uncertain send of its hash, so it is an earlier attempt's. Spark + * dates a payment when it starts it, in epoch seconds; with the start unknown, as after a restart, it is not. + */ + private fun Payment.isEarlierFailureOfUncertainSend(): Boolean { + val hash = sendHash(PaymentStatus.FAILED) ?: return false + val sentAt = uncertainSends[hash.lowercase()]?.sentAt ?: return false + return timestamp < sentAt + } + private fun Payment.sendHash(status: PaymentStatus? = null): String? = (details as? PaymentDetails.Lightning) ?.takeIf { paymentType == SparkPaymentType.SEND && (status == null || this.status == status) } ?.htlcDetails?.paymentHash @@ -1766,6 +1792,12 @@ class SparkRepo @Inject constructor( runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after payment '${payment.id}'", it, context = TAG) } recordActivity(payment, settlesJournal = false) + // An earlier attempt's failure can arrive after a retry of its invoice went uncertain, and ends nothing of the + // retry's: Spark may still finish it, so its hold stays until the expiry rule of trySettleUncertainSend. + if (payment.isEarlierFailureOfUncertainSend()) { + Logger.info("Kept uncertain Spark send '${payment.sendHash()}' held past an older failure", context = TAG) + return + } // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. payment.sendHash()?.let { uncertainSends.remove(it.lowercase()) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 597177f9a3..7f4e34934d 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -2332,6 +2332,40 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(SparkDepositClaim.Claimed, sut.depositClaims.value["txid"]) } + @Test + fun `instant stops quoting once spark waits for the early claim`() = test { + listDeposit() + whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) + whenever { sparkService.claimDeposit("txid", 0u, 300uL) } + .thenReturn(ClaimDepositOutcome.Deferred(ClaimDeferredReason.NoEarlyClaimAvailable)) + val sut = createSut() + + sut.followDepositClaim("txid", SparkClaimSpeed.Instant, ceilingSats = 500uL) + advanceUntilIdle() + + verify(sparkService, times(1)).fetchClaimQuote("txid", 0u) + verify(sparkService, times(1)).claimDeposit("txid", 0u, 300uL) + assertEquals(SparkDepositClaim.Unavailable, sut.depositClaims.value["txid"]) + } + + @Test + fun `instant shows adding once spark claims a deposit it waited on`() = test { + val deposit = DepositInfo("txid", 0u, 50_000uL, false, null, null, null, null, null, null) + // Listed until Spark claims it early by itself, a few polls after it waited. + whenever { sparkService.listUnclaimedDeposits() } + .thenReturn(listOf(deposit), listOf(deposit), listOf(deposit), emptyList()) + whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) + whenever { sparkService.claimDeposit("txid", 0u, 300uL) } + .thenReturn(ClaimDepositOutcome.Deferred(ClaimDeferredReason.NoEarlyClaimAvailable)) + val sut = createSut() + + sut.followDepositClaim("txid", SparkClaimSpeed.Instant, ceilingSats = 500uL) + advanceUntilIdle() + + verify(sparkService, times(1)).claimDeposit("txid", 0u, 300uL) + assertEquals(SparkDepositClaim.Adding, sut.depositClaims.value["txid"]) + } + @Test fun `instant asks the user when the early fee is over the ceiling`() = test { listDeposit() @@ -3519,6 +3553,69 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) } + @Test + fun `an older attempt's late failure event keeps an uncertain spark retry held`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + val olderFailure = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + whenever { sparkService.listPayments() }.thenReturn(listOf(olderFailure)) + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable"), lastSyncedAt = 1uL) + ) + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + runCurrent() + + // The earlier attempt's failure, made before the retry started, arrives after the retry went uncertain. + sparkEvents.emit(SdkEvent.PaymentFailed(olderFailure)) + advanceUntilIdle() + + assertTrue(events.none { it is Event.PaymentFailed }, "an older failure ended a send Spark may finish") + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + } + + @Test + fun `an uncertain spark retry's own failure after a restart ends its hold`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + // The send call times out a while after Spark started the payment. + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { + now += 5.seconds + throw SdkException.Generic("timeout") + } + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + ) + val before = createSut(store) + before.start(0).getOrThrow() + val sentAt = now.epochSeconds.toULong() + assertIs(before.payInvoice("lnbc1", 100uL).exceptionOrNull()) + runCurrent() + now += 30.seconds + whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val after = createSut(store) + after.start(0).getOrThrow() + runCurrent() + + // Spark resumes the retry after the restart and it fails, dated when Spark started it, before it was held. + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = sentAt) + whenever { sparkService.listPayments() }.thenReturn(listOf(failed)) + sparkEvents.emit(SdkEvent.PaymentFailed(failed)) + advanceUntilIdle() + + assertNull(after.earlierLightningSend("lnbc1", "hash"), "the retry's own failure still held the node off") + } + @Test fun `an uncertain spark retry stays held after a restart while spark lists only its older failure`() = test { assertUncertainRetryHeldAfterRestart(syncError = null) @@ -3687,7 +3784,7 @@ class SparkRepoTest : BaseUnitTest() { advanceUntilIdle() // Spark resumes the send later and it fails. - val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) whenever { sparkService.listPayments() }.thenReturn(listOf(failed)) sparkEvents.emit(SdkEvent.PaymentFailed(failed)) advanceUntilIdle() From a7349cf2490fbed75ff2b44299fd9b8d13c62317 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 14:58:19 +0100 Subject: [PATCH 02/96] fix: keep a move to spark running after its screen closes --- .../main/java/to/bitkit/data/CacheStore.kt | 11 ++ .../to/bitkit/repositories/MoveToSparkRepo.kt | 28 +++- .../settings/lightning/MoveToSparkManager.kt | 147 ++++++++++++++++++ .../lightning/MoveToSparkViewModel.kt | 88 +---------- .../NotifyPaymentReceivedHandlerTest.kt | 1 + .../repositories/MoveToSparkRepoTest.kt | 55 ++++++- .../lightning/MoveToSparkViewModelTest.kt | 48 +++++- 7 files changed, 285 insertions(+), 93 deletions(-) create mode 100644 app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 47e49828e2..6b6930e6ba 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -186,6 +186,12 @@ class CacheStore internal constructor( store.updateData { it.copy(sparkUncertainSends = it.sparkUncertainSends - hash) } } + suspend fun addMoveToSparkHash(paymentHash: String) { + val hash = paymentHash.lowercase() + if (hash in store.data.first().moveToSparkHashes) return + store.updateData { it.copy(moveToSparkHashes = it.moveToSparkHashes + hash) } + } + /** Keeps [paymentHash] with its invoice's expiry in epoch seconds, [expiresAt], when known. */ suspend fun addLdkSendHash(paymentHash: String, expiresAt: Long? = null) { val hash = paymentHash.lowercase() @@ -369,6 +375,11 @@ data class AppCacheData( * never reads a retry's earlier failed attempt as its outcome. */ val sparkUncertainSends: Map = mapOf(), + /** + * Payment hashes of the moves to Spark, kept across restarts so neither leg of a move is announced as a payment and + * Activity shows the move as one. + */ + val moveToSparkHashes: List = listOf(), /** Hashes of the Lightning sends the node started, so Spark holds off while the node can't list them. */ val ldkSendHashes: List = listOf(), /** Invoice expiry in epoch seconds of the [ldkSendHashes] that know it. */ diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index e46b0f3da3..9760ad06de 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -16,6 +16,7 @@ import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.NodeException import org.lightningdevkit.ldknode.PaymentFailureReason import org.lightningdevkit.ldknode.PaymentStatus +import to.bitkit.data.CacheStore import to.bitkit.di.BgDispatcher import to.bitkit.ext.runSuspendCatching import to.bitkit.ext.totalNextOutboundHtlcLimitSats @@ -35,10 +36,12 @@ import kotlin.time.Duration.Companion.minutes * channels only. Blocktank is closing its channels, and this is the cheapest way to keep the balance in Spending. */ @Singleton -class MoveToSparkRepo @Inject constructor( - @BgDispatcher private val bgDispatcher: CoroutineDispatcher, +class MoveToSparkRepo internal constructor( + private val bgDispatcher: CoroutineDispatcher, private val lightningRepo: LightningRepo, private val sparkRepo: SparkRepo, + private val cacheStore: CacheStore, + private val paymentHashOf: (bolt11: String) -> String, ) { companion object { private const val TAG = "MoveToSparkRepo" @@ -54,12 +57,23 @@ class MoveToSparkRepo @Inject constructor( setOf(PaymentFailureReason.ROUTE_NOT_FOUND, PaymentFailureReason.RETRIES_EXHAUSTED) } - private val ownPaymentHashes = ConcurrentHashMap.newKeySet() + @Inject + constructor( + @BgDispatcher bgDispatcher: CoroutineDispatcher, + lightningRepo: LightningRepo, + sparkRepo: SparkRepo, + cacheStore: CacheStore, + ) : this(bgDispatcher, lightningRepo, sparkRepo, cacheStore, { Bolt11Invoice.fromStr(it).paymentHash() }) + private val watchedPaymentHashes = ConcurrentHashMap.newKeySet() private val reportedPaymentHashes = ConcurrentHashMap.newKeySet() - /** Whether [paymentHash] is a move to Spark, whose send and receive the app does not announce as payments. */ - fun isMovePayment(paymentHash: String): Boolean = paymentHash in ownPaymentHashes + /** + * Whether [paymentHash] is a move to Spark, whose send and receive the app does not announce as payments; also one + * from before a restart. + */ + suspend fun isMovePayment(paymentHash: String): Boolean = + paymentHash.lowercase() in cacheStore.data.first().moveToSparkHashes /** * Whether the move screen waits on [paymentHash] or already reported its outcome, so the app raises no failure @@ -116,8 +130,8 @@ class MoveToSparkRepo @Inject constructor( /** Pays [quote] over the channels and waits for it to settle in Spark. */ suspend fun move(quote: MoveToSparkQuote): Result = withContext(bgDispatcher) { runSuspendCatching { - val paymentHash = Bolt11Invoice.fromStr(quote.invoice).paymentHash() - ownPaymentHashes += paymentHash + val paymentHash = paymentHashOf(quote.invoice) + cacheStore.addMoveToSparkHash(paymentHash) watchedPaymentHashes += paymentHash try { payAndWait(quote, paymentHash) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt new file mode 100644 index 0000000000..8a27a6c3b0 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt @@ -0,0 +1,147 @@ +package to.bitkit.ui.settings.lightning + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Job +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import to.bitkit.di.BgDispatcher +import to.bitkit.ext.filterOpen +import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.MoveToSparkError +import to.bitkit.repositories.MoveToSparkMath +import to.bitkit.repositories.MoveToSparkOutcome +import to.bitkit.repositories.MoveToSparkRepo +import to.bitkit.repositories.WalletRepo +import to.bitkit.async.appScope +import java.util.concurrent.atomic.AtomicInteger +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Holds the Move to Spark screen's state for the app's lifetime, so a move and its outcome outlive the screen: leaving + * while the payment is under way no longer stops the wait, and opening the screen again shows that move. + */ +@Singleton +class MoveToSparkManager @Inject constructor( + @BgDispatcher bgDispatcher: CoroutineDispatcher, + private val moveToSparkRepo: MoveToSparkRepo, + private val lightningRepo: LightningRepo, + private val walletRepo: WalletRepo, +) { + companion object { + private const val TAG = "MoveToSparkManager" + } + + private val scope = appScope(bgDispatcher, TAG) + + private val _uiState = MutableStateFlow(MoveToSparkUiState.Quoting) + val uiState: StateFlow = _uiState.asStateFlow() + + /** Counts quotes, moves and resets; a quote or move writes its result only while it is still the latest. */ + private val generation = AtomicInteger(0) + private var quoteJob: Job? = null + + /** A move was started and its outcome is still the screen's, so opening the screen again keeps it. */ + @Volatile + private var keepsOutcome = false + + /** A swiped payment that has not settled yet; leaving the screen keeps it, so it is never quoted over. */ + @Volatile + private var isMoveInFlight = false + + /** Opens the screen: quotes a new move, unless one is quoting or a move is running or still shows its outcome. */ + fun start() { + if (keepsOutcome || quoteJob?.isActive == true) return + quote() + } + + /** Forgets the last move once its screen is left, unless its payment is still in flight. */ + fun reset() { + if (isMoveInFlight) return + generation.incrementAndGet() + quoteJob?.cancel() + keepsOutcome = false + _uiState.update { MoveToSparkUiState.Quoting } + } + + /** Quotes moving [targetSats], or everything the channels can send. */ + fun quote(targetSats: ULong? = null) { + val quoteGeneration = generation.incrementAndGet() + keepsOutcome = false + _uiState.update { MoveToSparkUiState.Quoting } + quoteJob?.cancel() + quoteJob = scope.launch { + val quoted = moveToSparkRepo.quote(targetSats).fold( + onSuccess = { MoveToSparkUiState.Confirm(it) }, + onFailure = { it.toUiState() }, + ) + if (generation.get() == quoteGeneration) _uiState.update { quoted } + } + } + + fun move() { + val confirm = _uiState.value as? MoveToSparkUiState.Confirm ?: return + if (confirm.isMoving) return + val quote = confirm.quote + val moveGeneration = generation.incrementAndGet() + keepsOutcome = true + isMoveInFlight = true + _uiState.update { MoveToSparkUiState.Confirm(quote, isMoving = true) } + scope.launch { + try { + moveToSparkRepo.move(quote).fold( + onSuccess = { outcome -> + val settled = (outcome as? MoveToSparkOutcome.InFlight)?.let { + async(start = CoroutineStart.UNDISPATCHED) { moveToSparkRepo.awaitSettled(it) } + } + val done = done(outcome) + if (generation.get() == moveGeneration) _uiState.update { done } + settled?.await()?.let { showLateOutcome(it, moveGeneration) } + }, + onFailure = { error -> + if (generation.get() == moveGeneration) _uiState.update { error.toUiState() } + }, + ) + } finally { + if (generation.get() == moveGeneration) isMoveInFlight = false + } + } + } + + private suspend fun done(outcome: MoveToSparkOutcome): MoveToSparkUiState.Done { + walletRepo.syncNodeAndWallet() + val hasRest = MoveToSparkMath.hasMovableBalance(moveToSparkRepo.movableSats()) + return MoveToSparkUiState.Done(outcome, emptiedChannelId(), hasRest) + } + + private suspend fun showLateOutcome(settled: Result, moveGeneration: Int) { + if (generation.get() != moveGeneration || !uiState.value.isInFlight()) return + val late = settled.fold( + onSuccess = { done(it) }, + onFailure = { MoveToSparkUiState.Failed(MoveToSparkFailure.UNKNOWN) }, + ) + _uiState.update { if (generation.get() == moveGeneration && it.isInFlight()) late else it } + } + + private fun MoveToSparkUiState.isInFlight(): Boolean = + this is MoveToSparkUiState.Done && outcome is MoveToSparkOutcome.InFlight + + /** The channel to close after the move, when exactly one is open; with several, the user picks in Connections. */ + private fun emptiedChannelId(): String? = lightningRepo.lightningState.value.channels.filterOpen() + .singleOrNull()?.channelId + + private fun Throwable.toUiState(): MoveToSparkUiState = when (this) { + is MoveToSparkError.TooLarge -> MoveToSparkUiState.TooLarge( + amountSats = amountSats, + smallerSats = MoveToSparkMath.smallerAmount(amountSats), + ) + is MoveToSparkError.NothingToMove -> MoveToSparkUiState.Failed(MoveToSparkFailure.NOTHING_TO_MOVE) + is MoveToSparkError.SparkUnavailable -> MoveToSparkUiState.Failed(MoveToSparkFailure.SPARK_UNAVAILABLE) + else -> MoveToSparkUiState.Failed(MoveToSparkFailure.UNKNOWN) + } +} diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModel.kt index b84ca7b74d..29f3c69b2c 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModel.kt @@ -2,102 +2,30 @@ package to.bitkit.ui.settings.lightning import androidx.compose.runtime.Immutable import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel -import kotlinx.coroutines.CoroutineStart -import kotlinx.coroutines.async -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.launch -import to.bitkit.ext.filterOpen -import to.bitkit.repositories.LightningRepo -import to.bitkit.repositories.MoveToSparkError -import to.bitkit.repositories.MoveToSparkMath import to.bitkit.repositories.MoveToSparkOutcome import to.bitkit.repositories.MoveToSparkQuote -import to.bitkit.repositories.MoveToSparkRepo -import to.bitkit.repositories.WalletRepo import javax.inject.Inject +/** The Move to Spark screen's view of [MoveToSparkManager], which keeps a move running after the screen closes. */ @HiltViewModel class MoveToSparkViewModel @Inject constructor( - private val moveToSparkRepo: MoveToSparkRepo, - private val lightningRepo: LightningRepo, - private val walletRepo: WalletRepo, + private val manager: MoveToSparkManager, ) : ViewModel() { - private val _uiState = MutableStateFlow(MoveToSparkUiState.Quoting) - val uiState = _uiState.asStateFlow() - - private var moveGeneration = 0 + val uiState = manager.uiState init { - quote() + manager.start() } /** Quotes moving [targetSats], or everything the channels can send. */ - fun quote(targetSats: ULong? = null) { - _uiState.update { MoveToSparkUiState.Quoting } - viewModelScope.launch { - moveToSparkRepo.quote(targetSats).fold( - onSuccess = { quote -> _uiState.update { MoveToSparkUiState.Confirm(quote) } }, - onFailure = { error -> _uiState.update { error.toUiState() } }, - ) - } - } - - fun move() { - val confirm = _uiState.value as? MoveToSparkUiState.Confirm ?: return - if (confirm.isMoving) return - val quote = confirm.quote - _uiState.update { MoveToSparkUiState.Confirm(quote, isMoving = true) } - val generation = ++moveGeneration - viewModelScope.launch { - moveToSparkRepo.move(quote).fold( - onSuccess = { outcome -> - val settled = (outcome as? MoveToSparkOutcome.InFlight)?.let { - async(start = CoroutineStart.UNDISPATCHED) { moveToSparkRepo.awaitSettled(it) } - } - val done = done(outcome) - _uiState.update { done } - settled?.await()?.let { showLateOutcome(it, generation) } - }, - onFailure = { error -> _uiState.update { error.toUiState() } }, - ) - } - } - - private suspend fun done(outcome: MoveToSparkOutcome): MoveToSparkUiState.Done { - walletRepo.syncNodeAndWallet() - val hasRest = MoveToSparkMath.hasMovableBalance(moveToSparkRepo.movableSats()) - return MoveToSparkUiState.Done(outcome, emptiedChannelId(), hasRest) - } - - private suspend fun showLateOutcome(settled: Result, generation: Int) { - if (generation != moveGeneration || !uiState.value.isInFlight()) return - val late = settled.fold( - onSuccess = { done(it) }, - onFailure = { MoveToSparkUiState.Failed(MoveToSparkFailure.UNKNOWN) }, - ) - _uiState.update { if (generation == moveGeneration && it.isInFlight()) late else it } - } - - private fun MoveToSparkUiState.isInFlight(): Boolean = - this is MoveToSparkUiState.Done && outcome is MoveToSparkOutcome.InFlight + fun quote(targetSats: ULong? = null) = manager.quote(targetSats) - /** The channel to close after the move, when exactly one is open; with several, the user picks in Connections. */ - private fun emptiedChannelId(): String? = lightningRepo.lightningState.value.channels.filterOpen() - .singleOrNull()?.channelId + fun move() = manager.move() - private fun Throwable.toUiState(): MoveToSparkUiState = when (this) { - is MoveToSparkError.TooLarge -> MoveToSparkUiState.TooLarge( - amountSats = amountSats, - smallerSats = MoveToSparkMath.smallerAmount(amountSats), - ) - is MoveToSparkError.NothingToMove -> MoveToSparkUiState.Failed(MoveToSparkFailure.NOTHING_TO_MOVE) - is MoveToSparkError.SparkUnavailable -> MoveToSparkUiState.Failed(MoveToSparkFailure.SPARK_UNAVAILABLE) - else -> MoveToSparkUiState.Failed(MoveToSparkFailure.UNKNOWN) + override fun onCleared() { + manager.reset() } } diff --git a/app/src/test/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandlerTest.kt b/app/src/test/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandlerTest.kt index 7480bd4112..f429b7d1cd 100644 --- a/app/src/test/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandlerTest.kt +++ b/app/src/test/java/to/bitkit/domain/commands/NotifyPaymentReceivedHandlerTest.kt @@ -71,6 +71,7 @@ class NotifyPaymentReceivedHandlerTest : BaseUnitTest() { @Before fun setUp() { + whenever { moveToSparkRepo.isMovePayment(any()) }.thenReturn(false) whenever(context.getString(R.string.notification__received__title)).thenReturn("Payment Received") whenever(context.getString(any(), any())).thenReturn("Received amount") whenever(settingsStore.data).thenReturn(settingsData) diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index 5ff73f3f3d..076deb9b3d 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -21,8 +21,11 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify import org.mockito.kotlin.whenever +import to.bitkit.data.AppCacheData +import to.bitkit.data.CacheStore import to.bitkit.ext.createChannelDetails import to.bitkit.test.BaseUnitTest +import to.bitkit.test.InMemoryDataStore import to.bitkit.utils.LdkError import kotlin.test.assertEquals import kotlin.test.assertIs @@ -40,6 +43,8 @@ class MoveToSparkRepoTest : BaseUnitTest() { private val lightningState = MutableStateFlow(LightningState()) private val nodeEvents = MutableSharedFlow() private val inFlight = MoveToSparkOutcome.InFlight(50_000uL, paymentHash = "hash", paymentId = "id") + private val cacheStore = CacheStore(InMemoryDataStore(AppCacheData())) + private val quote = MoveToSparkQuote(INVOICE, amountSats = 50_000uL, feeSats = 12uL) private lateinit var sut: MoveToSparkRepo @Before @@ -47,9 +52,11 @@ class MoveToSparkRepoTest : BaseUnitTest() { whenever(lightningRepo.lightningState).thenReturn(lightningState) whenever(sparkRepo.state).thenReturn(sparkState) whenever(lightningRepo.nodeEvents).thenReturn(nodeEvents) - sut = MoveToSparkRepo(testDispatcher, lightningRepo, sparkRepo) + sut = createSut() } + private fun createSut() = MoveToSparkRepo(testDispatcher, lightningRepo, sparkRepo, cacheStore) { "hash" } + private fun sendable(sats: ULong) { val channel = createChannelDetails().copy(isUsable = true, nextOutboundHtlcLimitMsat = sats * 1000uL) lightningState.value = LightningState(channels = persistentListOf(channel)) @@ -223,6 +230,52 @@ class MoveToSparkRepoTest : BaseUnitTest() { assertIs(sut.awaitSettled(inFlight).exceptionOrNull()) } + @Test + fun `move pays over the channels capped at the quoted fee and reports the fee paid`() = test { + whenever(lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull())).thenReturn(Result.success("id")) + val moving = async { sut.move(quote) } + + nodeEvents.emit(Event.PaymentSuccessful("other", "other_hash", null, 1_000uL)) + nodeEvents.emit(Event.PaymentSuccessful("id", "hash", null, 9_000uL)) + + assertEquals(MoveToSparkOutcome.Moved(50_000uL, feeSats = 9uL), moving.await().getOrThrow()) + verify(lightningRepo).payInvoiceOverLdk( + bolt11 = INVOICE, + paymentHash = "hash", + sats = 50_000uL, + maxTotalRoutingFeeMsat = 12_000uL, + ) + } + + @Test + fun `move matches a failure without its hash by the payment id`() = test { + whenever(lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull())).thenReturn(Result.success("id")) + val moving = async { sut.move(quote) } + + nodeEvents.emit(Event.PaymentFailed("other", null, PaymentFailureReason.ROUTE_NOT_FOUND)) + nodeEvents.emit(Event.PaymentFailed("id", null, PaymentFailureReason.PAYMENT_EXPIRED)) + + val error = assertIs(moving.await().exceptionOrNull()) + assertEquals(PaymentFailureReason.PAYMENT_EXPIRED, error.reason) + } + + @Test + fun `move reports a payment without an outcome in time as in flight`() = test { + whenever(lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull())).thenReturn(Result.success("id")) + // Nothing settles it, so the virtual clock runs to the end of the wait. + assertEquals(inFlight, sut.move(quote).getOrThrow()) + assertTrue(sut.isWatchedMovePayment("hash").not(), "a move no one waits on still mutes the app's notices") + } + + @Test + fun `a move's payment stays a move after a restart`() = test { + whenever(lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull())).thenReturn(Result.success("id")) + sut.move(quote) + + assertTrue(createSut().isMovePayment("HASH"), "a restart forgot the move's payment") + assertTrue(!createSut().isMovePayment("other")) + } + private fun nodeSend(status: PaymentStatus) = PaymentDetails( id = "id", kind = PaymentKind.Bolt11(hash = "hash", preimage = null, secret = null, description = null, bolt11 = INVOICE), diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt index fdb532eba4..a00298f56b 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt @@ -9,6 +9,8 @@ import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.ext.createChannelDetails import to.bitkit.repositories.LightningRepo @@ -36,6 +38,7 @@ class MoveToSparkViewModelTest : BaseUnitTest() { private val secondMove = MoveToSparkOutcome.InFlight(50_000uL, paymentHash = "hash_2", paymentId = "id_2") private val firstSettled = CompletableDeferred>() private val secondSettled = CompletableDeferred>() + private val manager by lazy { MoveToSparkManager(testDispatcher, moveToSparkRepo, lightningRepo, walletRepo) } @Before fun setUp() { @@ -99,9 +102,44 @@ class MoveToSparkViewModelTest : BaseUnitTest() { return sut } - private fun createViewModel() = MoveToSparkViewModel( - moveToSparkRepo = moveToSparkRepo, - lightningRepo = lightningRepo, - walletRepo = walletRepo, - ) + @Test + fun `leaving the screen while a move runs keeps the move and shows it again`() = test { + val payment = CompletableDeferred>() + whenever(moveToSparkRepo.move(eq(quote))).doSuspendableAnswer { payment.await() } + createViewModel().move() + + manager.reset() + val reopened = createViewModel() + assertEquals(MoveToSparkUiState.Confirm(quote, isMoving = true), reopened.uiState.value) + + payment.complete(Result.success(moved)) + + assertEquals(MoveToSparkUiState.Done(moved, closeChannelId = null), reopened.uiState.value) + verify(moveToSparkRepo, times(1)).quote(anyOrNull()) + } + + @Test + fun `leaving the screen while a move is in flight keeps waiting for its outcome`() = test { + createViewModel().move() + + manager.reset() + val reopened = createViewModel() + firstSettled.complete(Result.success(moved)) + + assertEquals(MoveToSparkUiState.Done(moved, closeChannelId = null), reopened.uiState.value) + } + + @Test + fun `leaving the screen after a settled move quotes anew on return`() = test { + whenever(moveToSparkRepo.move(eq(quote))).thenReturn(Result.success(moved)) + createViewModel().move() + + manager.reset() + val reopened = createViewModel() + + assertEquals(MoveToSparkUiState.Confirm(quote), reopened.uiState.value) + verify(moveToSparkRepo, times(2)).quote(anyOrNull()) + } + + private fun createViewModel() = MoveToSparkViewModel(manager) } From 2c2b780c0e803051bff06ae8d533fa3869cf3521 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 15:05:11 +0100 Subject: [PATCH 03/96] feat: show a move to spark in activity --- app/src/main/java/to/bitkit/ext/Activities.kt | 4 ++++ .../java/to/bitkit/repositories/MoveToSparkRepo.kt | 4 ++++ .../wallets/activity/ActivityDetailScreen.kt | 14 ++++++++++---- .../wallets/activity/components/ActivityIcon.kt | 9 +++++++++ .../wallets/activity/components/ActivityRow.kt | 14 +++++++++++--- .../main/java/to/bitkit/viewmodels/AppViewModel.kt | 2 ++ app/src/main/res/values/strings.xml | 1 + changelog.d/next/1819.added.md | 1 + 8 files changed, 42 insertions(+), 7 deletions(-) create mode 100644 changelog.d/next/1819.added.md diff --git a/app/src/main/java/to/bitkit/ext/Activities.kt b/app/src/main/java/to/bitkit/ext/Activities.kt index ba9c832c42..f4213b1146 100644 --- a/app/src/main/java/to/bitkit/ext/Activities.kt +++ b/app/src/main/java/to/bitkit/ext/Activities.kt @@ -76,6 +76,10 @@ fun Activity.matchesPaymentId(paymentHashOrTxId: String): Boolean = when (this) fun Activity.isTransfer() = this is Activity.Onchain && this.v1.isTransfer +/** Whether this is the channel send of a move to Spark, one of [moveHashes], which Activity shows as a move. */ +fun Activity.isMoveToSpark(moveHashes: Set) = this is Activity.Lightning && + v1.txType == PaymentType.SENT && v1.status != PaymentState.FAILED && v1.id.lowercase() in moveHashes + fun Activity.doesExist() = this is Activity.Onchain && this.v1.doesExist fun Activity.isReplacedSentTransaction(txIdsInBoostTxIds: Set): Boolean = diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index 9760ad06de..5745ba2941 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -8,6 +8,7 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import org.lightningdevkit.ldknode.Bolt11Invoice @@ -82,6 +83,9 @@ class MoveToSparkRepo internal constructor( fun isWatchedMovePayment(paymentHash: String): Boolean = paymentHash in watchedPaymentHashes || paymentHash in reportedPaymentHashes + /** The payment hashes of the moves to Spark, so Activity shows each as a move rather than a payment. */ + val moveHashes: Flow> = cacheStore.data.map { it.moveToSparkHashes.toSet() }.distinctUntilChanged() + /** Whether the channels hold a balance worth moving to a usable Spark wallet. */ val canMove: Flow = combine(lightningRepo.lightningState, sparkRepo.state) { lightning, spark -> MoveToSparkMath.canMove(lightning.channels, spark) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt index 6128329df6..7779b41a3a 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt @@ -58,6 +58,7 @@ import to.bitkit.ext.contact import to.bitkit.ext.create import to.bitkit.ext.ellipsisMiddle import to.bitkit.ext.isSent +import to.bitkit.ext.isMoveToSpark import to.bitkit.ext.isTransfer import to.bitkit.ext.rawId import to.bitkit.ext.timestamp @@ -180,6 +181,8 @@ fun ActivityDetailScreen( val settings = settingsViewModel ?: return@Box val hideBalance by settings.hideBalance.collectAsStateWithLifecycle() val isPaykitEnabled by settings.isPaykitEnabled.collectAsStateWithLifecycle() + val moveHashes by app.moveToSparkHashes.collectAsStateWithLifecycle(initialValue = emptySet()) + val isMoveToSpark = item.isMoveToSpark(moveHashes) val copyToastTitle = stringResource(R.string.common__copied) val tags by detailViewModel.tags.collectAsStateWithLifecycle() @@ -232,10 +235,10 @@ fun ActivityDetailScreen( ) { AppTopBar( titleText = stringResource( - if (isCpfpChild) { - R.string.wallet__activity_boost_fee - } else { - item.getScreenTitleRes() + when { + isCpfpChild -> R.string.wallet__activity_boost_fee + isMoveToSpark -> R.string.wallet__activity_move_to_spark + else -> item.getScreenTitleRes() } ), onBackClick = onBackClick, @@ -257,6 +260,7 @@ fun ActivityDetailScreen( isCpfpChild = isCpfpChild, isHardware = uiState.isHardwareActivity, isSparkWithdrawal = isSparkWithdrawal, + isMoveToSpark = isMoveToSpark, showContactActions = isPaykitEnabled && (!uiState.isHardwareActivity || assignedContact != null), boostTxDoesExist = boostTxDoesExist, @@ -351,6 +355,7 @@ private fun ActivityDetailContent( isCpfpChild: Boolean = false, isHardware: Boolean = false, isSparkWithdrawal: Boolean = false, + isMoveToSpark: Boolean = false, showContactActions: Boolean = true, boostTxDoesExist: ImmutableMap = persistentMapOf(), onCopy: (String) -> Unit, @@ -428,6 +433,7 @@ private fun ActivityDetailContent( size = 48.dp, isCpfpChild = isCpfpChild, isHardware = isHardware, + isMoveToSpark = isMoveToSpark, ) } diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityIcon.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityIcon.kt index 1127c8c768..14e2b5836e 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityIcon.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityIcon.kt @@ -42,6 +42,7 @@ fun ActivityIcon( size: Dp = 32.dp, isCpfpChild: Boolean = false, isHardware: Boolean = false, + isMoveToSpark: Boolean = false, contact: PubkyProfile? = null, ) { val isLightning = activity is Activity.Lightning @@ -61,6 +62,14 @@ fun ActivityIcon( ) } + isMoveToSpark -> CircularIcon( + icon = painterResource(R.drawable.ic_transfer), + iconColor = Colors.Purple, + backgroundColor = Colors.Purple16, + size = size, + modifier = modifier.testTag("MoveToSparkIcon"), + ) + contact != null -> PubkyContactAvatar( profile = contact, size = size, diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityRow.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityRow.kt index c204cc0fc9..b085ac0a51 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityRow.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityRow.kt @@ -32,6 +32,7 @@ import com.synonym.bitkitcore.PaymentState import com.synonym.bitkitcore.PaymentType import to.bitkit.R import to.bitkit.ext.isSent +import to.bitkit.ext.isMoveToSpark import to.bitkit.ext.isTransfer import to.bitkit.ext.timestamp import to.bitkit.ext.totalValue @@ -86,6 +87,9 @@ fun ActivityRow( is Activity.Onchain -> item.v1.txId }.lowercase() val receiptStatus = receiptStatuses[paymentId].takeIf { item.txType() == PaymentType.RECEIVED } + val moveHashes by appViewModel?.moveToSparkHashes?.collectAsStateWithLifecycle(initialValue = emptySet()) + ?: remember { mutableStateOf(emptySet()) } + val isMoveToSpark = item.isMoveToSpark(moveHashes) val status: PaymentState? = when (item) { is Activity.Lightning -> item.v1.status @@ -103,11 +107,13 @@ fun ActivityRow( val isTransfer = item.isTransfer() val activityListViewModel = activityListViewModel var isCpfpChild by remember { mutableStateOf(false) } - val resolvedTitle = title.takeIf { - shouldUseContactActivityTitle(item, status, isTransfer, isCpfpChild) + val resolvedTitle = if (isMoveToSpark) { + stringResource(R.string.wallet__activity_move_to_spark) + } else { + title.takeIf { shouldUseContactActivityTitle(item, status, isTransfer, isCpfpChild) } } val resolvedContact = contact.takeIf { - shouldUseContactActivityTitle(item, status, isTransfer, isCpfpChild) + !isMoveToSpark && shouldUseContactActivityTitle(item, status, isTransfer, isCpfpChild) } LaunchedEffect(item) { @@ -124,6 +130,7 @@ fun ActivityRow( size = 40.dp, isCpfpChild = isCpfpChild, isHardware = isHardware, + isMoveToSpark = isMoveToSpark, contact = resolvedContact, ) HorizontalSpacer(16.dp) @@ -141,6 +148,7 @@ fun ActivityRow( ) val context = LocalContext.current val subtitleText = when (item) { + is Activity.Lightning if isMoveToSpark -> activityTimeText(timestamp) is Activity.Lightning -> item.v1.message.ifEmpty { activityTimeText(timestamp) } is Activity.Onchain -> { when { diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index a646786060..dbe871fef6 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -8724,6 +8724,8 @@ class AppViewModel @Inject constructor( /** Receipt status by the payment's hash, txid or USDT transfer id, lowercase. */ val paykitReceiptStatuses get() = paykitReceiptRepo.statuses + val moveToSparkHashes get() = moveToSparkRepo.moveHashes + fun retryPaykitReceipt(paymentId: String) = viewModelScope.launch(bgDispatcher) { paykitReceiptRepo.retry(paymentId) } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 53a9e11f1f..e2368b2cb9 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1508,6 +1508,7 @@ {count, plural, one {INPUT} other {INPUTS (#)}} Invoice Invoice note + Move to Spark Next month No activity yet Receive some funds to get started diff --git a/changelog.d/next/1819.added.md b/changelog.d/next/1819.added.md new file mode 100644 index 0000000000..b71c93c681 --- /dev/null +++ b/changelog.d/next/1819.added.md @@ -0,0 +1 @@ +Moving funds to Spark now shows as a Move to Spark entry in Activity and keeps going after you leave its screen. From 4c064ab94cfb479a253488683302022f41d408df Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 15:05:11 +0100 Subject: [PATCH 04/96] fix: back up spark exit state past an unimportable remote copy --- .../java/to/bitkit/repositories/BackupRepo.kt | 25 +++++++- .../java/to/bitkit/repositories/SparkRepo.kt | 14 ++++- .../java/to/bitkit/services/SparkService.kt | 3 + .../to/bitkit/repositories/BackupRepoTest.kt | 58 +++++++++++++++++++ 4 files changed, 96 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 b7e4faf5ac..14e6752e0d 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -87,6 +87,7 @@ import to.bitkit.models.toLdkNetwork import to.bitkit.services.CoreService import to.bitkit.services.LightningService import to.bitkit.services.PaykitSdkService +import to.bitkit.services.SparkError import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.utils.AppError import to.bitkit.utils.Logger @@ -718,9 +719,17 @@ class BackupRepo @Inject constructor( private suspend fun uploadSparkExitBackup(): Result = runSuspendCatching { if (!sparkRepo.hasMergedRemoteExitState) { sparkRepo.exitBackup().getOrThrow() ?: throw SparkExitBackupDeferred() - val remote = vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name).getOrThrow()?.value - ?.let { json.decodeFromString(String(it)) } - sparkRepo.mergeRemoteExitBackup(remote).getOrThrow() + val stored = vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name).getOrThrow()?.value + val remote = stored?.let { runCatching { json.decodeFromString(String(it)) }.getOrNull() } + val merged = if (stored != null && remote == null) { + Result.failure(SparkError.ExitStateUnimportable()) + } else { + sparkRepo.mergeRemoteExitBackup(remote) + } + merged.recoverCatching { + if (it !is SparkError.ExitStateUnimportable || stored == null) throw it + keepUnimportableExitBackup(stored) + }.getOrThrow() } val backup = sparkRepo.exitBackup().getOrThrow() ?: throw SparkExitBackupDeferred() vssBackupClient.putObject( @@ -729,6 +738,13 @@ class BackupRepo @Inject constructor( ).getOrThrow() } + /** Keeps stored exit data Spark can never import under its own key, so the fresh export doesn't replace it. */ + private suspend fun keepUnimportableExitBackup(stored: ByteArray) { + vssBackupClient.putObject(key = SPARK_EXIT_UNIMPORTED_KEY, data = stored).getOrThrow() + sparkRepo.skipUnimportableRemoteExitState() + Logger.warn("Kept unimportable Spark exit data under '$SPARK_EXIT_UNIMPORTED_KEY'", context = TAG) + } + suspend fun persistWalletBackup(): Result = withContext(ioDispatcher) { walletBackupMutex.withLock { uploadWalletBackup() } @@ -1555,6 +1571,9 @@ class BackupRepo @Inject constructor( private const val MINUTE_IN_MS = 60_000 private const val BACKUP_DEBOUNCE = 5000L // 5 seconds + /** Where stored Spark exit data that Spark can't import is kept, apart from the exit data backups. */ + internal const val SPARK_EXIT_UNIMPORTED_KEY = "SPARK_EXIT_UNIMPORTED" + /** Spark's exit data can reach several MB and changes with every payment, so its uploads are spaced out. */ private const val SPARK_EXIT_BACKUP_DEBOUNCE = 60_000L diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 81c82d8274..8b04ef061c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1147,13 +1147,25 @@ class SparkRepo @Inject constructor( suspend fun mergeRemoteExitBackup(remote: SparkExitBackupV1?): Result = withContext(bgDispatcher) { runSuspendCatching { if (remote != null && remote.network == sparkService.networkName) { - val merged = sparkService.importExitState(remote.exitState) + val merged = runSuspendCatching { sparkService.importExitState(remote.exitState) }.getOrElse { + // Spark checks the version and parses the payload without the operators, so this one never passes. + throw if (it is SdkException.InvalidInput) SparkError.ExitStateUnimportable(it) else it + } Logger.info("Merged stored Spark exit data: '${merged.importedLeaves}' leaves", context = TAG) } hasMergedRemoteExitState = true } } + /** + * Stops merging stored exit data Spark can never import, which the caller kept apart, so the next upload replaces + * it; a staged restore of it is dropped too. + */ + fun skipUnimportableRemoteExitState() { + File(Env.sparkExitRestorePath(walletIndex)).delete() + hasMergedRemoteExitState = true + } + /** * Puts a restored exit data backup back: at once while Spark is connected, otherwise right after it connects, * before it is used, so a restored wallet can exit on-chain even while the Spark operators are unreachable. diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 594bc11371..e37a421ef9 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -360,6 +360,9 @@ sealed class SparkError(message: String, cause: Throwable? = null) : AppError(me class WipeInProgress : SparkError("Spark wallet cannot connect while the wallet is wiped") class WipeFailed(path: String) : SparkError("Failed to delete Spark storage at '$path'") + /** Stored exit data Spark can never import: an exit state version it doesn't support, or one it can't read. */ + class ExitStateUnimportable(cause: Throwable? = null) : SparkError("Spark can't import the exit data", cause) + /** What the withdrawal leaves after its fee is below the on-chain dust limit. */ class WithdrawalTooSmall : SparkError("Spark balance is too small to withdraw after its fee") diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index a95531fae7..82a1bd18f1 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -94,6 +94,7 @@ import to.bitkit.models.WalletScope import to.bitkit.models.WatchOnlyAccountRecord import to.bitkit.models.WatchOnlyAccountSetupState import to.bitkit.models.WidgetsBackupV1 +import to.bitkit.services.SparkError import to.bitkit.services.AddressDerivationInfo import to.bitkit.services.LightningService import to.bitkit.services.PaykitSdkService @@ -417,6 +418,63 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `stored spark exit data spark can't import is kept apart and the upload goes through`() = test { + val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "v9")) + .toByteArray() + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.mergeRemoteExitBackup(anyOrNull())) + .thenReturn(Result.failure(SparkError.ExitStateUnimportable())) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + inOrder(sparkRepo, vssBackupClient) { + verify(vssBackupClient).putObject(BackupRepo.SPARK_EXIT_UNIMPORTED_KEY, stored) + verify(sparkRepo).skipUnimportableRemoteExitState() + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + } + + @Test + fun `stored spark exit data that doesn't parse is kept apart and the upload goes through`() = test { + val stored = "not exit data".toByteArray() + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + verify(vssBackupClient).putObject(BackupRepo.SPARK_EXIT_UNIMPORTED_KEY, stored) + verify(sparkRepo, never()).mergeRemoteExitBackup(anyOrNull()) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + + @Test + fun `a spark exit merge that fails for another reason still blocks the upload`() = test { + val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "v1")) + .toByteArray() + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.mergeRemoteExitBackup(anyOrNull())).thenReturn(Result.failure(AppError("not connected"))) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + assertTrue(sut.triggerBackup(BackupCategory.SPARK_EXIT).isFailure) + + verify(vssBackupClient, never()).putObject(eq(BackupRepo.SPARK_EXIT_UNIMPORTED_KEY), any()) + verify(vssBackupClient, never()).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + @Test fun `spark exit backup never replaces a stored one it could not read`() = test { whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) From a894c894f162d715c801fcd1f4e7d66e83db175b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 15:05:11 +0100 Subject: [PATCH 05/96] chore: translate spark strings --- app/src/main/res/values-ar/strings.xml | 59 ++++++++++++++++-- app/src/main/res/values-b+es+419/strings.xml | 59 ++++++++++++++++-- app/src/main/res/values-ca/strings.xml | 59 ++++++++++++++++-- app/src/main/res/values-cs/strings.xml | 59 ++++++++++++++++-- app/src/main/res/values-de/strings.xml | 61 ++++++++++++++++--- app/src/main/res/values-el/strings.xml | 61 ++++++++++++++++--- app/src/main/res/values-es-rES/strings.xml | 61 ++++++++++++++++--- app/src/main/res/values-es/strings.xml | 63 +++++++++++++++++--- app/src/main/res/values-fr/strings.xml | 61 ++++++++++++++++--- app/src/main/res/values-it/strings.xml | 61 ++++++++++++++++--- app/src/main/res/values-nl/strings.xml | 59 ++++++++++++++++-- app/src/main/res/values-pl/strings.xml | 59 ++++++++++++++++-- app/src/main/res/values-pt-rBR/strings.xml | 59 ++++++++++++++++-- app/src/main/res/values-pt/strings.xml | 61 ++++++++++++++++--- app/src/main/res/values-ru/strings.xml | 63 +++++++++++++++++--- 15 files changed, 804 insertions(+), 101 deletions(-) diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index b15701949a..645dc84503 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -167,6 +167,31 @@ قابل للاستخدام أرصدة Lightning ارتفاع أرشفة مراقب القناة + المبلغ + سينتقل رصيدك إلى Spark عبر Lightning، وهي أقل طريقة رسومًا للإبقاء عليه في الإنفاق. رسوم التوجيه أدناه هي أقصى ما تدفعه. + النقل إلى\n<accent>Spark</accent> + جزء من رصيدك على Spark الآن. انقل الباقي بالطريقة نفسها، ثم أغلق الاتصال الذي فرغ. + رصيدك على Spark الآن. أغلق الاتصال الذي فرغ لإعادة احتياطيه إلى المدخرات. + تم النقل إلى\n<accent>Spark</accent> + لم يعد في اتصالات Lightning الخاصة بك رصيد للنقل. + Spark غير جاهز للاستلام بعد. حاول مرة أخرى بعد قليل. + تعذّر\n<accent>النقل</accent> + حدث خطأ أثناء تجهيز النقل. حاول مرة أخرى. + رسوم التوجيه + الدفعة في طريقها وستظهر في Spark بمجرد اكتمالها. إذا فشلت، يبقى المبلغ في اتصالك. + جارٍ النقل إلى\n<accent>Spark</accent> + يغلق Blocktank اتصالات Lightning الخاصة به. انقل رصيدك إلى Spark الآن: إنه الخيار الأقل رسومًا، ويبقى في الإنفاق. + اتصالك\n<accent>يُغلق</accent> + انقل النصف + انقل الآن + انقل الباقي + النقل إلى Spark + جارٍ البحث عن مسار ورسومه… + اسحب للنقل + أغلق الاتصال بدلًا من ذلك لإعادة الرصيد إلى المدخرات. + يمكنك نقله على أجزاء أصغر. + %1$s كبير جدًا بحيث لا يمكن توجيهه إلى Spark في دفعة واحدة. + المبلغ\n<accent>كبير جدًا</accent> حد HTLC الصادر التالي الحد الأدنى لـ HTLC الصادر التالي قبل أن تتمكن من تحويل الأموال من رصيد مدخراتك، تحتاج إلى إرسال Bitcoin إلى محفظة Bitkit الخاصة بك. @@ -209,7 +234,18 @@ تحويل\n<accent>إلى المدخرات</accent> يرجى الانتظار، جارٍ تحويل أموالك. يجب أن يستغرق هذا <accent>±10 ثوانٍ.</accent> الأموال\n<accent>قيد التحويل</accent> + فشل\n<accent>التحويل</accent> وقت مزامنة درجات تحديد المسار + موافقة + <accent>رسوم التحويل السريع الآن ₿ {amount}.</accent> وافق للوصول إلى أموالك بسرعة، أو انتظر نحو 30 دقيقة. + تغيّرت رسوم\n<accent>التحويل السريع</accent> + جارٍ الإضافة إلى رصيد الإنفاق + تغيّرت رسوم التحويل السريع + استخدام سرعة التحويل العادية + رائع! + يرجى الانتظار، تحويل أموالك قيد التنفيذ. يستغرق هذا <accent>بضع دقائق.</accent> + يرجى الانتظار، تحويل أموالك قيد التنفيذ. يستغرق هذا <accent>نحو 30 دقيقة.</accent> + التحويل السريع\n<accent>غير متاح</accent> متابعة استخدام Bitkit جارٍ معالجة الدفع الدفع ناجح @@ -233,6 +269,9 @@ وصل {amount} إلى مدخراتك. أموالك في المدخرات. اكتمل\n<accent>الخروج</accent> + عناوين الخروج السابقة + استخدمت عمليات الخروج الطارئ السابقة عناوين التمويل هذه. ما بقي من عملات في أحدها يظل ملكك: أنفقها باستخدام عبارة الاسترداد ومسار الاشتقاق الخاص بها. + مسار الاشتقاق نقل مشغّلو Spark مبلغ {amount} على السلسلة ولم يعد على Spark. لا يزال بإمكان المشغّلين الإفراج عنه لك. يبقى {amount} على Spark. تعذّر استرداد أي شيء. @@ -323,16 +362,20 @@ المدخرات غير كافية المبلغ الذي يمكنك تحويله إلى رصيد الإنفاق محدود حاليًا بـ ₿ {amount}. الحد الأقصى لرصيد الإنفاق - حوّل أكثر من ₿ {amount} لتغطية رسوم إضافته إلى رصيد الإنفاق. - المبلغ صغير جدًا + يلزم حد أدنى قدره ₿ {amount} لإعداد رصيد الإنفاق. + الحد الأدنى لرصيد المدخرات 25% تحويل\n<accent>إلى الإنفاق</accent> + ± إلى الإنفاق + تعذّر على Bitkit الحصول على رسوم هذا التحويل. تحقق من اتصالك وحاول مرة أخرى. الرسوم أعلى بمقدار {amount} لأن معدلات الرسوم أو رصيد مدخراتك تغيّر أثناء وجودك في هذه الشاشة. اسحب مرة أخرى للتأكيد. تغيّرت الرسوم جاهز خلال دقائق بعد 3 تأكيدات، نحو 30 دقيقة رسوم الخدمة + أقصى مبلغ يمكنك تحويله الآن هو {amount}، لأن معدلات الرسوم أو رصيد مدخراتك تغيّر أثناء وجودك في هذه الشاشة. اسحب مرة أخرى للتأكيد. + تغيّر المبلغ رسوم الشبكة تعذّر على Bitkit الحصول على الرسوم الحالية لهذا التحويل. تحقق من اتصالك وحاول مرة أخرى. الرسوم غير متاحة @@ -343,7 +386,7 @@ تحويل\n<accent>إلى الإنفاق</accent> رصيد الإنفاق يدفع الفوري للمزوّد لإضافة تحويلك إلى رصيد الإنفاق قبل تأكيده، عادةً خلال دقائق.\n\nأما لاحقًا فينتظر 3 تأكيدات، نحو 30 دقيقة، برسوم أقل. - Transfer\n<accent>speed</accent> + سرعة\n<accent>التحويل</accent> الحالة الدعم إجمالي احتياطي قنوات Anchor @@ -977,6 +1020,7 @@ {count, plural, one {إدخال} other {إدخالات (#)}} الفاتورة ملاحظة الفاتورة + النقل إلى Spark الشهر القادم لا يوجد نشاط بعد استلم بعض الأموال للبدء @@ -1056,6 +1100,7 @@ زِد الرسوم المخصصة وحاول مرة أخرى. ملاحظة تم استلام Bitcoin + لا يستطيع Bitkit التأكد من أن هذه الفاتورة لم تُدفع قبل استعادة محفظتك. يرجى طلب فاتورة جديدة. انقطع اتصال النظير. فشل إرسال الإيصال جارٍ إرسال الإيصال @@ -1067,7 +1112,7 @@ تم نسخ الفاتورة إلى الحافظة فاتورة Lightning ملاحظة اختيارية للدافع - استمتع بمعاملات فورية ورخيصة\nمع الأصدقاء والعائلة\nوالتجار. + استمتع بمعاملات فورية ورخيصة مع الأصدقاء والعائلة والتجار. استلم على <accent>رصيد الإنفاق</accent> عرض التفاصيل عرض رمز QR @@ -1117,12 +1162,14 @@ الرصيد الاحتياطي ليس لدى جهة الاتصال هذه أي طريقة دفع يمكن لـ Bitkit استخدامها الآن. لا يمكن الدفع لجهة الاتصال هذه + لا يزال سحب سابق من رصيد الإنفاق قيد التسوية. حاول مرة أخرى بعد اكتماله. لم تعد التحويلات إلى رصيد الإنفاق متاحة. يتحقق Bitkit أولًا من الشبكة، ثم يعيد عملات هذا التحويل إلى محفظتك حتى لا يتأكد التحويل الأصلي أبدًا. يكلّف ذلك رسوم شبكة. QuickPay جارٍ دفع\n<accent>الفاتورة...</accent> تأكيد تم إرسال Bitcoin المسار + Spark اسحب للدفع إلى نعم، أرسل @@ -1360,8 +1407,8 @@ رسوم Spark بدأ التحويل وهو <accent>قيد التسوية على السلسلة</accent>. سيتم تحديث رصيد مدخراتك تلقائيًا عند اكتماله. التحويل\n<accent>في الطريق</accent> - تعذّر نقل رصيد Spark إلى المدخرات ويبقى في رصيد الإنفاق. - تعذّر نقل رصيد Spark إلى المدخرات ويبقى في رصيد الإنفاق. اتصالاتك قيد النقل إلى المدخرات. + تعذّر نقل رصيد Spark الخاص بك إلى المدخرات، ويبقى في رصيد الإنفاق. + أموال قنواتك في طريقها إلى المدخرات، لكن رصيد Spark الخاص بك تعذّر نقله ويبقى في رصيد الإنفاق. <accent>جارٍ الاتصال</accent>\nبالشبكة يرجى إعادة توصيل جهازك، يبدو أنه غير متصل بهاتفك. إعادة توصيل الجهاز diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index b55b5e2ea4..a279730347 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -174,6 +174,31 @@ Es utilizable Saldos Lightning Altura de archivo del monitor de canal + Monto + Tu saldo pasa a Spark por Lightning, la forma de menor comisión para mantenerlo en Gastos. La comisión de enrutamiento de abajo es lo máximo que pagas. + Mover a\n<accent>Spark</accent> + Una parte de tu saldo ya está en Spark. Mueve el resto de la misma manera y luego cierra la conexión vacía. + Tu saldo ya está en Spark. Cierra la conexión vacía para devolver su reserva a Ahorros. + Movido a\n<accent>Spark</accent> + Tus conexiones Lightning ya no tienen saldo para mover. + Spark aún no está listo para recibir. Inténtalo de nuevo en un momento. + No se pudo\n<accent>mover</accent> + Algo salió mal al preparar el movimiento. Inténtalo de nuevo. + Comisión de enrutamiento + El pago está en camino y aparecerá en Spark cuando se complete. Si falla, el monto permanece en tu conexión. + Moviendo a\n<accent>Spark</accent> + Blocktank está cerrando sus conexiones Lightning. Mueve tu saldo a Spark ahora: es la opción de menor comisión y se queda en Gastos. + Tu conexión\n<accent>se está cerrando</accent> + Mover la mitad + Mover ahora + Mover el resto + Mover a Spark + Buscando una ruta y su comisión… + Desliza para mover + Mejor cierra la conexión para devolver el saldo a Ahorros. + Puedes moverlo en partes más pequeñas. + %1$s es demasiado grande para enrutarse a Spark en un solo pago. + Monto\n<accent>demasiado grande</accent> Límite del próximo HTLC saliente Mínimo del próximo HTLC saliente Para transferir fondos a su saldo de ahorros, primero tiene que enviar bitcoin a su billetera Bitkit. @@ -216,7 +241,18 @@ Transferir\n<accent>a ahorros</accent> Espera un momento, tu transferencia está en proceso. Tomará aproximadamente <accent>10 segundos.</accent> Fondos\n<accent>en proceso</accent> + Transferencia\n<accent>fallida</accent> Hora de sincronización de puntuaciones de ruta + Aprobar + <accent>La comisión de transferencia rápida ahora es ₿ {amount}.</accent> Aprueba para acceder a tus fondos rápidamente, o espera ±30 min. + Cambió la comisión de\n<accent>transferencia rápida</accent> + Agregando al saldo para gastos + Cambió la comisión de transferencia rápida + Usando velocidad de transferencia normal + ¡Genial! + Espera, la transferencia de tus fondos está en curso. Debería tardar <accent>unos minutos.</accent> + Espera, la transferencia de tus fondos está en curso. Debería tardar <accent>unos 30 minutos.</accent> + Transferencia rápida\n<accent>no disponible</accent> Continuar Usando Bitkit Procesando pago Pago Efectuado @@ -240,6 +276,9 @@ {amount} llegó a tus ahorros. Tus fondos están en tus ahorros. Salida\n<accent>completada</accent> + Direcciones de salida anteriores + Las salidas de emergencia anteriores usaron estas direcciones de financiación. Las monedas que queden en una siguen siendo tuyas: gástalas con tu frase de recuperación y su ruta de derivación. + Ruta de derivación Los operadores de Spark movieron {amount} on-chain y ya no está en Spark. Los operadores aún pueden liberártelo. {amount} se queda en Spark. No se pudo recuperar nada. @@ -330,16 +369,20 @@ Ahorros insuficientes El monto que puedes transferir a tu saldo para gastar está limitado a ₿ {amount}. Saldo máximo de gastos - Transfiere más de ₿ {amount} para cubrir las comisiones de agregarlo a tu saldo para gastos. - Monto demasiado bajo + Se necesita un mínimo de ₿ {amount} para configurar tu saldo para gastos. + Mínimo del saldo de ahorros 25% Transferir\n<accent>a gastos</accent> + ± Hacia Gastos + Bitkit no pudo obtener las comisiones de esta transferencia. Revisa tu conexión e inténtalo de nuevo. Las comisiones son {amount} más altas porque las tarifas o su saldo de ahorros cambiaron mientras estaba en esta pantalla. Deslice de nuevo para confirmar. Las comisiones cambiaron Listo en unos minutos Después de 3 confirmaciones, unos 30 minutos Comisión de servicio + Lo máximo que puedes transferir ahora es {amount}, porque las tarifas o tu saldo de ahorros cambiaron mientras estabas en esta pantalla. Desliza de nuevo para confirmar. + El monto cambió Comisiones de red Bitkit no pudo obtener las comisiones actuales de esta transferencia. Revisa tu conexión e inténtalo de nuevo. Comisiones no disponibles @@ -350,7 +393,7 @@ Transferir\n<accent>a gastos</accent> Saldo para gastos Instantáneo le paga al proveedor para agregar tu transferencia a tu saldo para gastos antes de que se confirme, normalmente en unos minutos.\n\nDespués espera 3 confirmaciones, unos 30 minutos, con una comisión menor. - Transfer\n<accent>speed</accent> + Velocidad de\n<accent>transferencia</accent> Estatus Soporte Reserva total de canales ancla @@ -1002,6 +1045,7 @@ {count, plural, one {ENTRADA} many {ENTRADAS (#)} other {ENTRADAS (#)}} Factura Nota de factura + Mover a Spark Mes siguiente Aún no hay actividad Reciba algunos fondos para empezar @@ -1086,6 +1130,7 @@ Aumente la tasa e inténtelo de nuevo. Nota Bitcoin recibido + Bitkit no puede confirmar que esta factura no se pagó antes de que restauraras tu billetera. Solicita una factura nueva. Par desconectado. Error al enviar el recibo Enviando recibo @@ -1097,7 +1142,7 @@ Factura copiada en el portapapeles Factura Lightning Nota opcional para el pagador - Disfruta transacciones instantáneas\ny baratas con amigos, familia\ny comercios. + Disfruta transacciones instantáneas y baratas con amigos, familia y comercios. Recibe en <accent>saldo de gastos</accent> Ver detalles Mostrar código QR @@ -1148,6 +1193,7 @@ Saldo de reserva Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora. No se puede pagar a este contacto + Un retiro anterior de tu saldo para gastos aún se está liquidando. Inténtalo de nuevo cuando termine. Las transferencias al saldo de gasto ya no están disponibles. Bitkit primero revisa la red y luego devuelve las monedas de esta transferencia a tu billetera para que la transferencia original nunca se confirme. Esto tiene una comisión de red. Este pago está tardando un poco más de lo esperado. Puede seguir utilizando Bitkit. Pago pendiente @@ -1156,6 +1202,7 @@ Confirmar Bitcoin Enviado Ruta + Spark Deslizar para pagar Para Sí, enviar @@ -1390,8 +1437,8 @@ Comisión de Spark Su transferencia se inició y se está <accent>liquidando onchain</accent>. Su saldo de ahorros se actualizará automáticamente cuando termine. Transferencia\n<accent>en camino</accent> - Tu saldo de Spark no pudo pasar a ahorros y se queda en tu saldo de gastos. - Tu saldo de Spark no pudo pasar a ahorros y se queda en tu saldo de gastos. Tus conexiones se están pasando a ahorros. + Tu saldo de Spark no se pudo mover a ahorros y permanece en tu saldo para gastos. + Los fondos de tus canales se están moviendo a ahorros, pero tu saldo de Spark no se pudo mover y permanece en tu saldo para gastos. <accent>Conectando</accent>\na la red Vuelva a conectar su dispositivo de hardware; parece que está desconectado de su teléfono. Reconectar dispositivo de hardware diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 0d2f1094f2..937fdd0583 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -171,6 +171,31 @@ És utilitzable Saldos Lightning Alçada d\'arxiu del monitor de canal + Import + El teu saldo passa a Spark per Lightning, la manera amb menys comissió de mantenir-lo a despesa. La comissió d\'encaminament de sota és el màxim que pagues. + Mou a\n<accent>Spark</accent> + Una part del teu saldo ja és a Spark. Mou la resta de la mateixa manera i després tanca la connexió buida. + El teu saldo ja és a Spark. Tanca la connexió buida per retornar-ne la reserva als estalvis. + Mogut a\n<accent>Spark</accent> + Les teves connexions Lightning ja no tenen saldo per moure. + Spark encara no està a punt per rebre. Torna-ho a provar d\'aquí a un moment. + No s\'ha pogut\n<accent>moure</accent> + Alguna cosa ha fallat en preparar el moviment. Torna-ho a provar. + Comissió d\'encaminament + El pagament està en camí i apareixerà a Spark quan es completi. Si falla, l\'import es queda a la teva connexió. + Movent a\n<accent>Spark</accent> + Blocktank tanca les seves connexions Lightning. Mou ara el teu saldo a Spark: és l\'opció amb menys comissió i es queda a despesa. + La teva connexió\n<accent>es tanca</accent> + Mou la meitat + Mou ara + Mou la resta + Moure a Spark + Cercant una ruta i la seva comissió… + Desplaça per moure + Tanca la connexió per retornar el saldo als estalvis. + Pots moure\'l en parts més petites. + %1$s és massa gran per encaminar-se a Spark en un sol pagament. + Import\n<accent>massa gran</accent> Límit del pròxim HTLC de sortida Mínim del pròxim HTLC de sortida Abans de poder transferir fons del teu saldo d\'estalvis, has d\'enviar bitcoin a la teva cartera Bitkit. @@ -213,7 +238,18 @@ Transferir\n<accent>a estalvis</accent> Si us plau, espera, la transferència de fons està en curs. Hauria de trigar <accent>±10 segons.</accent> Fons\n<accent>en transferència</accent> + Transferència\n<accent>fallida</accent> Temps de sincronització de puntuacions de rutes + Aprova + <accent>La comissió de la transferència ràpida ara és ₿ {amount}.</accent> Aprova per accedir als teus fons ràpidament, o espera ±30 min. + Ha canviat la comissió de\n<accent>transferència ràpida</accent> + Afegint al saldo de despesa + Ha canviat la comissió de transferència ràpida + Usant velocitat de transferència normal + Genial! + Espera, la transferència dels teus fons està en curs. Hauria de trigar <accent>uns minuts.</accent> + Espera, la transferència dels teus fons està en curs. Hauria de trigar <accent>uns 30 minuts.</accent> + Transferència ràpida\n<accent>no disponible</accent> Continua utilitzant Bitkit Processant pagament Pagament realitzat amb èxit @@ -237,6 +273,9 @@ {amount} ha arribat als teus estalvis. Els teus fons són als estalvis. Sortida\n<accent>completada</accent> + Adreces de sortida anteriors + Les sortides d\'emergència anteriors han usat aquestes adreces de finançament. Les monedes que hi quedin continuen sent teves: gasta-les amb la teva frase de recuperació i el seu camí de derivació. + Camí de derivació Els operadors de Spark han mogut {amount} on-chain i no és a Spark. Els operadors encara te\'l poden alliberar. {amount} es queda a Spark. No s\'ha pogut recuperar res. @@ -327,16 +366,20 @@ Estalvis insuficients L\'import que pots transferir al teu saldo de despesa està limitat a ₿ {amount}. Màxim del saldo de despesa - Transfereix més de ₿ {amount} perquè cobreixi les comissions d\'afegir-ho al teu saldo de despesa. - Import massa baix + Cal un mínim de ₿ {amount} per configurar el teu saldo de despesa. + Mínim del saldo d\'estalvis 25% Transferir\n<accent>a despesa</accent> + ± A despesa + Bitkit no ha pogut obtenir les comissions d\'aquesta transferència. Comprova la connexió i torna-ho a provar. Les tarifes són {amount} més altes perquè les taxes de tarifa o el teu saldo d\'estalvis han canviat mentre eres en aquesta pantalla. Torna a desplaçar per confirmar. Les tarifes han canviat A punt en pocs minuts Després de 3 confirmacions, uns 30 minuts Tarifes de servei + El màxim que pots transferir ara és {amount}, perquè les tarifes o el teu saldo d\'estalvis han canviat mentre eres en aquesta pantalla. Torna a desplaçar per confirmar. + L\'import ha canviat Tarifes de xarxa Bitkit no ha pogut obtenir les comissions actuals d\'aquesta transferència. Comprova la connexió i torna-ho a provar. Comissions no disponibles @@ -347,7 +390,7 @@ Transferir\n<accent>a despesa</accent> Saldo de despesa Instant paga el proveïdor per afegir la teva transferència al saldo de despesa abans que es confirmi, normalment en pocs minuts.\n\nDesprés espera 3 confirmacions, uns 30 minuts, amb una comissió més baixa. - Transfer\n<accent>speed</accent> + Velocitat de\n<accent>transferència</accent> Estat Suport Reserva total de canals Anchor @@ -996,6 +1039,7 @@ {count, plural, one {ENTRADA} other {ENTRADES (#)}} Factura Nota de la factura + Moure a Spark Mes següent Encara no hi ha cap activitat Rebi alguns fons per començar @@ -1080,6 +1124,7 @@ Augmenta la tarifa personalitzada i torna-ho a provar. Nota Rebut Bitcoin + Bitkit no pot confirmar que aquesta factura no es va pagar abans que restauressis la cartera. Sol·licita una factura nova. Parell desconnectat. No s\'ha pogut enviar el rebut S\'està enviant el rebut @@ -1091,7 +1136,7 @@ Factura copiada al porta-retalls Factura Lightning Nota opcional per al pagador - Gaudeix de transaccions instantànies i barates\namb amics, família\ni comerciants. + Gaudeix de transaccions instantànies i barates amb amics, família i comerciants. Rebre al <accent>saldo de despesa</accent> Mostrar detalls Mostra el codi QR @@ -1142,6 +1187,7 @@ Saldo de reserva Aquest contacte no té cap mètode de pagament que Bitkit pugui fer servir ara. No es pot pagar aquest contacte + Una retirada anterior del teu saldo de despesa encara s\'està liquidant. Torna-ho a provar quan es completi. Les transferències al saldo de despesa ja no estan disponibles. Bitkit primer comprova la xarxa i després retorna les monedes d\'aquesta transferència a la teva cartera perquè la transferència original no es pugui confirmar mai. Això té una comissió de xarxa. Pagament pendent QuickPay @@ -1149,6 +1195,7 @@ Confirmar Bitcoin enviat Ruta + Spark Desplaça per pagar A Sí, Enviar @@ -1384,8 +1431,8 @@ Tarifa de Spark La teva transferència s\'ha iniciat i <accent>s\'està liquidant onchain</accent>. El teu saldo d\'estalvis s\'actualitzarà automàticament quan es completi. Transferència\n<accent>en camí</accent> - El saldo de Spark no s\'ha pogut moure a estalvis i es queda al saldo de despesa. - El saldo de Spark no s\'ha pogut moure a estalvis i es queda al saldo de despesa. Les teves connexions s\'estan movent a estalvis. + El teu saldo de Spark no s\'ha pogut moure als estalvis i es queda al teu saldo de despesa. + Els fons dels teus canals es mouen als estalvis, però el teu saldo de Spark no s\'ha pogut moure i es queda al teu saldo de despesa. <accent>Connectant</accent>\na la xarxa Torna a connectar el teu dispositiu de maquinari; sembla que s\'ha desconnectat del telèfon. Torna a connectar el dispositiu diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index ccbb0d48d0..6b5d6427e8 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -174,6 +174,31 @@ Je použitelný? Lightning zůstatky Archivní výška monitoru kanálu + Částka + Váš zůstatek se přesune do Spark přes Lightning, což je nejlevnější způsob, jak ho ponechat ve výdajích. Poplatek za směrování níže je nejvíc, co zaplatíte. + Přesun do\n<accent>Spark</accent> + Část vašeho zůstatku je nyní ve Spark. Zbytek přesuňte stejným způsobem a pak zavřete vyprázdněné spojení. + Váš zůstatek je nyní ve Spark. Zavřete vyprázdněné spojení, aby se jeho rezerva vrátila do úspor. + Přesunuto do\n<accent>Spark</accent> + Vaše spojení Lightning už nemají žádný zůstatek k přesunu. + Spark ještě není připraven přijímat. Zkuste to za chvíli znovu. + Přesun se\n<accent>nezdařil</accent> + Při přípravě přesunu se něco pokazilo. Zkuste to znovu. + Poplatek za směrování + Platba je na cestě a po dokončení se zobrazí ve Spark. Pokud selže, částka zůstane ve vašem spojení. + Přesun do\n<accent>Spark</accent> + Blocktank zavírá svá spojení Lightning. Přesuňte svůj zůstatek do Spark hned: je to nejlevnější možnost a zůstane ve výdajích. + Vaše spojení\n<accent>se zavírá</accent> + Přesunout polovinu + Přesunout hned + Přesunout zbytek + Přesun do Spark + Hledání trasy a jejího poplatku… + Přejetím přesunout + Místo toho zavřete spojení, aby se zůstatek vrátil do úspor. + Můžete ho přesunout po menších částech. + %1$s je příliš velká částka na směrování do Spark jednou platbou. + Částka je\n<accent>příliš velká</accent> Limit dalšího odchozího HTLC Min dalšího odchozího HTLC Než budete moci převést prostředky ze svého zůstatku na spořicím účtu, musíte poslat bitcoiny do peněženky Bitkit. @@ -216,7 +241,18 @@ Převést\n<accent>do úspor</accent> Počkejte prosím, probíhá převod finančních prostředků. To by mělo trvat <accent>±10 sekund.</accent> Finanční prostředky\n<accent>v převodu</accent> + Převod\n<accent>se nezdařil</accent> Čas synchronizace skóre hledání cest + Schválit + <accent>Poplatek za rychlý převod je nyní ₿ {amount}.</accent> Schvalte pro rychlý přístup k prostředkům, nebo počkejte ±30 min. + Poplatek za rychlý převod\n<accent>se změnil</accent> + Přidávání do zůstatku pro výdaje + Poplatek za rychlý převod se změnil + Použití běžné rychlosti převodu + Skvělé! + Počkejte prosím, převod vašich prostředků probíhá. Mělo by to trvat <accent>několik minut.</accent> + Počkejte prosím, převod vašich prostředků probíhá. Mělo by to trvat <accent>asi 30 minut.</accent> + Rychlý převod\n<accent>není dostupný</accent> Pokračujte v používání Bitkit Zpracování platby Platba úspěšně proběhla @@ -240,6 +276,9 @@ {amount} dorazilo do vašich úspor. Vaše prostředky jsou v úsporách. Odchod\n<accent>dokončen</accent> + Dřívější adresy odchodu + Dřívější nouzové odchody používaly tyto adresy pro financování. Mince, které na některé zůstanou, jsou stále vaše: utraťte je pomocí své obnovovací fráze a její derivační cesty. + Derivační cesta {amount} přesunuli operátoři Sparku on-chain a není na Spark. Operátoři vám je stále mohou uvolnit. {amount} zůstává na Spark. Nic se nepodařilo získat zpět. @@ -330,16 +369,20 @@ Nedostatečné úspory Částka, kterou můžete převést na svůj disponibilní zůstatek, je v současné době omezena na ₿ {amount}. Maximální disponibilní zůstatek - Převeď více než ₿ {amount}, aby to pokrylo poplatky za přidání do zůstatku pro výdaje. - Příliš malá částka + K nastavení zůstatku pro výdaje je potřeba minimálně ₿ {amount}. + Minimální zůstatek úspor 25% Převést\n<accent>do výdajů</accent> + ± Do výdajů + Bitkit nedokázal získat poplatky za tento převod. Zkontrolujte připojení a zkuste to znovu. Poplatky jsou o {amount} vyšší, protože se během zobrazení této obrazovky změnily sazby poplatků nebo zůstatek vašich úspor. Pro potvrzení přejeďte znovu. Poplatky se změnily Hotovo za pár minut Po 3 potvrzeních, asi 30 minut Poplatky za služby + Nejvíc, co nyní můžete převést, je {amount}, protože se během zobrazení této obrazovky změnily sazby poplatků nebo zůstatek vašich úspor. Pro potvrzení přejeďte znovu. + Částka se změnila Síťové poplatky Bitkit nedokázal získat aktuální poplatky za tento převod. Zkontroluj připojení a zkus to znovu. Poplatky nedostupné @@ -350,7 +393,7 @@ Převést\n<accent>do výdajů</accent> Disponibilní zůstatek Okamžitě platí poskytovateli za přidání převodu do zůstatku pro výdaje ještě před potvrzením, obvykle během pár minut.\n\nPozději čeká na 3 potvrzení, asi 30 minut, s nižším poplatkem. - Transfer\n<accent>speed</accent> + Rychlost\n<accent>převodu</accent> Status Podpora Celková rezerva kotevních kanálů @@ -1000,6 +1043,7 @@ {count, plural, one {INPUT} few {VSTUPY (#)} many {VSTUPY (#)} other {VSTUPY (#)}} Faktura Poznámka k faktuře + Přesun do Spark Další měsíc Zatím žádná aktivita Získejte finanční prostředky, abyste mohli začít @@ -1084,6 +1128,7 @@ Zvyšte vlastní poplatek a zkuste to znovu. Poznámka bitcoin přijatý + Bitkit nemůže potvrdit, že tato faktura nebyla zaplacena před obnovením vaší peněženky. Požádejte prosím o novou fakturu. Peer odpojen. Odeslání potvrzení selhalo Odesílání potvrzení @@ -1095,7 +1140,7 @@ Faktura zkopírovaná do schránky Lightningová faktura Nepovinná poznámka pro plátce - Užívejte si okamžité a levné\ntransakce s přáteli, rodinou\na obchodníky. + Užívejte si okamžité a levné transakce s přáteli, rodinou a obchodníky. Přijímat na disponibilní zůstatek Zobrazit podrobnosti Zobrazit QR kód @@ -1146,6 +1191,7 @@ Zůstatek rezervy Tento kontakt nemá žádnou platební metodu, kterou by Bitkit mohl nyní použít. Tomuto kontaktu nelze zaplatit + Dřívější výběr z vašeho zůstatku pro výdaje se stále vypořádává. Zkuste to znovu, až se dokončí. Převody na útratový zůstatek už nejsou dostupné. Bitkit nejprve zkontroluje síť a pak vrátí mince tohoto převodu do vaší peněženky, aby se původní převod nikdy nepotvrdil. Stojí to síťový poplatek. Tato platba trvá o něco déle, než se očekávalo. Bitkit můžete používat i nadále. Platba čeká na vyřízení @@ -1154,6 +1200,7 @@ Potvrdit bitcoin odeslán Trasa + Spark Zaplatit přejetím prstem Komu Ano, odeslat @@ -1388,8 +1435,8 @@ Poplatek Spark Váš převod byl zahájen a <accent>vypořádává se on-chain</accent>. Zůstatek vašich úspor se po dokončení automaticky aktualizuje. Převod\n<accent>je na cestě</accent> - Zůstatek Spark se nepodařilo přesunout do úspor a zůstává ve výdajovém zůstatku. - Zůstatek Spark se nepodařilo přesunout do úspor a zůstává ve výdajovém zůstatku. Vaše spojení se přesouvají do úspor. + Váš zůstatek ve Spark se nepodařilo přesunout do úspor a zůstává ve zůstatku pro výdaje. + Prostředky z vašich kanálů se přesouvají do úspor, ale váš zůstatek ve Spark se nepodařilo přesunout a zůstává ve zůstatku pro výdaje. <accent>Připojování</accent>\nk síti Připojte prosím znovu své hardwarové zařízení, zdá se, že je od telefonu odpojené. Znovu připojte hardwarové zařízení diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index c20520eb71..d4614fa751 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -102,6 +102,42 @@ Anderes Wallet verwenden Von HW-Wallet übertragen Am einfachsten ist es, deine Bitkit-Ersparnisse zu verwenden oder Bitcoin von einer anderen Wallet zu senden. + Betrag + Dein Guthaben wird über Lightning zu Spark verschoben, der gebührengünstigsten Möglichkeit, es in den Ausgaben zu behalten. Die Routing-Gebühr unten ist das Maximum, das du zahlst. + Zu\n<accent>Spark</accent> verschieben + Ein Teil deines Guthabens ist jetzt auf Spark. Verschiebe den Rest auf dieselbe Weise und schließe dann die geleerte Verbindung. + Dein Guthaben ist jetzt auf Spark. Schließe die geleerte Verbindung, um ihre Reserve zurück aufs Sparkonto zu holen. + Zu\n<accent>Spark</accent> verschoben + Deine Lightning-Verbindungen haben kein Guthaben mehr zum Verschieben. + Spark ist noch nicht bereit zum Empfangen. Versuche es gleich noch einmal. + Verschieben\n<accent>fehlgeschlagen</accent> + Beim Vorbereiten des Verschiebens ist etwas schiefgelaufen. Versuche es erneut. + Routing-Gebühr + Die Zahlung ist unterwegs und erscheint in Spark, sobald sie abgeschlossen ist. Schlägt sie fehl, bleibt der Betrag in deiner Verbindung. + Verschiebe zu\n<accent>Spark</accent> + Blocktank schließt seine Lightning-Verbindungen. Verschiebe dein Guthaben jetzt zu Spark: Das ist die gebührengünstigste Option, und es bleibt in den Ausgaben. + Deine Verbindung\n<accent>wird geschlossen</accent> + Hälfte verschieben + Jetzt verschieben + Rest verschieben + Zu Spark verschieben + Route und Gebühr werden gesucht… + Swipe zum Verschieben + Schließe stattdessen die Verbindung, um das Guthaben aufs Sparkonto zurückzuholen. + Du kannst es in kleineren Teilen verschieben. + %1$s ist zu groß, um in einer Zahlung zu Spark geroutet zu werden. + Betrag\n<accent>zu groß</accent> + Übertragung\n<accent>fehlgeschlagen</accent> + Genehmigen + <accent>Die Gebühr für die schnelle Übertragung beträgt jetzt ₿ {amount}.</accent> Genehmige, um schnell auf deine Gelder zuzugreifen, oder warte ±30 Min. + Gebühr für schnelle Übertragung\n<accent>geändert</accent> + Zum Ausgabenguthaben hinzufügen + Gebühr für schnelle Übertragung geändert + Normale Übertragungsgeschwindigkeit wird verwendet + Super! + Bitte warte, die Übertragung deiner Gelder läuft. Das sollte <accent>einige Minuten</accent> dauern. + Bitte warte, die Übertragung deiner Gelder läuft. Das sollte <accent>etwa 30 Minuten</accent> dauern. + Schnelle Übertragung\n<accent>nicht verfügbar</accent> Spark Einlösegebühr %1$d/3 Bestätigungen @@ -122,6 +158,9 @@ {amount} ist auf deinem Sparkonto angekommen. Deine Mittel sind auf deinem Sparkonto. Ausstieg\n<accent>abgeschlossen</accent> + Frühere Ausstiegsadressen + Frühere Notausstiege haben diese Finanzierungsadressen verwendet. Coins, die auf einer verbleiben, gehören weiterhin dir: Gib sie mit deiner Wiederherstellungsphrase und ihrem Ableitungspfad aus. + Ableitungspfad {amount} wurde von den Spark-Betreibern on-chain verschoben und ist nicht auf Spark. Die Betreiber können es dir weiterhin freigeben. {amount} bleibt auf Spark. Es konnte nichts zurückgeholt werden. @@ -211,14 +250,18 @@ Von Sparkonto übertragen Manuelle Einrichtung <accent>zu den Ausgaben</accent> + ± + Bitkit konnte die Gebühren für diese Übertragung nicht abrufen. Prüfe deine Verbindung und versuche es erneut. + Du kannst jetzt höchstens {amount} übertragen, weil sich die Gebührensätze oder dein Sparguthaben geändert haben, während du auf diesem Bildschirm warst. Wische erneut, um zu bestätigen. + Betrag geändert Übertrage Guthaben Bitte\n<accent>bestätige</accent> Swipe zum Übertragen Trezor Connect öffnen 25% Maximaler Ausgabensaldo - Überweise mehr als ₿ {amount}, damit die Gebühren für dein Ausgabenguthaben gedeckt sind. - Betrag zu klein + Mindestens ₿ {amount} sind nötig, um dein Ausgabenguthaben einzurichten. + Mindestguthaben Sparkonto Der Betrag, den du auf dein Ausgabenkonto übertragen kannst, ist derzeit auf ₿ {amount} begrenzt. Netzgebühren Bitkit konnte die aktuellen Gebühren für diese Überweisung nicht abrufen. Prüfe deine Verbindung und versuche es erneut. @@ -274,7 +317,7 @@ Sparkonto Ausgabenguthaben Sofort bezahlt den Anbieter dafür, deine Überweisung schon vor der Bestätigung deinem Ausgabenguthaben hinzuzufügen, meist innerhalb weniger Minuten.\n\nSpäter wartet auf 3 Bestätigungen, etwa 30 Minuten, zu einer niedrigeren Gebühr. - Transfer\n<accent>speed</accent> + Übertragungs-\n<accent>geschwindigkeit</accent> Empfangskapazität Lightning Node LDK Node ID @@ -370,7 +413,7 @@ ÜBERTRAGUNG LÄUFT Los geht\'s Fülle dein Guthaben auf, um sofortige und günstige Transaktionen mit Freunden, Familie und Händlern zu genießen. - Spending\n<accent>Balance</accent> + Ausgaben-\n<accent>guthaben</accent> Bitte warte bis sich Bitkit mit dem Zahlungsnetzwerk verbunden hat (±10 Sekunden). Bitte warte bis sich Bitkit mit dem Bitcoin-Netzwerk verbunden hat (±10 Sekunden). Wallet-Guthaben @@ -962,6 +1005,7 @@ Zieladresse Ins Netzwerk {network} Netzübergreifende Zustellung verfolgen + Zu Spark verschieben Wallet Aktivität Kontakte @@ -971,6 +1015,7 @@ Einstellungen App Status Support + Bitkit kann nicht bestätigen, dass diese Rechnung nicht bezahlt wurde, bevor du deine Wallet wiederhergestellt hast. Bitte fordere eine neue Rechnung an. Beleg konnte nicht gesendet werden Beleg wird gesendet Beleg gesendet @@ -979,7 +1024,9 @@ Bitcoin senden Dieser Kontakt hat derzeit keine Zahlungsmethode, die Bitkit nutzen kann. Zahlung an diesen Kontakt nicht möglich + Eine frühere Auszahlung von deinem Ausgabenguthaben wird noch abgewickelt. Versuche es erneut, sobald sie abgeschlossen ist. Überweisungen auf dein Ausgabenguthaben sind nicht mehr verfügbar. Bitkit prüft zuerst das Netzwerk und schickt die Coins dieser Überweisung dann zurück in deine Wallet, damit die ursprüngliche Überweisung nie bestätigt wird. Dafür fällt eine Netzwerkgebühr an. + Spark An Kontakt Rechnung einfügen @@ -1085,7 +1132,7 @@ QR-Code anzeigen Lightning-Gelder empfangen Empfangen auf <accent>Ausgabenguthaben</accent> - Genieße sofortige und günstige\nTransaktionen mit Freunden, Familie\nund Händlern. + Genieße sofortige und günstige Transaktionen mit Freunden, Familie und Händlern. Details anzeigen Auto Sparkonto @@ -1385,8 +1432,8 @@ Spark-Gebühr Deine Übertragung wurde gestartet und wird <accent>onchain abgewickelt</accent>. Dein Sparguthaben wird automatisch aktualisiert, sobald sie abgeschlossen ist. Übertragung\n<accent>unterwegs</accent> - Dein Spark-Guthaben konnte nicht in die Ersparnisse verschoben werden und bleibt im Ausgabenguthaben. - Dein Spark-Guthaben konnte nicht in die Ersparnisse verschoben werden und bleibt im Ausgabenguthaben. Deine Verbindungen werden in die Ersparnisse verschoben. + Dein Spark-Guthaben konnte nicht aufs Sparkonto verschoben werden und bleibt in deinem Ausgabenguthaben. + Deine Kanalgelder werden aufs Sparkonto verschoben, aber dein Spark-Guthaben konnte nicht verschoben werden und bleibt in deinem Ausgabenguthaben. <accent>Verbinde</accent>\nmit Netzwerk Bitte verbinde dein Hardware-Gerät erneut, es scheint von deinem Telefon getrennt zu sein. Hardware-Gerät neu verbinden diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 38ce4f74cb..c3bf7031bd 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -154,7 +154,7 @@ Αναγκαστική μεταφορά Δεν ήταν δυνατή η έναρξη της μεταφοράς. Θέλεις να επιβάλεις αυτή τη μεταφορά; Δεν θα μπορείς να χρησιμοποιήσεις αυτά τα κεφάλαια για ±14 ημέρες (!) Αναγκαστική\n<accent>μεταφορά</accent> - Μεταφορά από αποταμιεύσεις + Μεταφορά από Αποταμιεύσεις Χρήση άλλου πορτοφολιού Μεταφορά από πορτοφόλι HW Υπόλοιπο δαπανών @@ -167,6 +167,31 @@ Είναι χρησιμοποιήσιμο Υπόλοιπα Lightning Ύψος αρχειοθέτησης παρακολούθησης καναλιού + Ποσό + Το υπόλοιπό σου μεταφέρεται στο Spark μέσω Lightning, τον τρόπο με τα χαμηλότερα τέλη για να παραμείνει στις Δαπάνες. Τα τέλη δρομολόγησης παρακάτω είναι το μέγιστο που πληρώνεις. + Μεταφορά στο\n<accent>Spark</accent> + Μέρος του υπολοίπου σου βρίσκεται πλέον στο Spark. Μετάφερε το υπόλοιπο με τον ίδιο τρόπο και μετά κλείσε την άδεια σύνδεση. + Το υπόλοιπό σου βρίσκεται πλέον στο Spark. Κλείσε την άδεια σύνδεση για να επιστρέψει το απόθεμά της στις Αποταμιεύσεις. + Μεταφέρθηκε στο\n<accent>Spark</accent> + Οι συνδέσεις Lightning σου δεν έχουν πλέον υπόλοιπο για μεταφορά. + Το Spark δεν είναι ακόμη έτοιμο να λάβει. Δοκίμασε ξανά σε λίγο. + Αδυναμία\n<accent>μεταφοράς</accent> + Κάτι πήγε στραβά κατά την προετοιμασία της μεταφοράς. Δοκίμασε ξανά. + Τέλη δρομολόγησης + Η πληρωμή βρίσκεται καθ\'οδόν και θα εμφανιστεί στο Spark μόλις διακανονιστεί. Αν αποτύχει, το ποσό παραμένει στη σύνδεσή σου. + Μεταφορά στο\n<accent>Spark</accent> + Το Blocktank κλείνει τις συνδέσεις Lightning του. Μετάφερε τώρα το υπόλοιπό σου στο Spark: είναι η επιλογή με τα χαμηλότερα τέλη και παραμένει στις Δαπάνες. + Η σύνδεσή σου\n<accent>κλείνει</accent> + Μεταφορά του μισού + Μεταφορά τώρα + Μεταφορά του υπολοίπου + Μεταφορά στο Spark + Αναζήτηση διαδρομής και των τελών της… + Σύρε για μεταφορά + Κλείσε αντί γι\' αυτό τη σύνδεση για να επιστρέψει το υπόλοιπο στις Αποταμιεύσεις. + Μπορείς να το μεταφέρεις σε μικρότερα μέρη. + Το %1$s είναι πολύ μεγάλο για να δρομολογηθεί στο Spark με μία πληρωμή. + Πολύ μεγάλο\n<accent>ποσό</accent> Όριο επόμενου εξερχόμενου HTLC Ελάχιστο επόμενο εξερχόμενο HTLC Πριν μπορέσεις να μεταφέρεις κεφάλαια από το υπόλοιπο αποταμιεύσεων, πρέπει να στείλεις bitcoin στο πορτοφόλι Bitkit. @@ -209,7 +234,18 @@ Μεταφορά\n<accent>σε αποταμιεύσεις</accent> Περίμενε, η μεταφορά κεφαλαίων σου είναι σε εξέλιξη. Αυτό θα διαρκέσει <accent>±10 δευτερόλεπτα.</accent> Κεφάλαια\n<accent>σε μεταφορά</accent> + Η μεταφορά\n<accent>απέτυχε</accent> Χρόνος συγχρονισμού βαθμολογιών εύρεσης διαδρομής + Έγκριση + <accent>Τα τέλη γρήγορης μεταφοράς είναι τώρα ₿ {amount}.</accent> Έγκρινε για γρήγορη πρόσβαση στα κεφάλαιά σου ή περίμενε ±30 λεπτά. + Τα τέλη γρήγορης μεταφοράς\n<accent>άλλαξαν</accent> + Προσθήκη στο υπόλοιπο δαπανών + Τα τέλη γρήγορης μεταφοράς άλλαξαν + Χρήση κανονικής ταχύτητας μεταφοράς + Φοβερό! + Περίμενε, η μεταφορά των κεφαλαίων σου βρίσκεται σε εξέλιξη. Θα διαρκέσει <accent>λίγα λεπτά.</accent> + Περίμενε, η μεταφορά των κεφαλαίων σου βρίσκεται σε εξέλιξη. Θα διαρκέσει <accent>περίπου 30 λεπτά.</accent> + Η γρήγορη μεταφορά\n<accent>δεν είναι διαθέσιμη</accent> Συνέχισε να χρησιμοποιείς το Bitkit Επεξεργασία πληρωμής Επιτυχής πληρωμή @@ -233,6 +269,9 @@ {amount} έφτασαν στις αποταμιεύσεις σας. Τα κεφάλαιά σας είναι στις αποταμιεύσεις. Η έξοδος\n<accent>ολοκληρώθηκε</accent> + Προηγούμενες διευθύνσεις εξόδου + Οι προηγούμενες έξοδοι έκτακτης ανάγκης χρησιμοποιούσαν αυτές τις διευθύνσεις χρηματοδότησης. Τα νομίσματα που έμειναν σε μία από αυτές παραμένουν δικά σου: ξόδεψέ τα με τη φράση ανάκτησής σου και τη διαδρομή παραγωγής της. + Διαδρομή παραγωγής {amount} μεταφέρθηκαν on-chain από τους διαχειριστές του Spark και δεν βρίσκονται στο Spark. Οι διαχειριστές μπορούν ακόμα να σας τα αποδεσμεύσουν. {amount} παραμένουν στο Spark. Δεν ήταν δυνατή η ανάκτηση τίποτα. @@ -323,16 +362,20 @@ Ανεπαρκείς αποταμιεύσεις Το ποσό που μπορείς να μεταφέρεις στο υπόλοιπο δαπανών περιορίζεται προς το παρόν σε ₿ {amount}. Μέγιστο υπόλοιπο δαπανών - Μετέφερε περισσότερα από ₿ {amount}, ώστε να καλύπτονται οι χρεώσεις για την προσθήκη στο υπόλοιπο δαπανών σου. - Πολύ μικρό ποσό + Απαιτείται ελάχιστο ποσό ₿ {amount} για τη ρύθμιση του υπολοίπου δαπανών σου. + Ελάχιστο υπόλοιπο αποταμίευσης 25% Μεταφορά\n<accent>σε δαπάνες</accent> + ± Σε δαπάνες + Το Bitkit δεν μπόρεσε να λάβει τα τέλη για αυτή τη μεταφορά. Έλεγξε τη σύνδεσή σου και δοκίμασε ξανά. Τα τέλη είναι {amount} υψηλότερα, επειδή τα ποσοστά τελών ή το υπόλοιπο αποταμιεύσεων άλλαξαν ενώ ήσουν σε αυτή την οθόνη. Σύρε ξανά για επιβεβαίωση. Τα τέλη άλλαξαν Έτοιμο σε λίγα λεπτά Μετά από 3 επιβεβαιώσεις, περίπου 30 λεπτά Τέλη υπηρεσίας + Το μέγιστο που μπορείς να μεταφέρεις είναι τώρα {amount}, επειδή άλλαξαν τα επίπεδα τελών ή το υπόλοιπο αποταμίευσής σου ενώ ήσουν σε αυτή την οθόνη. Σύρε ξανά για επιβεβαίωση. + Το ποσό άλλαξε Τέλη δικτύου Το Bitkit δεν μπόρεσε να λάβει τις τρέχουσες χρεώσεις για αυτή τη μεταφορά. Έλεγξε τη σύνδεσή σου και δοκίμασε ξανά. Μη διαθέσιμες χρεώσεις @@ -343,7 +386,7 @@ Μεταφορά\n<accent>σε δαπάνες</accent> Υπόλοιπο δαπανών Το Άμεσα πληρώνει τον πάροχο για να προσθέσει τη μεταφορά σου στο υπόλοιπο δαπανών πριν επιβεβαιωθεί, συνήθως μέσα σε λίγα λεπτά.\n\nΤο Αργότερα περιμένει 3 επιβεβαιώσεις, περίπου 30 λεπτά, με χαμηλότερη χρέωση. - Transfer\n<accent>speed</accent> + Ταχύτητα\n<accent>μεταφοράς</accent> Κατάσταση Υποστήριξη Συνολικό αποθεματικό anchor καναλιών @@ -978,6 +1021,7 @@ {count, plural, one {ΕΙΣΟΔΟΣ} other {ΕΙΣΟΔΟΙ (#)}} Τιμολόγιο Σημείωση τιμολογίου + Μεταφορά στο Spark Επόμενος μήνας Καμία δραστηριότητα ακόμα Λάβε κεφάλαια για να ξεκινήσεις @@ -1061,6 +1105,7 @@ Αύξησε το προσαρμοσμένο τέλος και δοκίμασε ξανά. Σημείωση Ελήφθησαν Bitcoin + Το Bitkit δεν μπορεί να επιβεβαιώσει ότι αυτό το τιμολόγιο δεν πληρώθηκε πριν επαναφέρεις το πορτοφόλι σου. Ζήτησε νέο τιμολόγιο. Ο ομότιμος αποσυνδέθηκε. Η αποστολή της απόδειξης απέτυχε Αποστολή απόδειξης @@ -1072,7 +1117,7 @@ Το τιμολόγιο αντιγράφηκε στο πρόχειρο Τιμολόγιο Lightning Προαιρετική σημείωση προς τον πληρωτή - Απόλαυσε άμεσες και φθηνές\nσυναλλαγές με φίλους, οικογένεια\nκαι εμπόρους. + Απόλαυσε άμεσες και φθηνές συναλλαγές με φίλους, οικογένεια και εμπόρους. Λήψη σε <accent>υπόλοιπο δαπανών</accent> Εμφάνιση λεπτομερειών Εμφάνιση κωδικού QR @@ -1122,12 +1167,14 @@ Αποθεματικό υπόλοιπο Αυτή η επαφή δεν έχει τρόπο πληρωμής που μπορεί να χρησιμοποιήσει το Bitkit αυτή τη στιγμή. Δεν είναι δυνατή η πληρωμή αυτής της επαφής + Μια προηγούμενη ανάληψη από το υπόλοιπο δαπανών σου διακανονίζεται ακόμη. Δοκίμασε ξανά μόλις ολοκληρωθεί. Οι μεταφορές στο υπόλοιπο δαπανών δεν είναι πλέον διαθέσιμες. Το Bitkit ελέγχει πρώτα το δίκτυο και μετά επιστρέφει τα νομίσματα αυτής της μεταφοράς στο πορτοφόλι σας, ώστε η αρχική μεταφορά να μην επιβεβαιωθεί ποτέ. Αυτό έχει χρέωση δικτύου. QuickPay Πληρωμή\n<accent>τιμολογίου...</accent> Επιβεβαίωση Τα Bitcoin στάλθηκαν Διαδρομή + Spark Σύρε για πληρωμή Προς Ναι, Στείλε @@ -1366,8 +1413,8 @@ Τέλος Spark Η μεταφορά σου ξεκίνησε και <accent>εκκαθαρίζεται onchain</accent>. Το υπόλοιπο αποταμιεύσεων θα ενημερωθεί αυτόματα μόλις ολοκληρωθεί. Η μεταφορά\n<accent>είναι καθ\' οδόν</accent> - Το υπόλοιπο Spark δεν μεταφέρθηκε στις αποταμιεύσεις και παραμένει στο υπόλοιπο δαπανών. - Το υπόλοιπο Spark δεν μεταφέρθηκε στις αποταμιεύσεις και παραμένει στο υπόλοιπο δαπανών. Οι συνδέσεις σας μεταφέρονται στις αποταμιεύσεις. + Το υπόλοιπό σου στο Spark δεν μπόρεσε να μεταφερθεί στις αποταμιεύσεις και παραμένει στο υπόλοιπο δαπανών σου. + Τα κεφάλαια του καναλιού σου μεταφέρονται στις αποταμιεύσεις, αλλά το υπόλοιπό σου στο Spark δεν μπόρεσε να μεταφερθεί και παραμένει στο υπόλοιπο δαπανών σου. <accent>Σύνδεση</accent>\nστο δίκτυο Σύνδεσε ξανά τη συσκευή υλικού σου, φαίνεται ότι αποσυνδέθηκε από το τηλέφωνό σου. Επανασύνδεση συσκευής υλικού diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index d12d501a56..823c985554 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -160,7 +160,7 @@ Fuerzar transferencia No se ha podido iniciar la transferencia. ¿Desea forzar esta transferencia? No podrá utilizar estos fondos durante ±14 días (!) Forzar\n<accent>Transferencia</accent> - Transferir desde Ahorros + Transferir desde Ahorro Usar Otro Monedero Transferir desde billetera HW Saldo de gastos @@ -173,6 +173,31 @@ ¿Es utilizable? Saldos Lightning Altura de archivo del monitor de canales + Importe + Tu saldo se mueve a Spark por Lightning, la forma de menor comisión de mantenerlo en Gasto. La comisión de enrutamiento de abajo es lo máximo que pagas. + Mover a\n<accent>Spark</accent> + Una parte de tu saldo ya está en Spark. Mueve el resto de la misma forma y luego cierra la conexión vacía. + Tu saldo ya está en Spark. Cierra la conexión vacía para devolver su reserva a Ahorro. + Movido a\n<accent>Spark</accent> + Tus conexiones Lightning ya no tienen saldo que mover. + Spark aún no está listo para recibir. Inténtalo de nuevo en un momento. + No se pudo\n<accent>mover</accent> + Algo salió mal al preparar el movimiento. Inténtalo de nuevo. + Comisión de enrutamiento + El pago está en camino y aparecerá en Spark cuando se liquide. Si falla, el importe permanece en tu conexión. + Moviendo a\n<accent>Spark</accent> + Blocktank está cerrando sus conexiones Lightning. Mueve tu saldo a Spark ahora: es la opción de menor comisión y se mantiene en Gasto. + Tu conexión\n<accent>se está cerrando</accent> + Mover la mitad + Mover ahora + Mover el resto + Mover a Spark + Buscando una ruta y su comisión… + Desliza para mover + Cierra la conexión en su lugar para devolver el saldo a Ahorro. + Puedes moverlo en partes más pequeñas. + %1$s es demasiado grande para enrutarse a Spark en un solo pago. + Importe\n<accent>demasiado grande</accent> Límite del siguiente HTLC saliente Mínimo del siguiente HTLC saliente Antes de que pueda transferir fondos a su saldo de ahorros, tiene que enviar bitcoin a su monedero Bitkit. @@ -215,7 +240,18 @@ Transferir\n<accent>a ahorros</accent> Por favor espera, tu transferencia de fondos está en curso. Debería tardar <accent>±10 segundos.</accent> Fondos\n<accent>en transferencia</accent> + Transferencia\n<accent>fallida</accent> Hora de sincronización de puntuaciones de rutas + Aprobar + <accent>La comisión de transferencia rápida ahora es ₿ {amount}.</accent> Aprueba para acceder a tus fondos rápidamente, o espera ±30 min. + Comisión de transferencia rápida\n<accent>modificada</accent> + Añadiendo al saldo de gasto + Comisión de transferencia rápida modificada + Usando velocidad de transferencia normal + ¡Genial! + Espera, la transferencia de tus fondos está en curso. Debería tardar <accent>unos minutos.</accent> + Espera, la transferencia de tus fondos está en curso. Debería tardar <accent>unos 30 minutos.</accent> + Transferencia rápida\n<accent>no disponible</accent> Continuar Usando Bitkit Procesando Pago Pago exitoso @@ -239,6 +275,9 @@ {amount} ha llegado a tus ahorros. Tus fondos están en tus ahorros. Salida\n<accent>completada</accent> + Direcciones de salida anteriores + Las salidas de emergencia anteriores usaron estas direcciones de financiación. Las monedas que queden en una siguen siendo tuyas: gástalas con tu frase de recuperación y su ruta de derivación. + Ruta de derivación Los operadores de Spark han movido {amount} on-chain y ya no está en Spark. Los operadores aún pueden liberártelo. {amount} se queda en Spark. No se pudo recuperar nada. @@ -329,16 +368,20 @@ Ahorros Insuficientes La cantidad que puedes transferir a tu saldo de gasto está actualmente limitada a ₿ {amount}. Máximo del saldo de gasto - Transfiera más de ₿ {amount} para cubrir las comisiones de añadirlo a su saldo para gastos. - Importe demasiado bajo + Se necesita un mínimo de ₿ {amount} para configurar tu saldo de gasto. + Saldo mínimo de ahorro 25% Transferir\n<accent>a gasto</accent> + ± A gasto + Bitkit no pudo obtener las comisiones de esta transferencia. Revisa tu conexión e inténtalo de nuevo. Las comisiones son {amount} más altas porque las tasas de comisión o tu saldo de ahorro cambiaron mientras estabas en esta pantalla. Desliza de nuevo para confirmar. Las comisiones han cambiado Listo en unos minutos Tras 3 confirmaciones, unos 30 minutos Comisión de servicio + Lo máximo que puedes transferir ahora es {amount}, porque las tarifas de comisión o tu saldo de ahorro cambiaron mientras estabas en esta pantalla. Desliza de nuevo para confirmar. + Importe modificado Comisión de red Bitkit no pudo obtener las comisiones actuales de esta transferencia. Compruebe su conexión e inténtelo de nuevo. Comisiones no disponibles @@ -349,7 +392,7 @@ Transferir\n<accent>a gasto</accent> Saldo para gastos Instantáneo paga al proveedor para añadir su transferencia a su saldo para gastos antes de que se confirme, normalmente en unos minutos.\n\nMás tarde espera 3 confirmaciones, unos 30 minutos, con una comisión menor. - Transfer\n<accent>speed</accent> + Velocidad de\n<accent>transferencia</accent> Estatus Soporte Reserva total de canales ancla @@ -998,6 +1041,7 @@ {count, plural, one {ENTRADA} many {ENTRADAS (#)} other {ENTRADAS (#)}} Factura Nota de la factura + Mover a Spark Mes siguiente Aún no hay actividad Reciba algunos fondos para empezar @@ -1081,6 +1125,7 @@ Aumenta la comisión personalizada e inténtalo de nuevo. Nota Bitcoin recibido + Bitkit no puede confirmar que esta factura no se pagó antes de restaurar tu monedero. Solicita una nueva factura. Par desconectado. Error al enviar el recibo Enviando recibo @@ -1092,7 +1137,7 @@ Factura copiada al portapapeles Factura Lightning Nota opcional para el pagador - Disfruta de transacciones instantáneas y baratas\ncon amigos, familia\ny comerciantes. + Disfruta de transacciones instantáneas y baratas con amigos, familia y comercios. Recibe en el <accent>saldo de gasto</accent> Mostrar detalles Mostrar código QR @@ -1143,12 +1188,14 @@ Saldo de reserva Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora. No se puede pagar a este contacto + Un retiro anterior de tu saldo de gasto aún se está liquidando. Inténtalo de nuevo cuando termine. Las transferencias al saldo de gasto ya no están disponibles. Bitkit primero comprueba la red y después devuelve las monedas de esta transferencia a tu billetera para que la transferencia original nunca se confirme. Esto tiene una comisión de red. QuickPay Pagando\n<accent>factura...</accent> Confirmar Bitcoin Enviado Ruta + Spark Deslizar para pagar Para Sí, enviar @@ -1382,8 +1429,8 @@ Comisión de Spark Tu transferencia se ha iniciado y se está <accent>liquidando en cadena</accent>. Tu saldo de ahorro se actualizará automáticamente cuando se complete. Transferencia\n<accent>en camino</accent> - Tu saldo de Spark no se ha podido pasar a ahorros y se queda en tu saldo de gastos. - Tu saldo de Spark no se ha podido pasar a ahorros y se queda en tu saldo de gastos. Tus conexiones se están pasando a ahorros. + Tu saldo de Spark no se pudo mover a ahorro y permanece en tu saldo de gasto. + Los fondos de tu canal se están moviendo a ahorro, pero tu saldo de Spark no se pudo mover y permanece en tu saldo de gasto. <accent>Conectando</accent>\na la red Vuelve a conectar tu dispositivo de hardware; parece que se ha desconectado de tu teléfono. Reconecta el dispositivo de hardware diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 7bf2841ec3..6f7c98716a 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -140,6 +140,31 @@ HTLC de entrada mínimo Saldos Lightning Altura de archivo del monitor de canal + Monto + Tu saldo se mueve a Spark por Lightning, la forma de menor comisión de mantenerlo en Gasto. La comisión de enrutamiento de abajo es lo máximo que pagas. + Mover a\n<accent>Spark</accent> + Una parte de tu saldo ya está en Spark. Mueve el resto de la misma forma y luego cierra la conexión vacía. + Tu saldo ya está en Spark. Cierra la conexión vacía para devolver su reserva a Ahorro. + Movido a\n<accent>Spark</accent> + Tus conexiones Lightning ya no tienen saldo que mover. + Spark aún no está listo para recibir. Inténtalo de nuevo en un momento. + No se pudo\n<accent>mover</accent> + Algo salió mal al preparar el movimiento. Inténtalo de nuevo. + Comisión de enrutamiento + El pago está en camino y aparecerá en Spark cuando se liquide. Si falla, el monto permanece en tu conexión. + Moviendo a\n<accent>Spark</accent> + Blocktank está cerrando sus conexiones Lightning. Mueve tu saldo a Spark ahora: es la opción de menor comisión y se mantiene en Gasto. + Tu conexión\n<accent>se está cerrando</accent> + Mover la mitad + Mover ahora + Mover el resto + Mover a Spark + Buscando una ruta y su comisión… + Desliza para mover + Cierra la conexión en su lugar para devolver el saldo a Ahorro. + Puedes moverlo en partes más pequeñas. + %1$s es demasiado grande para enrutarse a Spark en un solo pago. + Monto\n<accent>demasiado grande</accent> Límite del siguiente HTLC saliente Mínimo del siguiente HTLC saliente Antes de que pueda transferir fondos a su saldo de ahorros, tiene que enviar bitcoin a su monedero Bitkit. @@ -157,7 +182,18 @@ Transfiere tu saldo de gastos a tus ahorros para guardar tu Bitcoin a largo plazo y asegurar tu futuro. Por favor espera, la transferencia de tus fondos está en progreso. Esto debería llevar <accent>±10 segundos.</accent> Fondos\n<accent>en transferencia</accent> + Transferencia\n<accent>fallida</accent> Hora de sincronización de puntuaciones de rutas + Aprobar + <accent>La comisión de transferencia rápida ahora es ₿ {amount}.</accent> Aprueba para acceder a tus fondos rápidamente, o espera ±30 min. + Comisión de transferencia rápida\n<accent>modificada</accent> + Añadiendo al saldo de gasto + Comisión de transferencia rápida modificada + Usando velocidad de transferencia normal + ¡Genial! + Espera, la transferencia de tus fondos está en curso. Debería tardar <accent>unos minutos.</accent> + Espera, la transferencia de tus fondos está en curso. Debería tardar <accent>unos 30 minutos.</accent> + Transferencia rápida\n<accent>no disponible</accent> Continuar Usando Bitkit Pago Exitoso Procesando Pago @@ -181,6 +217,9 @@ {amount} llegó a tus ahorros. Tus fondos están en tus ahorros. Salida\n<accent>completada</accent> + Direcciones de salida anteriores + Las salidas de emergencia anteriores usaron estas direcciones de financiación. Las monedas que queden en una siguen siendo tuyas: gástalas con tu frase de recuperación y su ruta de derivación. + Ruta de derivación Los operadores de Spark movieron {amount} on-chain y ya no está en Spark. Los operadores aún pueden liberártelo. {amount} se queda en Spark. No se pudo recuperar nada. @@ -268,14 +307,18 @@ Gastable onchain La cantidad que puedes transferir a tu saldo de gastos está actualmente limitada a ₿ {amount}. Máximo del Saldo de Gastos - Transfiere más de ₿ {amount} para cubrir las comisiones de añadirlo a tu saldo para gastos. - Importe demasiado bajo + Se necesita un mínimo de ₿ {amount} para configurar tu saldo de gasto. + Saldo mínimo de ahorro Transferir\n<accent>a gastos</accent> + ± A gastos + Bitkit no pudo obtener las comisiones de esta transferencia. Revisa tu conexión e inténtalo de nuevo. Las comisiones son {amount} más altas porque las tasas de comisión o su saldo de ahorro cambiaron mientras estaba en esta pantalla. Deslice de nuevo para confirmar. Las comisiones han cambiado Listo en unos minutos Tras 3 confirmaciones, unos 30 minutos + Lo máximo que puedes transferir ahora es {amount}, porque las tarifas de comisión o tu saldo de ahorro cambiaron mientras estabas en esta pantalla. Desliza de nuevo para confirmar. + Monto modificado Reserva total de canales ancla Total Lightning Total onchain @@ -285,7 +328,7 @@ Saldo de\n<accent>Gasto</accent> Saldo de gastos Rellene su <accent>saldo de gastos</accent> - Transferir desde Ahorros + Transferir desde Ahorro Transferir fondos Por favor,\n<accent>confirme</accent> Deslizar para transferir @@ -325,7 +368,7 @@ Ahorro Saldo para gastos Instantáneo paga al proveedor para añadir tu transferencia a tu saldo para gastos antes de que se confirme, normalmente en unos minutos.\n\nMás tarde espera 3 confirmaciones, unos 30 minutos, con una comisión menor. - Transfer\n<accent>speed</accent> + Velocidad de\n<accent>transferencia</accent> Capacidad de recepción Nodo Lightning ID del nodo LDK @@ -959,6 +1002,7 @@ Destino A la red {network} Seguir la entrega entre redes + Mover a Spark Actividad Contactos Perfil @@ -968,6 +1012,7 @@ Estado de la App Soporte Monedero + Bitkit no puede confirmar que esta factura no se pagó antes de restaurar tu monedero. Solicita una nueva factura. Error al enviar el recibo Enviando recibo Recibo enviado @@ -977,7 +1022,9 @@ Enviar Bitcoin Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora. No se puede pagar a este contacto + Un retiro anterior de tu saldo de gasto aún se está liquidando. Inténtalo de nuevo cuando termine. Las transferencias al saldo de gasto ya no están disponibles. Bitkit primero comprueba la red y después devuelve las monedas de esta transferencia a tu billetera para que la transferencia original nunca se confirme. Esto tiene una comisión de red. + Spark Para Contactar Pegar factura @@ -1070,14 +1117,14 @@ Factura bitcoin Factura Lightning Nota opcional para el pagador - Disfruta de transacciones\ninstantáneas y baratas con\namigos, familia y comerciantes. + Disfruta de transacciones instantáneas y baratas con amigos, familia y comercios. Recibir en <accent>saldo de gastos</accent> Mostrar Detalles Mostrar código QR Auto Ahorros Gastos - Recibir fondos de Lightning + Recibir fondos Lightning Actividad Mostrar todo Aún no hay actividad @@ -1381,8 +1428,8 @@ Comisión de Spark Su transferencia se ha iniciado y se está <accent>liquidando onchain</accent>. Su saldo de ahorro se actualizará automáticamente cuando se complete. Transferencia\n<accent>en camino</accent> - Tu saldo de Spark no se ha podido pasar a ahorros y se queda en tu saldo de gastos. - Tu saldo de Spark no se ha podido pasar a ahorros y se queda en tu saldo de gastos. Tus conexiones se están pasando a ahorros. + Tu saldo de Spark no se pudo mover a ahorro y permanece en tu saldo de gasto. + Los fondos de tu canal se están moviendo a ahorro, pero tu saldo de Spark no se pudo mover y permanece en tu saldo de gasto. <accent>Conectando</accent>\na la red Vuelva a conectar su dispositivo de hardware; parece que se ha desconectado de su teléfono. Reconecte el dispositivo de hardware diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 8e2a6b947f..ab52721cf0 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -101,6 +101,42 @@ Utiliser un autre portefeuille Transfert depuis le portefeuille HW Le plus simple est d\'utiliser vos économies Bitkit ou d\'envoyer des bitcoins depuis un autre portefeuille. + Montant + Votre solde passe vers Spark via Lightning, le moyen le moins cher de le garder dans Dépenses. Les frais de routage ci-dessous sont le maximum que vous payez. + Passer à\n<accent>Spark</accent> + Une partie de votre solde est maintenant sur Spark. Déplacez le reste de la même façon, puis fermez la connexion vidée. + Votre solde est maintenant sur Spark. Fermez la connexion vidée pour rendre sa réserve à l\'épargne. + Passé à\n<accent>Spark</accent> + Vos connexions Lightning n\'ont plus de solde à déplacer. + Spark n\'est pas encore prêt à recevoir. Réessayez dans un instant. + Impossible de\n<accent>déplacer</accent> + Une erreur s\'est produite lors de la préparation du transfert. Réessayez. + Frais de routage + Le paiement est en route et apparaîtra dans Spark une fois réglé. En cas d\'échec, le montant reste dans votre connexion. + Passage à\n<accent>Spark</accent> + Blocktank ferme ses connexions Lightning. Déplacez dès maintenant votre solde vers Spark : c\'est l\'option la moins chère, et il reste dans Dépenses. + Votre connexion\n<accent>se ferme</accent> + Déplacer la moitié + Déplacer maintenant + Déplacer le reste + Passer à Spark + Recherche d\'une route et de ses frais… + Glissez pour déplacer + Fermez plutôt la connexion pour rendre le solde à l\'épargne. + Vous pouvez le déplacer en plusieurs parties plus petites. + %1$s est trop élevé pour être acheminé vers Spark en un seul paiement. + Montant\n<accent>trop élevé</accent> + Transfert\n<accent>échoué</accent> + Approuver + <accent>Les frais de transfert rapide sont maintenant de ₿ {amount}.</accent> Approuvez pour accéder rapidement à vos fonds, ou attendez ±30 min. + Frais de transfert rapide\n<accent>modifiés</accent> + Ajout au solde dépenses + Frais de transfert rapide modifiés + Vitesse de transfert normale utilisée + Génial ! + Veuillez patienter, le transfert de vos fonds est en cours. Cela devrait prendre <accent>quelques minutes.</accent> + Veuillez patienter, le transfert de vos fonds est en cours. Cela devrait prendre <accent>environ 30 minutes.</accent> + Transfert rapide\n<accent>indisponible</accent> Spark Frais de réclamation %1$d/3 confirmations @@ -121,6 +157,9 @@ {amount} est arrivé dans votre épargne. Vos fonds sont dans votre épargne. Sortie\n<accent>terminée</accent> + Adresses de sortie précédentes + Les sorties d\'urgence précédentes utilisaient ces adresses de financement. Les pièces laissées sur l\'une d\'elles restent à vous : dépensez-les avec votre phrase de récupération et son chemin de dérivation. + Chemin de dérivation {amount} a été déplacé on-chain par les opérateurs Spark et n\'est pas sur Spark. Les opérateurs peuvent encore vous le libérer. {amount} reste sur Spark. Rien n\'a pu être récupéré. @@ -207,17 +246,21 @@ Ce solde est détenu sur Spark, géré par Lightspark, Breez et Flashnet. Il est en sécurité tant qu’au moins l’un d’eux agit honnêtement. Ils peuvent suspendre l’accès, et en sortir sans eux nécessite une sortie on-chain. Solde Dépenses Financez votre <accent>solde Dépenses</accent> - Transfert depuis l\'épargne + Transférer depuis l\'épargne Configuration manuelle Transfert \n<accent>Dépenses</accent> + ± + Bitkit n\'a pas pu obtenir les frais de ce transfert. Vérifiez votre connexion et réessayez. + Le maximum que vous pouvez transférer est désormais {amount}, car les taux de frais ou votre solde d\'épargne ont changé pendant que vous étiez sur cet écran. Glissez à nouveau pour confirmer. + Montant modifié Transfert de fonds Veuillez\n<accent>confirmer</accent> Glissez pour transférer Ouvrir Trezor Connect 25% Seuil Maximum Épargne - Transférez plus de ₿ {amount} pour couvrir les frais d\'ajout à votre solde de dépenses. - Montant trop faible + Un minimum de ₿ {amount} est nécessaire pour configurer votre solde dépenses. + Solde d\'épargne minimum Le montant que vous pouvez transférer vers votre solde de dépenses est actuellement limité à ₿ {amount}. Frais de réseau Bitkit n\'a pas pu obtenir les frais actuels de ce transfert. Vérifiez votre connexion et réessayez. @@ -273,7 +316,7 @@ Épargner Solde Dépenses Instantané paie le fournisseur pour ajouter votre transfert à votre solde de dépenses avant sa confirmation, généralement en quelques minutes.\n\nPlus tard attend 3 confirmations, environ 30 minutes, pour des frais moins élevés. - Transfer\n<accent>speed</accent> + Vitesse de\n<accent>transfert</accent> Capacité de réception Heure de l\'instantané Rapid Gossip Sync Heure de synchronisation des scores de routage @@ -963,6 +1006,7 @@ Adresse de destination Vers le réseau {network} Suivre la livraison inter-réseaux + Passer à Spark Wallet Activité Contacts @@ -972,6 +1016,7 @@ Config Statut de l\'application Assistance + Bitkit ne peut pas confirmer que cette facture n\'a pas été payée avant la restauration de votre portefeuille. Veuillez demander une nouvelle facture. Échec de l\'envoi du reçu Envoi du reçu Reçu envoyé @@ -980,7 +1025,9 @@ Envoyer des bitcoins Ce contact n\'a aucun moyen de paiement que Bitkit peut utiliser pour le moment. Impossible de payer ce contact + Un retrait précédent de votre solde dépenses est encore en cours de règlement. Réessayez une fois terminé. Les transferts vers le solde de dépenses ne sont plus disponibles. Bitkit vérifie d\'abord le réseau, puis renvoie les pièces de ce transfert vers votre portefeuille afin que le transfert d\'origine ne soit jamais confirmé. Cela coûte des frais de réseau. + Spark Pour Contact Coller la facture @@ -1189,7 +1236,7 @@ Pair déconnecté. Erreur de démarrage de Lightning Recevoir des fonds Lightning - Profitez de transactions instantanées\net peu coûteuses avec vos amis, votre\nfamille et les commerçants. + Profitez de transactions instantanées et peu coûteuses avec vos amis, votre famille et les commerçants. Recevoir sur le <accent>solde dépenses</accent> Afficher les détails Auto @@ -1384,8 +1431,8 @@ Frais Spark Votre transfert a été initié et est <accent>en cours de règlement on-chain</accent>. Votre solde d\'épargne se mettra à jour automatiquement une fois terminé. Transfert\n<accent>en cours</accent> - Votre solde Spark n\'a pas pu être transféré vers l\'épargne et reste dans votre solde de dépenses. - Votre solde Spark n\'a pas pu être transféré vers l\'épargne et reste dans votre solde de dépenses. Vos connexions sont en cours de transfert vers l\'épargne. + Votre solde Spark n\'a pas pu passer à l\'épargne et reste dans votre solde dépenses. + Les fonds de votre canal passent à l\'épargne, mais votre solde Spark n\'a pas pu être déplacé et reste dans votre solde dépenses. <accent>Connexion</accent>\nau réseau Veuillez reconnecter votre appareil matériel, il semble être déconnecté de votre téléphone. Reconnecter l\'appareil matériel diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 0702497a37..841494661a 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -159,7 +159,7 @@ Trasferimento Forzato Non è stato possibile avviare il trasferimento. Vuoi forzare questo trasferimento? Non postrai utilizzare questi fondi per ±14 giorni (!) Trasferimento\n<accent>forzoso</accent> - Trasferimento da risparmio + Trasferisci dai Risparmi Usa un altro portafoglio Trasferimento da wallet HW Conto di Spesa @@ -172,6 +172,31 @@ È utilizzabile? Saldi Lightning Altezza Archivio Monitor Canali + Importo + Il tuo saldo passa a Spark tramite Lightning, il modo con le commissioni più basse per tenerlo nel conto Spesa. La commissione di instradamento qui sotto è il massimo che paghi. + Sposta su\n<accent>Spark</accent> + Una parte del tuo saldo è ora su Spark. Sposta il resto allo stesso modo, poi chiudi la connessione svuotata. + Il tuo saldo è ora su Spark. Chiudi la connessione svuotata per restituire la sua riserva ai Risparmi. + Spostato su\n<accent>Spark</accent> + Le tue connessioni Lightning non hanno più saldo da spostare. + Spark non è ancora pronto a ricevere. Riprova tra un momento. + Impossibile\n<accent>spostare</accent> + Qualcosa è andato storto durante la preparazione dello spostamento. Riprova. + Commissione di instradamento + Il pagamento è in corso e comparirà su Spark una volta completato. Se fallisce, l\'importo resta nella tua connessione. + Spostamento su\n<accent>Spark</accent> + Blocktank sta chiudendo le sue connessioni Lightning. Sposta subito il tuo saldo su Spark: è l\'opzione con le commissioni più basse e resta nel conto Spesa. + La tua connessione\n<accent>si sta chiudendo</accent> + Sposta Metà + Sposta Ora + Sposta Il Resto + Sposta Su Spark + Ricerca di un percorso e della sua commissione… + Swipe Per Spostare + Chiudi invece la connessione per restituire il saldo ai Risparmi. + Puoi spostarlo in parti più piccole. + %1$s è troppo grande per essere instradato su Spark in un solo pagamento. + Importo\n<accent>troppo grande</accent> Limite HTLC in Uscita Successivo HTLC Min in Uscita Successivo Prima di poter trasferire fondi dal tuo conto di risparmio, devi inviare bitcoin al tuo portafoglio Bitkit. @@ -214,7 +239,18 @@ Trasferisci\n<accent>ai risparmi</accent> Attendi, il trasferimento dei fondi e\' in corso. Dovrebbe richiedere <accent>circa 10 secondi.</accent> Fondi\n<accent>in trasferimento</accent> + Trasferimento\n<accent>non riuscito</accent> Tempo Sincronizzazione Punteggi Pathfinding + Approva + <accent>La commissione per il trasferimento rapido è ora ₿ {amount}.</accent> Approva per accedere subito ai tuoi fondi, oppure attendi ±30 min. + Commissione trasferimento rapido\n<accent>modificata</accent> + Aggiunta al saldo di spesa + Commissione trasferimento rapido modificata + Uso della velocità di trasferimento normale + Fantastico! + Attendi, il trasferimento dei tuoi fondi è in corso. Dovrebbe richiedere <accent>qualche minuto.</accent> + Attendi, il trasferimento dei tuoi fondi è in corso. Dovrebbe richiedere <accent>circa 30 minuti.</accent> + Trasferimento rapido\n<accent>non disponibile</accent> Continua ad utilizzare Bitkit Elaborazione del pagamento Pagamento Riuscito @@ -238,6 +274,9 @@ {amount} è arrivato nei tuoi risparmi. I tuoi fondi sono nei risparmi. Uscita\n<accent>completata</accent> + Indirizzi di uscita precedenti + Le precedenti uscite di emergenza usavano questi indirizzi di finanziamento. Le monete rimaste su uno di essi restano tue: spendile con la tua frase di recupero e il suo percorso di derivazione. + Percorso di derivazione {amount} è stato spostato on-chain dagli operatori Spark e non è su Spark. Gli operatori possono ancora sbloccarlo per te. {amount} resta su Spark. Non è stato possibile recuperare nulla. @@ -328,16 +367,20 @@ Risparmi insufficienti L\'importo che puoi trasferire al tuo conto di spesa e\' attualmente limitato a ₿ {amount}. Massimo Conto di Spesa - Trasferisci più di ₿ {amount}, così copre le commissioni per aggiungerlo al tuo conto di spesa. - Importo troppo basso + È necessario un minimo di ₿ {amount} per configurare il tuo saldo di spesa. + Saldo minimo dei risparmi 25% Trasferisci\n<accent>alle spese</accent> + ± Alle spese + Bitkit non è riuscito a ottenere le commissioni per questo trasferimento. Controlla la connessione e riprova. Le commissioni sono aumentate di {amount} perché i tassi di commissione o il saldo dei tuoi risparmi sono cambiati mentre eri su questa schermata. Scorri di nuovo per confermare. Commissioni cambiate Pronto in pochi minuti Dopo 3 conferme, circa 30 minuti Commissioni servizio + Il massimo che puoi trasferire ora è {amount}, perché le tariffe delle commissioni o il tuo saldo dei risparmi sono cambiati mentre eri su questa schermata. Scorri di nuovo per confermare. + Importo modificato Commissioni rete Bitkit non è riuscito a ottenere le commissioni attuali per questo trasferimento. Controlla la connessione e riprova. Commissioni non disponibili @@ -348,7 +391,7 @@ Trasferisci\n<accent>alle spese</accent> Conto di spesa Istantanea paga il fornitore per aggiungere il tuo trasferimento al conto di spesa prima della conferma, di solito in pochi minuti.\n\nPiù tardi attende 3 conferme, circa 30 minuti, con una commissione più bassa. - Transfer\n<accent>speed</accent> + Velocità di\n<accent>trasferimento</accent> Stato Supporto Riserva Totale Canali Anchor @@ -998,6 +1041,7 @@ {count, plural, one {INGRESSO} many {INGRESSI (#)} other {ENTRATE (#)}} Invoice Nota invoice + Sposta su Spark Mese prossimo Nessuna attività ancora Ricevi dei fondi per iniziare @@ -1082,6 +1126,7 @@ Aumenta la commissione personalizzata e riprova. Note Bitcoin ricevuti + Bitkit non può confermare che questa fattura non sia stata pagata prima del ripristino del tuo wallet. Richiedi una nuova fattura. Peer disconnesso. Invio della ricevuta non riuscito Invio della ricevuta @@ -1093,7 +1138,7 @@ Fattura copiata negli appunti Lightning invoice Nota opzionale per chi paga - Goditi transazioni istantanee\ned economiche con amici, familiari\ne commercianti. + Goditi transazioni istantanee ed economiche con amici, familiari ed esercenti. Ricevi sul <accent>conto di spesa</accent> Mostra Dettagli Visualizza QR Code @@ -1144,6 +1189,7 @@ Saldo di Riserva Questo contatto non ha alcun metodo di pagamento che Bitkit possa usare ora. Impossibile pagare questo contatto + Un precedente prelievo dal tuo saldo di spesa è ancora in fase di regolamento. Riprova al termine. I trasferimenti al saldo di spesa non sono più disponibili. Bitkit controlla prima la rete, poi rimanda le monete di questo trasferimento al tuo wallet, così il trasferimento originale non potrà mai essere confermato. Questo costa una commissione di rete. Questo pagamento sta richiedendo un po\' più tempo del previsto. Puoi continuare a utilizzare Bitkit. Pagamento in sospeso @@ -1152,6 +1198,7 @@ Conferma Bitcoin Inviati Percorso + Spark Scorri per Pagare A Si, Invia @@ -1387,8 +1434,8 @@ Commissione Spark Il tuo trasferimento è stato avviato ed è <accent>in regolamento on-chain</accent>. Il saldo dei tuoi risparmi si aggiornerà automaticamente al termine. Trasferimento\n<accent>in corso</accent> - Il saldo Spark non è stato spostato nei risparmi e resta nel saldo di spesa. - Il saldo Spark non è stato spostato nei risparmi e resta nel saldo di spesa. Le tue connessioni stanno passando ai risparmi. + Il tuo saldo Spark non è stato spostato nei risparmi e resta nel tuo saldo di spesa. + I fondi del tuo canale vengono spostati nei risparmi, ma il tuo saldo Spark non è stato spostato e resta nel tuo saldo di spesa. <accent>Connessione</accent>\nalla rete Ricollega il tuo dispositivo hardware, sembra essere disconnesso dal telefono. Ricollega il Dispositivo Hardware diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 61cbdea222..4bbd57d24d 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -171,6 +171,31 @@ Is bruikbaar Lightning-saldi Kanaalmonitor archiveringshoogte + Bedrag + Je saldo gaat via Lightning naar Spark, de goedkoopste manier om het in je bestedingssaldo te houden. De routeringskosten hieronder zijn het maximum dat je betaalt. + Verplaatsen naar\n<accent>Spark</accent> + Een deel van je saldo staat nu op Spark. Verplaats de rest op dezelfde manier en sluit daarna de lege verbinding. + Je saldo staat nu op Spark. Sluit de lege verbinding om de reserve terug te zetten naar spaargeld. + Verplaatst naar\n<accent>Spark</accent> + Je Lightning-verbindingen hebben geen saldo meer om te verplaatsen. + Spark is nog niet klaar om te ontvangen. Probeer het zo opnieuw. + Verplaatsen\n<accent>mislukt</accent> + Er ging iets mis bij het voorbereiden van de verplaatsing. Probeer opnieuw. + Routeringskosten + De betaling is onderweg en verschijnt in Spark zodra ze is afgerond. Als ze mislukt, blijft het bedrag in je verbinding. + Verplaatsen naar\n<accent>Spark</accent> + Blocktank sluit zijn Lightning-verbindingen. Verplaats je saldo nu naar Spark: dat is de goedkoopste optie en het blijft in je bestedingssaldo. + Je verbinding\n<accent>wordt gesloten</accent> + Helft verplaatsen + Nu verplaatsen + Rest verplaatsen + Verplaatsen naar Spark + Route en kosten zoeken… + Veeg om te verplaatsen + Sluit in plaats daarvan de verbinding om het saldo terug te zetten naar spaargeld. + Je kunt het in kleinere delen verplaatsen. + %1$s is te groot om in één betaling naar Spark te routeren. + Bedrag\n<accent>te groot</accent> Volgende uitgaande HTLC-limiet Volgende uitgaande HTLC min Voordat je geld van je spaargeld kunt overboeken, moet je bitcoin naar je Bitkit-wallet sturen. @@ -213,7 +238,18 @@ Overboeken\n<accent>naar spaargeld</accent> Even geduld, je geld wordt overgeboekt. Dit duurt <accent>±10 seconden.</accent> Geld\n<accent>in overboeking</accent> + Overboeking\n<accent>mislukt</accent> Pathfinding scores synchronisatietijd + Goedkeuren + <accent>De kosten voor snel overboeken zijn nu ₿ {amount}.</accent> Keur goed om snel bij je geld te komen, of wacht ±30 min. + Kosten snel overboeken\n<accent>gewijzigd</accent> + Toevoegen aan bestedingssaldo + Kosten snel overboeken gewijzigd + Normale overboekingssnelheid gebruiken + Geweldig! + Even geduld, je geld wordt overgeboekt. Dit duurt <accent>een paar minuten.</accent> + Even geduld, je geld wordt overgeboekt. Dit duurt <accent>ongeveer 30 minuten.</accent> + Snel overboeken\n<accent>niet beschikbaar</accent> Doorgaan met Bitkit Betaling verwerken Betaling succesvol @@ -237,6 +273,9 @@ {amount} is in je spaargeld aangekomen. Je geld staat in je spaargeld. Exit\n<accent>voltooid</accent> + Eerdere exitadressen + Eerdere noodexits gebruikten deze financieringsadressen. Munten die op een adres zijn achtergebleven blijven van jou: besteed ze met je herstelzin en het bijbehorende afleidingspad. + Afleidingspad {amount} is door de Spark-beheerders on-chain verplaatst en staat niet op Spark. De beheerders kunnen het nog steeds aan je vrijgeven. {amount} blijft op Spark. Er kon niets worden teruggehaald. @@ -327,16 +366,20 @@ Onvoldoende spaargeld Het bedrag dat je kunt overboeken naar je bestedingssaldo is momenteel beperkt tot ₿ {amount}. Maximum bestedingssaldo - Boek meer dan ₿ {amount} over, zodat de kosten om het aan je bestedingssaldo toe te voegen gedekt zijn. - Bedrag te klein + Er is minimaal ₿ {amount} nodig om je bestedingssaldo in te stellen. + Minimaal spaarsaldo 25% Overboeken\n<accent>naar bestedingssaldo</accent> + ± Naar bestedingssaldo + Bitkit kon de kosten voor deze overboeking niet ophalen. Controleer je verbinding en probeer opnieuw. De vergoedingen zijn {amount} hoger, omdat de vergoedingstarieven of uw spaargeld zijn gewijzigd terwijl u op dit scherm was. Veeg opnieuw om te bevestigen. Vergoedingen gewijzigd Klaar binnen enkele minuten Na 3 bevestigingen, ongeveer 30 minuten Servicevergoedingen + Het maximale bedrag dat je kunt overboeken is nu {amount}, omdat de tarieven of je spaarsaldo zijn gewijzigd terwijl je op dit scherm was. Veeg opnieuw om te bevestigen. + Bedrag gewijzigd Netwerkvergoedingen Bitkit kon de huidige kosten voor deze overboeking niet ophalen. Controleer je verbinding en probeer het opnieuw. Kosten niet beschikbaar @@ -347,7 +390,7 @@ Overboeken\n<accent>naar bestedingssaldo</accent> Bestedingssaldo Direct betaalt de aanbieder om je overboeking al vóór de bevestiging aan je bestedingssaldo toe te voegen, meestal binnen enkele minuten.\n\nLater wacht op 3 bevestigingen, ongeveer 30 minuten, tegen lagere kosten. - Transfer\n<accent>speed</accent> + Overboekings\n<accent>snelheid</accent> Status Ondersteuning Totale ankerkanalen reserve @@ -993,6 +1036,7 @@ {count, plural, one {INVOER} other {INVOEREN (#)}} Factuur Factuurnotitie + Verplaatsen naar Spark Volgende maand Nog geen activiteit Ontvang wat geld om te beginnen @@ -1077,6 +1121,7 @@ Verhoog de aangepaste vergoeding en probeer het opnieuw. Notitie Bitcoin ontvangen + Bitkit kan niet bevestigen dat deze factuur niet is betaald voordat je je wallet herstelde. Vraag een nieuwe factuur aan. Peer niet verbonden. Ontvangstbewijs verzenden mislukt Ontvangstbewijs verzenden @@ -1088,7 +1133,7 @@ Factuur gekopieerd naar klembord Lightning-factuur Optionele notitie voor betaler - Geniet van directe en goedkope\ntransacties met vrienden, familie\nen winkeliers. + Geniet van directe en goedkope transacties met vrienden, familie en winkeliers. Ontvangen op <accent>bestedingssaldo</accent> Details tonen QR-code tonen @@ -1139,6 +1184,7 @@ Reservesaldo Dit contact heeft nu geen betaalmethode die Bitkit kan gebruiken. Kan dit contact niet betalen + Een eerdere opname van je bestedingssaldo wordt nog verwerkt. Probeer het opnieuw zodra die is voltooid. Overboekingen naar je bestedingssaldo zijn niet meer beschikbaar. Bitkit controleert eerst het netwerk en stuurt de munten van deze overboeking dan terug naar je wallet, zodat de oorspronkelijke overboeking nooit bevestigd wordt. Dit kost netwerkkosten. Deze betaling duurt iets langer dan verwacht. U kunt Bitkit blijven gebruiken. Betaling Onderweg @@ -1147,6 +1193,7 @@ Bevestigen Bitcoin verzonden Route + Spark Veeg om te betalen Naar Ja, verzenden @@ -1383,8 +1430,8 @@ Spark-vergoeding Uw overboeking is gestart en wordt <accent>on-chain afgehandeld</accent>. Uw spaargeld wordt automatisch bijgewerkt zodra deze is voltooid. Overboeking\n<accent>onderweg</accent> - Je Spark-saldo kon niet naar sparen en blijft in je bestedingssaldo. - Je Spark-saldo kon niet naar sparen en blijft in je bestedingssaldo. Je verbindingen gaan naar sparen. + Je Spark-saldo kon niet naar spaargeld worden overgeboekt en blijft in je bestedingssaldo. + Je kanaalfondsen worden naar spaargeld overgeboekt, maar je Spark-saldo kon niet worden verplaatst en blijft in je bestedingssaldo. <accent>Verbinden</accent>\nmet netwerk Verbind uw hardwareapparaat opnieuw, de verbinding met uw telefoon lijkt verbroken. Hardwareapparaat opnieuw verbinden diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index db4c3150cc..d17a12c48a 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -103,6 +103,42 @@ Użyj innego portfela Prześlij z portfela HW Najłatwiejszą opcją jest użycie oszczędności Bitkit lub wysłanie bitcoinów z innego portfela. + Kwota + Twoje saldo przechodzi do Spark przez Lightning, najtańszym sposobem na zachowanie go w Wydatkach. Opłata za routing poniżej to maksimum, jakie zapłacisz. + Przenieś do\n<accent>Spark</accent> + Część Twojego salda jest już w Spark. Przenieś resztę w ten sam sposób, a potem zamknij opróżnione połączenie. + Twoje saldo jest już w Spark. Zamknij opróżnione połączenie, aby zwrócić jego rezerwę do Oszczędności. + Przeniesiono do\n<accent>Spark</accent> + Twoje połączenia Lightning nie mają już salda do przeniesienia. + Spark nie jest jeszcze gotowy do odbioru. Spróbuj ponownie za chwilę. + Nie udało się\n<accent>przenieść</accent> + Coś poszło nie tak podczas przygotowywania przeniesienia. Spróbuj ponownie. + Opłata za routing + Płatność jest w drodze i pojawi się w Spark po rozliczeniu. Jeśli się nie powiedzie, kwota pozostanie w Twoim połączeniu. + Przenoszenie do\n<accent>Spark</accent> + Blocktank zamyka swoje połączenia Lightning. Przenieś teraz saldo do Spark: to najtańsza opcja i środki pozostają w Wydatkach. + Twoje połączenie\n<accent>się zamyka</accent> + Przenieś połowę + Przenieś teraz + Przenieś resztę + Przenieś do Spark + Szukanie trasy i opłaty… + Przesuń, aby przenieść + Zamiast tego zamknij połączenie, aby zwrócić saldo do Oszczędności. + Możesz je przenieść w mniejszych częściach. + Kwota %1$s jest zbyt duża, aby przesłać ją do Spark jedną płatnością. + Kwota\n<accent>zbyt duża</accent> + Transfer\n<accent>nieudany</accent> + Zatwierdź + <accent>Opłata za szybki transfer wynosi teraz ₿ {amount}.</accent> Zatwierdź, aby szybko uzyskać dostęp do środków, lub poczekaj ±30 min. + Opłata za szybki transfer\n<accent>zmieniona</accent> + Dodawanie do salda wydatków + Opłata za szybki transfer zmieniona + Użycie normalnej szybkości transferu + Świetnie! + Proszę czekać, trwa transfer Twoich środków. Powinno to zająć <accent>kilka minut.</accent> + Proszę czekać, trwa transfer Twoich środków. Powinno to zająć <accent>około 30 minut.</accent> + Szybki transfer\n<accent>niedostępny</accent> Spark Opłata za odbiór %1$d/3 potwierdzeń @@ -123,6 +159,9 @@ {amount} trafiło do Twoich Oszczędności. Twoje środki są w Oszczędnościach. Wyjście\n<accent>zakończone</accent> + Wcześniejsze adresy wyjścia + Wcześniejsze wyjścia awaryjne używały tych adresów finansowania. Monety pozostawione na którymś z nich nadal są Twoje: wydaj je za pomocą frazy odzyskiwania i ścieżki derywacji. + Ścieżka derywacji {amount} zostało przeniesione on-chain przez operatorów Spark i nie jest na Spark. Operatorzy wciąż mogą Ci je zwolnić. {amount} pozostaje na Spark. Nie udało się niczego odzyskać. @@ -212,14 +251,18 @@ Prześlij z Oszczędności Konfiguracja ręczna Prześlij \n<accent>na saldo wydatków</accent> + ± + Bitkit nie mógł pobrać opłat za ten transfer. Sprawdź połączenie i spróbuj ponownie. + Maksymalna kwota do przesłania wynosi teraz {amount}, ponieważ stawki opłat lub Twoje saldo oszczędności zmieniły się, gdy byłeś na tym ekranie. Przesuń ponownie, aby potwierdzić. + Kwota zmieniona Prześlij środki Proszę \n<accent>potwierdzić</accent> Przesuń, aby przesłać Otwórz Trezor Connect 25% Maksymalne saldo wydatków - Prześlij więcej niż ₿ {amount}, aby pokryć opłaty za dodanie do salda wydatków. - Kwota zbyt mała + Do skonfigurowania salda wydatków potrzeba co najmniej ₿ {amount}. + Minimalne saldo oszczędności Kwota, którą można przelać na saldo wydatków, jest obecnie ograniczona do ₿ {amount}. Opłaty sieciowe Bitkit nie mógł pobrać aktualnych opłat za ten przelew. Sprawdź połączenie i spróbuj ponownie. @@ -275,7 +318,7 @@ Oszczędności Saldo wydatków Natychmiast płaci dostawcy za dodanie przelewu do salda wydatków jeszcze przed potwierdzeniem, zwykle w kilka minut.\n\nPóźniej czeka na 3 potwierdzenia, około 30 minut, z niższą opłatą. - Transfer\n<accent>speed</accent> + Szybkość\n<accent>transferu</accent> Zdolność odbioru Węzeł Lightning Identyfikator węzła LDK @@ -965,6 +1008,7 @@ Na adres Do sieci {network} Śledź dostarczenie między sieciami + Przenieś do Spark Portfel Aktywność Kontakty @@ -974,6 +1018,7 @@ Ustawienia Status aplikacji Wsparcie + Bitkit nie może potwierdzić, że ta faktura nie została opłacona przed przywróceniem portfela. Poproś o nową fakturę. Nie udało się wysłać potwierdzenia Wysyłanie potwierdzenia Potwierdzenie wysłane @@ -982,7 +1027,9 @@ Wyślij Bitcoin Ten kontakt nie ma teraz metody płatności, której Bitkit może użyć. Nie można zapłacić temu kontaktowi + Wcześniejsza wypłata z Twojego salda wydatków wciąż się rozlicza. Spróbuj ponownie po jej zakończeniu. Przelewy na saldo wydatków nie są już dostępne. Bitkit najpierw sprawdza sieć, a potem odsyła monety z tego przelewu do Twojego portfela, aby pierwotny przelew nigdy nie został potwierdzony. Wiąże się to z opłatą sieciową. + Spark Do Kontakt Wklej fakturę @@ -1195,7 +1242,7 @@ Węzeł rozłączony. Błąd uruchamiania Lightning Odbierz środki Lightning - Ciesz się natychmiastowymi i tanimi\ntransakcjami z przyjaciółmi, rodziną\ni sprzedawcami. + Ciesz się natychmiastowymi i tanimi transakcjami z przyjaciółmi, rodziną i sprzedawcami. Odbierz na <accent>saldo wydatków</accent> Pokaż szczegóły Auto @@ -1387,8 +1434,8 @@ Opłata Spark Twój transfer został zainicjowany i jest <accent>rozliczany on-chain</accent>. Saldo oszczędności zaktualizuje się automatycznie po jego zakończeniu. Transfer\n<accent>w drodze</accent> - Nie udało się przenieść salda Spark do oszczędności; pozostaje w saldzie wydatków. - Nie udało się przenieść salda Spark do oszczędności; pozostaje w saldzie wydatków. Twoje połączenia są przenoszone do oszczędności. + Twojego salda Spark nie udało się przenieść do Oszczędności i pozostaje ono w saldzie wydatków. + Środki z Twoich kanałów są przenoszone do Oszczędności, ale Twojego salda Spark nie udało się przenieść i pozostaje ono w saldzie wydatków. <accent>Łączenie</accent>\nz siecią Połącz ponownie urządzenie sprzętowe, wygląda na to, że zostało odłączone od telefonu. Połącz ponownie urządzenie diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 8ec81691da..4943bd5f61 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -175,6 +175,31 @@ É utilizável Saldos Lightning Altura de Arquivamento do Monitor de Canal + Valor + Seu saldo passa para a Spark através da Lightning, a forma mais barata de o manter nos Gastos. A taxa de roteamento abaixo é o máximo que paga. + Mover para a\n<accent>Spark</accent> + Parte dseu saldo já está na Spark. Mova o resto da mesma forma e depois feche a conexão esvaziada. + Seu saldo já está na Spark. Feche a conexão esvaziada para devolver a reserva dela à poupança. + Movido para a\n<accent>Spark</accent> + Suas conexões Lightning não têm mais saldo para mover. + A Spark ainda não está pronta para receber. Tente novamente em instantes. + Não foi possível\n<accent>mover</accent> + Algo deu errado ao preparar a movimentação. Tente novamente. + Taxa de roteamento + O pagamento está a caminho e aparece na Spark quando for concluído. Se falhar, o valor fica na sua conexão. + Movendo para a\n<accent>Spark</accent> + A Blocktank está fechando as suas conexões Lightning. Mova já seu saldo para a Spark: é a opção mais barata e fica nos Gastos. + Sua conexão\n<accent>está fechando</accent> + Mover metade + Mover agora + Mover o restante + Mover para a Spark + Buscando rota e taxa… + Deslizar Para Mover + Em vez disso, feche a conexão para devolver o saldo à poupança. + Você pode movê-lo em partes menores. + %1$s é grande demais para ser roteado para a Spark num único pagamento. + Valor\n<accent>grande demais</accent> Limite do Próximo HTLC de Saída HTLC de Saída Mín Próximo Antes de transferir fundos de seu saldo de poupança, receba bitcoin na sua carteira Bitkit. @@ -217,7 +242,18 @@ Transferir\n<accent>para poupança</accent> Aguarde, sua transferência de fundos está em andamento. Isso deve levar <accent>±10 segundos.</accent> <accent>Transferindo</accent>\nfundos + Transferência\n<accent>falhou</accent> Sincronização de Scores de Roteamento + Aprovar + <accent>A taxa da transferência rápida é agora ₿ {amount}.</accent> Aprove para acessar seus fundos rapidamente ou aguarde ±30 min. + Taxa da transferência rápida\n<accent>alterada</accent> + Adicionando ao saldo de gastos + Taxa da transferência rápida alterada + Usando velocidade de transferência normal + Incrível! + Aguarde, a transferência dos seus fundos está em andamento. Isso deve levar <accent>alguns minutos.</accent> + Aguarde, a transferência dos seus fundos está em andamento. Isso deve levar <accent>cerca de 30 minutos.</accent> + Transferência rápida\n<accent>indisponível</accent> Continuar Usando o Bitkit Processando Pagamento Pagamento Realizado @@ -241,6 +277,9 @@ {amount} chegou à sua poupança. Seus fundos estão na poupança. Saída\n<accent>concluída</accent> + Endereços de saída anteriores + As saídas de emergência anteriores usaram estes endereços de financiamento. As moedas deixadas em um deles continuam sendo suas: gaste-as com sua frase de recuperação e o respectivo caminho de derivação. + Caminho de derivação {amount} foi movido on-chain pelos operadores da Spark e não está na Spark. Os operadores ainda podem liberá-lo para você. {amount} fica na Spark. Nada pôde ser recuperado. @@ -331,16 +370,20 @@ Saldo de Poupança Insuficiente O valor que você pode transferir para seu saldo de gastos está atualmente limitado a ₿ {amount}. Saldo de gastos Máximo - Transfira mais de ₿ {amount} para cobrir as taxas de adicioná-la ao seu saldo de gastos. - Valor muito baixo + É necessário um mínimo de ₿ {amount} para configurar seu saldo de gastos. + Saldo mínimo da poupança 25% Transferir\n<accent>para gastos</accent> + ± Para gastos + O Bitkit não conseguiu obter as taxas desta transferência. Verifique sua conexão e tente novamente. As taxas estão {amount} mais altas porque as taxas de rede ou seu saldo de poupança mudaram enquanto você estava nesta tela. Deslize novamente para confirmar. Taxas alteradas Pronto em poucos minutos Após 3 confirmações, cerca de 30 minutos Taxa de serviço + O máximo que pode transferir é agora {amount}, porque as taxas ou seu saldo de poupança mudaram enquanto estava neste ecrã. Deslize novamente para confirmar. + Valor alterado Taxa da rede O Bitkit não conseguiu obter as taxas atuais desta transferência. Verifique sua conexão e tente novamente. Taxas indisponíveis @@ -351,7 +394,7 @@ Transferir\n<accent>para gastos</accent> Saldo de gastos Instantâneo paga ao provedor para adicionar sua transferência ao saldo de gastos antes de ela ser confirmada, normalmente em poucos minutos.\n\nDepois aguarda 3 confirmações, cerca de 30 minutos, com uma taxa menor. - Transfer\n<accent>speed</accent> + Velocidade da\n<accent>transferência</accent> Status Suporte Reserva Total de Canais Anchor @@ -1002,6 +1045,7 @@ {count, plural, one {ENTRADA} many {ENTRADAS (#)} other {ENTRADAS (#)}} Invoice Descrição do invoice + Mover para a Spark Próximo mês Nenhuma atividade ainda Receba alguns bitcoins para começar @@ -1086,6 +1130,7 @@ Aumente a taxa personalizada e tente novamente. Nota Bitcoin Recebido + O Bitkit não consegue confirmar que esta fatura não foi paga antes de você restaurar sua carteira. Peça uma nova fatura. Peer desconectado. Falha ao enviar o recibo Enviando recibo @@ -1097,7 +1142,7 @@ Invoice copiado para a área de transferência. Invoice Lightning Comentário opcional para o pagador - Aproveite transações instantâneas\ne baratas com amigos, família\ne comerciantes. + Aproveite transações instantâneas e baratas com amigos, familiares e comerciantes. Receba no <accent>saldo de gastos</accent> Mostrar Detalhes Mostrar código QR @@ -1148,6 +1193,7 @@ Saldo de reserva Este contato não tem nenhum método de pagamento que o Bitkit possa usar agora. Não é possível pagar este contato + Um levantamento anterior dseu saldo de gastos ainda está a ser concluído. Tente novamente quando for concluído. As transferências para o saldo de gastos não estão mais disponíveis. O Bitkit primeiro verifica a rede e depois devolve as moedas desta transferência para sua carteira, para que a transferência original nunca seja confirmada. Isso tem uma taxa de rede. Esse pagamento está demorando mais do que o esperado. Enquanto isso, você pode continuar usando a Bitkit. Pagamento Pendente @@ -1156,6 +1202,7 @@ Confirmar Bitcoin Enviado Rota + Spark Deslize para Pagar Para Sim, Enviar @@ -1389,8 +1436,8 @@ Taxa do Spark Sua transferência foi iniciada e está sendo <accent>liquidada onchain</accent>. Seu saldo de poupança será atualizado automaticamente quando ela for concluída. Transferência\n<accent>a caminho</accent> - Não foi possível mover seu saldo do Spark para a poupança; ele continua no saldo de gastos. - Não foi possível mover seu saldo do Spark para a poupança; ele continua no saldo de gastos. Suas conexões estão sendo movidas para a poupança. + Seu saldo Spark não pôde ser movido para a poupança e fica nseu saldo de gastos. + Os fundos dos seus canais estão sendo movidos para a poupança, mas seu saldo Spark não pôde ser movido e fica nseu saldo de gastos. <accent>Conectando</accent>\nà rede Reconecte seu dispositivo de hardware, ele parece estar desconectado do seu telefone. Reconectar Dispositivo de Hardware diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index fb66951439..568d501692 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -98,6 +98,42 @@ Transferir de Outra Carteira Transferir da carteira HW A forma mais fácil é usar as suas poupanças Bitkit ou enviar bitcoin de uma carteira diferente. + Montante + O seu saldo passa para a Spark através da Lightning, a forma mais barata de o manter nos Gastos. A taxa de roteamento abaixo é o máximo que paga. + Mover para a\n<accent>Spark</accent> + Parte do seu saldo já está na Spark. Mova o resto da mesma forma e depois feche a conexão esvaziada. + O seu saldo já está na Spark. Feche a conexão esvaziada para devolver a sua reserva à poupança. + Movido para a\n<accent>Spark</accent> + As suas conexões Lightning já não têm saldo para mover. + A Spark ainda não está pronta para receber. Tente novamente dentro de instantes. + Não foi possível\n<accent>mover</accent> + Algo correu mal ao preparar a movimentação. Tente novamente. + Taxa de roteamento + O pagamento está a caminho e aparece na Spark quando for concluído. Se falhar, o montante fica na sua conexão. + A mover para a\n<accent>Spark</accent> + A Blocktank está a fechar as suas conexões Lightning. Mova já o seu saldo para a Spark: é a opção mais barata e fica nos Gastos. + A sua conexão\n<accent>está a fechar</accent> + Mover metade + Mover agora + Mover o resto + Mover para a Spark + A procurar rota e taxa… + Deslizar Para Mover + Em vez disso, feche a conexão para devolver o saldo à poupança. + Pode movê-lo em partes mais pequenas. + %1$s é demasiado grande para ser encaminhado para a Spark num único pagamento. + Montante\n<accent>demasiado grande</accent> + Transferência\n<accent>falhada</accent> + Aprovar + <accent>A taxa da transferência rápida é agora ₿ {amount}.</accent> Aprove para aceder rapidamente aos seus fundos ou aguarde ±30 min. + Taxa da transferência rápida\n<accent>alterada</accent> + A adicionar ao saldo de gastos + Taxa da transferência rápida alterada + A usar velocidade de transferência normal + Fantástico! + Aguarde, a transferência dos seus fundos está em curso. Isto deve demorar <accent>alguns minutos.</accent> + Aguarde, a transferência dos seus fundos está em curso. Isto deve demorar <accent>cerca de 30 minutos.</accent> + Transferência rápida\n<accent>indisponível</accent> Spark Taxa de resgate %1$d/3 confirmações @@ -118,6 +154,9 @@ {amount} chegou à sua poupança. Os seus fundos estão na poupança. Saída\n<accent>concluída</accent> + Endereços de saída anteriores + As saídas de emergência anteriores usaram estes endereços de financiamento. As moedas deixadas num deles continuam a ser suas: gaste-as com a sua frase de recuperação e o respetivo caminho de derivação. + Caminho de derivação {amount} foi movido on-chain pelos operadores da Spark e não está na Spark. Os operadores ainda o podem libertar para si. {amount} fica na Spark. Não foi possível recuperar nada. @@ -204,17 +243,21 @@ Este saldo é mantido na Spark, operada pela Lightspark, Breez e Flashnet. Está seguro enquanto pelo menos um deles agir com honestidade. Podem suspender o acesso, e sair sem eles exige uma saída on-chain. Saldo de Gastos Transfira para seu <accent>saldo de gastos</accent> - Transferir do Saldo de Poupança + Transferir da poupança Setup Manual Transferir\n<accent>para gastos</accent> + ± + A Bitkit não conseguiu obter as taxas desta transferência. Verifique a sua ligação e tente novamente. + O máximo que pode transferir é agora {amount}, porque as taxas ou o seu saldo de poupança mudaram enquanto estava neste ecrã. Deslize novamente para confirmar. + Montante alterado Transf. fundos Por favor\n<accent>confirme</accent> Deslizar Para Transferir Abrir Trezor Connect 25% Saldo de gastos Máximo - Transfira mais de ₿ {amount} para cobrir as taxas de a adicionar ao seu saldo de gastos. - Montante demasiado baixo + É necessário um mínimo de ₿ {amount} para configurar o seu saldo de gastos. + Saldo mínimo da poupança O valor que você pode transferir para seu saldo de gastos está atualmente limitado a ₿ {amount}. Taxa da rede A Bitkit não conseguiu obter as taxas atuais desta transferência. Verifique a sua ligação e tente novamente. @@ -270,7 +313,7 @@ Poupança Saldo de gastos Instantâneo paga ao fornecedor para adicionar a sua transferência ao saldo de gastos antes de ser confirmada, normalmente em poucos minutos.\n\nDepois aguarda 3 confirmações, cerca de 30 minutos, com uma taxa mais baixa. - Transfer\n<accent>speed</accent> + Velocidade da\n<accent>transferência</accent> Capacidade de recebimento Nó Lightning ID do LDK Node @@ -829,6 +872,7 @@ Single Random Draw Configurações do sistema Idioma + Mover para a Spark Carteira Atividade Contatos @@ -838,6 +882,7 @@ Ajustes Status do Aplicativo Suporte + A Bitkit não consegue confirmar que esta fatura não foi paga antes de restaurar a sua carteira. Peça uma nova fatura. Falha ao enviar o recibo A enviar recibo Recibo enviado @@ -846,7 +891,9 @@ Enviar Bitcoin Este contacto não tem nenhum método de pagamento que a Bitkit possa usar agora. Não é possível pagar a este contacto + Um levantamento anterior do seu saldo de gastos ainda está a ser concluído. Tente novamente quando terminar. As transferências para o saldo de gastos já não estão disponíveis. A Bitkit verifica primeiro a rede e depois devolve as moedas desta transferência à sua carteira, para que a transferência original nunca seja confirmada. Isto tem uma taxa de rede. + Spark Para Contato Colar Invoice @@ -1044,7 +1091,7 @@ Gastos Mostrar Detalhes Receba no <accent>saldo de gastos</accent> - Aproveite transações instantâneas e baratas\ncom amigos, familiares\ne comerciantes. + Aproveite transações instantâneas e baratas com amigos, familiares e comerciantes. Transação Substituída Sua transação foi substituída por um aumento de taxa Transação Recebida Substituída @@ -1358,8 +1405,8 @@ Taxa do Spark A sua transferência foi iniciada e está a ser <accent>liquidada on-chain</accent>. O saldo de poupança será atualizado automaticamente quando terminar. Transferência\n<accent>a caminho</accent> - Não foi possível mover o saldo do Spark para a poupança; continua no saldo de gastos. - Não foi possível mover o saldo do Spark para a poupança; continua no saldo de gastos. As suas ligações estão a ser movidas para a poupança. + O seu saldo Spark não pôde ser movido para a poupança e fica no seu saldo de gastos. + Os fundos dos seus canais estão a ser movidos para a poupança, mas o seu saldo Spark não pôde ser movido e fica no seu saldo de gastos. <accent>A ligar</accent>\nà rede Volte a ligar o seu dispositivo de hardware; parece estar desligado do telemóvel. Voltar a ligar o dispositivo diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index e061c8cc57..21d2ce7fc6 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -170,7 +170,7 @@ Принудительный Перевод Не удалось инициировать перевод. Хотите выполнить принудительный перевод? Вы не сможете использовать эти средства в течение ±14 дней (!) Принудительный\n<accent>Перевод</accent> - Перевести из Сбережений + Перевести из сбережений Использовать Другой Кошелёк Перевести с аппаратного кошелька Баланс Расходов @@ -183,6 +183,31 @@ Можно Использовать Балансы Lightning Архивная высота мониторинга канала + Сумма + Ваш баланс переходит в Spark через Lightning — это самый дешёвый способ сохранить его в расходах. Комиссия за маршрутизацию ниже — максимум, который вы заплатите. + Перенос в\n<accent>Spark</accent> + Часть вашего баланса уже в Spark. Перенесите остаток так же, затем закройте опустевшее соединение. + Ваш баланс уже в Spark. Закройте опустевшее соединение, чтобы вернуть его резерв в сбережения. + Перенесено в\n<accent>Spark</accent> + В ваших Lightning-соединениях не осталось баланса для переноса. + Spark пока не готов к получению. Попробуйте ещё раз чуть позже. + Не удалось\n<accent>перенести</accent> + Что-то пошло не так при подготовке переноса. Попробуйте ещё раз. + Комиссия за маршрутизацию + Платёж в пути и появится в Spark после завершения. Если он не пройдёт, сумма останется в вашем соединении. + Перенос в\n<accent>Spark</accent> + Blocktank закрывает свои Lightning-соединения. Перенесите баланс в Spark сейчас: это самый дешёвый вариант, и средства остаются в расходах. + Ваше соединение\n<accent>закрывается</accent> + Перенести половину + Перенести сейчас + Перенести остаток + Перенос в Spark + Поиск маршрута и комиссии… + Проведите для переноса + Вместо этого закройте соединение, чтобы вернуть баланс в сбережения. + Вы можете перенести его меньшими частями. + %1$s слишком много для маршрутизации в Spark одним платежом. + Сумма\n<accent>слишком велика</accent> Лимит след. исходящего HTLC Мин. след. исходящего HTLC Прежде чем вы сможете перевести средства со своего баланса сбережений, вам нужно отправить биткойны в ваш кошелёк Bitkit. @@ -225,7 +250,18 @@ Перевод\n<accent>в Сбережения</accent> Пожалуйста, подождите, ваш перевод средств выполняется. Это займёт <accent>±10 секунд.</accent> Средства\n<accent>в Процессе Перевода</accent> + Перевод\n<accent>не удался</accent> Время синхронизации оценок маршрутизации + Подтвердить + <accent>Комиссия за быстрый перевод теперь ₿ {amount}.</accent> Подтвердите, чтобы быстро получить доступ к средствам, или подождите ±30 мин. + Комиссия за быстрый перевод\n<accent>изменилась</accent> + Зачисление на баланс расходов + Комиссия за быстрый перевод изменилась + Используется обычная скорость перевода + Отлично! + Пожалуйста, подождите, идёт перевод ваших средств. Это займёт <accent>несколько минут.</accent> + Пожалуйста, подождите, идёт перевод ваших средств. Это займёт <accent>около 30 минут.</accent> + Быстрый перевод\n<accent>недоступен</accent> Продолжить Использование Bitkit Обработка Платежа Платеж Успешен @@ -249,6 +285,9 @@ {amount} поступили в ваши сбережения. Ваши средства в сбережениях. Выход\n<accent>завершён</accent> + Прежние адреса выхода + Прежние экстренные выходы использовали эти адреса пополнения. Монеты, оставшиеся на одном из них, по-прежнему ваши: потратьте их с помощью фразы восстановления и пути деривации. + Путь деривации {amount} операторы Spark перевели ончейн, и этих средств больше нет в Spark. Операторы всё ещё могут выдать их вам. {amount} остаются в Spark. Ничего не удалось вернуть. @@ -339,16 +378,20 @@ Недостаточно Сбережений Сумма, которую вы можете перевести на баланс расходов, в настоящее время ограничена ₿ {amount}. Максимум Баланса Расходов - Переведите больше ₿ {amount}, чтобы покрыть комиссии за зачисление на баланс расходов. - Слишком маленькая сумма + Для настройки баланса расходов нужно не менее ₿ {amount}. + Минимум баланса сбережений 25% Перевод\n<accent>на Расходы</accent> + ± На Баланс Расходов + Bitkit не удалось получить комиссии за этот перевод. Проверьте соединение и попробуйте ещё раз. Комиссии выросли на {amount}, потому что ставки комиссий или баланс сбережений изменились, пока вы были на этом экране. Проведите ещё раз для подтверждения. Комиссии изменились Готово через несколько минут После 3 подтверждений, около 30 минут Сервисные Комиссии + Максимум для перевода теперь {amount}, потому что ставки комиссий или ваш баланс сбережений изменились, пока вы были на этом экране. Проведите ещё раз для подтверждения. + Сумма изменилась Сетевые Комиссии Bitkit не смог получить текущие комиссии за этот перевод. Проверьте соединение и попробуйте снова. Комиссии недоступны @@ -359,7 +402,7 @@ Перевод\n<accent>на Расходы</accent> Баланс Расходов Мгновенно платит провайдеру, чтобы зачислить перевод на баланс расходов до подтверждения, обычно за несколько минут.\n\nПозже ждёт 3 подтверждений, около 30 минут, с меньшей комиссией. - Transfer\n<accent>speed</accent> + Скорость\n<accent>перевода</accent> Статус Поддержка Общий резерв Anchor каналов @@ -1015,6 +1058,7 @@ {count, plural, one {ВВОД} few {ВВОДЫ (#)} many {ВВОДЫ (#)} other {ВВОДЫ (#)}} Инвойс Заметка инвойса + Перенести в Spark Следующий месяц Пока нет транзакций Получите немного средств, чтобы начать @@ -1099,6 +1143,7 @@ Увеличьте заданную комиссию и попробуйте снова. Заметка Получен Биткоин + Bitkit не может подтвердить, что этот счёт не был оплачен до восстановления вашего кошелька. Запросите новый счёт. Пир отключён. Не удалось отправить квитанцию Отправка квитанции @@ -1110,9 +1155,7 @@ Инвойс скопирован в буфер обмена Лайтнинг инвойс Опциональная заметка для плательщика - Наслаждайтесь мгновенными и недорогими -транзакциями с друзьями, семьёй -и продавцами. + Наслаждайтесь мгновенными и недорогими транзакциями с друзьями, семьёй и продавцами. Получить на <accent>баланс расходов</accent> Показать детали Показать QR-код @@ -1163,6 +1206,7 @@ Резервный баланс У этого контакта сейчас нет способа оплаты, который может использовать Bitkit. Невозможно оплатить этому контакту + Предыдущий вывод с вашего баланса расходов ещё проводится. Попробуйте ещё раз после его завершения. Переводы на баланс расходов больше недоступны. Bitkit сначала проверяет сеть, а затем возвращает монеты этого перевода в ваш кошелёк, чтобы исходный перевод никогда не подтвердился. За это взимается сетевая комиссия. Этот платеж занимает больше времени, чем ожидалось. Вы можете продолжать использовать Bitkit. Платеж в ожидании @@ -1172,6 +1216,7 @@ Подтвердить Биткоины отправлены Маршрут + Spark Отправить Кому Да, Отправить @@ -1405,8 +1450,8 @@ Комиссия Spark Ваш перевод инициирован и <accent>проводится в блокчейне</accent>. Баланс сбережений обновится автоматически после завершения. Перевод\n<accent>в пути</accent> - Не удалось перевести баланс Spark в сбережения, он остаётся в балансе расходов. - Не удалось перевести баланс Spark в сбережения, он остаётся в балансе расходов. Ваши соединения переводятся в сбережения. + Ваш баланс Spark не удалось перевести в сбережения, он остаётся на балансе расходов. + Средства ваших каналов переводятся в сбережения, но баланс Spark перевести не удалось, он остаётся на балансе расходов. <accent>Подключение</accent>\nк сети Переподключите аппаратное устройство: похоже, оно отключилось от телефона. Переподключите Аппаратное Устройство From 001af49fc2c08d9d98e76fb119a83a20250e8439 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 15:18:26 +0100 Subject: [PATCH 06/96] chore: tidy spark follow-ups for lint Stub the now-suspending move check in the send flow tests, drop translations of two keys English marks untranslatable, wrap long lines, and add the Activity row to the move-to-spark journey. Verified: detekt, lintDevDebug, MoveToSparkRepoTest, BackupRepoTest, AppViewModelSendFlowTest, MoveToSparkViewModelTest --- .../java/to/bitkit/repositories/BackupRepo.kt | 4 +++- .../wallets/activity/ActivityDetailScreen.kt | 2 +- .../wallets/activity/components/ActivityRow.kt | 2 +- .../ui/settings/lightning/MoveToSparkManager.kt | 2 +- app/src/main/res/values-ar/strings.xml | 2 -- app/src/main/res/values-b+es+419/strings.xml | 2 -- app/src/main/res/values-ca/strings.xml | 2 -- app/src/main/res/values-cs/strings.xml | 2 -- app/src/main/res/values-de/strings.xml | 2 -- app/src/main/res/values-el/strings.xml | 2 -- app/src/main/res/values-es-rES/strings.xml | 2 -- app/src/main/res/values-es/strings.xml | 2 -- app/src/main/res/values-fr/strings.xml | 2 -- app/src/main/res/values-it/strings.xml | 2 -- app/src/main/res/values-nl/strings.xml | 2 -- app/src/main/res/values-pl/strings.xml | 2 -- app/src/main/res/values-pt-rBR/strings.xml | 2 -- app/src/main/res/values-pt/strings.xml | 2 -- app/src/main/res/values-ru/strings.xml | 2 -- .../to/bitkit/repositories/BackupRepoTest.kt | 2 +- .../bitkit/repositories/MoveToSparkRepoTest.kt | 16 ++++++++++++---- .../viewmodels/AppViewModelSendFlowTest.kt | 5 ++++- journeys/transfer/move-to-spark.xml | 2 ++ 23 files changed, 25 insertions(+), 40 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 14e6752e0d..57b5bd48c0 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -720,7 +720,9 @@ class BackupRepo @Inject constructor( if (!sparkRepo.hasMergedRemoteExitState) { sparkRepo.exitBackup().getOrThrow() ?: throw SparkExitBackupDeferred() val stored = vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name).getOrThrow()?.value - val remote = stored?.let { runCatching { json.decodeFromString(String(it)) }.getOrNull() } + val remote = stored?.let { bytes -> + runCatching { json.decodeFromString(String(bytes)) }.getOrNull() + } val merged = if (stored != null && remote == null) { Result.failure(SparkError.ExitStateUnimportable()) } else { diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt index 7779b41a3a..8cea520cee 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt @@ -57,8 +57,8 @@ import to.bitkit.ext.UiDateStyle import to.bitkit.ext.contact import to.bitkit.ext.create import to.bitkit.ext.ellipsisMiddle -import to.bitkit.ext.isSent import to.bitkit.ext.isMoveToSpark +import to.bitkit.ext.isSent import to.bitkit.ext.isTransfer import to.bitkit.ext.rawId import to.bitkit.ext.timestamp diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityRow.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityRow.kt index b085ac0a51..e75c238a29 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityRow.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityRow.kt @@ -31,8 +31,8 @@ import com.synonym.bitkitcore.Activity import com.synonym.bitkitcore.PaymentState import com.synonym.bitkitcore.PaymentType import to.bitkit.R -import to.bitkit.ext.isSent import to.bitkit.ext.isMoveToSpark +import to.bitkit.ext.isSent import to.bitkit.ext.isTransfer import to.bitkit.ext.timestamp import to.bitkit.ext.totalValue diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt index 8a27a6c3b0..b77b6122ff 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt @@ -9,6 +9,7 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import to.bitkit.async.appScope import to.bitkit.di.BgDispatcher import to.bitkit.ext.filterOpen import to.bitkit.repositories.LightningRepo @@ -17,7 +18,6 @@ import to.bitkit.repositories.MoveToSparkMath import to.bitkit.repositories.MoveToSparkOutcome import to.bitkit.repositories.MoveToSparkRepo import to.bitkit.repositories.WalletRepo -import to.bitkit.async.appScope import java.util.concurrent.atomic.AtomicInteger import javax.inject.Inject import javax.inject.Singleton diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 645dc84503..6b2b63d0d4 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -366,7 +366,6 @@ الحد الأدنى لرصيد المدخرات 25% تحويل\n<accent>إلى الإنفاق</accent> - ± إلى الإنفاق تعذّر على Bitkit الحصول على رسوم هذا التحويل. تحقق من اتصالك وحاول مرة أخرى. الرسوم أعلى بمقدار {amount} لأن معدلات الرسوم أو رصيد مدخراتك تغيّر أثناء وجودك في هذه الشاشة. اسحب مرة أخرى للتأكيد. @@ -1169,7 +1168,6 @@ تأكيد تم إرسال Bitcoin المسار - Spark اسحب للدفع إلى نعم، أرسل diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index a279730347..990f8a7c97 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -373,7 +373,6 @@ Mínimo del saldo de ahorros 25% Transferir\n<accent>a gastos</accent> - ± Hacia Gastos Bitkit no pudo obtener las comisiones de esta transferencia. Revisa tu conexión e inténtalo de nuevo. Las comisiones son {amount} más altas porque las tarifas o su saldo de ahorros cambiaron mientras estaba en esta pantalla. Deslice de nuevo para confirmar. @@ -1202,7 +1201,6 @@ Confirmar Bitcoin Enviado Ruta - Spark Deslizar para pagar Para Sí, enviar diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 937fdd0583..19a78ec4fa 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -370,7 +370,6 @@ Mínim del saldo d\'estalvis 25% Transferir\n<accent>a despesa</accent> - ± A despesa Bitkit no ha pogut obtenir les comissions d\'aquesta transferència. Comprova la connexió i torna-ho a provar. Les tarifes són {amount} més altes perquè les taxes de tarifa o el teu saldo d\'estalvis han canviat mentre eres en aquesta pantalla. Torna a desplaçar per confirmar. @@ -1195,7 +1194,6 @@ Confirmar Bitcoin enviat Ruta - Spark Desplaça per pagar A Sí, Enviar diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 6b5d6427e8..6707b699ee 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -373,7 +373,6 @@ Minimální zůstatek úspor 25% Převést\n<accent>do výdajů</accent> - ± Do výdajů Bitkit nedokázal získat poplatky za tento převod. Zkontrolujte připojení a zkuste to znovu. Poplatky jsou o {amount} vyšší, protože se během zobrazení této obrazovky změnily sazby poplatků nebo zůstatek vašich úspor. Pro potvrzení přejeďte znovu. @@ -1200,7 +1199,6 @@ Potvrdit bitcoin odeslán Trasa - Spark Zaplatit přejetím prstem Komu Ano, odeslat diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index d4614fa751..36dddb6c6c 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -250,7 +250,6 @@ Von Sparkonto übertragen Manuelle Einrichtung <accent>zu den Ausgaben</accent> - ± Bitkit konnte die Gebühren für diese Übertragung nicht abrufen. Prüfe deine Verbindung und versuche es erneut. Du kannst jetzt höchstens {amount} übertragen, weil sich die Gebührensätze oder dein Sparguthaben geändert haben, während du auf diesem Bildschirm warst. Wische erneut, um zu bestätigen. Betrag geändert @@ -1026,7 +1025,6 @@ Zahlung an diesen Kontakt nicht möglich Eine frühere Auszahlung von deinem Ausgabenguthaben wird noch abgewickelt. Versuche es erneut, sobald sie abgeschlossen ist. Überweisungen auf dein Ausgabenguthaben sind nicht mehr verfügbar. Bitkit prüft zuerst das Netzwerk und schickt die Coins dieser Überweisung dann zurück in deine Wallet, damit die ursprüngliche Überweisung nie bestätigt wird. Dafür fällt eine Netzwerkgebühr an. - Spark An Kontakt Rechnung einfügen diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index c3bf7031bd..5384e45e8c 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -366,7 +366,6 @@ Ελάχιστο υπόλοιπο αποταμίευσης 25% Μεταφορά\n<accent>σε δαπάνες</accent> - ± Σε δαπάνες Το Bitkit δεν μπόρεσε να λάβει τα τέλη για αυτή τη μεταφορά. Έλεγξε τη σύνδεσή σου και δοκίμασε ξανά. Τα τέλη είναι {amount} υψηλότερα, επειδή τα ποσοστά τελών ή το υπόλοιπο αποταμιεύσεων άλλαξαν ενώ ήσουν σε αυτή την οθόνη. Σύρε ξανά για επιβεβαίωση. @@ -1174,7 +1173,6 @@ Επιβεβαίωση Τα Bitcoin στάλθηκαν Διαδρομή - Spark Σύρε για πληρωμή Προς Ναι, Στείλε diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 823c985554..6ff0e34176 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -372,7 +372,6 @@ Saldo mínimo de ahorro 25% Transferir\n<accent>a gasto</accent> - ± A gasto Bitkit no pudo obtener las comisiones de esta transferencia. Revisa tu conexión e inténtalo de nuevo. Las comisiones son {amount} más altas porque las tasas de comisión o tu saldo de ahorro cambiaron mientras estabas en esta pantalla. Desliza de nuevo para confirmar. @@ -1195,7 +1194,6 @@ Confirmar Bitcoin Enviado Ruta - Spark Deslizar para pagar Para Sí, enviar diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 6f7c98716a..c41ca5c6eb 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -310,7 +310,6 @@ Se necesita un mínimo de ₿ {amount} para configurar tu saldo de gasto. Saldo mínimo de ahorro Transferir\n<accent>a gastos</accent> - ± A gastos Bitkit no pudo obtener las comisiones de esta transferencia. Revisa tu conexión e inténtalo de nuevo. Las comisiones son {amount} más altas porque las tasas de comisión o su saldo de ahorro cambiaron mientras estaba en esta pantalla. Deslice de nuevo para confirmar. @@ -1024,7 +1023,6 @@ No se puede pagar a este contacto Un retiro anterior de tu saldo de gasto aún se está liquidando. Inténtalo de nuevo cuando termine. Las transferencias al saldo de gasto ya no están disponibles. Bitkit primero comprueba la red y después devuelve las monedas de esta transferencia a tu billetera para que la transferencia original nunca se confirme. Esto tiene una comisión de red. - Spark Para Contactar Pegar factura diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index ab52721cf0..fbe60802f5 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -249,7 +249,6 @@ Transférer depuis l\'épargne Configuration manuelle Transfert \n<accent>Dépenses</accent> - ± Bitkit n\'a pas pu obtenir les frais de ce transfert. Vérifiez votre connexion et réessayez. Le maximum que vous pouvez transférer est désormais {amount}, car les taux de frais ou votre solde d\'épargne ont changé pendant que vous étiez sur cet écran. Glissez à nouveau pour confirmer. Montant modifié @@ -1027,7 +1026,6 @@ Impossible de payer ce contact Un retrait précédent de votre solde dépenses est encore en cours de règlement. Réessayez une fois terminé. Les transferts vers le solde de dépenses ne sont plus disponibles. Bitkit vérifie d\'abord le réseau, puis renvoie les pièces de ce transfert vers votre portefeuille afin que le transfert d\'origine ne soit jamais confirmé. Cela coûte des frais de réseau. - Spark Pour Contact Coller la facture diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 841494661a..71e80c3c6b 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -371,7 +371,6 @@ Saldo minimo dei risparmi 25% Trasferisci\n<accent>alle spese</accent> - ± Alle spese Bitkit non è riuscito a ottenere le commissioni per questo trasferimento. Controlla la connessione e riprova. Le commissioni sono aumentate di {amount} perché i tassi di commissione o il saldo dei tuoi risparmi sono cambiati mentre eri su questa schermata. Scorri di nuovo per confermare. @@ -1198,7 +1197,6 @@ Conferma Bitcoin Inviati Percorso - Spark Scorri per Pagare A Si, Invia diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 4bbd57d24d..f94d19ffed 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -370,7 +370,6 @@ Minimaal spaarsaldo 25% Overboeken\n<accent>naar bestedingssaldo</accent> - ± Naar bestedingssaldo Bitkit kon de kosten voor deze overboeking niet ophalen. Controleer je verbinding en probeer opnieuw. De vergoedingen zijn {amount} hoger, omdat de vergoedingstarieven of uw spaargeld zijn gewijzigd terwijl u op dit scherm was. Veeg opnieuw om te bevestigen. @@ -1193,7 +1192,6 @@ Bevestigen Bitcoin verzonden Route - Spark Veeg om te betalen Naar Ja, verzenden diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index d17a12c48a..ec7b060058 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -251,7 +251,6 @@ Prześlij z Oszczędności Konfiguracja ręczna Prześlij \n<accent>na saldo wydatków</accent> - ± Bitkit nie mógł pobrać opłat za ten transfer. Sprawdź połączenie i spróbuj ponownie. Maksymalna kwota do przesłania wynosi teraz {amount}, ponieważ stawki opłat lub Twoje saldo oszczędności zmieniły się, gdy byłeś na tym ekranie. Przesuń ponownie, aby potwierdzić. Kwota zmieniona @@ -1029,7 +1028,6 @@ Nie można zapłacić temu kontaktowi Wcześniejsza wypłata z Twojego salda wydatków wciąż się rozlicza. Spróbuj ponownie po jej zakończeniu. Przelewy na saldo wydatków nie są już dostępne. Bitkit najpierw sprawdza sieć, a potem odsyła monety z tego przelewu do Twojego portfela, aby pierwotny przelew nigdy nie został potwierdzony. Wiąże się to z opłatą sieciową. - Spark Do Kontakt Wklej fakturę diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 4943bd5f61..d98102aca2 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -374,7 +374,6 @@ Saldo mínimo da poupança 25% Transferir\n<accent>para gastos</accent> - ± Para gastos O Bitkit não conseguiu obter as taxas desta transferência. Verifique sua conexão e tente novamente. As taxas estão {amount} mais altas porque as taxas de rede ou seu saldo de poupança mudaram enquanto você estava nesta tela. Deslize novamente para confirmar. @@ -1202,7 +1201,6 @@ Confirmar Bitcoin Enviado Rota - Spark Deslize para Pagar Para Sim, Enviar diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 568d501692..96468c81c9 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -246,7 +246,6 @@ Transferir da poupança Setup Manual Transferir\n<accent>para gastos</accent> - ± A Bitkit não conseguiu obter as taxas desta transferência. Verifique a sua ligação e tente novamente. O máximo que pode transferir é agora {amount}, porque as taxas ou o seu saldo de poupança mudaram enquanto estava neste ecrã. Deslize novamente para confirmar. Montante alterado @@ -893,7 +892,6 @@ Não é possível pagar a este contacto Um levantamento anterior do seu saldo de gastos ainda está a ser concluído. Tente novamente quando terminar. As transferências para o saldo de gastos já não estão disponíveis. A Bitkit verifica primeiro a rede e depois devolve as moedas desta transferência à sua carteira, para que a transferência original nunca seja confirmada. Isto tem uma taxa de rede. - Spark Para Contato Colar Invoice diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 21d2ce7fc6..e73eeec7b1 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -382,7 +382,6 @@ Минимум баланса сбережений 25% Перевод\n<accent>на Расходы</accent> - ± На Баланс Расходов Bitkit не удалось получить комиссии за этот перевод. Проверьте соединение и попробуйте ещё раз. Комиссии выросли на {amount}, потому что ставки комиссий или баланс сбережений изменились, пока вы были на этом экране. Проведите ещё раз для подтверждения. @@ -1216,7 +1215,6 @@ Подтвердить Биткоины отправлены Маршрут - Spark Отправить Кому Да, Отправить diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 82a1bd18f1..475149f063 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -94,10 +94,10 @@ import to.bitkit.models.WalletScope import to.bitkit.models.WatchOnlyAccountRecord import to.bitkit.models.WatchOnlyAccountSetupState import to.bitkit.models.WidgetsBackupV1 -import to.bitkit.services.SparkError import to.bitkit.services.AddressDerivationInfo import to.bitkit.services.LightningService import to.bitkit.services.PaykitSdkService +import to.bitkit.services.SparkError import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture import to.bitkit.utils.AppError diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index 076deb9b3d..53b4bec4fa 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -232,7 +232,9 @@ class MoveToSparkRepoTest : BaseUnitTest() { @Test fun `move pays over the channels capped at the quoted fee and reports the fee paid`() = test { - whenever(lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull())).thenReturn(Result.success("id")) + whenever( + lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) + ).thenReturn(Result.success("id")) val moving = async { sut.move(quote) } nodeEvents.emit(Event.PaymentSuccessful("other", "other_hash", null, 1_000uL)) @@ -249,7 +251,9 @@ class MoveToSparkRepoTest : BaseUnitTest() { @Test fun `move matches a failure without its hash by the payment id`() = test { - whenever(lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull())).thenReturn(Result.success("id")) + whenever( + lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) + ).thenReturn(Result.success("id")) val moving = async { sut.move(quote) } nodeEvents.emit(Event.PaymentFailed("other", null, PaymentFailureReason.ROUTE_NOT_FOUND)) @@ -261,7 +265,9 @@ class MoveToSparkRepoTest : BaseUnitTest() { @Test fun `move reports a payment without an outcome in time as in flight`() = test { - whenever(lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull())).thenReturn(Result.success("id")) + whenever( + lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) + ).thenReturn(Result.success("id")) // Nothing settles it, so the virtual clock runs to the end of the wait. assertEquals(inFlight, sut.move(quote).getOrThrow()) assertTrue(sut.isWatchedMovePayment("hash").not(), "a move no one waits on still mutes the app's notices") @@ -269,7 +275,9 @@ class MoveToSparkRepoTest : BaseUnitTest() { @Test fun `a move's payment stays a move after a restart`() = test { - whenever(lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull())).thenReturn(Result.success("id")) + whenever( + lightningRepo.payInvoiceOverLdk(any(), any(), anyOrNull(), anyOrNull()) + ).thenReturn(Result.success("id")) sut.move(quote) assertTrue(createSut().isMovePayment("HASH"), "a restart forgot the move's payment") diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 3b45e96c05..71f471fbbf 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -1045,7 +1045,10 @@ class AppViewModelSendFlowTest : BaseUnitTest() { on { type } doReturn TimedSheetType.MOVE_TO_SPARK onBlocking { shouldShow() } doReturn false }, - moveToSparkRepo = mock { on { canMove } doReturn emptyFlow() }, + moveToSparkRepo = mock { + on { canMove } doReturn emptyFlow() + onBlocking { isMovePayment(any()) } doReturn false + }, formatMoneyValue = formatMoneyValue, widgetsRepo = widgetsRepo, wakeRepo = wakeRepo, diff --git a/journeys/transfer/move-to-spark.xml b/journeys/transfer/move-to-spark.xml index 2379e4c496..bbf26d9ad4 100644 --- a/journeys/transfer/move-to-spark.xml +++ b/journeys/transfer/move-to-spark.xml @@ -25,5 +25,7 @@ Swipe to move (testTag "MoveToSparkSwipe") and verify "Moved to Spark" shows the moved amount (testTag "MoveToSparkMoved") and "Close" (testTag "MoveToSparkClose") Tap "Close" (testTag "MoveToSparkClose"), then "Close" on the close confirmation, and verify Lightning Connections shows no open connection and the Spark balance grew by the moved amount Go back to Home, open Spending and verify the "Move To Spark" button is gone + Open All Activity and verify the move shows as one outgoing row titled "Move to Spark" with the transfer icon (testTag "MoveToSparkIcon") and the moved amount plus the routing fee, and no received row + Tap the "Move to Spark" row and verify the detail's title is "Move to Spark" and it shows the routing fee From 8b6dfd7dae5a71a11e0e29840ccff67d5acce2a4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 15:24:22 +0100 Subject: [PATCH 07/96] fix: keep staged exit data and a reopened move screen A closed Move to Spark screen's late cleanup no longer clears the quote of a screen opened after it. Skipping unimportable stored exit data drops a staged restore only when it holds that same data. Verified: detekt, BackupRepoTest, MoveToSparkViewModelTest, SparkRepoTest, MoveToSparkRepoTest --- .../java/to/bitkit/repositories/BackupRepo.kt | 7 +++--- .../java/to/bitkit/repositories/SparkRepo.kt | 13 +++++------ .../settings/lightning/MoveToSparkManager.kt | 22 +++++++++++++------ .../lightning/MoveToSparkViewModel.kt | 6 ++--- .../to/bitkit/repositories/BackupRepoTest.kt | 2 +- .../lightning/MoveToSparkViewModelTest.kt | 16 +++++++++++--- 6 files changed, 39 insertions(+), 27 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 57b5bd48c0..a9e8c8fb39 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -730,7 +730,7 @@ class BackupRepo @Inject constructor( } merged.recoverCatching { if (it !is SparkError.ExitStateUnimportable || stored == null) throw it - keepUnimportableExitBackup(stored) + keepUnimportableExitBackup(stored, remote?.exitState) }.getOrThrow() } val backup = sparkRepo.exitBackup().getOrThrow() ?: throw SparkExitBackupDeferred() @@ -740,10 +740,9 @@ class BackupRepo @Inject constructor( ).getOrThrow() } - /** Keeps stored exit data Spark can never import under its own key, so the fresh export doesn't replace it. */ - private suspend fun keepUnimportableExitBackup(stored: ByteArray) { + private suspend fun keepUnimportableExitBackup(stored: ByteArray, exitState: String?) { vssBackupClient.putObject(key = SPARK_EXIT_UNIMPORTED_KEY, data = stored).getOrThrow() - sparkRepo.skipUnimportableRemoteExitState() + sparkRepo.skipUnimportableRemoteExitState(exitState) Logger.warn("Kept unimportable Spark exit data under '$SPARK_EXIT_UNIMPORTED_KEY'", context = TAG) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 8b04ef061c..9260f7d9f2 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1159,10 +1159,11 @@ class SparkRepo @Inject constructor( /** * Stops merging stored exit data Spark can never import, which the caller kept apart, so the next upload replaces - * it; a staged restore of it is dropped too. + * it. A staged restore is dropped only when it holds that same [exitState]; other staged data still imports. */ - fun skipUnimportableRemoteExitState() { - File(Env.sparkExitRestorePath(walletIndex)).delete() + fun skipUnimportableRemoteExitState(exitState: String?) { + val staged = File(Env.sparkExitRestorePath(walletIndex)) + if (exitState != null && staged.exists() && staged.readText() == exitState) staged.delete() hasMergedRemoteExitState = true } @@ -1749,17 +1750,13 @@ class SparkRepo @Inject constructor( private fun recordedSince(records: Long): Set = sendRecordedAt.filterValues { it > records }.keys - /** The payment hash of this send, at [status] when given. */ - /** - * Whether this failed send started before the uncertain send of its hash, so it is an earlier attempt's. Spark - * dates a payment when it starts it, in epoch seconds; with the start unknown, as after a restart, it is not. - */ private fun Payment.isEarlierFailureOfUncertainSend(): Boolean { val hash = sendHash(PaymentStatus.FAILED) ?: return false val sentAt = uncertainSends[hash.lowercase()]?.sentAt ?: return false return timestamp < sentAt } + /** The payment hash of this send, at [status] when given. */ private fun Payment.sendHash(status: PaymentStatus? = null): String? = (details as? PaymentDetails.Lightning) ?.takeIf { paymentType == SparkPaymentType.SEND && (status == null || this.status == status) } ?.htlcDetails?.paymentHash diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt index b77b6122ff..5b1fb9290e 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt @@ -44,6 +44,7 @@ class MoveToSparkManager @Inject constructor( /** Counts quotes, moves and resets; a quote or move writes its result only while it is still the latest. */ private val generation = AtomicInteger(0) + private val latestScreen = AtomicInteger(0) private var quoteJob: Job? = null /** A move was started and its outcome is still the screen's, so opening the screen again keeps it. */ @@ -54,15 +55,22 @@ class MoveToSparkManager @Inject constructor( @Volatile private var isMoveInFlight = false - /** Opens the screen: quotes a new move, unless one is quoting or a move is running or still shows its outcome. */ - fun start() { - if (keepsOutcome || quoteJob?.isActive == true) return - quote() + /** + * Opens the screen: quotes a new move, unless one is quoting or a move is running or still shows its outcome. + * Returns the screen's token for [reset]. + */ + fun start(): Int { + val screen = latestScreen.incrementAndGet() + if (!keepsOutcome && quoteJob?.isActive != true) quote() + return screen } - /** Forgets the last move once its screen is left, unless its payment is still in flight. */ - fun reset() { - if (isMoveInFlight) return + /** + * Forgets the last move once its [screen] is left, unless its payment is still in flight or a newer screen opened + * before this one closed. + */ + fun reset(screen: Int) { + if (screen != latestScreen.get() || isMoveInFlight) return generation.incrementAndGet() quoteJob?.cancel() keepsOutcome = false diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModel.kt index 29f3c69b2c..d883139998 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModel.kt @@ -15,9 +15,7 @@ class MoveToSparkViewModel @Inject constructor( val uiState = manager.uiState - init { - manager.start() - } + private val screen = manager.start() /** Quotes moving [targetSats], or everything the channels can send. */ fun quote(targetSats: ULong? = null) = manager.quote(targetSats) @@ -25,7 +23,7 @@ class MoveToSparkViewModel @Inject constructor( fun move() = manager.move() override fun onCleared() { - manager.reset() + manager.reset(screen) } } diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 475149f063..a41b9d6431 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -435,7 +435,7 @@ class BackupRepoTest : BaseUnitTest() { inOrder(sparkRepo, vssBackupClient) { verify(vssBackupClient).putObject(BackupRepo.SPARK_EXIT_UNIMPORTED_KEY, stored) - verify(sparkRepo).skipUnimportableRemoteExitState() + verify(sparkRepo).skipUnimportableRemoteExitState("v9") verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) } } diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt index a00298f56b..e11b96d67a 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt @@ -108,7 +108,7 @@ class MoveToSparkViewModelTest : BaseUnitTest() { whenever(moveToSparkRepo.move(eq(quote))).doSuspendableAnswer { payment.await() } createViewModel().move() - manager.reset() + manager.reset(screen = 1) val reopened = createViewModel() assertEquals(MoveToSparkUiState.Confirm(quote, isMoving = true), reopened.uiState.value) @@ -122,7 +122,7 @@ class MoveToSparkViewModelTest : BaseUnitTest() { fun `leaving the screen while a move is in flight keeps waiting for its outcome`() = test { createViewModel().move() - manager.reset() + manager.reset(screen = 1) val reopened = createViewModel() firstSettled.complete(Result.success(moved)) @@ -134,12 +134,22 @@ class MoveToSparkViewModelTest : BaseUnitTest() { whenever(moveToSparkRepo.move(eq(quote))).thenReturn(Result.success(moved)) createViewModel().move() - manager.reset() + manager.reset(screen = 1) val reopened = createViewModel() assertEquals(MoveToSparkUiState.Confirm(quote), reopened.uiState.value) verify(moveToSparkRepo, times(2)).quote(anyOrNull()) } + @Test + fun `a closed screen's late cleanup leaves the reopened screen's quote`() = test { + createViewModel() + val reopened = createViewModel() + + manager.reset(screen = 1) + + assertEquals(MoveToSparkUiState.Confirm(quote), reopened.uiState.value) + } + private fun createViewModel() = MoveToSparkViewModel(manager) } From 114f3a88c8599598a35515f49fde0082f80c02fb Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 15:51:52 +0100 Subject: [PATCH 08/96] fix: match ios on move backup, exit set-aside and move rows Back up move to Spark hashes in the metadata envelope as bitkit-ios does (lowercase, sorted, left out when empty, read leniently) and merge them on restore. Set unimportable exit data aside under SPARK_EXIT_REJECTED, keeping the first copy and a different one under its digest. List moves under Other, not Sent, and keep a pending or failed move's row with its status. Verified: just test, just lint --- app/src/main/java/to/bitkit/ext/Activities.kt | 2 +- .../java/to/bitkit/models/BackupPayloads.kt | 33 +++++++ .../java/to/bitkit/repositories/BackupRepo.kt | 30 +++++- .../activity/components/ActivityIcon.kt | 2 +- .../activity/components/ActivityRow.kt | 6 +- .../viewmodels/ActivityListViewModel.kt | 11 ++- .../java/to/bitkit/models/BackupJsonTest.kt | 14 +++ .../to/bitkit/repositories/BackupRepoTest.kt | 91 ++++++++++++++++++- .../viewmodels/ActivityListViewModelTest.kt | 45 +++++++++ journeys/transfer/move-to-spark.xml | 2 +- 10 files changed, 223 insertions(+), 13 deletions(-) diff --git a/app/src/main/java/to/bitkit/ext/Activities.kt b/app/src/main/java/to/bitkit/ext/Activities.kt index f4213b1146..fc2d68971e 100644 --- a/app/src/main/java/to/bitkit/ext/Activities.kt +++ b/app/src/main/java/to/bitkit/ext/Activities.kt @@ -78,7 +78,7 @@ fun Activity.isTransfer() = this is Activity.Onchain && this.v1.isTransfer /** Whether this is the channel send of a move to Spark, one of [moveHashes], which Activity shows as a move. */ fun Activity.isMoveToSpark(moveHashes: Set) = this is Activity.Lightning && - v1.txType == PaymentType.SENT && v1.status != PaymentState.FAILED && v1.id.lowercase() in moveHashes + v1.txType == PaymentType.SENT && v1.id.lowercase() in moveHashes fun Activity.doesExist() = this is Activity.Onchain && this.v1.doesExist diff --git a/app/src/main/java/to/bitkit/models/BackupPayloads.kt b/app/src/main/java/to/bitkit/models/BackupPayloads.kt index ef9d2d903c..f47b49e10c 100644 --- a/app/src/main/java/to/bitkit/models/BackupPayloads.kt +++ b/app/src/main/java/to/bitkit/models/BackupPayloads.kt @@ -7,8 +7,18 @@ import com.synonym.bitkitcore.IBtInfo import com.synonym.bitkitcore.IBtOrder import com.synonym.bitkitcore.IcJitEntry import com.synonym.bitkitcore.PreActivityMetadata +import kotlinx.serialization.EncodeDefault +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonDecoder +import kotlinx.serialization.json.JsonPrimitive import to.bitkit.data.AppCacheData import to.bitkit.data.SettingsData import to.bitkit.data.WatchOnlyAccountAllocationState @@ -44,8 +54,31 @@ data class MetadataBackupV1( * `sparkExitNextFundingIndexes`. Null in envelopes written before this field. */ val sparkExitEarlierAddresses: Map>? = null, + /** + * The payment hashes of moves to Spark, lowercase hex and sorted, which Activity shows as moves. Null in envelopes + * written before this field or with none; a value that is not a list of strings reads as none. + */ + @OptIn(ExperimentalSerializationApi::class) + @EncodeDefault(EncodeDefault.Mode.NEVER) + @Serializable(with = LenientStringListSerializer::class) + val moveToSparkPaymentHashes: List? = null, ) +/** Reads a list of strings, or an empty list for any other value, so one unreadable field keeps the rest. */ +internal object LenientStringListSerializer : KSerializer> { + private val delegate = ListSerializer(String.serializer()) + override val descriptor = delegate.descriptor + + override fun serialize(encoder: Encoder, value: List) = delegate.serialize(encoder, value) + + override fun deserialize(decoder: Decoder): List { + val element = (decoder as? JsonDecoder)?.decodeJsonElement() ?: return delegate.deserialize(decoder) + val items = (element as? JsonArray)?.map { it as? JsonPrimitive } ?: return emptyList() + if (items.any { it == null || !it.isString }) return emptyList() + return items.map { requireNotNull(it).content } + } +} + /** * An earlier Spark exit address as both apps back it up. [kind] is `keptChange` or `cancelledFunding`; a reader skips * one it does not know. What the address holds is read again from the chain. diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index a9e8c8fb39..27f1f57fbd 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -741,9 +741,21 @@ class BackupRepo @Inject constructor( } private suspend fun keepUnimportableExitBackup(stored: ByteArray, exitState: String?) { - vssBackupClient.putObject(key = SPARK_EXIT_UNIMPORTED_KEY, data = stored).getOrThrow() + setAsideRejectedExitBackup(stored) sparkRepo.skipUnimportableRemoteExitState(exitState) - Logger.warn("Kept unimportable Spark exit data under '$SPARK_EXIT_UNIMPORTED_KEY'", context = TAG) + } + + private suspend fun setAsideRejectedExitBackup(data: ByteArray) { + var key = SPARK_EXIT_REJECTED_KEY + val kept = vssBackupClient.getObject(key).getOrThrow()?.value + if (kept != null) { + if (kept.contentEquals(data)) return + val digest = MessageDigest.getInstance("SHA-256").digest(data).joinToString("") { "%02x".format(it) } + key += "_" + digest.take(REJECTED_DIGEST_HEX_DIGITS) + if (vssBackupClient.getObject(key).getOrThrow() != null) return + } + vssBackupClient.putObject(key = key, data = data).getOrThrow() + Logger.warn("Set Spark exit data Spark can't import aside as '$key'", context = TAG) } suspend fun persistWalletBackup(): Result = @@ -938,6 +950,8 @@ class BackupRepo @Inject constructor( pubkyContactProfileOverrides = pubkyContactProfileOverrides, hwWalletNames = hwWalletNames, sparkExitEarlierAddresses = sparkExitEarlierAddressesBackup(), + moveToSparkPaymentHashes = cacheData.moveToSparkHashes.map { it.lowercase() }.distinct().sorted() + .takeIf { it.isNotEmpty() }, ) json.encodeToString(payload).toByteArray() @@ -1282,6 +1296,10 @@ class BackupRepo @Inject constructor( // The exit then looks once for funding addresses that still hold coins and nothing watches: each one // below the index, and those a scan forward from it finds used, which also moves the index past them. sparkExitFundingRecoveryPending = it.sparkExitFundingRecoveryPending + restoredIndexKeys, + // Both apps back the moves up beside the cache; the device's own stay. + moveToSparkHashes = ( + it.moveToSparkHashes + cleanCache.moveToSparkHashes + parsed.moveToSparkPaymentHashes.orEmpty() + ).map { hash -> hash.lowercase() }.distinct(), ) } runCatching { restoreSparkExitEarlierAddresses(parsed.sparkExitEarlierAddresses) } @@ -1572,8 +1590,12 @@ class BackupRepo @Inject constructor( private const val MINUTE_IN_MS = 60_000 private const val BACKUP_DEBOUNCE = 5000L // 5 seconds - /** Where stored Spark exit data that Spark can't import is kept, apart from the exit data backups. */ - internal const val SPARK_EXIT_UNIMPORTED_KEY = "SPARK_EXIT_UNIMPORTED" + /** + * The remote key of exit data Spark can never import, shared with bitkit-ios. A later, different copy goes + * under this key plus `_` and the first 16 hex digits of its SHA-256; an existing copy is never replaced. + */ + internal const val SPARK_EXIT_REJECTED_KEY = "SPARK_EXIT_REJECTED" + private const val REJECTED_DIGEST_HEX_DIGITS = 16 /** Spark's exit data can reach several MB and changes with every payment, so its uploads are spaced out. */ private const val SPARK_EXIT_BACKUP_DEBOUNCE = 60_000L diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityIcon.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityIcon.kt index 14e2b5836e..396524d9ec 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityIcon.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityIcon.kt @@ -62,7 +62,7 @@ fun ActivityIcon( ) } - isMoveToSpark -> CircularIcon( + isMoveToSpark && status == PaymentState.SUCCEEDED -> CircularIcon( icon = painterResource(R.drawable.ic_transfer), iconColor = Colors.Purple, backgroundColor = Colors.Purple16, diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityRow.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityRow.kt index e75c238a29..25c5658fa9 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityRow.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/components/ActivityRow.kt @@ -148,7 +148,11 @@ fun ActivityRow( ) val context = LocalContext.current val subtitleText = when (item) { - is Activity.Lightning if isMoveToSpark -> activityTimeText(timestamp) + is Activity.Lightning if isMoveToSpark -> when (item.v1.status) { + PaymentState.FAILED -> stringResource(R.string.wallet__activity_failed) + PaymentState.PENDING -> stringResource(R.string.wallet__activity_pending) + PaymentState.SUCCEEDED -> activityTimeText(timestamp) + } is Activity.Lightning -> item.v1.message.ifEmpty { activityTimeText(timestamp) } is Activity.Onchain -> { when { diff --git a/app/src/main/java/to/bitkit/viewmodels/ActivityListViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/ActivityListViewModel.kt index a75003aa5a..f5ad42cfb2 100644 --- a/app/src/main/java/to/bitkit/viewmodels/ActivityListViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/ActivityListViewModel.kt @@ -21,6 +21,7 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.debounce +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update @@ -28,6 +29,7 @@ import kotlinx.coroutines.launch import to.bitkit.data.SettingsStore import to.bitkit.di.BgDispatcher import to.bitkit.ext.isFromHardwareWallet +import to.bitkit.ext.isMoveToSpark import to.bitkit.ext.isReplacedSentTransaction import to.bitkit.ext.isTransfer import to.bitkit.ext.rawId @@ -40,6 +42,7 @@ import to.bitkit.models.PubkyProfile import to.bitkit.models.WalletScope import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.HwWalletRepo +import to.bitkit.repositories.MoveToSparkRepo import to.bitkit.repositories.PubkyRepo import to.bitkit.ui.screens.wallets.activity.components.ActivityTab import to.bitkit.utils.Logger @@ -49,6 +52,7 @@ import javax.inject.Inject class ActivityListViewModel @Inject constructor( @BgDispatcher private val bgDispatcher: CoroutineDispatcher, private val activityRepo: ActivityRepo, + private val moveToSparkRepo: MoveToSparkRepo, private val hwWalletRepo: HwWalletRepo, pubkyRepo: PubkyRepo, settingsStore: SettingsStore, @@ -226,9 +230,12 @@ class ActivityListViewModel @Inject constructor( return null } + val moveHashes = moveToSparkRepo.moveHashes.first() val filteredByTab = when (filters.tab) { - ActivityTab.OTHER -> activities.filter { it.isTransfer() } - ActivityTab.SENT, ActivityTab.RECEIVED -> activities.filterNot { it.isTransfer() } + ActivityTab.OTHER -> activities.filter { it.isTransfer() || it.isMoveToSpark(moveHashes) } + ActivityTab.SENT, ActivityTab.RECEIVED -> activities.filterNot { + it.isTransfer() || it.isMoveToSpark(moveHashes) + } else -> activities } diff --git a/app/src/test/java/to/bitkit/models/BackupJsonTest.kt b/app/src/test/java/to/bitkit/models/BackupJsonTest.kt index a4c128c0c4..6b757dc4ab 100644 --- a/app/src/test/java/to/bitkit/models/BackupJsonTest.kt +++ b/app/src/test/java/to/bitkit/models/BackupJsonTest.kt @@ -19,6 +19,20 @@ import kotlin.test.assertNull /** Fixtures in `resources/ios-backup` are bitkit-ios `BackupService` output, encoded by Swift's `JSONEncoder`. */ class BackupJsonTest { + @Test + fun `reads move to spark hashes and treats an unreadable value as none`() { + val base = """{"version":1,"createdAt":1,"tagMetadata":[],"cache":{}""" + + val readable = decodeBackup("""$base,"moveToSparkPaymentHashes":["aa","bb"]}""") + val unreadable = decodeBackup("""$base,"moveToSparkPaymentHashes":{"aa":1}}""") + val mixed = decodeBackup("""$base,"moveToSparkPaymentHashes":["aa",1]}""") + + assertEquals(listOf("aa", "bb"), readable.moveToSparkPaymentHashes) + assertEquals(emptyList(), unreadable.moveToSparkPaymentHashes) + assertEquals(emptyList(), mixed.moveToSparkPaymentHashes) + assertNull(decodeBackup("$base}").moveToSparkPaymentHashes) + } + @Test fun `decodes iOS metadata with omitted optionals`() { val backup = decodeBackup(iosFixture("metadata")) diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index a41b9d6431..d0e6c8b4ab 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -102,6 +102,7 @@ import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture import to.bitkit.utils.AppError import java.io.File +import java.security.MessageDigest import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import java.util.concurrent.TimeUnit @@ -434,7 +435,7 @@ class BackupRepoTest : BaseUnitTest() { sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() inOrder(sparkRepo, vssBackupClient) { - verify(vssBackupClient).putObject(BackupRepo.SPARK_EXIT_UNIMPORTED_KEY, stored) + verify(vssBackupClient).putObject(BackupRepo.SPARK_EXIT_REJECTED_KEY, stored) verify(sparkRepo).skipUnimportableRemoteExitState("v9") verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) } @@ -452,11 +453,50 @@ class BackupRepoTest : BaseUnitTest() { sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() - verify(vssBackupClient).putObject(BackupRepo.SPARK_EXIT_UNIMPORTED_KEY, stored) + verify(vssBackupClient).putObject(BackupRepo.SPARK_EXIT_REJECTED_KEY, stored) verify(sparkRepo, never()).mergeRemoteExitBackup(anyOrNull()) verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) } + @Test + fun `a rejected spark exit copy already set aside is kept and not uploaded again`() = test { + val stored = "not exit data".toByteArray() + stubUnreadableStoredExit(stored) + whenever(vssBackupClient.getObject(BackupRepo.SPARK_EXIT_REJECTED_KEY)) + .thenReturn(Result.success(VssItem(key = BackupRepo.SPARK_EXIT_REJECTED_KEY, value = stored, version = 1))) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + verify(vssBackupClient, never()).putObject(argThat { startsWith(BackupRepo.SPARK_EXIT_REJECTED_KEY) }, any()) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + + @Test + fun `a different rejected spark exit copy goes under its digest and the first stays`() = test { + val stored = "not exit data".toByteArray() + stubUnreadableStoredExit(stored) + whenever(vssBackupClient.getObject(BackupRepo.SPARK_EXIT_REJECTED_KEY)).thenReturn( + Result.success( + VssItem(key = BackupRepo.SPARK_EXIT_REJECTED_KEY, value = "older".toByteArray(), version = 1) + ) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + val digest = MessageDigest.getInstance("SHA-256").digest(stored).joinToString("") { "%02x".format(it) } + verify(vssBackupClient).putObject("${BackupRepo.SPARK_EXIT_REJECTED_KEY}_${digest.take(16)}", stored) + verify(vssBackupClient, never()).putObject(eq(BackupRepo.SPARK_EXIT_REJECTED_KEY), any()) + } + + private suspend fun stubUnreadableStoredExit(stored: ByteArray) { + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + } + @Test fun `a spark exit merge that fails for another reason still blocks the upload`() = test { val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "v1")) @@ -471,7 +511,7 @@ class BackupRepoTest : BaseUnitTest() { assertTrue(sut.triggerBackup(BackupCategory.SPARK_EXIT).isFailure) - verify(vssBackupClient, never()).putObject(eq(BackupRepo.SPARK_EXIT_UNIMPORTED_KEY), any()) + verify(vssBackupClient, never()).putObject(eq(BackupRepo.SPARK_EXIT_REJECTED_KEY), any()) verify(vssBackupClient, never()).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) } @@ -1999,6 +2039,51 @@ class BackupRepoTest : BaseUnitTest() { assertEquals(mapOf(sparkWalletKey to expected), payload.sparkExitEarlierAddresses) } + @Test + fun `a metadata backup carries the move to spark hashes lowercase and sorted`() = test { + stubMetadataBackupReads() + cacheData.value = cacheData.value.copy(moveToSparkHashes = listOf("bb", "AA")) + val dataCaptor = argumentCaptor() + + sut.triggerBackup(BackupCategory.METADATA) + + verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.METADATA.name), dataCaptor.capture()) } + val payload = json.decodeFromString(dataCaptor.firstValue.decodeToString()) + assertEquals(listOf("aa", "bb"), payload.moveToSparkPaymentHashes) + } + + @Test + fun `a metadata backup leaves the move to spark hashes out with none`() = test { + stubMetadataBackupReads() + val dataCaptor = argumentCaptor() + + sut.triggerBackup(BackupCategory.METADATA) + + verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.METADATA.name), dataCaptor.capture()) } + assertFalse("moveToSparkPaymentHashes" in dataCaptor.firstValue.decodeToString()) + } + + @Test + fun `a metadata restore adds the backed-up move to spark hashes to the device's`() = test { + whenever { cacheStore.update(any()) }.thenAnswer { + cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) + } + cacheData.value = cacheData.value.copy(moveToSparkHashes = listOf("dd")) + val envelope = json.encodeToString( + MetadataBackupV1( + createdAt = 123, + tagMetadata = emptyList(), + cache = AppCacheData(moveToSparkHashes = listOf("cc")), + moveToSparkPaymentHashes = listOf("AA"), + ) + ) + stubMetadataRestore(envelope = envelope) + + sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertEquals(setOf("dd", "cc", "aa"), cacheData.value.moveToSparkHashes.toSet()) + } + @Test fun `a restore lists the backed-up earlier spark exit addresses and keeps the device's`() = test { val store = earlierAddressStore() diff --git a/app/src/test/java/to/bitkit/viewmodels/ActivityListViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/ActivityListViewModelTest.kt index 856b72ca04..47e287a67f 100644 --- a/app/src/test/java/to/bitkit/viewmodels/ActivityListViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/ActivityListViewModelTest.kt @@ -1,7 +1,9 @@ package to.bitkit.viewmodels import com.synonym.bitkitcore.Activity +import com.synonym.bitkitcore.LightningActivity import com.synonym.bitkitcore.OnchainActivity +import com.synonym.bitkitcore.PaymentState import com.synonym.bitkitcore.PaymentType import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf @@ -21,6 +23,7 @@ import to.bitkit.ext.rawId import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.ActivityState import to.bitkit.repositories.HwWalletRepo +import to.bitkit.repositories.MoveToSparkRepo import to.bitkit.repositories.PubkyRepo import to.bitkit.test.BaseUnitTest import to.bitkit.ui.screens.wallets.activity.components.ActivityTab @@ -30,6 +33,7 @@ import kotlin.test.assertEquals class ActivityListViewModelTest : BaseUnitTest() { private val activityRepo = mock() + private val moveToSparkRepo = mock() private val hwWalletRepo = mock() private val pubkyRepo = mock() private val settingsStore = mock() @@ -47,6 +51,7 @@ class ActivityListViewModelTest : BaseUnitTest() { fun setUp() { hardwareActivities = MutableStateFlow(persistentListOf(hwActivity)) whenever(activityRepo.state).thenReturn(MutableStateFlow(ActivityState())) + whenever(moveToSparkRepo.moveHashes).thenReturn(MutableStateFlow(setOf("move"))) whenever(activityRepo.activitiesChanged).thenReturn(MutableStateFlow(0L)) whenever { activityRepo.syncActivities() }.thenReturn(Result.success(Unit)) whenever { activityRepo.getTxIdsInBoostTxIds(any()) }.thenReturn(emptySet()) @@ -71,6 +76,7 @@ class ActivityListViewModelTest : BaseUnitTest() { private fun createViewModel() = ActivityListViewModel( bgDispatcher = testDispatcher, activityRepo = activityRepo, + moveToSparkRepo = moveToSparkRepo, hwWalletRepo = hwWalletRepo, pubkyRepo = pubkyRepo, settingsStore = settingsStore, @@ -93,6 +99,33 @@ class ActivityListViewModelTest : BaseUnitTest() { assertEquals(listOf("db1"), sut.filteredActivities.value?.map { it.rawId() }) } + @Test + fun `a move to spark lists under other, failed too, and not under sent`() = test { + val move = lightningSend(id = "MOVE", status = PaymentState.FAILED) + whenever { + activityRepo.getActivities( + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + ) + }.thenReturn(Result.success(listOf(dbActivity, move))) + val sut = createViewModel() + + sut.setTab(ActivityTab.SENT) + advanceUntilIdle() + assertEquals(listOf("db1"), sut.filteredActivities.value?.map { it.rawId() }) + + sut.setTab(ActivityTab.OTHER) + advanceUntilIdle() + assertEquals(listOf("MOVE"), sut.filteredActivities.value?.map { it.rawId() }) + } + @Test fun `filtered activities exclude hardware activities when a tag filter is active`() = test { val sut = createViewModel() @@ -132,6 +165,18 @@ class ActivityListViewModelTest : BaseUnitTest() { job.cancel() } + private fun lightningSend(id: String, status: PaymentState) = Activity.Lightning( + LightningActivity.create( + walletId = "wallet0", + id = id, + txType = PaymentType.SENT, + status = status, + value = 1_000uL, + invoice = "lnbc", + timestamp = 150uL, + ) + ) + private fun onchainActivity( id: String, txType: PaymentType, diff --git a/journeys/transfer/move-to-spark.xml b/journeys/transfer/move-to-spark.xml index bbf26d9ad4..39e4a10b55 100644 --- a/journeys/transfer/move-to-spark.xml +++ b/journeys/transfer/move-to-spark.xml @@ -25,7 +25,7 @@ Swipe to move (testTag "MoveToSparkSwipe") and verify "Moved to Spark" shows the moved amount (testTag "MoveToSparkMoved") and "Close" (testTag "MoveToSparkClose") Tap "Close" (testTag "MoveToSparkClose"), then "Close" on the close confirmation, and verify Lightning Connections shows no open connection and the Spark balance grew by the moved amount Go back to Home, open Spending and verify the "Move To Spark" button is gone - Open All Activity and verify the move shows as one outgoing row titled "Move to Spark" with the transfer icon (testTag "MoveToSparkIcon") and the moved amount plus the routing fee, and no received row + Open All Activity and verify the move shows as one outgoing row titled "Move to Spark" with the transfer icon (testTag "MoveToSparkIcon") and the moved amount plus the routing fee, and no received row; on the Other tab the row lists, and on the Sent tab it does not Tap the "Move to Spark" row and verify the detail's title is "Move to Spark" and it shows the routing fee From 97b31e1c64c7d8a2c8cba3d7adc2123fd8236d31 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 16:04:36 +0100 Subject: [PATCH 09/96] fix: leave a held spark retry's row alone on an older failure An earlier attempt's late failure now returns before it is recorded, so the uncertain retry's Activity row stays pending, as on bitkit-ios. The move-to-spark journey takes the iOS wording for its last steps. Verified: just test, just lint --- app/src/main/java/to/bitkit/repositories/SparkRepo.kt | 5 +++-- app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt | 4 ++++ journeys/transfer/move-to-spark.xml | 5 ++--- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 9260f7d9f2..c8ff7db2b9 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1800,13 +1800,14 @@ class SparkRepo @Inject constructor( // The event carries its outcome, so a failed balance read never holds back its settlement. runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after payment '${payment.id}'", it, context = TAG) } - recordActivity(payment, settlesJournal = false) // An earlier attempt's failure can arrive after a retry of its invoice went uncertain, and ends nothing of the - // retry's: Spark may still finish it, so its hold stays until the expiry rule of trySettleUncertainSend. + // retry's: Spark may still finish it, so its hold and its Activity row stay until the expiry rule of + // trySettleUncertainSend. if (payment.isEarlierFailureOfUncertainSend()) { Logger.info("Kept uncertain Spark send '${payment.sendHash()}' held past an older failure", context = TAG) return } + recordActivity(payment, settlesJournal = false) // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. payment.sendHash()?.let { uncertainSends.remove(it.lowercase()) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 7f4e34934d..ce6de6d418 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -56,6 +56,7 @@ import org.junit.rules.TemporaryFolder import org.lightningdevkit.ldknode.Event import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.argThat import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.atLeastOnce import org.mockito.kotlin.clearInvocations @@ -3579,6 +3580,9 @@ class SparkRepoTest : BaseUnitTest() { assertTrue(events.none { it is Event.PaymentFailed }, "an older failure ended a send Spark may finish") assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) } @Test diff --git a/journeys/transfer/move-to-spark.xml b/journeys/transfer/move-to-spark.xml index 39e4a10b55..0b7e1fc20e 100644 --- a/journeys/transfer/move-to-spark.xml +++ b/journeys/transfer/move-to-spark.xml @@ -24,8 +24,7 @@ Tap "Move To Spark" and verify the screen shows an amount (testTag "MoveToSparkAmount") and a routing fee (testTag "MoveToSparkFee") Swipe to move (testTag "MoveToSparkSwipe") and verify "Moved to Spark" shows the moved amount (testTag "MoveToSparkMoved") and "Close" (testTag "MoveToSparkClose") Tap "Close" (testTag "MoveToSparkClose"), then "Close" on the close confirmation, and verify Lightning Connections shows no open connection and the Spark balance grew by the moved amount - Go back to Home, open Spending and verify the "Move To Spark" button is gone - Open All Activity and verify the move shows as one outgoing row titled "Move to Spark" with the transfer icon (testTag "MoveToSparkIcon") and the moved amount plus the routing fee, and no received row; on the Other tab the row lists, and on the Sent tab it does not - Tap the "Move to Spark" row and verify the detail's title is "Move to Spark" and it shows the routing fee + Go back to Home and verify Activity lists a "Move to Spark" transfer row with the moved amount plus the routing fee, and that its detail screen is titled "Move to Spark" + Open Spending and verify the "Move To Spark" button is gone From f7184edf3d6b44a51dd86548f8ae16549b023162 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 16:23:47 +0100 Subject: [PATCH 10/96] fix: spark exit set-aside and retry hold match ios Verified: just compile, just test, just lint --- .../java/to/bitkit/repositories/BackupRepo.kt | 35 +++++++--- .../java/to/bitkit/repositories/SparkRepo.kt | 45 ++++++++++++- .../to/bitkit/repositories/BackupRepoTest.kt | 67 +++++++++++++++---- .../to/bitkit/repositories/SparkRepoTest.kt | 57 ++++++++++++++++ 4 files changed, 183 insertions(+), 21 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 27f1f57fbd..c476466c80 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -717,6 +717,11 @@ class BackupRepo @Inject constructor( * read, so a failed or skipped restore never loses the stored exit data. */ private suspend fun uploadSparkExitBackup(): Result = runSuspendCatching { + val staged = sparkRepo.importStagedExitState() + if (staged is StagedExitImport.Rejected) { + setAsideRejectedExitBackup(rejectedStagedExitCopy(staged)) + sparkRepo.discardStagedExitState(staged.exitState) + } if (!sparkRepo.hasMergedRemoteExitState) { sparkRepo.exitBackup().getOrThrow() ?: throw SparkExitBackupDeferred() val stored = vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name).getOrThrow()?.value @@ -745,15 +750,23 @@ class BackupRepo @Inject constructor( sparkRepo.skipUnimportableRemoteExitState(exitState) } - private suspend fun setAsideRejectedExitBackup(data: ByteArray) { - var key = SPARK_EXIT_REJECTED_KEY - val kept = vssBackupClient.getObject(key).getOrThrow()?.value - if (kept != null) { - if (kept.contentEquals(data)) return - val digest = MessageDigest.getInstance("SHA-256").digest(data).joinToString("") { "%02x".format(it) } - key += "_" + digest.take(REJECTED_DIGEST_HEX_DIGITS) - if (vssBackupClient.getObject(key).getOrThrow() != null) return + private suspend fun rejectedStagedExitCopy(staged: StagedExitImport.Rejected): ByteArray { + val stored = vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name).getOrThrow()?.value + val remote = stored?.let { bytes -> + runCatching { json.decodeFromString(String(bytes)) }.getOrNull() } + if (stored != null && remote?.exitState == staged.exitState) return stored + val copy = SparkExitBackupV1( + createdAt = currentTimeMillis(), + network = remote?.network ?: staged.network, + exitState = staged.exitState, + ) + return json.encodeToString(copy).toByteArray() + } + + private suspend fun setAsideRejectedExitBackup(data: ByteArray) { + val key = rejectedExitKey(data) + if (vssBackupClient.getObject(key).getOrThrow() != null) return vssBackupClient.putObject(key = key, data = data).getOrThrow() Logger.warn("Set Spark exit data Spark can't import aside as '$key'", context = TAG) } @@ -1597,6 +1610,12 @@ class BackupRepo @Inject constructor( internal const val SPARK_EXIT_REJECTED_KEY = "SPARK_EXIT_REJECTED" private const val REJECTED_DIGEST_HEX_DIGITS = 16 + /** Where exit data Spark can't import is kept: one key per copy, so none replaces another. */ + internal fun rejectedExitKey(data: ByteArray): String { + val digest = MessageDigest.getInstance("SHA-256").digest(data).joinToString("") { "%02x".format(it) } + return SPARK_EXIT_REJECTED_KEY + "_" + digest.take(REJECTED_DIGEST_HEX_DIGITS) + } + /** Spark's exit data can reach several MB and changes with every payment, so its uploads are spaced out. */ private const val SPARK_EXIT_BACKUP_DEBOUNCE = 60_000L diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index c8ff7db2b9..6a531259b8 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -107,6 +107,12 @@ class SparkRepo @Inject constructor( /** Looks for 5 minutes before telling the user Spark hasn't seen the deposit yet. */ private const val CLAIM_POLL_ATTEMPTS = 60 + /** + * How far Spark's clock may run behind the phone's: a failure dated within this of a retry's start counts as + * the retry's own. + */ + private const val RAIL_CLOCK_SKEW_SECONDS = 10uL + private val SEND_STATUS_PRIORITY = listOf(PaymentStatus.COMPLETED, PaymentStatus.PENDING, PaymentStatus.FAILED) /** How long the SDK leaves the counter-swap of a leaf swap cut short unclaimed (its 300 s), plus a margin. */ @@ -1167,6 +1173,31 @@ class SparkRepo @Inject constructor( hasMergedRemoteExitState = true } + /** Tries the import of restored exit data again while connected, and says what became of it. */ + suspend fun importStagedExitState(): StagedExitImport = withContext(bgDispatcher) { + val file = File(Env.sparkExitRestorePath(walletIndex)) + if (!file.exists()) return@withContext StagedExitImport.NothingStaged + val network = sparkService.networkName + if (!sparkService.isConnected || network == null) return@withContext StagedExitImport.Pending + val staged = file.readText() + importRestoredExitState(walletIndex).fold( + onSuccess = { StagedExitImport.Imported }, + onFailure = { + if (it is SdkException.InvalidInput) { + StagedExitImport.Rejected(staged, network) + } else { + StagedExitImport.Pending + } + }, + ) + } + + /** Drops restored exit data Spark rejected, once the backup set a copy of it aside, unless newer data came. */ + fun discardStagedExitState(exitState: String) { + val staged = File(Env.sparkExitRestorePath(walletIndex)) + if (staged.exists() && staged.readText() == exitState) staged.delete() + } + /** * Puts a restored exit data backup back: at once while Spark is connected, otherwise right after it connects, * before it is used, so a restored wallet can exit on-chain even while the Spark operators are unreachable. @@ -1753,7 +1784,7 @@ class SparkRepo @Inject constructor( private fun Payment.isEarlierFailureOfUncertainSend(): Boolean { val hash = sendHash(PaymentStatus.FAILED) ?: return false val sentAt = uncertainSends[hash.lowercase()]?.sentAt ?: return false - return timestamp < sentAt + return timestamp + RAIL_CLOCK_SKEW_SECONDS < sentAt } /** The payment hash of this send, at [status] when given. */ @@ -2303,3 +2334,15 @@ fun SparkEarlyClaim.toDepositClaim(offer: SparkClaimOffer.Choice): SparkDepositC is SparkEarlyClaim.Repriced -> SparkDepositClaim.Repriced(offer.copy(earlyFeeSats = requiredFeeSats)) SparkEarlyClaim.Declined -> SparkDepositClaim.Unavailable } + +/** What became of restored exit data waiting for Spark to import it. */ +sealed interface StagedExitImport { + data object NothingStaged : StagedExitImport + data object Imported : StagedExitImport + + /** Spark is not connected, or the import failed for a reason that may pass. */ + data object Pending : StagedExitImport + + /** Spark can never import [exitState], restored for [network]. */ + data class Rejected(val exitState: String, val network: String) : StagedExitImport +} diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index d0e6c8b4ab..92864ff944 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -241,6 +241,7 @@ class BackupRepoTest : BaseUnitTest() { whenever { sparkRepo.restoreExitBackup(any(), any()) }.thenReturn(Result.success(Unit)) whenever { sparkRepo.mergeRemoteExitBackup(anyOrNull()) }.thenReturn(Result.success(Unit)) whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(true) + whenever { sparkRepo.importStagedExitState() }.thenReturn(StagedExitImport.NothingStaged) whenever(sparkRepo.exitStateGeneration).thenReturn(exitStateGeneration) whenever(sparkRepo.state).thenReturn(MutableStateFlow(SparkState())) @@ -435,7 +436,7 @@ class BackupRepoTest : BaseUnitTest() { sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() inOrder(sparkRepo, vssBackupClient) { - verify(vssBackupClient).putObject(BackupRepo.SPARK_EXIT_REJECTED_KEY, stored) + verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) verify(sparkRepo).skipUnimportableRemoteExitState("v9") verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) } @@ -453,17 +454,19 @@ class BackupRepoTest : BaseUnitTest() { sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() - verify(vssBackupClient).putObject(BackupRepo.SPARK_EXIT_REJECTED_KEY, stored) + verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) verify(sparkRepo, never()).mergeRemoteExitBackup(anyOrNull()) verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) } @Test - fun `a rejected spark exit copy already set aside is kept and not uploaded again`() = test { + fun `a rejected spark exit copy already set aside is not uploaded again`() = test { val stored = "not exit data".toByteArray() stubUnreadableStoredExit(stored) - whenever(vssBackupClient.getObject(BackupRepo.SPARK_EXIT_REJECTED_KEY)) - .thenReturn(Result.success(VssItem(key = BackupRepo.SPARK_EXIT_REJECTED_KEY, value = stored, version = 1))) + val key = BackupRepo.rejectedExitKey(stored) + whenever( + vssBackupClient.getObject(key) + ).thenReturn(Result.success(VssItem(key = key, value = stored, version = 1))) sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() @@ -472,14 +475,9 @@ class BackupRepoTest : BaseUnitTest() { } @Test - fun `a different rejected spark exit copy goes under its digest and the first stays`() = test { + fun `each rejected spark exit copy goes under its own digest key and never the plain key`() = test { val stored = "not exit data".toByteArray() stubUnreadableStoredExit(stored) - whenever(vssBackupClient.getObject(BackupRepo.SPARK_EXIT_REJECTED_KEY)).thenReturn( - Result.success( - VssItem(key = BackupRepo.SPARK_EXIT_REJECTED_KEY, value = "older".toByteArray(), version = 1) - ) - ) sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() @@ -497,6 +495,51 @@ class BackupRepoTest : BaseUnitTest() { ) } + @Test + fun `staged exit data spark rejects is set aside as the stored backup that holds it`() = test { + val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "v9")) + .toByteArray() + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.importStagedExitState()).thenReturn(StagedExitImport.Rejected("v9", "regtest")) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + inOrder(sparkRepo, vssBackupClient) { + verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) + verify(sparkRepo).discardStagedExitState("v9") + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + } + + @Test + fun `staged exit data spark rejects is set aside on its own once the stored backup moved on`() = test { + val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "newer")) + .toByteArray() + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + whenever(sparkRepo.importStagedExitState()).thenReturn(StagedExitImport.Rejected("v9", "regtest")) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + val kept = argumentCaptor() + verify( + vssBackupClient + ).putObject(argThat { startsWith("${BackupRepo.SPARK_EXIT_REJECTED_KEY}_") }, kept.capture()) + assertEquals( + SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "v9"), + json.decodeFromString(String(kept.firstValue)), + ) + verify(sparkRepo).discardStagedExitState("v9") + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + @Test fun `a spark exit merge that fails for another reason still blocks the upload`() = test { val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "v1")) @@ -511,7 +554,7 @@ class BackupRepoTest : BaseUnitTest() { assertTrue(sut.triggerBackup(BackupCategory.SPARK_EXIT).isFailure) - verify(vssBackupClient, never()).putObject(eq(BackupRepo.SPARK_EXIT_REJECTED_KEY), any()) + verify(vssBackupClient, never()).putObject(argThat { startsWith(BackupRepo.SPARK_EXIT_REJECTED_KEY) }, any()) verify(vssBackupClient, never()).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index ce6de6d418..e658222b39 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -2611,6 +2611,32 @@ class SparkRepoTest : BaseUnitTest() { assertTrue(File(Env.sparkExitRestorePath(0)).exists()) } + @Test + fun `staged exit data spark rejects as invalid reads as rejected and stays until discarded`() = test { + whenever { sparkService.importExitState(any()) }.thenAnswer { throw SdkException.InvalidInput("bad") } + val sut = createSut() + sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "s"), 0) + whenever(sparkService.isConnected).thenReturn(true) + + assertEquals(StagedExitImport.Rejected("s", "regtest"), sut.importStagedExitState()) + sut.discardStagedExitState("other") + assertTrue(File(Env.sparkExitRestorePath(0)).exists()) + sut.discardStagedExitState("s") + assertFalse(File(Env.sparkExitRestorePath(0)).exists()) + } + + @Test + fun `staged exit data spark fails to import for another reason stays pending`() = test { + whenever { sparkService.importExitState(any()) }.thenAnswer { throw SdkException.Generic("offline") } + val sut = createSut() + sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "s"), 0) + + assertEquals(StagedExitImport.Pending, sut.importStagedExitState()) + whenever(sparkService.isConnected).thenReturn(true) + assertEquals(StagedExitImport.Pending, sut.importStagedExitState()) + assertTrue(File(Env.sparkExitRestorePath(0)).exists()) + } + @Test fun `a failed withdrawal keeps the balance shown while spark reads zero`() = test { whenever(sparkService.isConnected).thenReturn(true) @@ -3585,6 +3611,37 @@ class SparkRepoTest : BaseUnitTest() { ) } + @Test + fun `a failure dated within spark's clock skew of an uncertain retry ends its hold`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + // Spark's clock runs 5 s behind the phone's, so the retry's own failure is dated before it started. + val failed = sentPayment(fees = 0).copy( + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong() - 5uL, + ) + whenever { sparkService.listPayments() }.thenReturn(listOf(failed)) + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable"), lastSyncedAt = 1uL) + ) + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + runCurrent() + + sparkEvents.emit(SdkEvent.PaymentFailed(failed)) + advanceUntilIdle() + + assertTrue(events.any { it is Event.PaymentFailed }, "a failure within the clock skew didn't end the send") + assertNull(sut.earlierLightningSend("lnbc1", "hash"), "a failure within the clock skew kept the retry held") + } + @Test fun `an uncertain spark retry's own failure after a restart ends its hold`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) From ab895d2a68fbf9fe163ff1bfc551ecb6a257adb5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 16:36:12 +0100 Subject: [PATCH 11/96] fix: spark retry start survives restart, unreadable exit data set aside Verified: just compile, just test, just lint --- .../main/java/to/bitkit/data/CacheStore.kt | 27 +++++++++++--- .../java/to/bitkit/repositories/BackupRepo.kt | 9 ++++- .../java/to/bitkit/repositories/SparkRepo.kt | 7 ++-- .../to/bitkit/repositories/BackupRepoTest.kt | 13 +++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 36 ++++++++++++++++++- 5 files changed, 83 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 6b6930e6ba..b38d067e0e 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -174,16 +174,30 @@ class CacheStore internal constructor( } } - /** Keeps Spark's send of [paymentHash] as one whose outcome Spark didn't report, since [failedAt] epoch seconds. */ - suspend fun addSparkUncertainSend(paymentHash: String, failedAt: Long) { + /** + * Keeps Spark's send of [paymentHash] as one whose outcome Spark didn't report, since [failedAt] epoch seconds, and + * when it was sent, [sentAt], once known. + */ + suspend fun addSparkUncertainSend(paymentHash: String, failedAt: Long, sentAt: Long? = null) { val hash = paymentHash.lowercase() - store.updateData { it.copy(sparkUncertainSends = it.sparkUncertainSends + (hash to failedAt)) } + store.updateData { + it.copy( + sparkUncertainSends = it.sparkUncertainSends + (hash to failedAt), + sparkUncertainSendStarts = sentAt?.let { start -> it.sparkUncertainSendStarts + (hash to start) } + ?: it.sparkUncertainSendStarts, + ) + } } suspend fun removeSparkUncertainSend(paymentHash: String) { val hash = paymentHash.lowercase() if (hash !in store.data.first().sparkUncertainSends) return - store.updateData { it.copy(sparkUncertainSends = it.sparkUncertainSends - hash) } + store.updateData { + it.copy( + sparkUncertainSends = it.sparkUncertainSends - hash, + sparkUncertainSendStarts = it.sparkUncertainSendStarts - hash, + ) + } } suspend fun addMoveToSparkHash(paymentHash: String) { @@ -375,6 +389,11 @@ data class AppCacheData( * never reads a retry's earlier failed attempt as its outcome. */ val sparkUncertainSends: Map = mapOf(), + /** + * When each of those sends went out, in epoch seconds, so a failure Spark dates before it still reads as an earlier + * attempt's after a restart. Sends kept before this was have none. + */ + val sparkUncertainSendStarts: Map = mapOf(), /** * Payment hashes of the moves to Spark, kept across restarts so neither leg of a move is announced as a payment and * Activity shows the move as one. diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index c476466c80..8d9b93814f 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1175,7 +1175,14 @@ class BackupRepo @Inject constructor( connectionSession.replay() // Before the slower categories, so the exit data is staged before Spark connects and syncs. performRestore(BackupCategory.SPARK_EXIT, failedCategories) { dataBytes -> - val parsed = json.decodeFromString(String(dataBytes)) + val parsed = runCatching { json.decodeFromString(String(dataBytes)) } + .getOrElse { + // A layout this app can't read never becomes readable here, so it is kept for one that can. + if (it !is IllegalArgumentException) throw it + Logger.warn("Failed to read '${BackupCategory.SPARK_EXIT}' backup", it, context = TAG) + setAsideRejectedExitBackup(dataBytes) + return@performRestore currentTimeMillis() + } sparkRepo.restoreExitBackup(parsed, backupWalletIndex()).getOrThrow() parsed.createdAt } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 6a531259b8..affd25de84 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -609,7 +609,7 @@ class SparkRepo @Inject constructor( private suspend fun settleUncertainSend(paymentHash: String, sentAt: Long, expiresAt: ULong) { val failedAt = clock.now().epochSeconds uncertainSends[paymentHash.lowercase()] = UncertainSend(failedAt.toULong(), expiresAt, sentAt.toULong()) - cacheStore.addSparkUncertainSend(paymentHash, failedAt) + cacheStore.addSparkUncertainSend(paymentHash, failedAt, sentAt) scope.launch { // The send screen tracks the hash as pending only once the send returns, and resolves tracked ones. withTimeoutOrNull(PENDING_TRACK_WAIT) { @@ -664,7 +664,7 @@ class SparkRepo @Inject constructor( /** * A send whose outcome Spark didn't report: when it failed, when its invoice expires and when it started, in epoch - * seconds. Its start is unknown after a restart, which keeps one stored time. + * seconds. Its start is kept across a restart; a send kept before starts were stored has none. */ private data class UncertainSend(val failedAt: ULong, val expiresAt: ULong, val sentAt: ULong? = null) @@ -673,7 +673,8 @@ class SparkRepo @Inject constructor( val cache = cacheStore.data.first() cache.sparkUncertainSends.forEach { (hash, failedAt) -> val expiresAt = cache.sparkSendExpiries[hash]?.toULong() ?: ULong.MAX_VALUE - uncertainSends.putIfAbsent(hash, UncertainSend(failedAt.toULong(), expiresAt)) + val sentAt = cache.sparkUncertainSendStarts[hash]?.toULong() + uncertainSends.putIfAbsent(hash, UncertainSend(failedAt.toULong(), expiresAt, sentAt)) } } diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 92864ff944..db51c7a75c 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -573,6 +573,19 @@ class BackupRepoTest : BaseUnitTest() { verify(vssBackupClient, never()).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) } + @Test + fun `a restore sets aside spark exit data it can't read and completes`() = test { + val stored = "not exit data".toByteArray() + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) + .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) + + val failed = sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertFalse(BackupCategory.SPARK_EXIT in failed) + verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) + verify(sparkRepo, never()).restoreExitBackup(any(), any()) + } + @Test fun `a failed spark exit restore is reported as an incomplete restore`() = test { whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index e658222b39..f9ce9b3ecc 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3540,7 +3540,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val deadline = now + 1.seconds - whenever { cacheStore.addSparkUncertainSend(any(), any()) }.thenAnswer { + whenever { cacheStore.addSparkUncertainSend(any(), any(), anyOrNull()) }.thenAnswer { now = deadline + 1.seconds Unit } @@ -3677,6 +3677,40 @@ class SparkRepoTest : BaseUnitTest() { assertNull(after.earlierLightningSend("lnbc1", "hash"), "the retry's own failure still held the node off") } + @Test + fun `an older attempt's failure after a restart keeps an uncertain spark retry held`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + ) + val before = createSut(store) + before.start(0).getOrThrow() + assertIs(before.payInvoice("lnbc1", 100uL).exceptionOrNull()) + runCurrent() + val after = createSut(store) + after.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { after.nodeEvents.collect { events += it } } + runCurrent() + + // The earlier attempt's failure, made long before the retry went out, arrives after the restart. + val olderFailure = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + whenever { sparkService.listPayments() }.thenReturn(listOf(olderFailure)) + sparkEvents.emit(SdkEvent.PaymentFailed(olderFailure)) + advanceUntilIdle() + + assertTrue(events.none { it is Event.PaymentFailed }, "an older failure ended a send Spark may finish") + assertEquals(EarlierSend.Pending("hash"), after.earlierLightningSend("lnbc1", "hash")) + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) + } + @Test fun `an uncertain spark retry stays held after a restart while spark lists only its older failure`() = test { assertUncertainRetryHeldAfterRestart(syncError = null) From daf1dfbd57fdb564a1c9ed724a1aab97199758d5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 17:08:02 +0100 Subject: [PATCH 12/96] fix: spark retry hold survives process death and startup sync Verified: just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 4 +++- .../to/bitkit/repositories/SparkRepoTest.kt | 19 +++++++++++++++++++ 2 files changed, 22 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 affd25de84..a36530b34d 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -560,7 +560,7 @@ class SparkRepo @Inject constructor( cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) spending { // Kept until the call returns, so a send cut off by process death or cancellation stays held. - cacheStore.addSparkUncertainSend(paymentHash, sentAt) + cacheStore.addSparkUncertainSend(paymentHash, sentAt, sentAt) // The checks above and both writes suspend, so the deadline and an exit that started meanwhile // are checked last, before the send. runCatching { @@ -1862,6 +1862,8 @@ class SparkRepo @Inject constructor( private suspend fun recordActivity(payment: Payment, settlesJournal: Boolean = true): Boolean { (payment.details as? PaymentDetails.Withdraw)?.let { return recordWithdrawal(payment, it, settlesJournal) } val lightning = payment.details as? PaymentDetails.Lightning ?: return true + // An earlier attempt's failure, listed or reported, leaves the row of a retry Spark may still finish. + if (payment.isEarlierFailureOfUncertainSend()) return true if (payment.status == PaymentStatus.PENDING && payment.paymentType == SparkPaymentType.RECEIVE) { return true } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index f9ce9b3ecc..85d382e90a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3741,9 +3741,13 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.getInfo() }.thenReturn( info(0uL).copy(lastSyncError = syncError, lastSyncedAt = now.epochSeconds.toULong() + 1uL) ) + clearInvocations(activityRepo) val after = createSut(store) after.start(0).getOrThrow() + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) assertTrue("hash" in store.data.first().sparkSendHashes, "A restart released a retry Spark may resume") assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), after.lightningSend("hash")) assertEquals(EarlierSend.Pending("hash"), after.earlierLightningSend("lnbc1", "hash")) @@ -3768,8 +3772,19 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.getInfo() }.thenReturn( info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) ) + assertEquals(now.epochSeconds, store.data.first().sparkUncertainSendStarts["hash"]) + clearInvocations(activityRepo) + // A new process: only the restarted repo hears Spark's events. + val restartedEvents = MutableSharedFlow() + whenever(sparkService.events).thenReturn(restartedEvents) val after = createSut(store) after.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { after.nodeEvents.collect { events += it } } + runCurrent() + // The earlier attempt's failure arrives again as an event after the restart. + restartedEvents.emit(SdkEvent.PaymentFailed(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + advanceUntilIdle() assertEquals( EarlierSend.Pending("hash"), @@ -3777,6 +3792,10 @@ class SparkRepoTest : BaseUnitTest() { "A restart released a retry Spark may resume to the node", ) assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), after.lightningSend("hash")) + assertTrue(events.none { it is Event.PaymentFailed }, "an older failure ended a send Spark may finish") + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) } @Test From d57bde73852d54ec206881a55b6ea4e0bb1529a7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 17:35:00 +0100 Subject: [PATCH 13/96] fix: older spark failure keeps an in-flight retry's hold Verified: just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 8 ++++- .../to/bitkit/repositories/SparkRepoTest.kt | 29 +++++++++++++++++++ 2 files changed, 36 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 a36530b34d..54e94b4583 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -181,6 +181,9 @@ class SparkRepo @Inject constructor( /** The invoice of each send still inside Spark's send call, by lowercase payment hash. */ private val sendsInFlight = ConcurrentHashMap() + /** When each send still inside Spark's send call went out, in epoch seconds, by lowercase payment hash. */ + private val inFlightSentAt = ConcurrentHashMap() + /** Counts sends recorded, so a listing drops a failed hash only when it was recorded before the listing. */ private val sendRecords = AtomicLong() private val sendRecordedAt = ConcurrentHashMap() @@ -556,6 +559,7 @@ class SparkRepo @Inject constructor( } val sentAt = clock.now().epochSeconds val sent = try { + inFlightSentAt[paymentHash.lowercase()] = sentAt.toULong() sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) spending { @@ -574,6 +578,7 @@ class SparkRepo @Inject constructor( runSuspendCatching { sparkService.send(prepared) } } } finally { + inFlightSentAt.remove(paymentHash.lowercase()) sendsInFlight.remove(paymentHash.lowercase()) } val payment = sent.getOrElse { @@ -1784,7 +1789,8 @@ class SparkRepo @Inject constructor( private fun Payment.isEarlierFailureOfUncertainSend(): Boolean { val hash = sendHash(PaymentStatus.FAILED) ?: return false - val sentAt = uncertainSends[hash.lowercase()]?.sentAt ?: return false + val key = hash.lowercase() + val sentAt = uncertainSends[key]?.sentAt ?: inFlightSentAt[key] ?: return false return timestamp + RAIL_CLOCK_SKEW_SECONDS < sentAt } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 85d382e90a..22f88f572d 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3798,6 +3798,35 @@ class SparkRepoTest : BaseUnitTest() { ) } + @Test + fun `an older attempt's failure during a spark retry's send keeps its hold`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + // Spark's send call is still running when the earlier attempt's failure arrives. + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { awaitCancellation() } + val sut = createSut(store) + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } + runCurrent() + val olderFailure = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + whenever { sparkService.listPayments() }.thenReturn(listOf(olderFailure)) + + sparkEvents.emit(SdkEvent.PaymentFailed(olderFailure)) + runCurrent() + + val cache = store.data.first() + assertTrue("hash" in cache.sparkUncertainSends, "an older failure dropped the in-flight send's hold") + assertTrue("hash" in cache.sparkSendHashes, "an older failure released the in-flight send's invoice") + assertTrue(events.none { it is Event.PaymentFailed }, "an older failure ended a send Spark may finish") + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) + } + @Test fun `a cancelled spark retry stays held while spark lists only its older failure`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) From ecbf41f0dcb608b23ac647a32b1a789e0893a12f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 18:23:03 +0100 Subject: [PATCH 14/96] fix: older spark failure never releases a retry sent meanwhile Verified: just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 53 +++++++++++++------ .../to/bitkit/repositories/SparkRepoTest.kt | 36 +++++++++++++ 2 files changed, 74 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 54e94b4583..8a97eaa7f9 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -178,6 +178,9 @@ class SparkRepo @Inject constructor( private val refreshMutex = Mutex() + /** Orders recording a send against a payment event releasing its invoice, so an older event never releases it. */ + private val sendReleaseMutex = Mutex() + /** The invoice of each send still inside Spark's send call, by lowercase payment hash. */ private val sendsInFlight = ConcurrentHashMap() @@ -560,7 +563,7 @@ class SparkRepo @Inject constructor( val sentAt = clock.now().epochSeconds val sent = try { inFlightSentAt[paymentHash.lowercase()] = sentAt.toULong() - sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() + sendReleaseMutex.withLock { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() } cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) spending { // Kept until the call returns, so a send cut off by process death or cancellation stays held. @@ -1787,6 +1790,10 @@ class SparkRepo @Inject constructor( private fun recordedSince(records: Long): Set = sendRecordedAt.filterValues { it > records }.keys + /** Whether this failure is an earlier attempt's, of a retry in doubt or one sent after [records] was read. */ + private fun Payment.isOutrunByRetry(records: Long): Boolean = + isEarlierFailureOfUncertainSend() || hasRecordedSendSince(records, sendHash(PaymentStatus.FAILED)) + private fun Payment.isEarlierFailureOfUncertainSend(): Boolean { val hash = sendHash(PaymentStatus.FAILED) ?: return false val key = hash.lowercase() @@ -1835,27 +1842,36 @@ class SparkRepo @Inject constructor( } private suspend fun onPayment(payment: Payment) { + // A retry of the invoice can start while this event is handled, so each step checks for one sent since now. + val records = sendRecords.get() // The event carries its outcome, so a failed balance read never holds back its settlement. runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after payment '${payment.id}'", it, context = TAG) } // An earlier attempt's failure can arrive after a retry of its invoice went uncertain, and ends nothing of the // retry's: Spark may still finish it, so its hold and its Activity row stay until the expiry rule of // trySettleUncertainSend. - if (payment.isEarlierFailureOfUncertainSend()) { + if (payment.isOutrunByRetry(records)) { Logger.info("Kept uncertain Spark send '${payment.sendHash()}' held past an older failure", context = TAG) return } - recordActivity(payment, settlesJournal = false) - // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. - payment.sendHash()?.let { - uncertainSends.remove(it.lowercase()) - cacheStore.removeSparkUncertainSend(it) - } - payment.sendHash(PaymentStatus.FAILED)?.let { hash -> - val latest = listedLightningSend(hash) + recordActivity(payment, settlesJournal = false, records = records) + val failedHash = payment.sendHash(PaymentStatus.FAILED) + val latest = failedHash?.let { listedLightningSend(it) } + val isSettled = sendReleaseMutex.withLock { + if (payment.isOutrunByRetry(records)) return@withLock false + // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. + payment.sendHash()?.let { + uncertainSends.remove(it.lowercase()) + cacheStore.removeSparkUncertainSend(it) + } val isReleased = latest == SparkLightningSend.NotFound || (latest as? SparkLightningSend.Found)?.status == PaymentStatus.FAILED - if (isReleased) cacheStore.removeSparkSendHash(hash) + if (failedHash != null && isReleased) cacheStore.removeSparkSendHash(failedHash) + true + } + if (!isSettled) { + Logger.info("Kept Spark send '${payment.sendHash()}' held for a retry sent meanwhile", context = TAG) + return } payment.toNodeEvent()?.let { _nodeEvents.emit(it) } } @@ -1865,11 +1881,15 @@ class SparkRepo @Inject constructor( * Spark's list or its send response [settlesJournal]: a payment event can come before the list holds the * withdrawal, which recovery reads, so its journal stays open until the list shows it. */ - private suspend fun recordActivity(payment: Payment, settlesJournal: Boolean = true): Boolean { + private suspend fun recordActivity( + payment: Payment, + settlesJournal: Boolean = true, + records: Long = sendRecords.get(), + ): Boolean { (payment.details as? PaymentDetails.Withdraw)?.let { return recordWithdrawal(payment, it, settlesJournal) } val lightning = payment.details as? PaymentDetails.Lightning ?: return true // An earlier attempt's failure, listed or reported, leaves the row of a retry Spark may still finish. - if (payment.isEarlierFailureOfUncertainSend()) return true + if (payment.isOutrunByRetry(records)) return true if (payment.status == PaymentStatus.PENDING && payment.paymentType == SparkPaymentType.RECEIVE) { return true } @@ -1917,8 +1937,11 @@ class SparkRepo @Inject constructor( contact = existing?.contact ?: receivedContact(payment, id), seenAt = existing?.seenAt, ) - val saved = activityRepo.get().upsertActivity(Activity.Lightning(activity)) - .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } + // The lookup above suspends, so a retry sent meanwhile is checked for again before the write. + val saved = sendReleaseMutex.withLock { + if (payment.isOutrunByRetry(records)) return true + activityRepo.get().upsertActivity(Activity.Lightning(activity)) + }.let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } if (!saved) { unsavedPayments.add(payment.id) return false diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 22f88f572d..70a9c14b68 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3827,6 +3827,42 @@ class SparkRepoTest : BaseUnitTest() { ) } + @Test + fun `an older failure handled across a retry's start leaves the retry's hold`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { awaitCancellation() } + val sut = createSut(store) + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + val olderFailure = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + whenever { sparkService.listPayments() }.thenReturn(listOf(olderFailure)) + // The older failure's handler waits on its Activity lookup while the retry starts. + val lookup = CompletableDeferred() + whenever { activityRepo.getActivity(any(), any()) }.doSuspendableAnswer { + lookup.await() + Result.success(null) + } + sparkEvents.emit(SdkEvent.PaymentFailed(olderFailure)) + runCurrent() + backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } + runCurrent() + + lookup.complete(Unit) + runCurrent() + + val cache = store.data.first() + assertTrue("hash" in cache.sparkUncertainSends, "an older failure dropped the retry's hold") + assertTrue("hash" in cache.sparkSendHashes, "an older failure released the retry's invoice") + assertTrue(events.none { it is Event.PaymentFailed }, "an older failure ended a send Spark may finish") + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) + } + @Test fun `a cancelled spark retry stays held while spark lists only its older failure`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) From 8bb7e6c94df041d660f763517aab9a5344886d84 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 18:53:04 +0100 Subject: [PATCH 15/96] fix: spark retry hold matches failures by earlier attempt ids Verified: just compile, just test, just lint --- .../main/java/to/bitkit/data/CacheStore.kt | 20 ++++- .../java/to/bitkit/repositories/SparkRepo.kt | 70 ++++++++++++----- .../to/bitkit/repositories/SparkRepoTest.kt | 75 ++++++++++++++----- 3 files changed, 126 insertions(+), 39 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index b38d067e0e..30ffd81712 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -175,16 +175,24 @@ class CacheStore internal constructor( } /** - * Keeps Spark's send of [paymentHash] as one whose outcome Spark didn't report, since [failedAt] epoch seconds, and - * when it was sent, [sentAt], once known. + * Keeps Spark's send of [paymentHash] as one whose outcome Spark didn't report, since [failedAt] epoch seconds, with + * when it was sent, [sentAt], and Spark's ids of the invoice's earlier attempts, [earlierIds], once known. */ - suspend fun addSparkUncertainSend(paymentHash: String, failedAt: Long, sentAt: Long? = null) { + suspend fun addSparkUncertainSend( + paymentHash: String, + failedAt: Long, + sentAt: Long? = null, + earlierIds: Set? = null, + ) { val hash = paymentHash.lowercase() store.updateData { it.copy( sparkUncertainSends = it.sparkUncertainSends + (hash to failedAt), sparkUncertainSendStarts = sentAt?.let { start -> it.sparkUncertainSendStarts + (hash to start) } ?: it.sparkUncertainSendStarts, + sparkUncertainSendEarlierIds = earlierIds + ?.let { ids -> it.sparkUncertainSendEarlierIds + (hash to ids.sorted()) } + ?: it.sparkUncertainSendEarlierIds, ) } } @@ -196,6 +204,7 @@ class CacheStore internal constructor( it.copy( sparkUncertainSends = it.sparkUncertainSends - hash, sparkUncertainSendStarts = it.sparkUncertainSendStarts - hash, + sparkUncertainSendEarlierIds = it.sparkUncertainSendEarlierIds - hash, ) } } @@ -394,6 +403,11 @@ data class AppCacheData( * attempt's after a restart. Sends kept before this was have none. */ val sparkUncertainSendStarts: Map = mapOf(), + /** + * Spark's payment ids of each of those sends' earlier attempts, read before it went out, so only those attempts' + * failures read as earlier ones. Absent where Spark couldn't list them. + */ + val sparkUncertainSendEarlierIds: Map> = mapOf(), /** * Payment hashes of the moves to Spark, kept across restarts so neither leg of a move is announced as a payment and * Activity shows the move as one. diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 8a97eaa7f9..2ced08c64a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -108,8 +108,8 @@ class SparkRepo @Inject constructor( private const val CLAIM_POLL_ATTEMPTS = 60 /** - * How far Spark's clock may run behind the phone's: a failure dated within this of a retry's start counts as - * the retry's own. + * How far Spark's clock may differ from the phone's: without the ids of a retry's earlier attempts, a failure + * Spark dates before the retry's start plus this may be an earlier attempt's, so it keeps the retry held. */ private const val RAIL_CLOCK_SKEW_SECONDS = 10uL @@ -184,8 +184,8 @@ class SparkRepo @Inject constructor( /** The invoice of each send still inside Spark's send call, by lowercase payment hash. */ private val sendsInFlight = ConcurrentHashMap() - /** When each send still inside Spark's send call went out, in epoch seconds, by lowercase payment hash. */ - private val inFlightSentAt = ConcurrentHashMap() + /** Each send still inside Spark's send call, by lowercase payment hash. */ + private val inFlightAttempts = ConcurrentHashMap() /** Counts sends recorded, so a listing drops a failed hash only when it was recorded before the listing. */ private val sendRecords = AtomicLong() @@ -555,6 +555,7 @@ class SparkRepo @Inject constructor( expiresAt.toEpochSeconds(), ) } + val earlierIds = earlierAttemptIds(paymentHash) // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. if (!onBeforeSend()) throw PaymentAbortedBeforeSend() if (sendsInFlight.putIfAbsent(paymentHash.lowercase(), bolt11) != null) { @@ -562,12 +563,12 @@ class SparkRepo @Inject constructor( } val sentAt = clock.now().epochSeconds val sent = try { - inFlightSentAt[paymentHash.lowercase()] = sentAt.toULong() + inFlightAttempts[paymentHash.lowercase()] = SendAttempt(sentAt.toULong(), earlierIds) sendReleaseMutex.withLock { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() } cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) spending { // Kept until the call returns, so a send cut off by process death or cancellation stays held. - cacheStore.addSparkUncertainSend(paymentHash, sentAt, sentAt) + cacheStore.addSparkUncertainSend(paymentHash, sentAt, sentAt, earlierIds) // The checks above and both writes suspend, so the deadline and an exit that started meanwhile // are checked last, before the send. runCatching { @@ -581,7 +582,7 @@ class SparkRepo @Inject constructor( runSuspendCatching { sparkService.send(prepared) } } } finally { - inFlightSentAt.remove(paymentHash.lowercase()) + inFlightAttempts.remove(paymentHash.lowercase()) sendsInFlight.remove(paymentHash.lowercase()) } val payment = sent.getOrElse { @@ -599,7 +600,7 @@ class SparkRepo @Inject constructor( 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) - settleUncertainSend(paymentHash, sentAt, expiresAt) + settleUncertainSend(paymentHash, SendAttempt(sentAt.toULong(), earlierIds), expiresAt) throw PaymentPendingException(paymentHash) } cacheStore.removeSparkUncertainSend(paymentHash) @@ -614,10 +615,10 @@ class SparkRepo @Inject constructor( } } - private suspend fun settleUncertainSend(paymentHash: String, sentAt: Long, expiresAt: ULong) { + private suspend fun settleUncertainSend(paymentHash: String, attempt: SendAttempt, expiresAt: ULong) { val failedAt = clock.now().epochSeconds - uncertainSends[paymentHash.lowercase()] = UncertainSend(failedAt.toULong(), expiresAt, sentAt.toULong()) - cacheStore.addSparkUncertainSend(paymentHash, failedAt, sentAt) + uncertainSends[paymentHash.lowercase()] = UncertainSend(failedAt.toULong(), expiresAt, attempt) + cacheStore.addSparkUncertainSend(paymentHash, failedAt, attempt.sentAt?.toLong(), attempt.earlierIds) scope.launch { // The send screen tracks the hash as pending only once the send returns, and resolves tracked ones. withTimeoutOrNull(PENDING_TRACK_WAIT) { @@ -671,18 +672,31 @@ class SparkRepo @Inject constructor( } /** - * A send whose outcome Spark didn't report: when it failed, when its invoice expires and when it started, in epoch - * seconds. Its start is kept across a restart; a send kept before starts were stored has none. + * A send whose outcome Spark didn't report: when it failed and when its invoice expires, in epoch seconds, and its + * [attempt], kept across a restart. */ - private data class UncertainSend(val failedAt: ULong, val expiresAt: ULong, val sentAt: ULong? = null) + private data class UncertainSend( + val failedAt: ULong, + val expiresAt: ULong, + val attempt: SendAttempt = SendAttempt() + ) + + /** + * When a send went out, in epoch seconds, and Spark's payment ids of its invoice's earlier attempts, read before it + * did; null where unknown, such as for a send kept before these were stored or one Spark couldn't list for. + */ + private data class SendAttempt(val sentAt: ULong? = null, val earlierIds: Set? = null) /** Takes back the sends whose outcome Spark didn't report before a restart, so a sync can still settle them. */ private suspend fun restoreUncertainSends() { val cache = cacheStore.data.first() cache.sparkUncertainSends.forEach { (hash, failedAt) -> val expiresAt = cache.sparkSendExpiries[hash]?.toULong() ?: ULong.MAX_VALUE - val sentAt = cache.sparkUncertainSendStarts[hash]?.toULong() - uncertainSends.putIfAbsent(hash, UncertainSend(failedAt.toULong(), expiresAt, sentAt)) + val attempt = SendAttempt( + sentAt = cache.sparkUncertainSendStarts[hash]?.toULong(), + earlierIds = cache.sparkUncertainSendEarlierIds[hash]?.toSet(), + ) + uncertainSends.putIfAbsent(hash, UncertainSend(failedAt.toULong(), expiresAt, attempt)) } } @@ -1794,11 +1808,31 @@ class SparkRepo @Inject constructor( private fun Payment.isOutrunByRetry(records: Long): Boolean = isEarlierFailureOfUncertainSend() || hasRecordedSendSince(records, sendHash(PaymentStatus.FAILED)) + /** + * Whether this failure is an earlier attempt's, of a retry still in Spark's send call or in doubt: one of the + * attempts Spark listed before the retry went out, or, with none listed, one Spark dates before the retry plus its + * clock skew, so a failure that may be either never ends the retry's hold. + */ private fun Payment.isEarlierFailureOfUncertainSend(): Boolean { val hash = sendHash(PaymentStatus.FAILED) ?: return false val key = hash.lowercase() - val sentAt = uncertainSends[key]?.sentAt ?: inFlightSentAt[key] ?: return false - return timestamp + RAIL_CLOCK_SKEW_SECONDS < sentAt + val attempt = uncertainSends[key]?.attempt ?: inFlightAttempts[key] ?: return false + attempt.earlierIds?.let { return id in it } + val sentAt = attempt.sentAt ?: return false + return timestamp < sentAt + RAIL_CLOCK_SKEW_SECONDS + } + + /** Spark's payment ids of the earlier attempts to pay [paymentHash], or null while it can't list them all. */ + private suspend fun earlierAttemptIds(paymentHash: String): Set? { + if (!canListPayments()) return null + val payments = runSuspendCatching { sparkService.listPayments() } + .onFailure { Logger.warn("Failed to list Spark payments before send '$paymentHash'", it, context = TAG) } + .getOrNull() ?: return null + return payments.filter { + val details = it.details as? PaymentDetails.Lightning + it.paymentType == SparkPaymentType.SEND && + details?.htlcDetails?.paymentHash.equals(paymentHash, ignoreCase = true) + }.mapTo(mutableSetOf()) { it.id } } /** The payment hash of this send, at [status] when given. */ diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 70a9c14b68..029d88c5ec 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3540,7 +3540,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val deadline = now + 1.seconds - whenever { cacheStore.addSparkUncertainSend(any(), any(), anyOrNull()) }.thenAnswer { + whenever { cacheStore.addSparkUncertainSend(any(), any(), anyOrNull(), anyOrNull()) }.thenAnswer { now = deadline + 1.seconds Unit } @@ -3612,34 +3612,68 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `a failure dated within spark's clock skew of an uncertain retry ends its hold`() = test { + fun `an earlier attempt's failure dated just before an uncertain retry keeps it held`() = test { + val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED) + assertTrue(retryHeldAfter(listOf(older), older.copy(timestamp = now.epochSeconds.toULong() - 5uL))) + } + + @Test + fun `an earlier attempt's failure dated just after an uncertain retry keeps it held`() = test { + val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED) + assertTrue(retryHeldAfter(listOf(older), older.copy(timestamp = now.epochSeconds.toULong() + 5uL))) + } + + @Test + fun `an uncertain retry's own failure dated before it by spark's clock ends its hold`() = test { + val own = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED) + assertFalse(retryHeldAfter(emptyList(), own.copy(timestamp = now.epochSeconds.toULong() - 5uL))) + } + + @Test + fun `a failure within the clock skew keeps an uncertain retry held while its earlier attempts are unknown`() = + test { + val failure = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED) + assertTrue(retryHeldAfter(null, failure.copy(timestamp = now.epochSeconds.toULong()))) + } + + @Test + fun `a failure past the clock skew ends an uncertain retry's hold while its earlier attempts are unknown`() = + test { + val failure = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED) + assertFalse(retryHeldAfter(null, failure.copy(timestamp = now.epochSeconds.toULong() + 10uL))) + } + + /** + * Sends a retry whose outcome stays unknown, with Spark listing [listedBeforeSend] before it goes out (null while it + * never synced, so it can't list), then delivers [failure]; true when the retry stays held. + */ + private suspend fun TestScope.retryHeldAfter(listedBeforeSend: List?, failure: Payment): Boolean { whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL) - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } + // Spark that never synced can't list every earlier attempt. + if (listedBeforeSend == null) { + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncError = SyncError.Network("down"))) + } val sut = createSut() sut.start(0).getOrThrow() val events = mutableListOf() backgroundScope.launch { sut.nodeEvents.collect { events += it } } runCurrent() - // Spark's clock runs 5 s behind the phone's, so the retry's own failure is dated before it started. - val failed = sentPayment(fees = 0).copy( - status = PaymentStatus.FAILED, - timestamp = now.epochSeconds.toULong() - 5uL, - ) - whenever { sparkService.listPayments() }.thenReturn(listOf(failed)) - whenever { sparkService.getInfo() }.thenReturn( + whenever(sparkService.listPayments()).thenReturn(listedBeforeSend.orEmpty()) + whenever(sparkService.getInfo()).thenReturn( info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable"), lastSyncedAt = 1uL) ) assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) runCurrent() - sparkEvents.emit(SdkEvent.PaymentFailed(failed)) + whenever(sparkService.listPayments()).thenReturn(listOf(failure)) + sparkEvents.emit(SdkEvent.PaymentFailed(failure)) advanceUntilIdle() - assertTrue(events.any { it is Event.PaymentFailed }, "a failure within the clock skew didn't end the send") - assertNull(sut.earlierLightningSend("lnbc1", "hash"), "a failure within the clock skew kept the retry held") + return events.none { it is Event.PaymentFailed } } @Test @@ -3654,11 +3688,13 @@ class SparkRepoTest : BaseUnitTest() { now += 5.seconds throw SdkException.Generic("timeout") } + // Spark lists no earlier attempt when the retry goes out, which the restart keeps. + whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = 1uL)) + val before = createSut(store) + before.start(0).getOrThrow() whenever { sparkService.getInfo() }.thenReturn( info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) ) - val before = createSut(store) - before.start(0).getOrThrow() val sentAt = now.epochSeconds.toULong() assertIs(before.payInvoice("lnbc1", 100uL).exceptionOrNull()) runCurrent() @@ -3674,6 +3710,7 @@ class SparkRepoTest : BaseUnitTest() { sparkEvents.emit(SdkEvent.PaymentFailed(failed)) advanceUntilIdle() + assertEquals(emptyList(), store.data.first().sparkUncertainSendEarlierIds["hash"].orEmpty()) assertNull(after.earlierLightningSend("lnbc1", "hash"), "the retry's own failure still held the node off") } @@ -3806,14 +3843,16 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) // Spark's send call is still running when the earlier attempt's failure arrives. whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { awaitCancellation() } + val olderFailure = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + whenever { sparkService.listPayments() }.thenReturn(listOf(olderFailure)) val sut = createSut(store) sut.start(0).getOrThrow() + // The start recorded the older attempt's failure, before the retry. + clearInvocations(activityRepo) val events = mutableListOf() backgroundScope.launch { sut.nodeEvents.collect { events += it } } backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } runCurrent() - val olderFailure = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) - whenever { sparkService.listPayments() }.thenReturn(listOf(olderFailure)) sparkEvents.emit(SdkEvent.PaymentFailed(olderFailure)) runCurrent() From 328df0dd67ccca28a1fd44a1c9907cd550819106 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 18:56:31 +0100 Subject: [PATCH 16/96] chore: wrap spark attempt kdoc lines Verified: just lint (compile and test passed on 8bb7e6c94; this commit changes comments only) --- app/src/main/java/to/bitkit/data/CacheStore.kt | 4 ++-- app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt | 4 ++-- 2 files changed, 4 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 30ffd81712..e385bf9fd0 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -175,8 +175,8 @@ class CacheStore internal constructor( } /** - * Keeps Spark's send of [paymentHash] as one whose outcome Spark didn't report, since [failedAt] epoch seconds, with - * when it was sent, [sentAt], and Spark's ids of the invoice's earlier attempts, [earlierIds], once known. + * Keeps Spark's send of [paymentHash] as one whose outcome Spark didn't report, since [failedAt] epoch seconds, + * with when it was sent, [sentAt], and Spark's ids of the invoice's earlier attempts, [earlierIds], once known. */ suspend fun addSparkUncertainSend( paymentHash: String, diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 029d88c5ec..23f2ff65d6 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3644,8 +3644,8 @@ class SparkRepoTest : BaseUnitTest() { } /** - * Sends a retry whose outcome stays unknown, with Spark listing [listedBeforeSend] before it goes out (null while it - * never synced, so it can't list), then delivers [failure]; true when the retry stays held. + * Sends a retry whose outcome stays unknown, with Spark listing [listedBeforeSend] before it goes out (null while + * it never synced, so it can't list), then delivers [failure]; true when the retry stays held. */ private suspend fun TestScope.retryHeldAfter(listedBeforeSend: List?, failure: Payment): Boolean { whenever(sparkService.isSupported).thenReturn(true) From 802cad46ffa2822517e630567653320b3685cf71 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 19:07:50 +0100 Subject: [PATCH 17/96] fix: drop the retained spark move on wallet wipe A wipe now cancels the move manager's quote and move, clears its kept outcome and returns it to quoting, so the next wallet in the same process gets a fresh quote. Verified: just compile, just test, just lint; MoveToSparkViewModelTest wipe case fails without the fix --- .../ui/settings/lightning/MoveToSparkManager.kt | 13 ++++++++++++- .../java/to/bitkit/usecases/WipeWalletUseCase.kt | 3 +++ .../settings/lightning/MoveToSparkViewModelTest.kt | 12 ++++++++++++ .../to/bitkit/usecases/WipeWalletUseCaseTest.kt | 5 +++++ 4 files changed, 32 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt index 5b1fb9290e..7d5c15e691 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt @@ -46,6 +46,7 @@ class MoveToSparkManager @Inject constructor( private val generation = AtomicInteger(0) private val latestScreen = AtomicInteger(0) private var quoteJob: Job? = null + private var moveJob: Job? = null /** A move was started and its outcome is still the screen's, so opening the screen again keeps it. */ @Volatile @@ -77,6 +78,16 @@ class MoveToSparkManager @Inject constructor( _uiState.update { MoveToSparkUiState.Quoting } } + /** Drops the move, its outcome and any quote when the wallet is wiped, so the next wallet starts on a new quote. */ + fun resetForWipe() { + generation.incrementAndGet() + quoteJob?.cancel() + moveJob?.cancel() + keepsOutcome = false + isMoveInFlight = false + _uiState.update { MoveToSparkUiState.Quoting } + } + /** Quotes moving [targetSats], or everything the channels can send. */ fun quote(targetSats: ULong? = null) { val quoteGeneration = generation.incrementAndGet() @@ -100,7 +111,7 @@ class MoveToSparkManager @Inject constructor( keepsOutcome = true isMoveInFlight = true _uiState.update { MoveToSparkUiState.Confirm(quote, isMoving = true) } - scope.launch { + moveJob = scope.launch { try { moveToSparkRepo.move(quote).fold( onSuccess = { outcome -> diff --git a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt index e238d7eee7..ef1abdcbac 100644 --- a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt @@ -26,6 +26,7 @@ import to.bitkit.repositories.WatchOnlyAccountRepo import to.bitkit.services.CoreService import to.bitkit.services.MigrationService import to.bitkit.services.PaykitSdkService +import to.bitkit.ui.settings.lightning.MoveToSparkManager import to.bitkit.utils.AppError import to.bitkit.utils.Logger import javax.inject.Inject @@ -58,6 +59,7 @@ class WipeWalletUseCase @Inject constructor( private val paykitReceiptRepo: PaykitReceiptRepo, private val connectionRecovery: WalletConnectionRecovery, private val wakeRepo: WakeRepo, + private val moveToSparkManager: Provider, ) { private val wipeMutex = Mutex() @@ -125,6 +127,7 @@ class WipeWalletUseCase @Inject constructor( blocktankRepo.resetState() activityRepo.resetState() hwWalletRepo.resetState() + moveToSparkManager.get().resetForWipe() resetWalletState() step("mark migration checked") { migrationService.markMigrationChecked() } return if (keychainWiped) Result.success(Unit) else Result.failure(WipeIncomplete()) diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt index e11b96d67a..cc870e26f8 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/MoveToSparkViewModelTest.kt @@ -151,5 +151,17 @@ class MoveToSparkViewModelTest : BaseUnitTest() { assertEquals(MoveToSparkUiState.Confirm(quote), reopened.uiState.value) } + @Test + fun `wiping the wallet drops an in-flight move and quotes anew on return`() = test { + createViewModel().move() + + manager.resetForWipe() + val reopened = createViewModel() + firstSettled.complete(Result.success(moved)) + + assertEquals(MoveToSparkUiState.Confirm(quote), reopened.uiState.value) + verify(moveToSparkRepo, times(2)).quote(anyOrNull()) + } + private fun createViewModel() = MoveToSparkViewModel(manager) } diff --git a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt index 9f6c9c61d3..ffcaebbf5c 100644 --- a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt @@ -42,6 +42,7 @@ import to.bitkit.services.MigrationService import to.bitkit.services.PaykitSdkService import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture +import to.bitkit.ui.settings.lightning.MoveToSparkManager import javax.inject.Provider import kotlin.test.assertFailsWith import kotlin.test.assertFalse @@ -74,6 +75,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { private val wakeRepo = mock() private val paykitSdkService = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { mock() } private val privatePaykitRepoProvider = Provider { privatePaykitRepo } + private val moveToSparkManager = mock() private lateinit var sut: WipeWalletUseCase @@ -122,6 +124,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { paykitSdkService = paykitSdkService, connectionRecovery = connectionRecoveryFixture(settingsStore), wakeRepo = wakeRepo, + moveToSparkManager = Provider { moveToSparkManager }, ) } @@ -154,6 +157,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { privatePaykitAddressReservationRepo, migrationService, wakeRepo, + moveToSparkManager, ) inOrder.verify(backupRepo).setWiping(true) inOrder.verify(lightningRepo).setWiping(true) @@ -181,6 +185,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() { inOrder.verify(blocktankRepo).resetState() inOrder.verify(activityRepo).resetState() inOrder.verify(hwWalletRepo).resetState() + inOrder.verify(moveToSparkManager).resetForWipe() inOrder.verify(migrationService).markMigrationChecked() assertTrue(onWipeCalled) assertTrue(onSetWalletExistsStateCalled) From 06e645bcbbd331e8a57526b2873601d0d518a4e7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 19:07:51 +0100 Subject: [PATCH 18/96] fix: correct pt-br spark balance strings Verified: just compile, just test, just lint --- app/src/main/res/values-pt-rBR/strings.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index d98102aca2..6dff2afc45 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -178,7 +178,7 @@ Valor Seu saldo passa para a Spark através da Lightning, a forma mais barata de o manter nos Gastos. A taxa de roteamento abaixo é o máximo que paga. Mover para a\n<accent>Spark</accent> - Parte dseu saldo já está na Spark. Mova o resto da mesma forma e depois feche a conexão esvaziada. + Parte do seu saldo já está na Spark. Mova o resto da mesma forma e depois feche a conexão esvaziada. Seu saldo já está na Spark. Feche a conexão esvaziada para devolver a reserva dela à poupança. Movido para a\n<accent>Spark</accent> Suas conexões Lightning não têm mais saldo para mover. @@ -1192,7 +1192,7 @@ Saldo de reserva Este contato não tem nenhum método de pagamento que o Bitkit possa usar agora. Não é possível pagar este contato - Um levantamento anterior dseu saldo de gastos ainda está a ser concluído. Tente novamente quando for concluído. + Um levantamento anterior do seu saldo de gastos ainda está a ser concluído. Tente novamente quando for concluído. As transferências para o saldo de gastos não estão mais disponíveis. O Bitkit primeiro verifica a rede e depois devolve as moedas desta transferência para sua carteira, para que a transferência original nunca seja confirmada. Isso tem uma taxa de rede. Esse pagamento está demorando mais do que o esperado. Enquanto isso, você pode continuar usando a Bitkit. Pagamento Pendente @@ -1434,8 +1434,8 @@ Taxa do Spark Sua transferência foi iniciada e está sendo <accent>liquidada onchain</accent>. Seu saldo de poupança será atualizado automaticamente quando ela for concluída. Transferência\n<accent>a caminho</accent> - Seu saldo Spark não pôde ser movido para a poupança e fica nseu saldo de gastos. - Os fundos dos seus canais estão sendo movidos para a poupança, mas seu saldo Spark não pôde ser movido e fica nseu saldo de gastos. + Seu saldo Spark não pôde ser movido para a poupança e fica no seu saldo de gastos. + Os fundos dos seus canais estão sendo movidos para a poupança, mas seu saldo Spark não pôde ser movido e fica no seu saldo de gastos. <accent>Conectando</accent>\nà rede Reconecte seu dispositivo de hardware, ele parece estar desconectado do seu telefone. Reconectar Dispositivo de Hardware From 2c7290df51279274afa6922800a7338e20bcf5a3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 21:40:20 +0100 Subject: [PATCH 19/96] fix: end a held spark retry's activity row on expiry When an uncertain retry's hold ends with a failed or missing send, its Activity row is written from Spark's latest listed send, or the pending send row is marked failed when Spark lists none, so a row an earlier failure left pending no longer stays pending. Verified: just compile, just test, just lint; the new SparkRepoTest expiry case fails without the fix --- .../java/to/bitkit/repositories/SparkRepo.kt | 25 ++++++++++- .../to/bitkit/repositories/SparkRepoTest.kt | 45 +++++++++++++++++++ 2 files changed, 69 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 2ced08c64a..64833454c6 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -658,12 +658,16 @@ class SparkRepo @Inject constructor( when (send) { SparkLightningSend.NotFound -> { cacheStore.removeSparkSendHash(paymentHash) + finishHeldActivity(paymentHash) _nodeEvents.emit(Event.PaymentFailed(paymentHash, paymentHash, PaymentFailureReason.UNEXPECTED_ERROR)) } // A pending send ends with its own payment event. is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> Unit is SparkLightningSend.Found -> { - if (send.status == PaymentStatus.FAILED) cacheStore.removeSparkSendHash(paymentHash) + if (send.status == PaymentStatus.FAILED) { + cacheStore.removeSparkSendHash(paymentHash) + finishHeldActivity(paymentHash) + } settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } } SparkLightningSend.Unavailable -> Unit @@ -671,6 +675,25 @@ class SparkRepo @Inject constructor( return true } + /** + * Ends the Activity row a held send kept pending, as an earlier attempt's failure is skipped while the hold lasts: + * from Spark's listed send, or as failed when Spark lists none. + */ + private suspend fun finishHeldActivity(paymentHash: String) { + val listed = runSuspendCatching { sparkService.listPayments() } + .onFailure { Logger.warn("Failed to list Spark payments for '$paymentHash'", it, context = TAG) } + .getOrNull() + ?.latestSend(paymentHash) + if (listed != null) { + recordActivity(listed) + return + } + val stored = activityRepo.get().getActivity(paymentHash).getOrNull() as? Activity.Lightning ?: return + if (stored.v1.txType != PaymentType.SENT || stored.v1.status != PaymentState.PENDING) return + activityRepo.get().upsertActivity(Activity.Lightning(stored.v1.copy(status = PaymentState.FAILED))) + .onFailure { Logger.warn("Failed to mark Spark send '$paymentHash' failed", it, context = TAG) } + } + /** * A send whose outcome Spark didn't report: when it failed and when its invoice expires, in epoch seconds, and its * [attempt], kept across a restart. diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 23f2ff65d6..bb2ca34302 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3835,6 +3835,51 @@ class SparkRepoTest : BaseUnitTest() { ) } + @Test + fun `an uncertain spark retry held past an older failure ends its row as failed once its invoice expires`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } + val olderFailure = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + whenever { sparkService.listPayments() }.thenReturn(listOf(olderFailure)) + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + ) + val before = createSut(store) + before.start(0).getOrThrow() + assertIs(before.payInvoice("lnbc1", 100uL).exceptionOrNull()) + runCurrent() + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) + ) + clearInvocations(activityRepo) + val restartedEvents = MutableSharedFlow() + whenever(sparkService.events).thenReturn(restartedEvents) + val after = createSut(store) + after.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { after.nodeEvents.collect { events += it } } + runCurrent() + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) + + // The invoice expires and Spark syncs, still listing only the older failure. + now += 2.hours + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) + ) + restartedEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertTrue(events.any { it is Event.PaymentFailed }, "the expired retry was never reported failed") + verify(activityRepo, atLeastOnce()).upsertActivity( + argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } + ) + } + @Test fun `an older attempt's failure during a spark retry's send keeps its hold`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) From b00bb8b04d95bcd4ae1bb9d3e7825375fce0b3d2 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 23:01:18 +0100 Subject: [PATCH 20/96] fix: keep spark retry holds until their attempt settles A retry cancelled inside Spark's send call stays held in memory as its journal entry does, so an earlier attempt's failure can't release it. An expired retry Spark lists no send for keeps its hold until its pending row is written failed, under the lock Spark's row writes take. An Instant early claim is capped at the approved ceiling, so Spark claims any later offer within it. Verified: just compile, just test, just lint; the new SparkRepoTest cases fail on the previous SparkRepo --- .../java/to/bitkit/repositories/SparkRepo.kt | 71 +++++++---- .../to/bitkit/repositories/SparkRepoTest.kt | 113 +++++++++++++++--- 2 files changed, 148 insertions(+), 36 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 64833454c6..d6f951eedd 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -562,6 +562,8 @@ class SparkRepo @Inject constructor( throw PaymentPendingException(paymentHash) } val sentAt = clock.now().epochSeconds + var isDispatched = false + var hasReturned = false val sent = try { inFlightAttempts[paymentHash.lowercase()] = SendAttempt(sentAt.toULong(), earlierIds) sendReleaseMutex.withLock { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() } @@ -579,9 +581,18 @@ class SparkRepo @Inject constructor( cacheStore.removeSparkSendHash(paymentHash) throw it } - runSuspendCatching { sparkService.send(prepared) } + isDispatched = true + runSuspendCatching { sparkService.send(prepared) }.also { hasReturned = true } } } finally { + // A send cancelled inside Spark's call stays in doubt, as its journal entry does, so a sync settles it. + if (isDispatched && !hasReturned) { + val attempt = SendAttempt(sentAt.toULong(), earlierIds) + uncertainSends.putIfAbsent( + paymentHash.lowercase(), + UncertainSend(clock.now().epochSeconds.toULong(), expiresAt, attempt), + ) + } inFlightAttempts.remove(paymentHash.lowercase()) sendsInFlight.remove(paymentHash.lowercase()) } @@ -652,13 +663,15 @@ class SparkRepo @Inject constructor( is SparkLightningSend.Found -> send.status != PaymentStatus.FAILED || isFinal SparkLightningSend.Unavailable -> false } + if (!isSettled) return false + // A missing send's row is ended here, as no listed payment revisits it, so the hold stays until it is written. + if (send == SparkLightningSend.NotFound && !failHeldRow(paymentHash)) return false // Only the caller that takes the hash off settles it, so its outcome is reported once. - if (!isSettled || !uncertainSends.remove(key, uncertain)) return isSettled + if (!uncertainSends.remove(key, uncertain)) return true cacheStore.removeSparkUncertainSend(paymentHash) when (send) { SparkLightningSend.NotFound -> { cacheStore.removeSparkSendHash(paymentHash) - finishHeldActivity(paymentHash) _nodeEvents.emit(Event.PaymentFailed(paymentHash, paymentHash, PaymentFailureReason.UNEXPECTED_ERROR)) } // A pending send ends with its own payment event. @@ -666,7 +679,7 @@ class SparkRepo @Inject constructor( is SparkLightningSend.Found -> { if (send.status == PaymentStatus.FAILED) { cacheStore.removeSparkSendHash(paymentHash) - finishHeldActivity(paymentHash) + recordHeldSend(paymentHash) } settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } } @@ -676,22 +689,31 @@ class SparkRepo @Inject constructor( } /** - * Ends the Activity row a held send kept pending, as an earlier attempt's failure is skipped while the hold lasts: - * from Spark's listed send, or as failed when Spark lists none. + * Records Spark's listed send of [paymentHash] once its hold ended, as an earlier attempt's failure is skipped + * while the hold lasts; a failed write is retried at the next refresh. */ - private suspend fun finishHeldActivity(paymentHash: String) { - val listed = runSuspendCatching { sparkService.listPayments() } + private suspend fun recordHeldSend(paymentHash: String) { + runSuspendCatching { sparkService.listPayments() } .onFailure { Logger.warn("Failed to list Spark payments for '$paymentHash'", it, context = TAG) } .getOrNull() ?.latestSend(paymentHash) - if (listed != null) { - recordActivity(listed) - return - } - val stored = activityRepo.get().getActivity(paymentHash).getOrNull() as? Activity.Lightning ?: return - if (stored.v1.txType != PaymentType.SENT || stored.v1.status != PaymentState.PENDING) return - activityRepo.get().upsertActivity(Activity.Lightning(stored.v1.copy(status = PaymentState.FAILED))) + ?.let { recordActivity(it) } + } + + /** + * Marks the pending send row of [paymentHash] failed, as Spark lists no send of it; true once nothing is pending. + * Read and write share the lock Spark's own row writes take, so a settlement written meanwhile is not overwritten. + */ + private suspend fun failHeldRow(paymentHash: String): Boolean = sendReleaseMutex.withLock { + val stored = activityRepo.get().getActivity(paymentHash).getOrElse { + Logger.warn("Failed to read activity of Spark send '$paymentHash'", it, context = TAG) + return@withLock false + } + val send = (stored as? Activity.Lightning)?.v1 + if (send?.txType != PaymentType.SENT || send.status != PaymentState.PENDING) return@withLock true + activityRepo.get().upsertActivity(Activity.Lightning(send.copy(status = PaymentState.FAILED))) .onFailure { Logger.warn("Failed to mark Spark send '$paymentHash' failed", it, context = TAG) } + .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } } /** @@ -803,8 +825,9 @@ class SparkRepo @Inject constructor( private suspend fun claimInstantly(txid: String, ceilingSats: ULong) { var isSeen = false - // Once Spark waits for the early claim, the fee cap stays on the deposit and Spark claims it by itself when the - // provider offers it, so the poll only watches for the claim and asks the provider nothing more. + // Once Spark waits for the early claim, the user's ceiling stays on the deposit as its cap and Spark claims it + // by itself when the provider offers it within the cap, so the poll only watches for the claim and asks the + // provider nothing more; an offer above the cap is never charged and the deposit is claimed at maturity. var isWaiting = false repeat(CLAIM_POLL_ATTEMPTS) { runSuspendCatching { refresh() } @@ -825,7 +848,7 @@ class SparkRepo @Inject constructor( SparkClaimStep.Adding -> SparkDepositClaim.Adding SparkClaimStep.Unavailable -> SparkDepositClaim.Unavailable is SparkClaimStep.Ask -> SparkDepositClaim.Repriced(step.offer) - is SparkClaimStep.ClaimEarly -> claimEarly(step.offer).getOrNull() + is SparkClaimStep.ClaimEarly -> claimEarly(step.offer, ceilingSats).getOrNull() ?.also { isWaiting = it == SparkEarlyClaim.Waiting } ?.toDepositClaim(step.offer) } @@ -869,10 +892,16 @@ class SparkRepo @Inject constructor( } } - /** Accepts the early claim of [offer] at its quoted fee. */ - suspend fun claimEarly(offer: SparkClaimOffer.Choice): Result = withContext(bgDispatcher) { + /** + * Accepts the early claim of [offer] for at most [maxFeeSats], the fee the user accepted. Spark keeps it as the cap + * when it waits, so a later offer within it is claimed too. + */ + suspend fun claimEarly( + offer: SparkClaimOffer.Choice, + maxFeeSats: ULong = offer.earlyFeeSats, + ): Result = withContext(bgDispatcher) { earlyClaimVouts[offer.txid] = offer.vout - runSuspendCatching { sparkService.claimDeposit(offer.txid, offer.vout, offer.earlyFeeSats) } + runSuspendCatching { sparkService.claimDeposit(offer.txid, offer.vout, maxFeeSats) } .map { SparkEarlyClaim.from(it) } .recoverCatching { if (it is SdkException.DepositClaimInProgress) SparkEarlyClaim.Claimed else throw it } .onSuccess { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index bb2ca34302..a18173fd3b 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -2322,22 +2322,23 @@ class SparkRepoTest : BaseUnitTest() { fun `instant claims early at once when the offer is within the ceiling`() = test { listDeposit() whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) - whenever { sparkService.claimDeposit("txid", 0u, 300uL) }.thenReturn(ClaimDepositOutcome.Submitted) + whenever { sparkService.claimDeposit("txid", 0u, 500uL) }.thenReturn(ClaimDepositOutcome.Submitted) whenever { sparkService.listPayments() }.thenReturn(emptyList(), listOf(depositPayment())) val sut = createSut() sut.followDepositClaim("txid", SparkClaimSpeed.Instant, ceilingSats = 500uL) advanceUntilIdle() - verify(sparkService).claimDeposit("txid", 0u, 300uL) + verify(sparkService).claimDeposit("txid", 0u, 500uL) assertEquals(SparkDepositClaim.Claimed, sut.depositClaims.value["txid"]) } @Test - fun `instant stops quoting once spark waits for the early claim`() = test { + fun `instant stops quoting once spark waits for the early claim, capped at the ceiling`() = test { listDeposit() + // Spark keeps the ceiling as the cap, so it claims a later offer within it by itself. whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) - whenever { sparkService.claimDeposit("txid", 0u, 300uL) } + whenever { sparkService.claimDeposit("txid", 0u, 500uL) } .thenReturn(ClaimDepositOutcome.Deferred(ClaimDeferredReason.NoEarlyClaimAvailable)) val sut = createSut() @@ -2345,7 +2346,8 @@ class SparkRepoTest : BaseUnitTest() { advanceUntilIdle() verify(sparkService, times(1)).fetchClaimQuote("txid", 0u) - verify(sparkService, times(1)).claimDeposit("txid", 0u, 300uL) + verify(sparkService, times(1)).claimDeposit(any(), any(), any()) + verify(sparkService).claimDeposit("txid", 0u, 500uL) assertEquals(SparkDepositClaim.Unavailable, sut.depositClaims.value["txid"]) } @@ -2356,14 +2358,14 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.listUnclaimedDeposits() } .thenReturn(listOf(deposit), listOf(deposit), listOf(deposit), emptyList()) whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) - whenever { sparkService.claimDeposit("txid", 0u, 300uL) } + whenever { sparkService.claimDeposit("txid", 0u, 500uL) } .thenReturn(ClaimDepositOutcome.Deferred(ClaimDeferredReason.NoEarlyClaimAvailable)) val sut = createSut() sut.followDepositClaim("txid", SparkClaimSpeed.Instant, ceilingSats = 500uL) advanceUntilIdle() - verify(sparkService, times(1)).claimDeposit("txid", 0u, 300uL) + verify(sparkService, times(1)).claimDeposit("txid", 0u, 500uL) assertEquals(SparkDepositClaim.Adding, sut.depositClaims.value["txid"]) } @@ -2401,9 +2403,9 @@ class SparkRepoTest : BaseUnitTest() { fun `instant shows the new price when the claim comes back repriced`() = test { listDeposit() whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) - whenever { sparkService.claimDeposit("txid", 0u, 300uL) }.thenReturn( + whenever { sparkService.claimDeposit("txid", 0u, 500uL) }.thenReturn( ClaimDepositOutcome.Deferred( - ClaimDeferredReason.MaxFeeExceeded(requiredFeeSats = 450uL, maxFeeSats = 300uL) + ClaimDeferredReason.MaxFeeExceeded(requiredFeeSats = 600uL, maxFeeSats = 500uL) ) ) val sut = createSut() @@ -2412,16 +2414,16 @@ class SparkRepoTest : BaseUnitTest() { advanceUntilIdle() val claim = assertIs(sut.depositClaims.value["txid"]) - assertEquals(450uL, claim.offer.earlyFeeSats) + assertEquals(600uL, claim.offer.earlyFeeSats) } @Test fun `wait after a claim time reprice clears the early claim cap`() = test { listDeposit() whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) - whenever { sparkService.claimDeposit("txid", 0u, 300uL) }.thenReturn( + whenever { sparkService.claimDeposit("txid", 0u, 500uL) }.thenReturn( ClaimDepositOutcome.Deferred( - ClaimDeferredReason.MaxFeeExceeded(requiredFeeSats = 450uL, maxFeeSats = 300uL) + ClaimDeferredReason.MaxFeeExceeded(requiredFeeSats = 600uL, maxFeeSats = 500uL) ) ) val sut = createSut() @@ -2439,9 +2441,9 @@ class SparkRepoTest : BaseUnitTest() { fun `wait clears the early claim cap again when another claim held the deposit`() = test { listDeposit() whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) - whenever { sparkService.claimDeposit("txid", 0u, 300uL) }.thenReturn( + whenever { sparkService.claimDeposit("txid", 0u, 500uL) }.thenReturn( ClaimDepositOutcome.Deferred( - ClaimDeferredReason.MaxFeeExceeded(requiredFeeSats = 450uL, maxFeeSats = 300uL) + ClaimDeferredReason.MaxFeeExceeded(requiredFeeSats = 600uL, maxFeeSats = 500uL) ) ) // The first call meets Spark's own sync claiming the deposit, which leaves the cap in place. @@ -2501,7 +2503,7 @@ class SparkRepoTest : BaseUnitTest() { fun `instant is unavailable when the provider declines the early claim`() = test { listDeposit() whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) - whenever { sparkService.claimDeposit("txid", 0u, 300uL) }.thenReturn( + whenever { sparkService.claimDeposit("txid", 0u, 500uL) }.thenReturn( ClaimDepositOutcome.Deferred(ClaimDeferredReason.ProviderDeclined("no")) ) val sut = createSut() @@ -3880,6 +3882,87 @@ class SparkRepoTest : BaseUnitTest() { ) } + @Test + fun `an older attempt's failure after a spark retry was cancelled inside its send keeps its hold`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { awaitCancellation() } + val olderFailure = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + whenever { sparkService.listPayments() }.thenReturn(listOf(olderFailure)) + val sut = createSut(store) + sut.start(0).getOrThrow() + clearInvocations(activityRepo) + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + val send = backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } + runCurrent() + + // The send screen goes away while Spark's send call runs, and the older failure arrives after. + send.cancel() + runCurrent() + sparkEvents.emit(SdkEvent.PaymentFailed(olderFailure)) + runCurrent() + + assertTrue( + events.none { it is Event.PaymentFailed }, + "an older failure ended a cancelled send Spark may finish" + ) + assertTrue( + "hash" in store.data.first().sparkUncertainSends, + "an older failure dropped the cancelled send's hold" + ) + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) + } + + @Test + fun `an expired spark send missing from spark keeps its hold until its row is marked failed`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } + val pending = LightningActivity.create( + id = "hash", + txType = ActivityPaymentType.SENT, + status = PaymentState.PENDING, + value = 100uL, + invoice = "lnbc1", + timestamp = 1uL, + ) + whenever { activityRepo.getActivity(eq("hash"), any()) }.thenReturn(Result.success(Activity.Lightning(pending))) + whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.failure(IllegalStateException("disk full"))) + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + + // The invoice expires and Spark syncs, listing no such send, while Activity can't be written. + now += 2.hours + whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertTrue(events.none { it is Event.PaymentFailed }, "a send was reported failed while its row stayed pending") + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + + // The next sync writes the row, which ends the hold. + whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.success(Unit)) + clearInvocations(activityRepo) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertTrue(events.any { it is Event.PaymentFailed }, "the expired send was never reported failed") + verify(activityRepo, atLeastOnce()).upsertActivity( + argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } + ) + } + @Test fun `an older attempt's failure during a spark retry's send keeps its hold`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) From 3bc175c51254602c0fd26d7e77296bc43af22521 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 23:01:18 +0100 Subject: [PATCH 21/96] fix: recheck a retained move's stored payment while waiting Verified: just compile, just test, just lint; the new MoveToSparkRepoTest case fails on the previous MoveToSparkRepo --- .../to/bitkit/repositories/MoveToSparkRepo.kt | 33 +++++++++++-------- .../repositories/MoveToSparkRepoTest.kt | 9 +++++ 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index 5745ba2941..35566bcecf 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -31,6 +31,7 @@ import java.util.concurrent.atomic.AtomicReference import javax.inject.Inject import javax.inject.Singleton import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds /** * Moves the balance of the user's Lightning channels to their own Spark wallet, paying a Spark invoice over the @@ -53,6 +54,9 @@ class MoveToSparkRepo internal constructor( /** How long the move waits for the payment to settle before it reports it as still in flight. */ private val PAYMENT_TIMEOUT = 2.minutes + /** How often a move waiting past its timeout reads the node's stored payment again, as the node may be down. */ + private val STORED_PAYMENT_RECHECK = 30.seconds + /** The failures that mean no route carried the amount, so a smaller one may route. */ private val NO_ROUTE_REASONS = setOf(PaymentFailureReason.ROUTE_NOT_FOUND, PaymentFailureReason.RETRIES_EXHAUSTED) @@ -189,7 +193,8 @@ class MoveToSparkRepo internal constructor( /** * Waits for the payment of a move still [inFlight] to settle after the move stopped waiting. It listens first, then - * reads the node's stored payment, so an outcome that arrived after the move stopped listening is not missed. + * reads the node's stored payment, so an outcome that arrived after the move stopped listening is not missed, and + * reads it again while it waits, as the node may be down for a read. */ suspend fun awaitSettled(inFlight: MoveToSparkOutcome.InFlight): Result = withContext(bgDispatcher) { @@ -198,21 +203,21 @@ class MoveToSparkRepo internal constructor( val settled = async(start = CoroutineStart.UNDISPATCHED) { lightningRepo.nodeEvents.first { it.settles(inFlight.paymentHash, inFlight.paymentId) } } - val stored = lightningRepo.listPaymentsOrNull()?.firstOrNull { it.id == inFlight.paymentId } - when (stored?.status) { - PaymentStatus.SUCCEEDED -> { - settled.cancel() - MoveToSparkOutcome.Moved(inFlight.amountSats, (stored.feePaidMsat ?: 0uL) / 1000uL) - } - PaymentStatus.FAILED -> { - settled.cancel() - throw MoveToSparkError.PaymentFailed(null) - } - else -> when (val event = settled.await()) { - is Event.PaymentSuccessful -> event.moved(inFlight.amountSats) - else -> throw MoveToSparkError.PaymentFailed((event as? Event.PaymentFailed)?.reason) + var moved: MoveToSparkOutcome.Moved? = null + while (moved == null) { + val stored = lightningRepo.listPaymentsOrNull()?.firstOrNull { it.id == inFlight.paymentId } + moved = when (stored?.status) { + PaymentStatus.SUCCEEDED -> + MoveToSparkOutcome.Moved(inFlight.amountSats, (stored.feePaidMsat ?: 0uL) / 1000uL) + PaymentStatus.FAILED -> throw MoveToSparkError.PaymentFailed(null) + else -> withTimeoutOrNull(STORED_PAYMENT_RECHECK) { settled.await() }?.let { + (it as? Event.PaymentSuccessful)?.moved(inFlight.amountSats) + ?: throw MoveToSparkError.PaymentFailed((it as? Event.PaymentFailed)?.reason) + } } } + settled.cancel() + moved } }.onFailure { Logger.warn("Failed to move '${inFlight.amountSats}' sats to Spark after the wait", it, context = TAG) diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index 53b4bec4fa..bb2f4f51bb 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -230,6 +230,15 @@ class MoveToSparkRepoTest : BaseUnitTest() { assertIs(sut.awaitSettled(inFlight).exceptionOrNull()) } + @Test + fun `an in-flight move whose outcome was missed while the node was down reads it once the node is back`() = test { + // The node can't list its payments at first, and the settling event came before the listener started. + whenever(lightningRepo.listPaymentsOrNull()).thenReturn(null, listOf(nodeSend(PaymentStatus.SUCCEEDED))) + val settled = async(start = CoroutineStart.UNDISPATCHED) { sut.awaitSettled(inFlight) } + + assertEquals(MoveToSparkOutcome.Moved(50_000uL, feeSats = 7uL), settled.await().getOrThrow()) + } + @Test fun `move pays over the channels capped at the quoted fee and reports the fee paid`() = test { whenever( From b188b6dba01156e01d091bca840c6c0fb8abea49 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 23:01:18 +0100 Subject: [PATCH 22/96] fix: report set-aside spark exit data as not restored Verified: just compile, just test, just lint --- app/src/main/java/to/bitkit/repositories/BackupRepo.kt | 4 +++- app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 8d9b93814f..e3c7accf5f 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1177,10 +1177,12 @@ class BackupRepo @Inject constructor( performRestore(BackupCategory.SPARK_EXIT, failedCategories) { dataBytes -> val parsed = runCatching { json.decodeFromString(String(dataBytes)) } .getOrElse { - // A layout this app can't read never becomes readable here, so it is kept for one that can. + // A layout this app can't read never becomes readable here, so it is kept for one that can, + // and the restore reports the exit data as not restored. if (it !is IllegalArgumentException) throw it Logger.warn("Failed to read '${BackupCategory.SPARK_EXIT}' backup", it, context = TAG) setAsideRejectedExitBackup(dataBytes) + failedCategories += BackupCategory.SPARK_EXIT return@performRestore currentTimeMillis() } sparkRepo.restoreExitBackup(parsed, backupWalletIndex()).getOrThrow() diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index db51c7a75c..b2f203ccff 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -574,14 +574,14 @@ class BackupRepoTest : BaseUnitTest() { } @Test - fun `a restore sets aside spark exit data it can't read and completes`() = test { + fun `a restore sets aside spark exit data it can't read and reports it not restored`() = test { val stored = "not exit data".toByteArray() whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)) .thenReturn(Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = stored, version = 1))) val failed = sut.performFullRestoreFromLatestBackup().getOrThrow() - assertFalse(BackupCategory.SPARK_EXIT in failed) + assertTrue(BackupCategory.SPARK_EXIT in failed) verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) verify(sparkRepo, never()).restoreExitBackup(any(), any()) } From 2a378bb55deed404e442d40b3740bc7ac1d62c51 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 23:45:49 +0100 Subject: [PATCH 23/96] fix: write an expired spark retry's row from the read that ends it The settle step reads Spark's list once and writes the row from that payment, so no second read can leave it pending. A send kept in doubt before start times were stored now stays held past any failure until its invoice expires, when that step settles it. Verified: just compile, just test, just lint; the new SparkRepoTest cases fail on the previous SparkRepo --- .../java/to/bitkit/repositories/SparkRepo.kt | 49 ++++++------ .../to/bitkit/repositories/SparkRepoTest.kt | 80 +++++++++++++++++++ 2 files changed, 104 insertions(+), 25 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index d6f951eedd..3ca8828f4a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -656,7 +656,8 @@ class SparkRepo @Inject constructor( // Spark keeps a send it committed but didn't finish in a cache no call exposes, and a sync that reached Spark // can still fail to resume it, so only an expired invoice shows a missing send will never go out. val isFinal = isSynced && clock.now().epochSeconds.toULong() >= uncertain.expiresAt - val send = listedLightningSend(paymentHash) + // The outcome and the payment its row is written from come from one read, so a later read can't miss it. + val (send, listed) = listedLightningSendPayment(paymentHash) val isSettled = when (send) { SparkLightningSend.NotFound -> isFinal // A failed row may be an earlier attempt's, so it is final only when a missing one would be. @@ -679,7 +680,9 @@ class SparkRepo @Inject constructor( is SparkLightningSend.Found -> { if (send.status == PaymentStatus.FAILED) { cacheStore.removeSparkSendHash(paymentHash) - recordHeldSend(paymentHash) + // An earlier attempt's failure was skipped while the hold lasted; a failed write is retried at the + // next refresh. + listed?.let { recordActivity(it) } } settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } } @@ -688,18 +691,6 @@ class SparkRepo @Inject constructor( return true } - /** - * Records Spark's listed send of [paymentHash] once its hold ended, as an earlier attempt's failure is skipped - * while the hold lasts; a failed write is retried at the next refresh. - */ - private suspend fun recordHeldSend(paymentHash: String) { - runSuspendCatching { sparkService.listPayments() } - .onFailure { Logger.warn("Failed to list Spark payments for '$paymentHash'", it, context = TAG) } - .getOrNull() - ?.latestSend(paymentHash) - ?.let { recordActivity(it) } - } - /** * Marks the pending send row of [paymentHash] failed, as Spark lists no send of it; true once nothing is pending. * Read and write share the lock Spark's own row writes take, so a settlement written meanwhile is not overwritten. @@ -1525,16 +1516,22 @@ class SparkRepo @Inject constructor( } /** Spark's listed record of the Lightning send with [paymentHash], as [lightningSend] reads it before its holds. */ - private suspend fun listedLightningSend(paymentHash: String): SparkLightningSend = withContext(bgDispatcher) { - if (!sparkService.isSupported) return@withContext SparkLightningSend.NotFound - if (!canListPayments()) return@withContext SparkLightningSend.Unavailable - val payments = runSuspendCatching { sparkService.listPayments() } - .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } - .getOrElse { return@withContext SparkLightningSend.Unavailable } - payments.latestSend(paymentHash) - ?.let { SparkLightningSend.Found(it.status, (it.details as PaymentDetails.Lightning).htlcDetails.preimage) } - ?: SparkLightningSend.NotFound - } + private suspend fun listedLightningSend(paymentHash: String): SparkLightningSend = + listedLightningSendPayment(paymentHash).first + + /** Spark's listed record of the Lightning send with [paymentHash] and the payment it was read from, in one read. */ + private suspend fun listedLightningSendPayment(paymentHash: String): Pair = + withContext(bgDispatcher) { + if (!sparkService.isSupported) return@withContext SparkLightningSend.NotFound to null + if (!canListPayments()) return@withContext SparkLightningSend.Unavailable to null + val payments = runSuspendCatching { sparkService.listPayments() } + .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } + .getOrElse { return@withContext SparkLightningSend.Unavailable to null } + val latest = payments.latestSend(paymentHash) + ?: return@withContext SparkLightningSend.NotFound to null + val preimage = (latest.details as PaymentDetails.Lightning).htlcDetails.preimage + SparkLightningSend.Found(latest.status, preimage) to latest + } /** * Spark's pending or paid send of [bolt11], matched by the invoice or its [paymentHash], so the node never pays it @@ -1870,7 +1867,9 @@ class SparkRepo @Inject constructor( val key = hash.lowercase() val attempt = uncertainSends[key]?.attempt ?: inFlightAttempts[key] ?: return false attempt.earlierIds?.let { return id in it } - val sentAt = attempt.sentAt ?: return false + // A send kept before start times were stored can't tell its own failure from an earlier one, so it stays held + // until its invoice expires, when the expiry rule settles it and its row. + val sentAt = attempt.sentAt ?: return true return timestamp < sentAt + RAIL_CLOCK_SKEW_SECONDS } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index a18173fd3b..64e7c4bdb1 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3716,6 +3716,36 @@ class SparkRepoTest : BaseUnitTest() { assertNull(after.earlierLightningSend("lnbc1", "hash"), "the retry's own failure still held the node off") } + @Test + fun `a spark send kept in doubt before start times were stored stays held past a failure`() = test { + val expiresAt = now.epochSeconds + 3_600 + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to expiresAt), + sparkUncertainSends = mapOf("hash" to now.epochSeconds), + ) + ), + clock, + ) + whenever(sparkService.isConnected).thenReturn(true) + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + whenever { sparkService.listPayments() }.thenReturn(listOf(failed)) + val sut = createSut(store) + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + + // The failure may be its own or an earlier attempt's: without a start time, nothing tells them apart. + sparkEvents.emit(SdkEvent.PaymentFailed(failed)) + advanceUntilIdle() + + assertTrue(events.none { it is Event.PaymentFailed }, "a send Spark may still finish was reported failed") + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + } + @Test fun `an older attempt's failure after a restart keeps an uncertain spark retry held`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) @@ -3882,6 +3912,56 @@ class SparkRepoTest : BaseUnitTest() { ) } + @Test + fun `an expired spark retry listed as failed writes its row from the read that ends its hold`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } + val olderFailure = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + whenever { sparkService.listPayments() }.thenReturn(listOf(olderFailure)) + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + ) + val before = createSut(store) + before.start(0).getOrThrow() + assertIs(before.payInvoice("lnbc1", 100uL).exceptionOrNull()) + runCurrent() + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) + ) + clearInvocations(activityRepo) + val restartedEvents = MutableSharedFlow() + whenever(sparkService.events).thenReturn(restartedEvents) + val after = createSut(store) + after.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { after.nodeEvents.collect { events += it } } + runCurrent() + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) + + // The invoice expires and Spark syncs, still listing only the older failure. + now += 2.hours + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) + ) + // Only the read that settles the hold reaches Spark; every other read of its list fails. + whenever { sparkService.listPayments() }.thenAnswer { + val isSettleRead = Thread.currentThread().stackTrace.any { it.className.contains("listedLightningSend") } + if (!isSettleRead) throw SdkException.Generic("operators unreachable") + listOf(olderFailure) + } + restartedEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + verify(activityRepo, atLeastOnce()).upsertActivity( + argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } + ) + } + @Test fun `an older attempt's failure after a spark retry was cancelled inside its send keeps its hold`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) From 037c77174d5fdbfa9728e99de01e177c8ed5f14e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 23:45:49 +0100 Subject: [PATCH 24/96] fix: merge a replaced spark exit backup before uploading over it A rejected staged copy now always merges the stored backup first, and stored data Spark can't import is replaced only when it is still the stored one after it was set aside. Verified: just compile, just test, just lint; the new BackupRepoTest cases fail on the previous BackupRepo --- .../java/to/bitkit/repositories/BackupRepo.kt | 51 +++++++++++------ .../to/bitkit/repositories/BackupRepoTest.kt | 56 +++++++++++++++++++ 2 files changed, 91 insertions(+), 16 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index e3c7accf5f..8886acc0b0 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -722,9 +722,26 @@ class BackupRepo @Inject constructor( setAsideRejectedExitBackup(rejectedStagedExitCopy(staged)) sparkRepo.discardStagedExitState(staged.exitState) } - if (!sparkRepo.hasMergedRemoteExitState) { + // A rejected staged copy may be older than the stored backup, which another device can have replaced, so the + // stored one is merged before anything replaces it. + if (!sparkRepo.hasMergedRemoteExitState || staged is StagedExitImport.Rejected) { sparkRepo.exitBackup().getOrThrow() ?: throw SparkExitBackupDeferred() - val stored = vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name).getOrThrow()?.value + mergeStoredExitBackup() + } + val backup = sparkRepo.exitBackup().getOrThrow() ?: throw SparkExitBackupDeferred() + vssBackupClient.putObject( + key = BackupCategory.SPARK_EXIT.name, + data = json.encodeToString(backup).toByteArray(), + ).getOrThrow() + } + + /** + * Merges the stored exit backup into Spark. One Spark can't import is set aside, and replaced only when it is still + * the stored one after that, so exit data another device stored meanwhile is merged first. + */ + private suspend fun mergeStoredExitBackup() { + var stored = vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name).getOrThrow()?.value + repeat(EXIT_MERGE_ATTEMPTS) { val remote = stored?.let { bytes -> runCatching { json.decodeFromString(String(bytes)) }.getOrNull() } @@ -733,21 +750,18 @@ class BackupRepo @Inject constructor( } else { sparkRepo.mergeRemoteExitBackup(remote) } - merged.recoverCatching { - if (it !is SparkError.ExitStateUnimportable || stored == null) throw it - keepUnimportableExitBackup(stored, remote?.exitState) - }.getOrThrow() + val error = merged.exceptionOrNull() ?: return + val unimportable = stored + if (error !is SparkError.ExitStateUnimportable || unimportable == null) throw error + setAsideRejectedExitBackup(unimportable) + val current = vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name).getOrThrow()?.value + if (current.contentEquals(unimportable)) { + sparkRepo.skipUnimportableRemoteExitState(remote?.exitState) + return + } + stored = current } - val backup = sparkRepo.exitBackup().getOrThrow() ?: throw SparkExitBackupDeferred() - vssBackupClient.putObject( - key = BackupCategory.SPARK_EXIT.name, - data = json.encodeToString(backup).toByteArray(), - ).getOrThrow() - } - - private suspend fun keepUnimportableExitBackup(stored: ByteArray, exitState: String?) { - setAsideRejectedExitBackup(stored) - sparkRepo.skipUnimportableRemoteExitState(exitState) + throw SparkExitBackupChanged() } private suspend fun rejectedStagedExitCopy(staged: StagedExitImport.Rejected): ByteArray { @@ -1628,6 +1642,9 @@ class BackupRepo @Inject constructor( /** Spark's exit data can reach several MB and changes with every payment, so its uploads are spaced out. */ private const val SPARK_EXIT_BACKUP_DEBOUNCE = 60_000L + /** How many times the exit backup merges stored data another device replaced meanwhile before it gives up. */ + private const val EXIT_MERGE_ATTEMPTS = 3 + /** Maximum captures before deferring a changing wallet to the next scheduled backup. */ private const val WALLET_SNAPSHOT_ATTEMPTS = 3 @@ -1658,6 +1675,8 @@ internal class WalletBackupSnapshotChanged : AppError("Private payment state cha internal class SparkExitBackupDeferred : AppError("Spark has not connected and synced yet") +internal class SparkExitBackupChanged : AppError("Stored Spark exit backup kept changing while it was merged") + private class PublicAddressRestoreFailed(cause: Throwable) : AppError( "Failed to retain public address exclusion during restore", cause, diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index b2f203ccff..063db7d084 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -540,6 +540,62 @@ class BackupRepoTest : BaseUnitTest() { verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) } + @Test + fun `staged exit data spark rejects merges the stored backup another device replaced before the upload`() = test { + val newer = SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "newer") + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( + Result.success( + VssItem( + key = BackupCategory.SPARK_EXIT.name, + value = json.encodeToString(newer).toByteArray(), + version = 2 + ) + ) + ) + // A merge already ran in this session, before another device stored newer exit data. + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(true) + whenever(sparkRepo.importStagedExitState()).thenReturn(StagedExitImport.Rejected("v9", "regtest")) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + inOrder(sparkRepo, vssBackupClient) { + verify(sparkRepo).mergeRemoteExitBackup(newer) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + } + + @Test + fun `stored exit data replaced while unreadable data was set aside is merged before the upload`() = test { + val unreadable = "not exit data".toByteArray() + val replaced = SparkExitBackupV1(createdAt = 600, network = "regtest", exitState = "other device") + whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(false) + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( + Result.success(VssItem(key = BackupCategory.SPARK_EXIT.name, value = unreadable, version = 1)), + Result.success( + VssItem( + key = BackupCategory.SPARK_EXIT.name, + value = json.encodeToString(replaced).toByteArray(), + version = 2 + ) + ), + ) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + inOrder(sparkRepo, vssBackupClient) { + verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(unreadable), unreadable) + verify(sparkRepo).mergeRemoteExitBackup(replaced) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + verify(sparkRepo, never()).skipUnimportableRemoteExitState(anyOrNull()) + } + @Test fun `a spark exit merge that fails for another reason still blocks the upload`() = test { val stored = json.encodeToString(SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "v1")) From 244833e1e83cded3139a9c18c2369c63bff74a8d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 00:07:30 +0100 Subject: [PATCH 25/96] fix: keep a running spark retry's earlier attempt ids until it settles A retry Spark took and still runs keeps its start time and earlier attempts' ids, across a restart too, until its own outcome, its invoice's expiry or a wipe, so an earlier attempt's late failure no longer ends it or fails its row. Verified: just compile, just test, just lint; the new SparkRepoTest cases fail on the previous SparkRepo --- .../main/java/to/bitkit/data/CacheStore.kt | 12 ++++- .../java/to/bitkit/repositories/SparkRepo.kt | 48 ++++++++++++++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 50 +++++++++++++++++++ 3 files changed, 105 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index e385bf9fd0..7d83e8d546 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -197,9 +197,19 @@ class CacheStore internal constructor( } } - suspend fun removeSparkUncertainSend(paymentHash: String) { + /** Ends the doubt over a send Spark took and still runs, keeping its start time and earlier attempts' ids. */ + suspend fun keepSparkSendAttempt(paymentHash: String) { val hash = paymentHash.lowercase() if (hash !in store.data.first().sparkUncertainSends) return + store.updateData { it.copy(sparkUncertainSends = it.sparkUncertainSends - hash) } + } + + suspend fun removeSparkUncertainSend(paymentHash: String) { + val hash = paymentHash.lowercase() + val data = store.data.first() + val isKept = hash in data.sparkUncertainSends || hash in data.sparkUncertainSendStarts || + hash in data.sparkUncertainSendEarlierIds + if (!isKept) return store.updateData { it.copy( sparkUncertainSends = it.sparkUncertainSends - hash, diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 3ca8828f4a..b06e1cd132 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -194,6 +194,9 @@ class SparkRepo @Inject constructor( /** Sends whose outcome Spark didn't report, by payment hash. */ private val uncertainSends = ConcurrentHashMap() + /** Sends Spark took and still runs, by payment hash, until they settle or their invoice expires. */ + private val takenAttempts = ConcurrentHashMap() + @Volatile private var hasSyncedActivities = false @@ -318,6 +321,7 @@ class SparkRepo @Inject constructor( unsavedPayments.clear() sendsInFlight.clear() uncertainSends.clear() + takenAttempts.clear() hasSyncedActivities = false hasMergedRemoteExitState = false _depositClaims.update { emptyMap() } @@ -582,7 +586,13 @@ class SparkRepo @Inject constructor( throw it } isDispatched = true - runSuspendCatching { sparkService.send(prepared) }.also { hasReturned = true } + runSuspendCatching { sparkService.send(prepared) }.also { result -> + hasReturned = true + // Taken before the in-flight attempt is dropped, so an earlier failure never finds neither. + if (result.getOrNull()?.status == PaymentStatus.PENDING) { + takenAttempts[paymentHash.lowercase()] = SendAttempt(sentAt.toULong(), earlierIds) + } + } } } finally { // A send cancelled inside Spark's call stays in doubt, as its journal entry does, so a sync settles it. @@ -614,7 +624,13 @@ class SparkRepo @Inject constructor( settleUncertainSend(paymentHash, SendAttempt(sentAt.toULong(), earlierIds), expiresAt) throw PaymentPendingException(paymentHash) } - cacheStore.removeSparkUncertainSend(paymentHash) + // A send Spark still runs keeps its earlier attempts' ids, so their late failures leave it alone. + if (payment.status == PaymentStatus.PENDING) { + cacheStore.keepSparkSendAttempt(paymentHash) + } else { + takenAttempts.remove(paymentHash.lowercase()) + cacheStore.removeSparkUncertainSend(paymentHash) + } Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) paymentHash }.onFailure { @@ -667,9 +683,12 @@ class SparkRepo @Inject constructor( if (!isSettled) return false // A missing send's row is ended here, as no listed payment revisits it, so the hold stays until it is written. if (send == SparkLightningSend.NotFound && !failHeldRow(paymentHash)) return false + // A send Spark now runs keeps its earlier attempts' ids until it settles, taken over before the doubt ends. + val isTaken = send is SparkLightningSend.Found && send.status == PaymentStatus.PENDING + if (isTaken) takenAttempts.putIfAbsent(key, uncertain.attempt) // Only the caller that takes the hash off settles it, so its outcome is reported once. if (!uncertainSends.remove(key, uncertain)) return true - cacheStore.removeSparkUncertainSend(paymentHash) + if (isTaken) cacheStore.keepSparkSendAttempt(paymentHash) else cacheStore.removeSparkUncertainSend(paymentHash) when (send) { SparkLightningSend.NotFound -> { cacheStore.removeSparkSendHash(paymentHash) @@ -734,6 +753,25 @@ class SparkRepo @Inject constructor( ) uncertainSends.putIfAbsent(hash, UncertainSend(failedAt.toULong(), expiresAt, attempt)) } + (cache.sparkUncertainSendStarts.keys + cache.sparkUncertainSendEarlierIds.keys) + .filter { it !in cache.sparkUncertainSends } + .forEach { hash -> + val attempt = SendAttempt( + sentAt = cache.sparkUncertainSendStarts[hash]?.toULong(), + earlierIds = cache.sparkUncertainSendEarlierIds[hash]?.toSet(), + ) + takenAttempts.putIfAbsent(hash, attempt) + } + } + + /** Drops the attempts of sends Spark took whose invoice expired, as nothing of them can settle any more. */ + private suspend fun dropExpiredTakenAttempts() { + val expiries = cacheStore.data.first().sparkSendExpiries + val now = clock.now().epochSeconds + takenAttempts.keys.filter { (expiries[it] ?: Long.MAX_VALUE) <= now }.forEach { + takenAttempts.remove(it) + cacheStore.removeSparkUncertainSend(it) + } } /** Sends whose outcome Spark didn't report, also ones kept from before a restart not yet taken back. */ @@ -1865,7 +1903,7 @@ class SparkRepo @Inject constructor( private fun Payment.isEarlierFailureOfUncertainSend(): Boolean { val hash = sendHash(PaymentStatus.FAILED) ?: return false val key = hash.lowercase() - val attempt = uncertainSends[key]?.attempt ?: inFlightAttempts[key] ?: return false + val attempt = uncertainSends[key]?.attempt ?: inFlightAttempts[key] ?: takenAttempts[key] ?: return false attempt.earlierIds?.let { return id in it } // A send kept before start times were stored can't tell its own failure from an earlier one, so it stays held // until its invoice expires, when the expiry rule settles it and its row. @@ -1901,6 +1939,7 @@ class SparkRepo @Inject constructor( refresh() // A send whose outcome stayed unknown past its polling settles on a later sync. uncertainSends.keys.toList().forEach { trySettleUncertainSend(it) } + if (hasSyncedSince(null)) dropExpiredTakenAttempts() // A journal left open past its grace period would block every later withdrawal until a restart. // Spark emits Synced after a sync that never reached it too, so only one since the journal // drops it. @@ -1947,6 +1986,7 @@ class SparkRepo @Inject constructor( // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. payment.sendHash()?.let { uncertainSends.remove(it.lowercase()) + takenAttempts.remove(it.lowercase()) cacheStore.removeSparkUncertainSend(it) } val isReleased = latest == SparkLightningSend.NotFound || diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 64e7c4bdb1..042d1a124f 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3746,6 +3746,56 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) } + @Test + fun `an earlier attempt's late failure leaves a spark retry spark took and still runs`() = test { + assertTakenRetryKeptPastEarlierFailure(restart = false) + } + + @Test + fun `an earlier attempt's late failure after a restart leaves a spark retry spark still runs`() = test { + assertTakenRetryKeptPastEarlierFailure(restart = true) + } + + private suspend fun TestScope.assertTakenRetryKeptPastEarlierFailure(restart: Boolean) { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + // Dated well after the retry went out, past the 10 s a clock difference may account for. + val older = sentPayment(fees = 0).copy( + id = "older", + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong() + 60uL, + ) + val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) + whenever { sparkService.listPayments() }.thenReturn(listOf(older)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(retry) + val before = createSut(store) + before.start(0).getOrThrow() + assertEquals("hash", before.payInvoice("lnbc1", 100uL).getOrThrow()) + runCurrent() + whenever { sparkService.listPayments() }.thenReturn(listOf(older, retry)) + clearInvocations(activityRepo) + val events = MutableSharedFlow() + val sut = if (restart) { + whenever(sparkService.events).thenReturn(events) + createSut(store).also { it.start(0).getOrThrow() } + } else { + before + } + val nodeEvents = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { nodeEvents += it } } + runCurrent() + + (if (restart) events else sparkEvents).emit(SdkEvent.PaymentFailed(older)) + advanceUntilIdle() + + assertTrue(nodeEvents.none { it is Event.PaymentFailed }, "an earlier failure ended a send Spark still runs") + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) + } + @Test fun `an older attempt's failure after a restart keeps an uncertain spark retry held`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) From cd8412def325d02c684acce79e219706bc3163e3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 00:24:01 +0100 Subject: [PATCH 26/96] fix: keep move to spark reachable while its result is kept Verified: just compile, just test and just lint pass; the new tests fail without the fix. --- app/src/main/java/to/bitkit/ui/ContentView.kt | 4 +++- .../lightning/LightningConnectionsViewModel.kt | 11 ++++++++--- .../ui/settings/lightning/MoveToSparkManager.kt | 14 +++++++++++--- .../java/to/bitkit/viewmodels/WalletViewModel.kt | 3 +++ .../test/java/to/bitkit/ui/WalletViewModelTest.kt | 11 +++++++++++ .../lightning/LightningConnectionsViewModelTest.kt | 11 +++++++++++ 6 files changed, 47 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index fcb11ea2e9..eb6f6ee869 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -1416,11 +1416,13 @@ private fun NavGraphBuilder.home( val sparkState by walletViewModel.sparkState.collectAsStateWithLifecycle() val lightningState by walletViewModel.lightningState.collectAsStateWithLifecycle() val lightningActivities by activityListViewModel.lightningActivities.collectAsStateWithLifecycle() + val hasRetainedMove by walletViewModel.hasRetainedMove.collectAsStateWithLifecycle() SpendingWalletScreen( channels = lightningState.channels, hasSparkBalance = sparkState.shownSpendingSats > 0uL, - canMoveToSpark = MoveToSparkMath.canMove(lightningState.channels, sparkState), + // A move left while it ran keeps its way back to its result, also once nothing is left to move. + canMoveToSpark = hasRetainedMove || MoveToSparkMath.canMove(lightningState.channels, sparkState), onMoveToSparkClick = { navController.navigateTo(Routes.MoveToSpark) }, lightningActivities = lightningActivities ?: persistentListOf(), onAllActivityButtonClick = { navController.navigateToAllActivity(activityListViewModel::clearFilters) }, diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt index 2cf199ddda..e567a4a688 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt @@ -61,6 +61,7 @@ class LightningConnectionsViewModel @Inject constructor( private val activityRepo: ActivityRepo, private val sparkRepo: SparkRepo, private val sparkExitRepo: SparkExitRepo, + private val moveToSparkManager: MoveToSparkManager, ) : ViewModel() { companion object { @@ -108,8 +109,9 @@ class LightningConnectionsViewModel @Inject constructor( lightningRepo.lastKnownChannels, sparkRepo.state, sparkExitRepo.state, - ) { lightningState, channels, sparkState, exitState -> - ConnectionsSnapshot(lightningState, channels, sparkState, exitState) + moveToSparkManager.hasRetainedMove, + ) { lightningState, channels, sparkState, exitState, hasRetainedMove -> + ConnectionsSnapshot(lightningState, channels, sparkState, exitState, hasRetainedMove) }.collect { snapshot -> val (lightningState, channels, sparkState) = snapshot val isNodeRunning = lightningState.nodeLifecycleState.isRunning() @@ -127,7 +129,9 @@ class LightningConnectionsViewModel @Inject constructor( localBalance = calculateLocalBalance(channels).safe() + sparkState.shownSpendingSats.safe(), remoteBalance = channels.calculateRemoteBalance(), // The cached channels outlive a stopped node; the move reads the live ones. - canMoveToSpark = MoveToSparkMath.canMove(lightningState.channels, sparkState), + // A move left while it ran keeps its way back to its result, also once nothing is left to move. + canMoveToSpark = snapshot.hasRetainedMove || + MoveToSparkMath.canMove(lightningState.channels, sparkState), spark = sparkState.toUi( lightningRepo, snapshot.exitState.showsResult, @@ -312,6 +316,7 @@ private data class ConnectionsSnapshot( val channels: List, val sparkState: SparkState, val exitState: SparkExitState, + val hasRetainedMove: Boolean, ) data class ChannelUi( diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt index 7d5c15e691..657ed31caf 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/MoveToSparkManager.kt @@ -48,9 +48,17 @@ class MoveToSparkManager @Inject constructor( private var quoteJob: Job? = null private var moveJob: Job? = null - /** A move was started and its outcome is still the screen's, so opening the screen again keeps it. */ - @Volatile - private var keepsOutcome = false + private val _hasRetainedMove = MutableStateFlow(false) + + /** + * A move was started and its outcome is still the screen's, so opening the screen again keeps it and its entry + * points stay, also once no balance is left to move. + */ + val hasRetainedMove: StateFlow = _hasRetainedMove.asStateFlow() + + private var keepsOutcome: Boolean + get() = _hasRetainedMove.value + set(value) = _hasRetainedMove.update { value } /** A swiped payment that has not settled yet; leaving the screen keeps it, so it is never quoted over. */ @Volatile diff --git a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt index 5e507ea248..0b6c46ff54 100644 --- a/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/WalletViewModel.kt @@ -58,6 +58,7 @@ import to.bitkit.repositories.WipeInProgressError import to.bitkit.services.BoltzService import to.bitkit.services.MigrationService import to.bitkit.ui.onboarding.LOADING_MS +import to.bitkit.ui.settings.lightning.MoveToSparkManager import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.utils.AppError import to.bitkit.utils.Logger @@ -84,6 +85,7 @@ class WalletViewModel @Inject constructor( private val connectionRecovery: WalletConnectionRecovery, private val pubkySwapsRouteRepo: PubkySwapsRouteRepo, sparkRepo: SparkRepo, + moveToSparkManager: MoveToSparkManager, ) : ViewModel() { companion object { private const val TAG = "WalletViewModel" @@ -104,6 +106,7 @@ class WalletViewModel @Inject constructor( val lightningState = lightningRepo.lightningState val sparkState = sparkRepo.state + val hasRetainedMove = moveToSparkManager.hasRetainedMove val walletState = walletRepo.walletState val balanceState = walletRepo.balanceState diff --git a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt index 709f0b5d51..d858b4459b 100644 --- a/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/WalletViewModelTest.kt @@ -24,6 +24,7 @@ import org.lightningdevkit.ldknode.PeerDetails import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.doReturn import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq import org.mockito.kotlin.inOrder @@ -61,6 +62,7 @@ import to.bitkit.services.PendingChannelMigration import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture import to.bitkit.test.idleSparkRepo +import to.bitkit.ui.settings.lightning.MoveToSparkManager import to.bitkit.ui.shared.toast.ToastEventBus import to.bitkit.utils.AppError import to.bitkit.viewmodels.RestoreState @@ -92,6 +94,9 @@ class WalletViewModelTest : BaseUnitTest() { private val boltzService = mock() private val pubkySwapsRouteRepo = mock() private val sparkRepo = idleSparkRepo() + private val moveToSparkManager = mock { + on { hasRetainedMove } doReturn MutableStateFlow(false) + } private val lightningState = MutableStateFlow(LightningState()) private val walletState = MutableStateFlow(WalletState()) @@ -134,6 +139,7 @@ class WalletViewModelTest : BaseUnitTest() { connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, + moveToSparkManager = moveToSparkManager, ) } @@ -1247,6 +1253,7 @@ class WalletViewModelTest : BaseUnitTest() { connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, + moveToSparkManager = moveToSparkManager, ) assertEquals(RestoreState.Initial, testSut.restoreState.value) @@ -1316,6 +1323,7 @@ class WalletViewModelTest : BaseUnitTest() { connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, + moveToSparkManager = moveToSparkManager, ) testSut.start() @@ -1374,6 +1382,7 @@ class WalletViewModelTest : BaseUnitTest() { connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, + moveToSparkManager = moveToSparkManager, ) // Trigger restore to put state in non-idle @@ -1416,6 +1425,7 @@ class WalletViewModelTest : BaseUnitTest() { connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, + moveToSparkManager = moveToSparkManager, ) testSut.restoreWallet("mnemonic", null) @@ -1509,6 +1519,7 @@ class WalletViewModelTest : BaseUnitTest() { connectionRecovery = connectionRecovery, pubkySwapsRouteRepo = pubkySwapsRouteRepo, sparkRepo = sparkRepo, + moveToSparkManager = moveToSparkManager, ) advanceUntilIdle() diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModelTest.kt index a594d2f6fe..8ae146e8f8 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModelTest.kt @@ -38,6 +38,7 @@ class LightningConnectionsViewModelTest : BaseUnitTest() { private val logsRepo = mock() private val activityRepo = mock() private val sparkRepo = mock() + private val hasRetainedMove = MutableStateFlow(false) private val lightningState = MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Running)) private val lastKnownChannels = MutableStateFlow( @@ -74,6 +75,15 @@ class LightningConnectionsViewModelTest : BaseUnitTest() { assertEquals("channel_1", sut.uiState.value.openChannels.single().details.channelId) } + @Test + fun `a move kept for its result keeps move to spark offered once nothing is left to move`() = test { + hasRetainedMove.value = true + val sut = createViewModel() + advanceUntilIdle() + + assertTrue(sut.uiState.value.canMoveToSpark) + } + private fun createViewModel() = LightningConnectionsViewModel( context = context, bgDispatcher = testDispatcher, @@ -83,5 +93,6 @@ class LightningConnectionsViewModelTest : BaseUnitTest() { activityRepo = activityRepo, sparkRepo = sparkRepo, sparkExitRepo = mock { on { state } doReturn MutableStateFlow(SparkExitState()) }, + moveToSparkManager = mock { on { hasRetainedMove } doReturn hasRetainedMove }, ) } From d93f61e80d146d626afd228bac02bbf5ebe1bb42 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 00:24:09 +0100 Subject: [PATCH 27/96] fix: keep spark retry holds and exit merges across failures A failed send call is in doubt before its in-flight attempt drops, refresh and the activity sync judge listed failures by the send records read before the list, and dropping a rejected staged exit copy asks for the stored backup to be merged again. Verified: just compile, just test and just lint pass; the new tests fail without the fix, except the ambiguous-return window, which no single-threaded test reaches. --- .../java/to/bitkit/repositories/BackupRepo.kt | 5 +- .../java/to/bitkit/repositories/SparkRepo.kt | 23 +++++- .../to/bitkit/repositories/BackupRepoTest.kt | 42 +++++++++- .../to/bitkit/repositories/SparkRepoTest.kt | 76 +++++++++++++++++++ 4 files changed, 138 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 8886acc0b0..1275083dfd 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -722,9 +722,8 @@ class BackupRepo @Inject constructor( setAsideRejectedExitBackup(rejectedStagedExitCopy(staged)) sparkRepo.discardStagedExitState(staged.exitState) } - // A rejected staged copy may be older than the stored backup, which another device can have replaced, so the - // stored one is merged before anything replaces it. - if (!sparkRepo.hasMergedRemoteExitState || staged is StagedExitImport.Rejected) { + // Dropping a rejected staged copy asks for the stored backup to be merged again, until a merge succeeds. + if (!sparkRepo.hasMergedRemoteExitState) { sparkRepo.exitBackup().getOrThrow() ?: throw SparkExitBackupDeferred() mergeStoredExitBackup() } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index b06e1cd132..7a57bb9967 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -589,8 +589,15 @@ class SparkRepo @Inject constructor( runSuspendCatching { sparkService.send(prepared) }.also { result -> hasReturned = true // Taken before the in-flight attempt is dropped, so an earlier failure never finds neither. + val attempt = SendAttempt(sentAt.toULong(), earlierIds) if (result.getOrNull()?.status == PaymentStatus.PENDING) { - takenAttempts[paymentHash.lowercase()] = SendAttempt(sentAt.toULong(), earlierIds) + takenAttempts[paymentHash.lowercase()] = attempt + } + // A send whose call failed may still have gone out, so it is in doubt before the in-flight + // attempt is dropped. + if (result.isFailure) { + uncertainSends[paymentHash.lowercase()] = + UncertainSend(clock.now().epochSeconds.toULong(), expiresAt, attempt) } } } @@ -609,6 +616,7 @@ 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()) { + uncertainSends.remove(paymentHash.lowercase()) cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) throw SparkError.InvoiceExpired(it) @@ -616,6 +624,7 @@ class SparkRepo @Inject constructor( // 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) { + uncertainSends.remove(paymentHash.lowercase()) cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) throw SparkError.SendRefused("Spark balance can't cover the payment", it) @@ -1296,8 +1305,12 @@ class SparkRepo @Inject constructor( ) } - /** Drops restored exit data Spark rejected, once the backup set a copy of it aside, unless newer data came. */ + /** + * Drops restored exit data Spark rejected, once the backup set a copy of it aside, unless newer data came. The + * stored backup is merged again before the next upload, as that copy may be older than it. + */ fun discardStagedExitState(exitState: String) { + hasMergedRemoteExitState = false val staged = File(Env.sparkExitRestorePath(walletIndex)) if (staged.exists() && staged.readText() == exitState) staged.delete() } @@ -1343,6 +1356,8 @@ class SparkRepo @Inject constructor( val info = sparkService.getInfo() info.lastSyncError?.let { Logger.warn("Failed to sync Spark, balances may be stale: '$it'", context = TAG) } val unclaimed = sparkService.listUnclaimedDeposits() + // Read before the list, so a retry recorded after it keeps its row from a failure the list still shows. + val records = sendRecords.get() val payments = sparkService.listPayments() val claimedPayments = payments .filter { it.method == PaymentMethod.DEPOSIT && it.status == PaymentStatus.COMPLETED } @@ -1395,7 +1410,7 @@ class SparkRepo @Inject constructor( markClaimedDeposits(claimed) payments .filter { it.id in unsavedPayments || (it.id in sendsRecordedWithoutFee && it.fees.toLong() > 0) } - .forEach { recordActivity(it) } + .forEach { recordActivity(it, records = records) } // Off the refresh, so a slow Electrum server never holds a send that waits for it. scope.launch { confirmMinedPayouts(payments) } markTransfers(payments) @@ -1807,7 +1822,7 @@ class SparkRepo @Inject constructor( val isSynced = canListPayments() val payments = sparkService.listPayments() if (isSynced) seedSendHashes(payments) - val isSaved = payments.map { recordActivity(it) }.all { it } + val isSaved = payments.map { recordActivity(it, records = recordsBefore) }.all { it } releaseFailedSends(payments, recordsBefore, inFlightBefore) if (!settleJournal || wasWithdrawing || isWithdrawing || withdrawalSendsEnded.get() != sendsEndedBefore) { return isSaved diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 063db7d084..83f0cf97a8 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -553,7 +553,7 @@ class BackupRepoTest : BaseUnitTest() { ) ) // A merge already ran in this session, before another device stored newer exit data. - whenever(sparkRepo.hasMergedRemoteExitState).thenReturn(true) + mergeFlagFollowsDiscard(hasMerged = true) whenever(sparkRepo.importStagedExitState()).thenReturn(StagedExitImport.Rejected("v9", "regtest")) whenever(sparkRepo.exitBackup()).thenReturn( Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) @@ -567,6 +567,36 @@ class BackupRepoTest : BaseUnitTest() { } } + @Test + fun `a rejected staged copy dropped before a failed merge still merges on the next upload`() = test { + val newer = SparkExitBackupV1(createdAt = 500, network = "regtest", exitState = "other device") + val stored = VssItem( + key = BackupCategory.SPARK_EXIT.name, + value = json.encodeToString(newer).toByteArray(), + version = 2 + ) + mergeFlagFollowsDiscard(hasMerged = true) + whenever(sparkRepo.importStagedExitState()) + .thenReturn(StagedExitImport.Rejected("v9", "regtest"), StagedExitImport.NothingStaged) + whenever(sparkRepo.exitBackup()).thenReturn( + Result.success(SparkExitBackupV1(createdAt = 1_000, network = "regtest", exitState = "fresh")) + ) + // The copy is set aside and dropped, then the read for the merge fails. + whenever(vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name)).thenReturn( + Result.success(stored), + Result.failure(IllegalStateException("offline")), + Result.success(stored), + ) + assertTrue(sut.triggerBackup(BackupCategory.SPARK_EXIT).isFailure) + + sut.triggerBackup(BackupCategory.SPARK_EXIT).getOrThrow() + + inOrder(sparkRepo, vssBackupClient) { + verify(sparkRepo).mergeRemoteExitBackup(newer) + verify(vssBackupClient).putObject(eq(BackupCategory.SPARK_EXIT.name), any()) + } + } + @Test fun `stored exit data replaced while unreadable data was set aside is merged before the upload`() = test { val unreadable = "not exit data".toByteArray() @@ -3863,4 +3893,14 @@ class BackupRepoTest : BaseUnitTest() { isTrackingEnabled = true, setupState = WatchOnlyAccountSetupState.Authorizing, ) + + private fun mergeFlagFollowsDiscard(hasMerged: Boolean) { + var merged = hasMerged + whenever(sparkRepo.hasMergedRemoteExitState).thenAnswer { merged } + whenever(sparkRepo.discardStagedExitState(any())).thenAnswer { merged = false } + whenever { sparkRepo.mergeRemoteExitBackup(anyOrNull()) }.thenAnswer { + merged = true + Result.success(Unit) + } + } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 042d1a124f..2c41e56f70 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -861,6 +861,39 @@ class SparkRepoTest : BaseUnitTest() { assertTrue("hash" in store.data.first().sparkSendHashes, "A stale listing dropped a retry that ended") } + @Test + fun `a retry recorded while the activity sync reads spark's list keeps its row from an older failure`() = test { + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + val sut = retryDuringListRead(failed) { lists -> lists == 2 } + + // The refresh reads the list first, then the activity sync, whose read a retry outruns. + sut.start(0).getOrThrow() + + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } + ) + } + + @Test + fun `a retry recorded while the refresh reads spark's list keeps its row from an older failure`() = test { + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + var isRetrying = false + val sut = retryDuringListRead(failed) { isRetrying } + // The activity sync can't read the row, so the next refresh records the failure. + whenever { activityRepo.getActivity(eq("hash"), any()) } + .thenReturn(Result.failure(IllegalStateException("db locked"))) + sut.start(0).getOrThrow() + whenever { activityRepo.getActivity(eq("hash"), any()) }.thenReturn(Result.success(pendingSendRow())) + + isRetrying = true + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } + ) + } + @Test fun `a retry in flight when the release reads spark's list again keeps its hash after it ends`() = test { cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) @@ -2627,6 +2660,17 @@ class SparkRepoTest : BaseUnitTest() { assertFalse(File(Env.sparkExitRestorePath(0)).exists()) } + @Test + fun `dropping rejected staged exit data asks for the stored backup to be merged again`() = test { + val sut = createSut() + sut.mergeRemoteExitBackup(null).getOrThrow() + assertTrue(sut.hasMergedRemoteExitState) + + sut.discardStagedExitState("s") + + assertFalse(sut.hasMergedRemoteExitState) + } + @Test fun `staged exit data spark fails to import for another reason stays pending`() = test { whenever { sparkService.importExitState(any()) }.thenAnswer { throw SdkException.Generic("offline") } @@ -4208,6 +4252,38 @@ class SparkRepoTest : BaseUnitTest() { ) } + /** Runs a retry of the invoice to its end inside the first list read [isRetryRead] picks, which lists [failed]. */ + private fun retryDuringListRead(failed: Payment, isRetryRead: (Int) -> Boolean): SparkRepo { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0).copy(id = "retry")) + whenever { activityRepo.getActivity(eq("hash"), any()) }.thenReturn(Result.success(pendingSendRow())) + whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.success(Unit)) + val sut = createSut() + var lists = 0 + var hasRetried = false + whenever { sparkService.listPayments() }.doSuspendableAnswer { + if (!hasRetried && isRetryRead(++lists)) { + hasRetried = true + sut.payInvoice("lnbc1280n1send", 128uL).getOrThrow() + } + listOf(failed) + } + return sut + } + + private fun pendingSendRow() = Activity.Lightning( + LightningActivity.create( + id = "hash", + txType = ActivityPaymentType.SENT, + status = PaymentState.PENDING, + value = 128uL, + invoice = "lnbc1280n1send", + timestamp = 1uL, + ) + ) + private fun unexpiredPrepared(): PrepareSendPaymentResponse { val details = mock { on { paymentHash } doReturn "hash" From 9e9fe4a600076a97e8995e16235679c4c5512965 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 00:59:26 +0100 Subject: [PATCH 28/96] fix: end an expired taken spark retry's row before dropping it A send Spark took keeps its hash until its invoice expires, and the expiry rule writes its row from Spark's list, or marks it failed when Spark lists none, before it drops the attempt. Verified: just compile, just test and just lint pass; the new test fails without the fix. --- .../java/to/bitkit/repositories/SparkRepo.kt | 28 +++++++++--- .../to/bitkit/repositories/SparkRepoTest.kt | 45 +++++++++++++++++++ 2 files changed, 66 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 7a57bb9967..9f464ffb55 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -773,13 +773,26 @@ class SparkRepo @Inject constructor( } } - /** Drops the attempts of sends Spark took whose invoice expired, as nothing of them can settle any more. */ + /** + * Drops the attempts of sends Spark took whose invoice expired, once their row is written from Spark's list, as a + * failure the attempt held back may be the send's own. A send Spark still runs, or a list it can't read, keeps it. + */ private suspend fun dropExpiredTakenAttempts() { val expiries = cacheStore.data.first().sparkSendExpiries val now = clock.now().epochSeconds - takenAttempts.keys.filter { (expiries[it] ?: Long.MAX_VALUE) <= now }.forEach { - takenAttempts.remove(it) - cacheStore.removeSparkUncertainSend(it) + takenAttempts.keys.filter { (expiries[it] ?: Long.MAX_VALUE) <= now }.forEach { hash -> + val (send, listed) = listedLightningSendPayment(hash) + when (send) { + SparkLightningSend.Unavailable -> return@forEach + SparkLightningSend.NotFound -> if (!failHeldRow(hash)) return@forEach + is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> return@forEach + is SparkLightningSend.Found -> Unit + } + takenAttempts.remove(hash) + cacheStore.removeSparkUncertainSend(hash) + // Written once the attempt is gone, so it no longer holds the row back; a failed write is retried at the + // next refresh. + listed?.let { recordActivity(it) } } } @@ -1877,9 +1890,10 @@ class SparkRepo @Inject constructor( } // A send in flight, also one that ended while this list was read, or recorded after it was read while the // activities were recorded, may be missing from it or show only its earlier failed attempt, so it stays, as - // does one whose outcome Spark didn't report, also from before a restart. + // does one whose outcome Spark didn't report, also from before a restart, and one Spark took that keeps its + // attempt, until the expiry rule writes its row. val live = sendHashes(PaymentStatus.PENDING) + sendsInFlight.keys + inFlightBefore + - recordedSince(recordsBefore) + uncertainSendHashes() + recordedSince(recordsBefore) + uncertainSendHashes() + takenAttempts.keys val paid = sendHashes(PaymentStatus.COMPLETED) - live cacheStore.trimSparkSendHashes( paid = paid, @@ -1897,7 +1911,7 @@ class SparkRepo @Inject constructor( val inFlightBeforeCurrent = sendsInFlight.keys.toSet() val current = runSuspendCatching { sparkService.listPayments() }.getOrNull() ?: return val liveCurrent = sendsInFlight.keys + inFlightBeforeCurrent + recordedSince(recordsBeforeCurrent) + - uncertainSendHashes() + uncertainSendHashes() + takenAttempts.keys failed .filter { it.lowercase() !in liveCurrent } .filter { current.latestSend(it)?.status == PaymentStatus.FAILED } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 2c41e56f70..ab5f0ff56c 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3800,6 +3800,51 @@ class SparkRepoTest : BaseUnitTest() { assertTakenRetryKeptPastEarlierFailure(restart = true) } + @Test + fun `a taken spark retry without earlier ids ends its row once its invoice expires`() = test { + val sentAt = now.epochSeconds + // Spark took the retry before a restart, while its earlier attempts' ids couldn't be read. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to sentAt + 3_600), + sparkUncertainSendStarts = mapOf("hash" to sentAt), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + whenever(activityRepo.getActivity(eq("hash"), any())).thenReturn(Result.success(pendingSendRow())) + whenever(activityRepo.upsertActivity(any())).thenReturn(Result.success(Unit)) + val ownFailure = sentPayment(fees = 0).copy( + id = "retry", + status = PaymentStatus.FAILED, + timestamp = sentAt.toULong() + 1uL, + ) + whenever(sparkService.listPayments()).thenReturn(listOf(ownFailure)) + val sut = createSut(store) + sut.start(0).getOrThrow() + // Its own failure, dated within the 10 s a clock difference may account for, can't be told from an earlier one. + sparkEvents.emit(SdkEvent.PaymentFailed(ownFailure)) + advanceUntilIdle() + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) + + now += 2.hours + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + verify(activityRepo).upsertActivity( + argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } + ) + assertFalse("hash" in store.data.first().sparkUncertainSendStarts) + } + private suspend fun TestScope.assertTakenRetryKeptPastEarlierFailure(restart: Boolean) { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) whenever(sparkService.isConnected).thenReturn(true) From 61730cb50b068f56316bce38f765923605d390bc Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 01:33:00 +0100 Subject: [PATCH 29/96] fix: report an expired taken spark retry's outcome When the expiry rule drops a taken attempt, it emits the send's outcome from the same list read, or a failure when Spark lists no send, so a pending send screen resolves. Verified: just compile, just test and just lint pass; the new assertion fails without the fix. --- app/src/main/java/to/bitkit/repositories/SparkRepo.kt | 7 ++++++- app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt | 5 ++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 9f464ffb55..456d97f3d7 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -788,11 +788,16 @@ class SparkRepo @Inject constructor( is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> return@forEach is SparkLightningSend.Found -> Unit } - takenAttempts.remove(hash) + takenAttempts.remove(hash) ?: return@forEach cacheStore.removeSparkUncertainSend(hash) + if (listed?.status != PaymentStatus.COMPLETED) cacheStore.removeSparkSendHash(hash) // Written once the attempt is gone, so it no longer holds the row back; a failed write is retried at the // next refresh. listed?.let { recordActivity(it) } + // The send's own outcome event may have been held back with the attempt, so the send screen learns it here. + val event = listed?.toNodeEvent() + ?: Event.PaymentFailed(hash, hash, PaymentFailureReason.UNEXPECTED_ERROR) + _nodeEvents.emit(event) } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index ab5f0ff56c..fb47b44f10 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3801,7 +3801,7 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `a taken spark retry without earlier ids ends its row once its invoice expires`() = test { + fun `a taken spark retry without earlier ids ends its row and send once its invoice expires`() = test { val sentAt = now.epochSeconds // Spark took the retry before a restart, while its earlier attempts' ids couldn't be read. val store = CacheStore( @@ -3827,6 +3827,8 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.listPayments()).thenReturn(listOf(ownFailure)) val sut = createSut(store) sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } // Its own failure, dated within the 10 s a clock difference may account for, can't be told from an earlier one. sparkEvents.emit(SdkEvent.PaymentFailed(ownFailure)) advanceUntilIdle() @@ -3843,6 +3845,7 @@ class SparkRepoTest : BaseUnitTest() { argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } ) assertFalse("hash" in store.data.first().sparkUncertainSendStarts) + assertTrue(events.any { it is Event.PaymentFailed }, "the send screen never learned the send failed") } private suspend fun TestScope.assertTakenRetryKeptPastEarlierFailure(restart: Boolean) { From 215cc754ed32fb12498ad7bc86714abfdb12baff Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 11:44:21 +0100 Subject: [PATCH 30/96] fix: report no outcome for a restored spark retry at expiry A taken retry restored after a restart settled while the app was closed, so its expiry reopened the Sent sheet or the failed toast. Its expiry now reports an outcome only when an event was held back. A retry's saved start and earlier ids also replace an older attempt's when it has none. Verified: both new SparkRepoTest cases fail on 61730cb50 and pass here; just compile, just test and just lint pass. --- .../main/java/to/bitkit/data/CacheStore.kt | 8 +- .../java/to/bitkit/repositories/SparkRepo.kt | 16 ++- .../to/bitkit/repositories/SparkRepoTest.kt | 105 ++++++++++++++++++ 3 files changed, 125 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 7d83e8d546..7236cbcfae 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -176,7 +176,8 @@ class CacheStore internal constructor( /** * Keeps Spark's send of [paymentHash] as one whose outcome Spark didn't report, since [failedAt] epoch seconds, - * with when it was sent, [sentAt], and Spark's ids of the invoice's earlier attempts, [earlierIds], once known. + * with when it was sent, [sentAt], and Spark's ids of the invoice's earlier attempts, [earlierIds], once known; + * either left out drops an older attempt's. */ suspend fun addSparkUncertainSend( paymentHash: String, @@ -188,11 +189,12 @@ class CacheStore internal constructor( store.updateData { it.copy( sparkUncertainSends = it.sparkUncertainSends + (hash to failedAt), + // Each write is one attempt's, so a value it lacks drops an older attempt's. sparkUncertainSendStarts = sentAt?.let { start -> it.sparkUncertainSendStarts + (hash to start) } - ?: it.sparkUncertainSendStarts, + ?: (it.sparkUncertainSendStarts - hash), sparkUncertainSendEarlierIds = earlierIds ?.let { ids -> it.sparkUncertainSendEarlierIds + (hash to ids.sorted()) } - ?: it.sparkUncertainSendEarlierIds, + ?: (it.sparkUncertainSendEarlierIds - hash), ) } } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 456d97f3d7..66e67ecc56 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -197,6 +197,9 @@ class SparkRepo @Inject constructor( /** Sends Spark took and still runs, by payment hash, until they settle or their invoice expires. */ private val takenAttempts = ConcurrentHashMap() + /** Taken attempts restored after a restart whose outcome no event held back, so their expiry reports none. */ + private val restoredTakenAttempts = ConcurrentHashMap.newKeySet() + @Volatile private var hasSyncedActivities = false @@ -322,6 +325,7 @@ class SparkRepo @Inject constructor( sendsInFlight.clear() uncertainSends.clear() takenAttempts.clear() + restoredTakenAttempts.clear() hasSyncedActivities = false hasMergedRemoteExitState = false _depositClaims.update { emptyMap() } @@ -592,6 +596,7 @@ class SparkRepo @Inject constructor( val attempt = SendAttempt(sentAt.toULong(), earlierIds) if (result.getOrNull()?.status == PaymentStatus.PENDING) { takenAttempts[paymentHash.lowercase()] = attempt + restoredTakenAttempts.remove(paymentHash.lowercase()) } // A send whose call failed may still have gone out, so it is in doubt before the in-flight // attempt is dropped. @@ -638,6 +643,7 @@ class SparkRepo @Inject constructor( cacheStore.keepSparkSendAttempt(paymentHash) } else { takenAttempts.remove(paymentHash.lowercase()) + restoredTakenAttempts.remove(paymentHash.lowercase()) cacheStore.removeSparkUncertainSend(paymentHash) } Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) @@ -769,7 +775,7 @@ class SparkRepo @Inject constructor( sentAt = cache.sparkUncertainSendStarts[hash]?.toULong(), earlierIds = cache.sparkUncertainSendEarlierIds[hash]?.toSet(), ) - takenAttempts.putIfAbsent(hash, attempt) + if (takenAttempts.putIfAbsent(hash, attempt) == null) restoredTakenAttempts.add(hash) } } @@ -789,11 +795,14 @@ class SparkRepo @Inject constructor( is SparkLightningSend.Found -> Unit } takenAttempts.remove(hash) ?: return@forEach + // A restored attempt's outcome came while the app was closed and no event held it back, so none is sent. + val isRestored = restoredTakenAttempts.remove(hash) cacheStore.removeSparkUncertainSend(hash) if (listed?.status != PaymentStatus.COMPLETED) cacheStore.removeSparkSendHash(hash) // Written once the attempt is gone, so it no longer holds the row back; a failed write is retried at the // next refresh. listed?.let { recordActivity(it) } + if (isRestored) return@forEach // The send's own outcome event may have been held back with the attempt, so the send screen learns it here. val event = listed?.toNodeEvent() ?: Event.PaymentFailed(hash, hash, PaymentFailureReason.UNEXPECTED_ERROR) @@ -2009,6 +2018,7 @@ class SparkRepo @Inject constructor( // retry's: Spark may still finish it, so its hold and its Activity row stay until the expiry rule of // trySettleUncertainSend. if (payment.isOutrunByRetry(records)) { + payment.heldBackOutcome() Logger.info("Kept uncertain Spark send '${payment.sendHash()}' held past an older failure", context = TAG) return } @@ -2021,6 +2031,7 @@ class SparkRepo @Inject constructor( payment.sendHash()?.let { uncertainSends.remove(it.lowercase()) takenAttempts.remove(it.lowercase()) + restoredTakenAttempts.remove(it.lowercase()) cacheStore.removeSparkUncertainSend(it) } val isReleased = latest == SparkLightningSend.NotFound || @@ -2029,12 +2040,15 @@ class SparkRepo @Inject constructor( true } if (!isSettled) { + payment.heldBackOutcome() Logger.info("Kept Spark send '${payment.sendHash()}' held for a retry sent meanwhile", context = TAG) return } payment.toNodeEvent()?.let { _nodeEvents.emit(it) } } + private fun Payment.heldBackOutcome() = sendHash()?.let { restoredTakenAttempts.remove(it.lowercase()) } + /** * Records [payment] as activity and returns whether it is saved; a failed write is kept in [unsavedPayments]. Only * Spark's list or its send response [settlesJournal]: a payment event can come before the list holds the diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index fb47b44f10..fcab0585be 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3848,6 +3848,111 @@ class SparkRepoTest : BaseUnitTest() { assertTrue(events.any { it is Event.PaymentFailed }, "the send screen never learned the send failed") } + @Test + fun `a taken spark retry settled while closed reports no outcome when its invoice expires`() = test { + val sentAt = now.epochSeconds + // Spark took the retry, then the app closed; the retry completed while it was closed. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to sentAt + 3_600), + sparkUncertainSendStarts = mapOf("hash" to sentAt), + sparkUncertainSendEarlierIds = mapOf("hash" to listOf("older")), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + whenever(activityRepo.getActivity(eq("hash"), any())).thenReturn(Result.success(pendingSendRow())) + whenever(activityRepo.upsertActivity(any())).thenReturn(Result.success(Unit)) + val completed = sentPayment(fees = 0).copy(id = "retry", timestamp = sentAt.toULong() + 5uL) + whenever(sparkService.listPayments()).thenReturn(listOf(completed)) + val sut = createSut(store) + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + advanceUntilIdle() + // The startup sync already wrote the completed row; Spark's event for it fired before the listener existed. + verify(activityRepo).upsertActivity( + argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.SUCCEEDED } + ) + + now += 2.hours + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertFalse("hash" in store.data.first().sparkUncertainSendStarts) + assertEquals( + emptyList(), + events.filter { it is Event.PaymentSuccessful || it is Event.PaymentFailed }, + "a payment settled hours earlier was reported again, opening the Sent sheet", + ) + } + + @Test + fun `a spark retry whose earlier ids went unread keeps none of an older attempt`() = test { + val aSentAt = now.epochSeconds + // Spark took attempt "a" of the invoice before a restart, while it listed only "older" for it. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to aSentAt + 3_600), + sparkUncertainSendStarts = mapOf("hash" to aSentAt), + sparkUncertainSendEarlierIds = mapOf("hash" to listOf("older")), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(activityRepo.getActivity(eq("hash"), any())).thenReturn(Result.success(pendingSendRow())) + whenever(activityRepo.upsertActivity(any())).thenReturn(Result.success(Unit)) + // Attempt "a" failed while the app was closed; after the restart the user pays the invoice again. + now += 60.seconds + val aFailed = sentPayment(fees = 0).copy( + id = "a", + status = PaymentStatus.FAILED, + timestamp = aSentAt.toULong() + 30uL, + ) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + whenever(sparkService.listPayments()).thenReturn(listOf(aFailed)) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(retry) + val second = createSut(store) + second.start(0).getOrThrow() + advanceUntilIdle() + // The retry's read of its earlier attempts fails right after the status read before it succeeded. + var reads = 0 + whenever(sparkService.listPayments()).thenAnswer { + if (reads++ == 1) throw SdkException.Generic("read") + listOf(aFailed) + } + val bSentAt = now.epochSeconds + assertEquals("hash", second.payInvoice("lnbc1", 100uL).getOrThrow()) + runCurrent() + + // The app restarts again while Spark still runs the retry. + now += 60.seconds + whenever(sparkService.listPayments()).thenReturn(listOf(aFailed, retry.copy(timestamp = bSentAt.toULong()))) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val events = MutableSharedFlow() + whenever(sparkService.events).thenReturn(events) + clearInvocations(activityRepo) + createSut(store).start(0).getOrThrow() + advanceUntilIdle() + + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) + } + private suspend fun TestScope.assertTakenRetryKeptPastEarlierFailure(restart: Boolean) { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) whenever(sparkService.isConnected).thenReturn(true) From 0337261f7a279a1ec96a0fb8f32f8f1c5c371614 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 20:32:44 +0100 Subject: [PATCH 31/96] fix: hold a taken spark retry in every payment lookup Payment lookups now read an earlier attempt's listed failure as pending while a retry is taken, in flight or in doubt, so the node never pays the invoice again. The hand-over to the taken attempts shares the event cleanup's lock, an expired retry's outcome comes from the read that settled it, and the restore's cache log leaves out payment history. Verified: the new and changed SparkRepoTest cases fail on 215cc754e and pass here; just compile, just test and just lint pass. --- .../java/to/bitkit/repositories/BackupRepo.kt | 9 ++- .../java/to/bitkit/repositories/SparkRepo.kt | 33 +++++++---- .../to/bitkit/repositories/SparkRepoTest.kt | 59 +++++++++++++++---- 3 files changed, 80 insertions(+), 21 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 1275083dfd..fb02f71e8d 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1339,7 +1339,14 @@ class BackupRepo @Inject constructor( } runCatching { restoreSparkExitEarlierAddresses(parsed.sparkExitEarlierAddresses) } .onFailure { Logger.warn("Failed to restore the earlier Spark exit addresses", it, context = TAG) } - Logger.debug("Restored caches: ${jsonLogOf(parsed.cache.copy(cachedRates = emptyList()))}", TAG) + // Payment history stays out of the log, as support requests attach it. + val logged = parsed.cache.copy( + cachedRates = emptyList(), + moveToSparkHashes = emptyList(), + sparkUncertainSendStarts = emptyMap(), + sparkUncertainSendEarlierIds = emptyMap(), + ) + Logger.debug("Restored caches: ${jsonLogOf(logged)}", TAG) onCacheRestored() val persisted = preActivityMetadataRepo.upsertPreActivityMetadata(parsed.tagMetadata) .onFailure { Logger.warn("Failed to restore pre-activity metadata", it, context = TAG) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 66e67ecc56..2b2f01ac8c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -700,9 +700,13 @@ class SparkRepo @Inject constructor( if (send == SparkLightningSend.NotFound && !failHeldRow(paymentHash)) return false // A send Spark now runs keeps its earlier attempts' ids until it settles, taken over before the doubt ends. val isTaken = send is SparkLightningSend.Found && send.status == PaymentStatus.PENDING - if (isTaken) takenAttempts.putIfAbsent(key, uncertain.attempt) - // Only the caller that takes the hash off settles it, so its outcome is reported once. - if (!uncertainSends.remove(key, uncertain)) return true + // Only the caller that takes the hash off settles it, so its outcome is reported once. The hand-over shares the + // lock a payment event's cleanup takes, so a send settled meanwhile keeps no attempt to report again at expiry. + val isOwner = sendReleaseMutex.withLock { + val isMarked = isTaken && takenAttempts.putIfAbsent(key, uncertain.attempt) == null + uncertainSends.remove(key, uncertain).also { if (!it && isMarked) takenAttempts.remove(key) } + } + if (!isOwner) return true if (isTaken) cacheStore.keepSparkSendAttempt(paymentHash) else cacheStore.removeSparkUncertainSend(paymentHash) when (send) { SparkLightningSend.NotFound -> { @@ -718,7 +722,8 @@ class SparkRepo @Inject constructor( // next refresh. listed?.let { recordActivity(it) } } - settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } + // The event comes from the read that settled it, so a failed later read can't leave the send pending. + listed?.toNodeEvent()?.let { _nodeEvents.emit(it) } } SparkLightningSend.Unavailable -> Unit } @@ -1538,6 +1543,7 @@ class SparkRepo @Inject constructor( .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrNull() ?.latestSend(paymentHash) + ?.takeUnless { it.isEarlierFailureOfUncertainSend() } ?.toNodeEvent() } @@ -1568,9 +1574,10 @@ class SparkRepo @Inject constructor( } .distinct() .associateWith { hash -> - val status = requireNotNull(payments.latestSend(hash)).status - // A failed row may be an earlier attempt's, while Spark may still finish the uncertain retry. - if (status == PaymentStatus.FAILED && hash.lowercase() in uncertain) PaymentStatus.PENDING else status + val latest = requireNotNull(payments.latestSend(hash)) + // A failed row may be an earlier attempt's, while Spark may still finish the uncertain or taken retry. + val isHeld = hash.lowercase() in uncertain || latest.isEarlierFailureOfUncertainSend() + if (latest.status == PaymentStatus.FAILED && isHeld) PaymentStatus.PENDING else latest.status } val listedHashes = listed.keys.mapTo(mutableSetOf()) { it.lowercase() } listed + (unlisted + uncertain - listedHashes).associateWith { PaymentStatus.PENDING } @@ -1586,11 +1593,14 @@ class SparkRepo @Inject constructor( suspend fun lightningSend(paymentHash: String): SparkLightningSend = withContext(bgDispatcher) { val hash = paymentHash.lowercase() val isUnlistedHeld = hash in unexpiredStartedSends() - val send = listedLightningSend(paymentHash) + val (send, listed) = listedLightningSendPayment(paymentHash) val isUncertain = hash in uncertainSendHashes() val isHeld = when (send) { SparkLightningSend.NotFound, SparkLightningSend.Unavailable -> isUncertain || isUnlistedHeld - is SparkLightningSend.Found -> isUncertain && send.status == PaymentStatus.FAILED + // An earlier attempt's failure leaves a retry Spark took or still sends pending. + is SparkLightningSend.Found -> + send.status == PaymentStatus.FAILED && + (isUncertain || listed?.isEarlierFailureOfUncertainSend() == true) } if (isHeld) SparkLightningSend.Found(PaymentStatus.PENDING, null) else send } @@ -1671,6 +1681,9 @@ class SparkRepo @Inject constructor( } if (send.status == PaymentStatus.FAILED) { retried()?.let { return@withContext EarlierSend.Pending(it) } + // An earlier attempt's failure leaves a retry Spark took or still sends pending. + send.takeIf { it.isEarlierFailureOfUncertainSend() }?.sendHash() + ?.let { return@withContext EarlierSend.Pending(it) } refuseUnverifiedRestoredInvoice(bolt11, invoiceCreatedAt, invoiceExpiresAt) } val hash = (send.details as PaymentDetails.Lightning).htlcDetails.paymentHash @@ -1778,7 +1791,7 @@ class SparkRepo @Inject constructor( val uncertain = uncertainSendHashes() val sends = lightningPaymentStatuses { it.paymentType == SparkPaymentType.SEND } ?: return null return sends.filterValues { it.any { status -> status != PaymentStatus.FAILED } }.keys + - (unlisted - sends.keys) + uncertain + (unlisted - sends.keys) + uncertain + takenAttempts.keys } /** The statuses of Spark's Lightning payments that match [filter], by lowercase payment hash. */ diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index fcab0585be..81ec202a6a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -131,7 +131,10 @@ class SparkRepoTest : BaseUnitTest() { override fun now() = this@SparkRepoTest.now } - private fun createSut(cacheStore: CacheStore = this.cacheStore) = SparkRepo( + private fun createSut( + cacheStore: CacheStore = this.cacheStore, + activityRepo: ActivityRepo = this.activityRepo, + ) = SparkRepo( bgDispatcher = testDispatcher, sparkService = sparkService, activityRepo = { activityRepo }, @@ -666,9 +669,10 @@ class SparkRepoTest : BaseUnitTest() { val retry = async { sut.payInvoice("lnbc1280n1send", 128uL) } runCurrent() - // Recorded, but its journal is not written yet, so Spark's list still reads the older attempt's failure. + // Recorded, but its journal is not written yet; Spark's list still holds only the older attempt's failure, + // which reads as pending while the retry runs. assertTrue(sut.hasRecordedSendSince(mark, "hash")) - assertEquals(PaymentStatus.FAILED, assertIs(sut.lightningSend("hash")).status) + assertEquals(PaymentStatus.PENDING, assertIs(sut.lightningSend("hash")).status) assertTrue(sut.isSendInFlight("hash"), "a paused retry read as settled") journaling.complete(Unit) assertEquals("hash", retry.await().getOrThrow()) @@ -4178,15 +4182,18 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.getInfo() }.thenReturn( info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) ) - clearInvocations(activityRepo) + // The restarted repository writes to its own Activity, so the first one's poll can't stand in for it. + val restartedActivity = mock() + whenever { restartedActivity.getActivity(any(), any()) }.thenReturn(Result.success(null)) + whenever { restartedActivity.upsertActivity(any()) }.thenReturn(Result.success(Unit)) val restartedEvents = MutableSharedFlow() whenever(sparkService.events).thenReturn(restartedEvents) - val after = createSut(store) + val after = createSut(store, restartedActivity) after.start(0).getOrThrow() val events = mutableListOf() backgroundScope.launch { after.nodeEvents.collect { events += it } } runCurrent() - verify(activityRepo, never()).upsertActivity( + verify(restartedActivity, never()).upsertActivity( argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } ) @@ -4195,18 +4202,50 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.getInfo() }.thenReturn( info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) ) - // Only the read that settles the hold reaches Spark; every other read of its list fails. + // Every read of Spark's list after the one that settles the hold fails. + var isSettled = false whenever { sparkService.listPayments() }.thenAnswer { - val isSettleRead = Thread.currentThread().stackTrace.any { it.className.contains("listedLightningSend") } - if (!isSettleRead) throw SdkException.Generic("operators unreachable") + if (isSettled) throw SdkException.Generic("operators unreachable") + isSettled = Thread.currentThread().stackTrace.any { it.methodName.contains("trySettleUncertainSend") } listOf(olderFailure) } restartedEvents.emit(SdkEvent.Synced) advanceUntilIdle() - verify(activityRepo, atLeastOnce()).upsertActivity( + verify(restartedActivity, atLeastOnce()).upsertActivity( argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } ) + assertTrue(events.any { it is Event.PaymentFailed }, "the send screen never learned the send failed") + } + + @Test + fun `a taken spark retry reads as pending while spark lists only an earlier attempt's failure`() = test { + val sentAt = now.epochSeconds + // Spark took a retry before a restart, while it listed only the earlier attempt "older" of the invoice. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to sentAt + 3_600), + sparkUncertainSendStarts = mapOf("hash" to sentAt), + sparkUncertainSendEarlierIds = mapOf("hash" to listOf("older")), + ) + ), + clock, + ) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(older)) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) + assertEquals(PaymentStatus.PENDING, sut.lightningSendStatuses()?.get("hash")) + assertTrue("hash" in sut.attemptedLightningPaymentHashes().orEmpty()) + assertNull(sut.settledSendEvent("hash")) } @Test From d1ecf2802dc393fa7a23ba3982881814cef1b584 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 21:04:11 +0100 Subject: [PATCH 32/96] fix: report rejected spark exit data as not restored The wallet's start waits for the restore, so Spark wasn't connected when the restore staged its exit data and the restore reported it restored before Spark could reject it. The restore now connects Spark and imports the data at once, and staging and importing share a lock. Verified: the new SparkRepoTest connect cases fail without the connect and pass with it; just compile, just test, detekt and lintDevDebug pass. --- .../java/to/bitkit/repositories/SparkRepo.kt | 22 +++++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 48 +++++++++++++++++++ changelog.d/next/1976.fixed.md | 1 + 3 files changed, 66 insertions(+), 5 deletions(-) create mode 100644 changelog.d/next/1976.fixed.md diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 2b2f01ac8c..968e0f5b72 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -194,6 +194,9 @@ class SparkRepo @Inject constructor( /** Sends whose outcome Spark didn't report, by payment hash. */ private val uncertainSends = ConcurrentHashMap() + /** Serialises the imports of staged exit data, so a restore and Spark's start never import it at once. */ + private val exitImportMutex = Mutex() + /** Sends Spark took and still runs, by payment hash, until they settle or their invoice expires. */ private val takenAttempts = ConcurrentHashMap() @@ -1349,7 +1352,9 @@ class SparkRepo @Inject constructor( /** * Puts a restored exit data backup back: at once while Spark is connected, otherwise right after it connects, - * before it is used, so a restored wallet can exit on-chain even while the Spark operators are unreachable. + * before it is used, so a restored wallet can exit on-chain even while the Spark operators are unreachable. The + * wallet's start waits for the restore, so the restore connects Spark itself and fails when Spark can't import the + * data; one that can't connect keeps the data staged for Spark's start. */ suspend fun restoreExitBackup(backup: SparkExitBackupV1, walletIndex: Int): Result = withContext(bgDispatcher) { @@ -1358,15 +1363,22 @@ class SparkRepo @Inject constructor( Logger.warn("Skipped Spark exit data from network '${backup.network}'", context = TAG) return@runSuspendCatching } - File(Env.sparkExitRestorePath(walletIndex)).writeText(backup.exitState) + exitImportMutex.withLock { File(Env.sparkExitRestorePath(walletIndex)).writeText(backup.exitState) } + if (sparkService.isSupported && !sparkService.isConnected) connectForRestore(walletIndex) if (sparkService.isConnected) importRestoredExitState(walletIndex).getOrThrow() } } - private suspend fun importRestoredExitState(walletIndex: Int): Result { + private suspend fun connectForRestore(walletIndex: Int) { + runSuspendCatching { sparkService.connect(walletIndex, exitStore(walletIndex).isActive()) } + .onSuccess { if (it) _exitStateGeneration.update { generation -> generation + 1 } } + .onFailure { Logger.warn("Failed to connect Spark to import restored exit data", it, context = TAG) } + } + + private suspend fun importRestoredExitState(walletIndex: Int): Result = exitImportMutex.withLock { val file = File(Env.sparkExitRestorePath(walletIndex)) - if (!file.exists()) return Result.success(Unit) - return runSuspendCatching { sparkService.importExitState(file.readText()) } + if (!file.exists()) return@withLock Result.success(Unit) + runSuspendCatching { sparkService.importExitState(file.readText()) } .onSuccess { file.delete() Logger.info( diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 81ec202a6a..78196c0349 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -2638,6 +2638,54 @@ class SparkRepoTest : BaseUnitTest() { assertEquals("hash", assertIs(events.single()).paymentHash) } + @Test + fun `a restore made before spark connects connects it and fails when spark rejects its exit data`() = test { + var isConnected = false + whenever(sparkService.isConnected).thenAnswer { isConnected } + whenever { sparkService.connect(any(), any()) }.thenAnswer { + isConnected = true + true + } + whenever { sparkService.importExitState(any()) }.thenAnswer { throw SdkException.InvalidInput("bad") } + val sut = createSut() + + val result = sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "s"), 0) + + assertIs(result.exceptionOrNull()) + verify(sparkService, times(1)).importExitState("s") + assertTrue(File(Env.sparkExitRestorePath(0)).exists()) + } + + @Test + fun `a restore made before spark connects connects it and imports its exit data`() = test { + var isConnected = false + whenever(sparkService.isConnected).thenAnswer { isConnected } + whenever { sparkService.connect(any(), any()) }.thenAnswer { + isConnected = true + true + } + whenever { sparkService.importExitState(any()) }.thenReturn(ImportUnilateralExitStateResponse(2u, 0u, 0u, 0u)) + val sut = createSut() + + val result = sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "s"), 0) + + assertTrue(result.isSuccess) + verify(sparkService, times(1)).importExitState("s") + assertFalse(File(Env.sparkExitRestorePath(0)).exists()) + } + + @Test + fun `a restore spark can't connect for keeps its exit data staged for spark's start`() = test { + whenever { sparkService.connect(any(), any()) }.thenAnswer { throw SdkException.Generic("offline") } + val sut = createSut() + + val result = sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "s"), 0) + + assertTrue(result.isSuccess) + verify(sparkService, never()).importExitState(any()) + assertTrue(File(Env.sparkExitRestorePath(0)).exists()) + } + @Test fun `a restore whose exit data spark rejects fails and keeps it staged`() = test { whenever(sparkService.isConnected).thenReturn(true) diff --git a/changelog.d/next/1976.fixed.md b/changelog.d/next/1976.fixed.md new file mode 100644 index 0000000000..f73f771ca5 --- /dev/null +++ b/changelog.d/next/1976.fixed.md @@ -0,0 +1 @@ +Fixed wallet restores reporting Spark exit data as restored when Spark can't import it. From 2979510b890a140b5e206207f73d7357dc24061e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 21:11:23 +0100 Subject: [PATCH 33/96] fix: roll back only the spark attempt a poll marked A retry that returned pending could replace the poll's marker outside the lock, and the poll's rollback then removed the retry's attempt, leaving a failure held by the clock-skew guard with nothing to settle it at expiry. The rollback now removes only the attempt the poll marked. Verified: just compile, just test and just lint pass; the interleaving needs two threads, so no unit test covers it. --- app/src/main/java/to/bitkit/repositories/SparkRepo.kt | 5 ++++- 1 file changed, 4 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 2b2f01ac8c..fe7236b36a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -704,7 +704,10 @@ class SparkRepo @Inject constructor( // lock a payment event's cleanup takes, so a send settled meanwhile keeps no attempt to report again at expiry. val isOwner = sendReleaseMutex.withLock { val isMarked = isTaken && takenAttempts.putIfAbsent(key, uncertain.attempt) == null - uncertainSends.remove(key, uncertain).also { if (!it && isMarked) takenAttempts.remove(key) } + // Only the attempt marked here is rolled back, as a retry may have replaced it meanwhile. + val isRemoved = uncertainSends.remove(key, uncertain) + if (!isRemoved && isMarked) takenAttempts.remove(key, uncertain.attempt) + isRemoved } if (!isOwner) return true if (isTaken) cacheStore.keepSparkSendAttempt(paymentHash) else cacheStore.removeSparkUncertainSend(paymentHash) From b34fa0dda28003a9e9671d561b38b2d662cd5d76 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 21:49:09 +0100 Subject: [PATCH 34/96] fix: never hold a taken spark retry past its own failure A retry Spark took without its earlier attempts' ids had its own failure within the clock skew read as an earlier one's, so its hold and row stayed until the invoice expired. The taken attempt now keeps the id of the payment Spark returned or listed, and a failure with that id is always its own. Verified: the new SparkRepoTest case fails without the id check and passes with it; just compile, just test and just lint pass. --- .../java/to/bitkit/repositories/SparkRepo.kt | 16 +++++++++---- .../to/bitkit/repositories/SparkRepoTest.kt | 24 +++++++++++++++---- 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index fe7236b36a..40b3657fa8 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -593,7 +593,8 @@ class SparkRepo @Inject constructor( runSuspendCatching { sparkService.send(prepared) }.also { result -> hasReturned = true // Taken before the in-flight attempt is dropped, so an earlier failure never finds neither. - val attempt = SendAttempt(sentAt.toULong(), earlierIds) + // A payment Spark took carries its own id, so its failure is never read as an earlier one's. + val attempt = SendAttempt(sentAt.toULong(), earlierIds, result.getOrNull()?.id) if (result.getOrNull()?.status == PaymentStatus.PENDING) { takenAttempts[paymentHash.lowercase()] = attempt restoredTakenAttempts.remove(paymentHash.lowercase()) @@ -702,11 +703,13 @@ class SparkRepo @Inject constructor( val isTaken = send is SparkLightningSend.Found && send.status == PaymentStatus.PENDING // Only the caller that takes the hash off settles it, so its outcome is reported once. The hand-over shares the // lock a payment event's cleanup takes, so a send settled meanwhile keeps no attempt to report again at expiry. + // The listed pending payment is the retry Spark now runs, so its id marks the retry's own failure. + val taken = uncertain.attempt.copy(ownId = listed?.id ?: uncertain.attempt.ownId) val isOwner = sendReleaseMutex.withLock { - val isMarked = isTaken && takenAttempts.putIfAbsent(key, uncertain.attempt) == null + val isMarked = isTaken && takenAttempts.putIfAbsent(key, taken) == null // Only the attempt marked here is rolled back, as a retry may have replaced it meanwhile. val isRemoved = uncertainSends.remove(key, uncertain) - if (!isRemoved && isMarked) takenAttempts.remove(key, uncertain.attempt) + if (!isRemoved && isMarked) takenAttempts.remove(key, taken) isRemoved } if (!isOwner) return true @@ -763,7 +766,11 @@ class SparkRepo @Inject constructor( * When a send went out, in epoch seconds, and Spark's payment ids of its invoice's earlier attempts, read before it * did; null where unknown, such as for a send kept before these were stored or one Spark couldn't list for. */ - private data class SendAttempt(val sentAt: ULong? = null, val earlierIds: Set? = null) + private data class SendAttempt( + val sentAt: ULong? = null, + val earlierIds: Set? = null, + val ownId: String? = null, + ) /** Takes back the sends whose outcome Spark didn't report before a restart, so a sync can still settle them. */ private suspend fun restoreUncertainSends() { @@ -1963,6 +1970,7 @@ class SparkRepo @Inject constructor( val hash = sendHash(PaymentStatus.FAILED) ?: return false val key = hash.lowercase() val attempt = uncertainSends[key]?.attempt ?: inFlightAttempts[key] ?: takenAttempts[key] ?: return false + if (id == attempt.ownId) return false attempt.earlierIds?.let { return id in it } // A send kept before start times were stored can't tell its own failure from an earlier one, so it stays held // until its invoice expires, when the expiry rule settles it and its row. diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 81ec202a6a..74187768b0 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3693,16 +3693,29 @@ class SparkRepoTest : BaseUnitTest() { assertFalse(retryHeldAfter(null, failure.copy(timestamp = now.epochSeconds.toULong() + 10uL))) } + @Test + fun `a taken retry's own failure within the clock skew ends its hold while its earlier attempts are unknown`() = + test { + val taken = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) + val failure = taken.copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) + assertFalse(retryHeldAfter(null, failure, taken = taken)) + } + /** - * Sends a retry whose outcome stays unknown, with Spark listing [listedBeforeSend] before it goes out (null while - * it never synced, so it can't list), then delivers [failure]; true when the retry stays held. + * Sends a retry whose outcome stays unknown, or that Spark [taken] and still runs, with Spark listing + * [listedBeforeSend] before it goes out (null while it never synced, so it can't list), then delivers [failure]; + * true when the retry stays held. */ - private suspend fun TestScope.retryHeldAfter(listedBeforeSend: List?, failure: Payment): Boolean { + private suspend fun TestScope.retryHeldAfter( + listedBeforeSend: List?, + failure: Payment, + taken: Payment? = null, + ): Boolean { whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL) whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { taken ?: throw SdkException.Generic("timeout") } // Spark that never synced can't list every earlier attempt. if (listedBeforeSend == null) { whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncError = SyncError.Network("down"))) @@ -3716,7 +3729,8 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.getInfo()).thenReturn( info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable"), lastSyncedAt = 1uL) ) - assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + val result = sut.payInvoice("lnbc1", 100uL) + if (taken == null) assertIs(result.exceptionOrNull()) else result.getOrThrow() runCurrent() whenever(sparkService.listPayments()).thenReturn(listOf(failure)) From a90f5e735344ff2a5c34ef55279e22d1e63c1e7a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 21:57:36 +0100 Subject: [PATCH 35/96] fix: collect spark events before a restore connects it Spark's listener drops events no one collects, and the wallet's start collected them only after the restore, so events after the restore's connect were lost. The restore now starts the collection first, which subscribes before it returns. The can't-connect test also checks the connect, and the changelog says rejects. Verified: the new SparkRepoTest events case fails without the early collection and passes with it; just compile, just test and just lint pass. --- .../java/to/bitkit/repositories/SparkRepo.kt | 13 +++++++++--- .../to/bitkit/repositories/SparkRepoTest.kt | 21 +++++++++++++++++++ changelog.d/next/1976.fixed.md | 2 +- 3 files changed, 32 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 968e0f5b72..19c743e818 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -25,6 +25,7 @@ import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow @@ -279,9 +280,7 @@ class SparkRepo @Inject constructor( // A retry reads as connecting until it fails again. _state.update { it.copy(hasStartFailed = false) } runSuspendCatching { - if (isCollectingEvents.compareAndSet(false, true)) { - scope.launch { sparkService.events.collect { onSdkEvent(it) } } - } + collectEvents() restoreUncertainSends() val isExiting = exitStore(walletIndex).isActive() _state.update { it.copy(isExiting = isExiting) } @@ -1369,7 +1368,15 @@ class SparkRepo @Inject constructor( } } + /** Collects Spark's events once, subscribed before it returns, so no event of a connect made after it is lost. */ + private fun collectEvents() { + if (!isCollectingEvents.compareAndSet(false, true)) return + scope.launch(start = CoroutineStart.UNDISPATCHED) { sparkService.events.collect { onSdkEvent(it) } } + } + private suspend fun connectForRestore(walletIndex: Int) { + // Spark's listener drops events no one collects, and the wallet's start collects them only after the restore. + collectEvents() runSuspendCatching { sparkService.connect(walletIndex, exitStore(walletIndex).isActive()) } .onSuccess { if (it) _exitStateGeneration.update { generation -> generation + 1 } } .onFailure { Logger.warn("Failed to connect Spark to import restored exit data", 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 78196c0349..ebec452ff9 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -2682,10 +2682,31 @@ class SparkRepoTest : BaseUnitTest() { val result = sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "s"), 0) assertTrue(result.isSuccess) + verify(sparkService).connect(0, false) verify(sparkService, never()).importExitState(any()) assertTrue(File(Env.sparkExitRestorePath(0)).exists()) } + @Test + fun `a restore that connects spark handles its events before the wallet starts`() = test { + var isConnected = false + whenever(sparkService.isConnected).thenAnswer { isConnected } + whenever { sparkService.connect(any(), any()) }.thenAnswer { + isConnected = true + true + } + whenever { sparkService.importExitState(any()) }.thenReturn(ImportUnilateralExitStateResponse(2u, 0u, 0u, 0u)) + val sut = createSut() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "s"), 0).getOrThrow() + + sparkEvents.emit(SdkEvent.PaymentSucceeded(sentPayment(fees = 0))) + advanceUntilIdle() + + assertEquals("hash", assertIs(events.single()).paymentHash) + } + @Test fun `a restore whose exit data spark rejects fails and keeps it staged`() = test { whenever(sparkService.isConnected).thenReturn(true) diff --git a/changelog.d/next/1976.fixed.md b/changelog.d/next/1976.fixed.md index f73f771ca5..9b2b2547e8 100644 --- a/changelog.d/next/1976.fixed.md +++ b/changelog.d/next/1976.fixed.md @@ -1 +1 @@ -Fixed wallet restores reporting Spark exit data as restored when Spark can't import it. +Fixed wallet restores reporting Spark exit data as restored when Spark rejects it. From 76a7355edc7a39e520890590d3068a11b322cbf5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 22:29:21 +0100 Subject: [PATCH 36/96] fix: keep a taken spark retry's payment id across restarts A taken retry's payment id lived only in memory, so after a restart its own failure within the clock skew read as an earlier attempt's again. The id is now kept in the cache with the attempt and restored with it, and left out of the restore log. Verified: the new SparkRepoTest restart case fails without the restored id and passes with it; just compile, just test, detekt and lintDevDebug pass. --- .../main/java/to/bitkit/data/CacheStore.kt | 26 +++++++++++--- .../java/to/bitkit/repositories/BackupRepo.kt | 1 + .../java/to/bitkit/repositories/SparkRepo.kt | 11 ++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 35 +++++++++++++++++++ 4 files changed, 65 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 7236cbcfae..c8bd849db4 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -195,28 +195,42 @@ class CacheStore internal constructor( sparkUncertainSendEarlierIds = earlierIds ?.let { ids -> it.sparkUncertainSendEarlierIds + (hash to ids.sorted()) } ?: (it.sparkUncertainSendEarlierIds - hash), + sparkTakenSendIds = it.sparkTakenSendIds - hash, ) } } - /** Ends the doubt over a send Spark took and still runs, keeping its start time and earlier attempts' ids. */ - suspend fun keepSparkSendAttempt(paymentHash: String) { + /** + * Ends the doubt over a send Spark took and still runs, keeping its start time and earlier attempts' ids, with + * Spark's id of the payment it took, [paymentId], so its own failure is told apart after a restart. + */ + suspend fun keepSparkSendAttempt(paymentHash: String, paymentId: String?) { val hash = paymentHash.lowercase() - if (hash !in store.data.first().sparkUncertainSends) return - store.updateData { it.copy(sparkUncertainSends = it.sparkUncertainSends - hash) } + val data = store.data.first() + val isIdKept = paymentId == null || data.sparkTakenSendIds[hash] == paymentId + if (hash !in data.sparkUncertainSends && isIdKept) return + store.updateData { + it.copy( + sparkUncertainSends = it.sparkUncertainSends - hash, + sparkTakenSendIds = paymentId + ?.let { id -> it.sparkTakenSendIds + (hash to id) } + ?: it.sparkTakenSendIds, + ) + } } suspend fun removeSparkUncertainSend(paymentHash: String) { val hash = paymentHash.lowercase() val data = store.data.first() val isKept = hash in data.sparkUncertainSends || hash in data.sparkUncertainSendStarts || - hash in data.sparkUncertainSendEarlierIds + hash in data.sparkUncertainSendEarlierIds || hash in data.sparkTakenSendIds if (!isKept) return store.updateData { it.copy( sparkUncertainSends = it.sparkUncertainSends - hash, sparkUncertainSendStarts = it.sparkUncertainSendStarts - hash, sparkUncertainSendEarlierIds = it.sparkUncertainSendEarlierIds - hash, + sparkTakenSendIds = it.sparkTakenSendIds - hash, ) } } @@ -420,6 +434,8 @@ data class AppCacheData( * failures read as earlier ones. Absent where Spark couldn't list them. */ val sparkUncertainSendEarlierIds: Map> = mapOf(), + /** Spark's id of the payment each send Spark took is, so its own failure never reads as an earlier attempt's. */ + val sparkTakenSendIds: Map = mapOf(), /** * Payment hashes of the moves to Spark, kept across restarts so neither leg of a move is announced as a payment and * Activity shows the move as one. diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index fb02f71e8d..f7d7100eab 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1345,6 +1345,7 @@ class BackupRepo @Inject constructor( moveToSparkHashes = emptyList(), sparkUncertainSendStarts = emptyMap(), sparkUncertainSendEarlierIds = emptyMap(), + sparkTakenSendIds = emptyMap(), ) Logger.debug("Restored caches: ${jsonLogOf(logged)}", TAG) onCacheRestored() diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 40b3657fa8..760e490b5f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -641,7 +641,7 @@ class SparkRepo @Inject constructor( } // A send Spark still runs keeps its earlier attempts' ids, so their late failures leave it alone. if (payment.status == PaymentStatus.PENDING) { - cacheStore.keepSparkSendAttempt(paymentHash) + cacheStore.keepSparkSendAttempt(paymentHash, payment.id) } else { takenAttempts.remove(paymentHash.lowercase()) restoredTakenAttempts.remove(paymentHash.lowercase()) @@ -713,7 +713,11 @@ class SparkRepo @Inject constructor( isRemoved } if (!isOwner) return true - if (isTaken) cacheStore.keepSparkSendAttempt(paymentHash) else cacheStore.removeSparkUncertainSend(paymentHash) + if (isTaken) { + cacheStore.keepSparkSendAttempt(paymentHash, taken.ownId) + } else { + cacheStore.removeSparkUncertainSend(paymentHash) + } when (send) { SparkLightningSend.NotFound -> { cacheStore.removeSparkSendHash(paymentHash) @@ -783,12 +787,13 @@ class SparkRepo @Inject constructor( ) uncertainSends.putIfAbsent(hash, UncertainSend(failedAt.toULong(), expiresAt, attempt)) } - (cache.sparkUncertainSendStarts.keys + cache.sparkUncertainSendEarlierIds.keys) + (cache.sparkUncertainSendStarts.keys + cache.sparkUncertainSendEarlierIds.keys + cache.sparkTakenSendIds.keys) .filter { it !in cache.sparkUncertainSends } .forEach { hash -> val attempt = SendAttempt( sentAt = cache.sparkUncertainSendStarts[hash]?.toULong(), earlierIds = cache.sparkUncertainSendEarlierIds[hash]?.toSet(), + ownId = cache.sparkTakenSendIds[hash], ) if (takenAttempts.putIfAbsent(hash, attempt) == null) restoredTakenAttempts.add(hash) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 74187768b0..1f3ef842e1 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3701,6 +3701,41 @@ class SparkRepoTest : BaseUnitTest() { assertFalse(retryHeldAfter(null, failure, taken = taken)) } + @Test + fun `a taken retry's own failure within the clock skew ends its hold after a restart without earlier ids`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val taken = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(taken) + // Spark that never synced can't list every earlier attempt. + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncError = SyncError.Network("down"))) + val before = createSut(store) + before.start(0).getOrThrow() + val sentAt = now.epochSeconds.toULong() + before.payInvoice("lnbc1", 100uL).getOrThrow() + runCurrent() + + val restartedEvents = MutableSharedFlow() + whenever(sparkService.events).thenReturn(restartedEvents) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + whenever(sparkService.listPayments()).thenReturn(listOf(taken)) + val after = createSut(store) + after.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { after.nodeEvents.collect { events += it } } + runCurrent() + + val failure = taken.copy(status = PaymentStatus.FAILED, timestamp = sentAt) + whenever(sparkService.listPayments()).thenReturn(listOf(failure)) + restartedEvents.emit(SdkEvent.PaymentFailed(failure)) + advanceUntilIdle() + + assertTrue(events.any { it is Event.PaymentFailed }, "the retry's own failure stayed held after the restart") + } + /** * Sends a retry whose outcome stays unknown, or that Spark [taken] and still runs, with Spark listing * [listedBeforeSend] before it goes out (null while it never synced, so it can't list), then delivers [failure]; From ae27cfd57999990490dd55ca0b99682e09b6751e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 22:38:11 +0100 Subject: [PATCH 37/96] fix: take back held spark sends before a restore's events A restore's connect now takes back the sends held before it and waits until Spark's events are subscribed, so a start on another thread can't leave a connect without a collector and an earlier attempt's failure can't end a restored retry. Adds a test for the import lock. Verified: the new lock and held-retry SparkRepoTest cases fail without their fixes and pass with them; just compile, just test and just lint pass. --- .../java/to/bitkit/repositories/SparkRepo.kt | 18 ++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 58 +++++++++++++++++++ 2 files changed, 71 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 89be41c774..9aa045ef8f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -24,8 +24,8 @@ import com.synonym.bitkitcore.ServiceRouteLeg import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher -import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow @@ -35,6 +35,7 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.onSubscription import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex @@ -176,6 +177,7 @@ class SparkRepo @Inject constructor( private val unsavedPayments = ConcurrentHashMap.newKeySet() private val isCollectingEvents = AtomicBoolean(false) + private val eventsSubscribed = CompletableDeferred() private val refreshMutex = Mutex() @@ -1383,14 +1385,20 @@ class SparkRepo @Inject constructor( } } - /** Collects Spark's events once, subscribed before it returns, so no event of a connect made after it is lost. */ - private fun collectEvents() { - if (!isCollectingEvents.compareAndSet(false, true)) return - scope.launch(start = CoroutineStart.UNDISPATCHED) { sparkService.events.collect { onSdkEvent(it) } } + /** Collects Spark's events once and returns once subscribed, so no event of a connect made after it is lost. */ + private suspend fun collectEvents() { + if (isCollectingEvents.compareAndSet(false, true)) { + scope.launch { + sparkService.events.onSubscription { eventsSubscribed.complete(Unit) }.collect { onSdkEvent(it) } + } + } + eventsSubscribed.await() } private suspend fun connectForRestore(walletIndex: Int) { // Spark's listener drops events no one collects, and the wallet's start collects them only after the restore. + // The sends held before the restore are taken back first, so its events read their earlier attempts. + restoreUncertainSends() collectEvents() runSuspendCatching { sparkService.connect(walletIndex, exitStore(walletIndex).isActive()) } .onSuccess { if (it) _exitStateGeneration.update { generation -> generation + 1 } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index bd0c79f672..e09449a79f 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -2687,6 +2687,64 @@ class SparkRepoTest : BaseUnitTest() { assertTrue(File(Env.sparkExitRestorePath(0)).exists()) } + @Test + fun `a restore staged while spark's start imports older data keeps and imports its own`() = test { + File(Env.sparkExitRestorePath(0)).apply { parentFile?.mkdirs() }.writeText("old") + val importing = CompletableDeferred() + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.importExitState(any()) }.doSuspendableAnswer { + if (it.getArgument(0) == "old") importing.await() + ImportUnilateralExitStateResponse(1u, 0u, 0u, 0u) + } + val sut = createSut() + val start = async { sut.start(0) } + runCurrent() + val restore = async { + sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "new"), 0) + } + runCurrent() + + importing.complete(Unit) + + assertTrue(restore.await().isSuccess) + start.await().getOrThrow() + verify(sparkService).importExitState("new") + } + + @Test + fun `a restore that connects spark keeps a held retry past an earlier attempt's failure`() = test { + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to now.epochSeconds + 3_600), + sparkUncertainSendStarts = mapOf("hash" to now.epochSeconds), + sparkUncertainSendEarlierIds = mapOf("hash" to listOf("older")), + ) + ), + clock, + ) + var isConnected = false + whenever(sparkService.isConnected).thenAnswer { isConnected } + whenever { sparkService.connect(any(), any()) }.thenAnswer { + isConnected = true + true + } + whenever { sparkService.importExitState(any()) }.thenReturn(ImportUnilateralExitStateResponse(2u, 0u, 0u, 0u)) + val sut = createSut(store) + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "s"), 0).getOrThrow() + + val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED) + whenever { sparkService.listPayments() }.thenReturn(listOf(older)) + sparkEvents.emit(SdkEvent.PaymentFailed(older)) + advanceUntilIdle() + + assertTrue(events.none { it is Event.PaymentFailed }, "an earlier attempt's failure ended the held retry") + assertTrue("hash" in store.data.first().sparkUncertainSendStarts) + } + @Test fun `a restore that connects spark handles its events before the wallet starts`() = test { var isConnected = false From 705a1026b4b7660502f035d49966de7b741381f9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 23:40:27 +0100 Subject: [PATCH 38/96] fix: load held spark sends under the release lock With a restore connecting Spark, a payment event can clear a hold while Spark's start reads the saved holds, and the start could then reload the cleared one. Loading now takes the lock a payment event's cleanup holds, so it reads the cache after the cleanup. Verified: just compile, just test and just lint pass; the interleaving needs two threads, so no unit test covers it. --- app/src/main/java/to/bitkit/repositories/SparkRepo.kt | 3 ++- 1 file changed, 2 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 760e490b5f..4207dab3de 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -777,7 +777,8 @@ class SparkRepo @Inject constructor( ) /** Takes back the sends whose outcome Spark didn't report before a restart, so a sync can still settle them. */ - private suspend fun restoreUncertainSends() { + private suspend fun restoreUncertainSends() = sendReleaseMutex.withLock { + // Read and installed under the lock a payment event's cleanup takes, so a hold it clears is never reloaded. val cache = cacheStore.data.first() cache.sparkUncertainSends.forEach { (hash, failedAt) -> val expiresAt = cache.sparkSendExpiries[hash]?.toULong() ?: ULong.MAX_VALUE From 0de9d04a2d842194996bca2ea585164b5f94d336 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 13:45:29 +0100 Subject: [PATCH 39/96] test: keep a taken spark retry's expiry across a restart A relaunch whose list shows only an earlier failed attempt must not release the hold on a retry Spark took. Verified: SparkRepoTest passes, and fails with the taken-attempt guard removed from the startup release; just compile, test and lint pass. --- .../to/bitkit/repositories/SparkRepoTest.kt | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 1f3ef842e1..4e87da051c 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3853,6 +3853,32 @@ class SparkRepoTest : BaseUnitTest() { assertTakenRetryKeptPastEarlierFailure(restart = true) } + @Test + fun `a taken spark retry keeps its expiry after a restart whose list shows only an earlier failure`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED) + val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) + whenever { sparkService.listPayments() }.thenReturn(listOf(older)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(retry) + val before = createSut(store) + before.start(0).getOrThrow() + assertEquals("hash", before.payInvoice("lnbc1", 100uL).getOrThrow()) + runCurrent() + assertTrue("hash" in store.data.first().sparkSendExpiries) + + // Spark's list after the relaunch doesn't show the retry yet, only its earlier failed attempt. + whenever(sparkService.events).thenReturn(MutableSharedFlow()) + createSut(store).start(0).getOrThrow() + advanceUntilIdle() + + val cache = store.data.first() + assertTrue("hash" in cache.sparkSendHashes, "the startup sync released a retry Spark took") + assertTrue("hash" in cache.sparkSendExpiries, "the startup sync dropped a taken retry's expiry") + } + @Test fun `a taken spark retry without earlier ids ends its row and send once its invoice expires`() = test { val sentAt = now.epochSeconds From 8fc1e9076a76cd11ac3f879296b8e09900dc0d8f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 15:38:10 +0100 Subject: [PATCH 40/96] fix: keep a taken spark retry's hold and entry, fail unread exit backups A taken retry's known id tells its own failure from an earlier one's, also while the earlier ids are unknown. Its id is written only while the same attempt still has its entry, so a send settled meanwhile is never kept again. Exit backup data a restore can't read fails its category and leaves its backup status unchanged. Verified: the new SparkRepoTest, CacheStoreTest and BackupRepoTest cases fail without their fixes and pass with them; just compile, test and lint pass. --- .../main/java/to/bitkit/data/CacheStore.kt | 8 +++-- .../java/to/bitkit/repositories/BackupRepo.kt | 9 ++---- .../java/to/bitkit/repositories/SparkRepo.kt | 7 ++-- .../java/to/bitkit/data/CacheStoreTest.kt | 32 +++++++++++++++++++ .../to/bitkit/repositories/BackupRepoTest.kt | 1 + .../to/bitkit/repositories/SparkRepoTest.kt | 12 +++++++ 6 files changed, 58 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index c8bd849db4..dc6d3f8cb7 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -202,14 +202,18 @@ class CacheStore internal constructor( /** * Ends the doubt over a send Spark took and still runs, keeping its start time and earlier attempts' ids, with - * Spark's id of the payment it took, [paymentId], so its own failure is told apart after a restart. + * Spark's id of the payment it took, [paymentId], so its own failure is told apart after a restart. Only the + * attempt sent at [sentAt] that still has its entry changes it, so a send settled meanwhile is never kept again. */ - suspend fun keepSparkSendAttempt(paymentHash: String, paymentId: String?) { + suspend fun keepSparkSendAttempt(paymentHash: String, paymentId: String?, sentAt: Long?) { val hash = paymentHash.lowercase() val data = store.data.first() val isIdKept = paymentId == null || data.sparkTakenSendIds[hash] == paymentId if (hash !in data.sparkUncertainSends && isIdKept) return store.updateData { + val isOwn = sentAt?.let { start -> it.sparkUncertainSendStarts[hash] == start } + ?: (hash in it.sparkUncertainSends) + if (!isOwn) return@updateData it it.copy( sparkUncertainSends = it.sparkUncertainSends - hash, sparkTakenSendIds = paymentId diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index f7d7100eab..abec15cf41 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1191,12 +1191,9 @@ class BackupRepo @Inject constructor( val parsed = runCatching { json.decodeFromString(String(dataBytes)) } .getOrElse { // A layout this app can't read never becomes readable here, so it is kept for one that can, - // and the restore reports the exit data as not restored. - if (it !is IllegalArgumentException) throw it - Logger.warn("Failed to read '${BackupCategory.SPARK_EXIT}' backup", it, context = TAG) - setAsideRejectedExitBackup(dataBytes) - failedCategories += BackupCategory.SPARK_EXIT - return@performRestore currentTimeMillis() + // and the restore reports the exit data as not restored, its backup status untouched. + if (it is IllegalArgumentException) setAsideRejectedExitBackup(dataBytes) + throw it } sparkRepo.restoreExitBackup(parsed, backupWalletIndex()).getOrThrow() parsed.createdAt diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index ed5af76cf6..a9cba80ff2 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -645,7 +645,7 @@ class SparkRepo @Inject constructor( } // A send Spark still runs keeps its earlier attempts' ids, so their late failures leave it alone. if (payment.status == PaymentStatus.PENDING) { - cacheStore.keepSparkSendAttempt(paymentHash, payment.id) + cacheStore.keepSparkSendAttempt(paymentHash, payment.id, sentAt) } else { takenAttempts.remove(paymentHash.lowercase()) restoredTakenAttempts.remove(paymentHash.lowercase()) @@ -718,7 +718,7 @@ class SparkRepo @Inject constructor( } if (!isOwner) return true if (isTaken) { - cacheStore.keepSparkSendAttempt(paymentHash, taken.ownId) + cacheStore.keepSparkSendAttempt(paymentHash, taken.ownId, taken.sentAt?.toLong()) } else { cacheStore.removeSparkUncertainSend(paymentHash) } @@ -2003,7 +2003,8 @@ class SparkRepo @Inject constructor( val hash = sendHash(PaymentStatus.FAILED) ?: return false val key = hash.lowercase() val attempt = uncertainSends[key]?.attempt ?: inFlightAttempts[key] ?: takenAttempts[key] ?: return false - if (id == attempt.ownId) return false + // A payment Spark took fails with its own id, so a failure with another id is an earlier attempt's. + attempt.ownId?.let { return id != it } attempt.earlierIds?.let { return id in it } // A send kept before start times were stored can't tell its own failure from an earlier one, so it stays held // until its invoice expires, when the expiry rule settles it and its row. diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index ac07d41885..47e82c3d27 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -247,4 +247,36 @@ class CacheStoreTest : BaseUnitTest() { private companion object { const val NOW = 1_800_000_000L } + + @Test + fun `keepSparkSendAttempt keeps the taken id of the attempt that still has its entry`() = test { + sut.addSparkUncertainSend("hash", failedAt = 100, sentAt = 100) + + sut.keepSparkSendAttempt("hash", "retry", sentAt = 100) + + val data = sut.data.first() + assertEquals("retry", data.sparkTakenSendIds["hash"]) + assertFalse("hash" in data.sparkUncertainSends) + } + + @Test + fun `keepSparkSendAttempt writes nothing for a send settled before it`() = test { + sut.addSparkUncertainSend("hash", failedAt = 100, sentAt = 100) + sut.removeSparkUncertainSend("hash") + + sut.keepSparkSendAttempt("hash", "retry", sentAt = 100) + + assertFalse("hash" in sut.data.first().sparkTakenSendIds) + } + + @Test + fun `keepSparkSendAttempt leaves a later attempt's entry alone`() = test { + sut.addSparkUncertainSend("hash", failedAt = 200, sentAt = 200) + + sut.keepSparkSendAttempt("hash", "retry", sentAt = 100) + + val data = sut.data.first() + assertFalse("hash" in data.sparkTakenSendIds) + assertTrue("hash" in data.sparkUncertainSends) + } } diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 83f0cf97a8..d29dd6a273 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -670,6 +670,7 @@ class BackupRepoTest : BaseUnitTest() { assertTrue(BackupCategory.SPARK_EXIT in failed) verify(vssBackupClient).putObject(BackupRepo.rejectedExitKey(stored), stored) verify(sparkRepo, never()).restoreExitBackup(any(), any()) + verify(cacheStore, never()).updateBackupStatus(eq(BackupCategory.SPARK_EXIT), any()) } @Test diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 641d867059..66ff835d6b 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3828,6 +3828,18 @@ class SparkRepoTest : BaseUnitTest() { assertFalse(retryHeldAfter(null, failure, taken = taken)) } + @Test + fun `an earlier failure past the clock skew keeps a taken retry held while its earlier ids are unknown`() = + test { + val taken = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) + val older = sentPayment(fees = 0).copy( + id = "older", + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong() + 60uL, + ) + assertTrue(retryHeldAfter(null, older, taken = taken)) + } + @Test fun `a taken retry's own failure within the clock skew ends its hold after a restart without earlier ids`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) From d1cd7155d9d23ca67a01738fde0506011f03b0a9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 16:42:44 +0100 Subject: [PATCH 41/96] fix: own a spark send's entry by a random attempt id Start times have second precision, so a retry sent in the second its predecessor failed could have its taken id written over. Each attempt now keeps a random id with its entry, and only that attempt writes its taken id. Verified: the same-second CacheStoreTest case fails with the start time check and passes with the attempt id; just compile, test and lint pass. --- .../main/java/to/bitkit/data/CacheStore.kt | 18 ++++++++--- .../java/to/bitkit/repositories/BackupRepo.kt | 1 + .../java/to/bitkit/repositories/SparkRepo.kt | 31 ++++++++++++++----- .../java/to/bitkit/data/CacheStoreTest.kt | 14 ++++----- .../to/bitkit/repositories/SparkRepoTest.kt | 2 +- 5 files changed, 45 insertions(+), 21 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index dc6d3f8cb7..8435291076 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -184,6 +184,7 @@ class CacheStore internal constructor( failedAt: Long, sentAt: Long? = null, earlierIds: Set? = null, + attemptId: String? = null, ) { val hash = paymentHash.lowercase() store.updateData { @@ -195,6 +196,8 @@ class CacheStore internal constructor( sparkUncertainSendEarlierIds = earlierIds ?.let { ids -> it.sparkUncertainSendEarlierIds + (hash to ids.sorted()) } ?: (it.sparkUncertainSendEarlierIds - hash), + sparkUncertainSendAttemptIds = attemptId?.let { id -> it.sparkUncertainSendAttemptIds + (hash to id) } + ?: (it.sparkUncertainSendAttemptIds - hash), sparkTakenSendIds = it.sparkTakenSendIds - hash, ) } @@ -203,16 +206,17 @@ class CacheStore internal constructor( /** * Ends the doubt over a send Spark took and still runs, keeping its start time and earlier attempts' ids, with * Spark's id of the payment it took, [paymentId], so its own failure is told apart after a restart. Only the - * attempt sent at [sentAt] that still has its entry changes it, so a send settled meanwhile is never kept again. + * attempt [attemptId] that still has its entry changes it, so a send settled meanwhile is never kept again. */ - suspend fun keepSparkSendAttempt(paymentHash: String, paymentId: String?, sentAt: Long?) { + suspend fun keepSparkSendAttempt(paymentHash: String, paymentId: String?, attemptId: String?) { val hash = paymentHash.lowercase() val data = store.data.first() val isIdKept = paymentId == null || data.sparkTakenSendIds[hash] == paymentId if (hash !in data.sparkUncertainSends && isIdKept) return store.updateData { - val isOwn = sentAt?.let { start -> it.sparkUncertainSendStarts[hash] == start } - ?: (hash in it.sparkUncertainSends) + // An entry kept before attempts had ids is one only an attempt without an id still owns. + val isOwn = attemptId?.let { id -> it.sparkUncertainSendAttemptIds[hash] == id } + ?: (hash in it.sparkUncertainSends && hash !in it.sparkUncertainSendAttemptIds) if (!isOwn) return@updateData it it.copy( sparkUncertainSends = it.sparkUncertainSends - hash, @@ -227,13 +231,15 @@ class CacheStore internal constructor( val hash = paymentHash.lowercase() val data = store.data.first() val isKept = hash in data.sparkUncertainSends || hash in data.sparkUncertainSendStarts || - hash in data.sparkUncertainSendEarlierIds || hash in data.sparkTakenSendIds + hash in data.sparkUncertainSendEarlierIds || hash in data.sparkTakenSendIds || + hash in data.sparkUncertainSendAttemptIds if (!isKept) return store.updateData { it.copy( sparkUncertainSends = it.sparkUncertainSends - hash, sparkUncertainSendStarts = it.sparkUncertainSendStarts - hash, sparkUncertainSendEarlierIds = it.sparkUncertainSendEarlierIds - hash, + sparkUncertainSendAttemptIds = it.sparkUncertainSendAttemptIds - hash, sparkTakenSendIds = it.sparkTakenSendIds - hash, ) } @@ -440,6 +446,8 @@ data class AppCacheData( val sparkUncertainSendEarlierIds: Map> = mapOf(), /** Spark's id of the payment each send Spark took is, so its own failure never reads as an earlier attempt's. */ val sparkTakenSendIds: Map = mapOf(), + /** A random id of the attempt each of those sends' entries belongs to, so a stale attempt never writes over it. */ + val sparkUncertainSendAttemptIds: Map = mapOf(), /** * Payment hashes of the moves to Spark, kept across restarts so neither leg of a move is announced as a payment and * Activity shows the move as one. diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index abec15cf41..f14ab299be 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1343,6 +1343,7 @@ class BackupRepo @Inject constructor( sparkUncertainSendStarts = emptyMap(), sparkUncertainSendEarlierIds = emptyMap(), sparkTakenSendIds = emptyMap(), + sparkUncertainSendAttemptIds = emptyMap(), ) Logger.debug("Restored caches: ${jsonLogOf(logged)}", TAG) onCacheRestored() diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index a9cba80ff2..59bf011036 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -574,15 +574,17 @@ class SparkRepo @Inject constructor( throw PaymentPendingException(paymentHash) } val sentAt = clock.now().epochSeconds + val attemptId = UUID.randomUUID().toString() var isDispatched = false var hasReturned = false val sent = try { - inFlightAttempts[paymentHash.lowercase()] = SendAttempt(sentAt.toULong(), earlierIds) + inFlightAttempts[paymentHash.lowercase()] = + SendAttempt(sentAt.toULong(), earlierIds, attemptId = attemptId) sendReleaseMutex.withLock { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() } cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) spending { // Kept until the call returns, so a send cut off by process death or cancellation stays held. - cacheStore.addSparkUncertainSend(paymentHash, sentAt, sentAt, earlierIds) + cacheStore.addSparkUncertainSend(paymentHash, sentAt, sentAt, earlierIds, attemptId) // The checks above and both writes suspend, so the deadline and an exit that started meanwhile // are checked last, before the send. runCatching { @@ -598,7 +600,7 @@ class SparkRepo @Inject constructor( hasReturned = true // Taken before the in-flight attempt is dropped, so an earlier failure never finds neither. // A payment Spark took carries its own id, so its failure is never read as an earlier one's. - val attempt = SendAttempt(sentAt.toULong(), earlierIds, result.getOrNull()?.id) + val attempt = SendAttempt(sentAt.toULong(), earlierIds, result.getOrNull()?.id, attemptId) if (result.getOrNull()?.status == PaymentStatus.PENDING) { takenAttempts[paymentHash.lowercase()] = attempt restoredTakenAttempts.remove(paymentHash.lowercase()) @@ -614,7 +616,7 @@ class SparkRepo @Inject constructor( } finally { // A send cancelled inside Spark's call stays in doubt, as its journal entry does, so a sync settles it. if (isDispatched && !hasReturned) { - val attempt = SendAttempt(sentAt.toULong(), earlierIds) + val attempt = SendAttempt(sentAt.toULong(), earlierIds, attemptId = attemptId) uncertainSends.putIfAbsent( paymentHash.lowercase(), UncertainSend(clock.now().epochSeconds.toULong(), expiresAt, attempt), @@ -640,12 +642,16 @@ class SparkRepo @Inject constructor( 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) - settleUncertainSend(paymentHash, SendAttempt(sentAt.toULong(), earlierIds), expiresAt) + settleUncertainSend( + paymentHash, + SendAttempt(sentAt.toULong(), earlierIds, attemptId = attemptId), + expiresAt + ) throw PaymentPendingException(paymentHash) } // A send Spark still runs keeps its earlier attempts' ids, so their late failures leave it alone. if (payment.status == PaymentStatus.PENDING) { - cacheStore.keepSparkSendAttempt(paymentHash, payment.id, sentAt) + cacheStore.keepSparkSendAttempt(paymentHash, payment.id, attemptId) } else { takenAttempts.remove(paymentHash.lowercase()) restoredTakenAttempts.remove(paymentHash.lowercase()) @@ -665,7 +671,13 @@ class SparkRepo @Inject constructor( private suspend fun settleUncertainSend(paymentHash: String, attempt: SendAttempt, expiresAt: ULong) { val failedAt = clock.now().epochSeconds uncertainSends[paymentHash.lowercase()] = UncertainSend(failedAt.toULong(), expiresAt, attempt) - cacheStore.addSparkUncertainSend(paymentHash, failedAt, attempt.sentAt?.toLong(), attempt.earlierIds) + cacheStore.addSparkUncertainSend( + paymentHash, + failedAt, + attempt.sentAt?.toLong(), + attempt.earlierIds, + attempt.attemptId, + ) scope.launch { // The send screen tracks the hash as pending only once the send returns, and resolves tracked ones. withTimeoutOrNull(PENDING_TRACK_WAIT) { @@ -718,7 +730,7 @@ class SparkRepo @Inject constructor( } if (!isOwner) return true if (isTaken) { - cacheStore.keepSparkSendAttempt(paymentHash, taken.ownId, taken.sentAt?.toLong()) + cacheStore.keepSparkSendAttempt(paymentHash, taken.ownId, taken.attemptId) } else { cacheStore.removeSparkUncertainSend(paymentHash) } @@ -778,6 +790,7 @@ class SparkRepo @Inject constructor( val sentAt: ULong? = null, val earlierIds: Set? = null, val ownId: String? = null, + val attemptId: String? = null, ) /** Takes back the sends whose outcome Spark didn't report before a restart, so a sync can still settle them. */ @@ -789,6 +802,7 @@ class SparkRepo @Inject constructor( val attempt = SendAttempt( sentAt = cache.sparkUncertainSendStarts[hash]?.toULong(), earlierIds = cache.sparkUncertainSendEarlierIds[hash]?.toSet(), + attemptId = cache.sparkUncertainSendAttemptIds[hash], ) uncertainSends.putIfAbsent(hash, UncertainSend(failedAt.toULong(), expiresAt, attempt)) } @@ -799,6 +813,7 @@ class SparkRepo @Inject constructor( sentAt = cache.sparkUncertainSendStarts[hash]?.toULong(), earlierIds = cache.sparkUncertainSendEarlierIds[hash]?.toSet(), ownId = cache.sparkTakenSendIds[hash], + attemptId = cache.sparkUncertainSendAttemptIds[hash], ) if (takenAttempts.putIfAbsent(hash, attempt) == null) restoredTakenAttempts.add(hash) } diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index 47e82c3d27..bed23a8ec9 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -250,9 +250,9 @@ class CacheStoreTest : BaseUnitTest() { @Test fun `keepSparkSendAttempt keeps the taken id of the attempt that still has its entry`() = test { - sut.addSparkUncertainSend("hash", failedAt = 100, sentAt = 100) + sut.addSparkUncertainSend("hash", failedAt = 100, sentAt = 100, attemptId = "a") - sut.keepSparkSendAttempt("hash", "retry", sentAt = 100) + sut.keepSparkSendAttempt("hash", "retry", attemptId = "a") val data = sut.data.first() assertEquals("retry", data.sparkTakenSendIds["hash"]) @@ -261,19 +261,19 @@ class CacheStoreTest : BaseUnitTest() { @Test fun `keepSparkSendAttempt writes nothing for a send settled before it`() = test { - sut.addSparkUncertainSend("hash", failedAt = 100, sentAt = 100) + sut.addSparkUncertainSend("hash", failedAt = 100, sentAt = 100, attemptId = "a") sut.removeSparkUncertainSend("hash") - sut.keepSparkSendAttempt("hash", "retry", sentAt = 100) + sut.keepSparkSendAttempt("hash", "retry", attemptId = "a") assertFalse("hash" in sut.data.first().sparkTakenSendIds) } @Test - fun `keepSparkSendAttempt leaves a later attempt's entry alone`() = test { - sut.addSparkUncertainSend("hash", failedAt = 200, sentAt = 200) + fun `keepSparkSendAttempt leaves a later attempt's entry from the same second alone`() = test { + sut.addSparkUncertainSend("hash", failedAt = 100, sentAt = 100, attemptId = "b") - sut.keepSparkSendAttempt("hash", "retry", sentAt = 100) + sut.keepSparkSendAttempt("hash", "retry", attemptId = "a") val data = sut.data.first() assertFalse("hash" in data.sparkTakenSendIds) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 66ff835d6b..be69c13e0f 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3717,7 +3717,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val deadline = now + 1.seconds - whenever { cacheStore.addSparkUncertainSend(any(), any(), anyOrNull(), anyOrNull()) }.thenAnswer { + whenever { cacheStore.addSparkUncertainSend(any(), any(), anyOrNull(), anyOrNull(), anyOrNull()) }.thenAnswer { now = deadline + 1.seconds Unit } From af32f2a9cf32d78cea4bc7cfafb69709f9edd7b4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 17:20:03 +0100 Subject: [PATCH 42/96] fix: bind spark retry expiry and reuse to its own attempt The expiry sweep keeps a taken retry whose listed failure is another payment's and drops only the attempt it read. An invoice whose taken retry Spark lists as failed itself is no longer counted as attempted. A deposit's early claim cap is cleared once its claim is shown at the normal speed. Verified: the new expiry, attempted-invoice and claim-cap SparkRepoTest cases fail without their fixes and pass with them; just compile, test and lint pass. --- .../java/to/bitkit/repositories/SparkRepo.kt | 46 +++++++------ .../to/bitkit/repositories/SparkRepoTest.kt | 64 ++++++++++++++++++- 2 files changed, 89 insertions(+), 21 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 59bf011036..4d0278ea52 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -827,14 +827,20 @@ class SparkRepo @Inject constructor( val expiries = cacheStore.data.first().sparkSendExpiries val now = clock.now().epochSeconds takenAttempts.keys.filter { (expiries[it] ?: Long.MAX_VALUE) <= now }.forEach { hash -> + val attempt = takenAttempts[hash] ?: return@forEach val (send, listed) = listedLightningSendPayment(hash) when (send) { SparkLightningSend.Unavailable -> return@forEach SparkLightningSend.NotFound -> if (!failHeldRow(hash)) return@forEach is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> return@forEach + // A failure with another id than the attempt's own is an earlier attempt's, listed before the attempt. + is SparkLightningSend.Found if send.status == PaymentStatus.FAILED && attempt.ownId != null && + listed?.id != attempt.ownId -> return@forEach + is SparkLightningSend.Found -> Unit } - takenAttempts.remove(hash) ?: return@forEach + // Only the attempt read here is dropped, as a retry may have replaced it meanwhile. + if (!takenAttempts.remove(hash, attempt)) return@forEach // A restored attempt's outcome came while the app was closed and no event held it back, so none is sent. val isRestored = restoredTakenAttempts.remove(hash) cacheStore.removeSparkUncertainSend(hash) @@ -914,6 +920,10 @@ class SparkRepo @Inject constructor( } claimJobs.remove(txid)?.cancel() setDepositClaim(txid, SparkDepositClaim.Later) + releaseEarlyClaimCap(txid) + } + + private fun releaseEarlyClaimCap(txid: String) { val vout = earlyClaimVouts.remove(txid) ?: return // Tried again while another claim of the deposit, such as Spark's own sync, leaves the cap in place. scope.launch { @@ -964,6 +974,8 @@ class SparkRepo @Inject constructor( } if (_depositClaims.value[txid] == SparkDepositClaim.Adding) return Logger.warn("Stopped looking for the Instant claim of Spark deposit '$txid'", context = TAG) + // Shown at the normal speed from here, so Spark no longer claims it early within the user's ceiling. + releaseEarlyClaimCap(txid) setDepositClaim(txid, if (isSeen) SparkDepositClaim.Unavailable else SparkDepositClaim.NotSeen) } @@ -1847,27 +1859,21 @@ class SparkRepo @Inject constructor( if (!sparkService.isSupported) return emptySet() val unlisted = unexpiredStartedSends() val uncertain = uncertainSendHashes() - val sends = lightningPaymentStatuses { it.paymentType == SparkPaymentType.SEND } ?: return null - return sends.filterValues { it.any { status -> status != PaymentStatus.FAILED } }.keys + - (unlisted - sends.keys) + uncertain + takenAttempts.keys + if (!sparkService.isConnected) return null + val payments = withContext(bgDispatcher) { runSuspendCatching { sparkService.listPayments() } } + .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } + .getOrNull() ?: return null + val sends = payments.mapNotNull { payment -> payment.sendHash()?.lowercase()?.let { it to payment } } + .groupBy({ it.first }, { it.second }) + // A retained attempt Spark lists as failed itself no longer holds its invoice; an earlier attempt's failure + // leaves it held. + val taken = takenAttempts.filter { (hash, attempt) -> + sends[hash].orEmpty().none { it.status == PaymentStatus.FAILED && it.id == attempt.ownId } + }.keys + return sends.filterValues { it.any { payment -> payment.status != PaymentStatus.FAILED } }.keys + + (unlisted - sends.keys) + uncertain + taken } - /** The statuses of Spark's Lightning payments that match [filter], by lowercase payment hash. */ - private suspend fun lightningPaymentStatuses(filter: (Payment) -> Boolean): Map>? = - withContext(bgDispatcher) { - if (!sparkService.isConnected) return@withContext null - runSuspendCatching { sparkService.listPayments() } - .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } - .getOrNull() - ?.filter(filter) - ?.mapNotNull { payment -> - (payment.details as? PaymentDetails.Lightning)?.htlcDetails?.paymentHash?.lowercase() - ?.let { it to payment.status } - } - ?.groupBy({ it.first }, { it.second }) - ?.mapValues { it.value.toSet() } - } - private suspend fun lightningPaymentHashes(filter: (Payment) -> Boolean): Set? = withContext(bgDispatcher) { if (!sparkService.isConnected) return@withContext null runSuspendCatching { sparkService.listPayments() } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index be69c13e0f..d863e4133f 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -2371,7 +2371,7 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `instant stops quoting once spark waits for the early claim, capped at the ceiling`() = test { + fun `instant stops quoting once spark waits for the early claim, and clears its cap at the normal speed`() = test { listDeposit() // Spark keeps the ceiling as the cap, so it claims a later offer within it by itself. whenever { sparkService.fetchClaimQuote("txid", 0u) }.thenReturn(quote(earlyFee = 300uL)) @@ -2386,6 +2386,8 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, times(1)).claimDeposit(any(), any(), any()) verify(sparkService).claimDeposit("txid", 0u, 500uL) assertEquals(SparkDepositClaim.Unavailable, sut.depositClaims.value["txid"]) + // Shown at the normal speed, so Spark no longer claims it early within the ceiling. + verify(sparkService).releaseDepositClaimFee("txid", 0u) } @Test @@ -2404,6 +2406,7 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, times(1)).claimDeposit("txid", 0u, 500uL) assertEquals(SparkDepositClaim.Adding, sut.depositClaims.value["txid"]) + verify(sparkService, never()).releaseDepositClaimFee(any(), any()) } @Test @@ -3992,6 +3995,65 @@ class SparkRepoTest : BaseUnitTest() { assertTakenRetryKeptPastEarlierFailure(restart = true) } + @Test + fun `an earlier attempt's failure at expiry leaves a taken spark retry spark still runs`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED) + val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) + whenever(sparkService.listPayments()).thenReturn(listOf(older)) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(retry) + val sut = createSut(store) + sut.start(0).getOrThrow() + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + runCurrent() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + + // The invoice expires while Spark's list still shows only the earlier attempt's failure. + now += 2.hours + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertTrue(events.none { it is Event.PaymentFailed }, "the expiry ended a retry Spark still runs") + assertTrue("hash" in store.data.first().sparkSendHashes) + } + + @Test + fun `a taken spark retry's own failure listed after a restart frees its invoice for paykit`() = test { + val sentAt = now.epochSeconds + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to sentAt + 3_600), + sparkUncertainSendStarts = mapOf("hash" to sentAt), + sparkTakenSendIds = mapOf("hash" to "retry"), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(older)) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + assertEquals(setOf("hash"), sut.attemptedLightningPaymentHashes(), "an earlier failure freed a taken retry") + + // The retry failed while the app was closed, so Spark lists its own failure. + val ownFailure = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(older, ownFailure)) + + assertEquals(emptySet(), sut.attemptedLightningPaymentHashes()) + } + @Test fun `a taken spark retry keeps its expiry after a restart whose list shows only an earlier failure`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) From 166c5685973ad3a1c30fc3875fdbdeaf28d5a98d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 18:26:51 +0100 Subject: [PATCH 43/96] fix: keep each spark invoice's hold with the attempt its journal names A retry going out drops the earlier attempt it replaces from memory, as its journal entry does, so that attempt's late failure or the sweep never ends or reports the retry. A pending send response no longer takes a hold its own outcome already settled. Between listed sends of equal status, the held attempt's own payment wins. Verified: the four new SparkRepoTest cases each fail with their fix reverted and pass with it; just compile, test and lint pass. --- .../java/to/bitkit/repositories/SparkRepo.kt | 42 ++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 136 ++++++++++++++++++ 2 files changed, 169 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 4d0278ea52..b4702566cd 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -580,6 +580,11 @@ class SparkRepo @Inject constructor( val sent = try { inFlightAttempts[paymentHash.lowercase()] = SendAttempt(sentAt.toULong(), earlierIds, attemptId = attemptId) + // Its journal entry replaces an earlier attempt's, which only goes out once that one failed, so the + // earlier attempt no longer holds the invoice; dropped after this one holds it, so a reader never + // finds neither. + takenAttempts.remove(paymentHash.lowercase()) + restoredTakenAttempts.remove(paymentHash.lowercase()) sendReleaseMutex.withLock { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() } cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) spending { @@ -602,8 +607,13 @@ class SparkRepo @Inject constructor( // A payment Spark took carries its own id, so its failure is never read as an earlier one's. val attempt = SendAttempt(sentAt.toULong(), earlierIds, result.getOrNull()?.id, attemptId) if (result.getOrNull()?.status == PaymentStatus.PENDING) { - takenAttempts[paymentHash.lowercase()] = attempt - restoredTakenAttempts.remove(paymentHash.lowercase()) + // Taken only while its own outcome wasn't handled meanwhile, as its journal write is. + sendReleaseMutex.withLock { + if (inFlightAttempts[paymentHash.lowercase()]?.attemptId == attemptId) { + takenAttempts[paymentHash.lowercase()] = attempt + restoredTakenAttempts.remove(paymentHash.lowercase()) + } + } } // A send whose call failed may still have gone out, so it is in doubt before the in-flight // attempt is dropped. @@ -1739,7 +1749,7 @@ class SparkRepo @Inject constructor( } seedSendHashes(payments) val send = payments - .latestSend { + .latestSend(paymentHash?.let { heldAttempt(it)?.ownId }) { it.invoice.equals(bolt11, ignoreCase = true) || it.htlcDetails.paymentHash.equals(paymentHash, ignoreCase = true) } @@ -1837,14 +1847,27 @@ class SparkRepo @Inject constructor( } private fun List.latestSend(paymentHash: String): Payment? = - latestSend { it.htlcDetails.paymentHash.equals(paymentHash, ignoreCase = true) } + latestSend( + heldAttempt(paymentHash)?.ownId + ) { it.htlcDetails.paymentHash.equals(paymentHash, ignoreCase = true) } - private fun List.latestSend(matches: (PaymentDetails.Lightning) -> Boolean): Payment? = filter { + /** + * The send that settles the invoice [matches] picks: a retry of a failed send shares its hash, so the outcome that + * settles it wins, and between equal outcomes the held attempt's own payment, [ownId]. + */ + private fun List.latestSend( + ownId: String? = null, + matches: (PaymentDetails.Lightning) -> Boolean, + ): Payment? = filter { val details = it.details as? PaymentDetails.Lightning it.paymentType == SparkPaymentType.SEND && details != null && matches(details) + }.minWithOrNull(compareBy({ SEND_STATUS_PRIORITY.indexOf(it.status) }, { it.id != ownId })) + + /** The attempt that holds [paymentHash]: one in doubt, one in Spark's send call, or one Spark took. */ + private fun heldAttempt(paymentHash: String): SendAttempt? { + val key = paymentHash.lowercase() + return uncertainSends[key]?.attempt ?: inFlightAttempts[key] ?: takenAttempts[key] } - // A retry of a failed send shares its hash, so the outcome that settles it wins. - .minByOrNull { SEND_STATUS_PRIORITY.indexOf(it.status) } /** Payment hashes of the Lightning payments Spark received. */ suspend fun receivedLightningPaymentHashes(): Set = @@ -2022,8 +2045,7 @@ class SparkRepo @Inject constructor( */ private fun Payment.isEarlierFailureOfUncertainSend(): Boolean { val hash = sendHash(PaymentStatus.FAILED) ?: return false - val key = hash.lowercase() - val attempt = uncertainSends[key]?.attempt ?: inFlightAttempts[key] ?: takenAttempts[key] ?: return false + val attempt = heldAttempt(hash) ?: return false // A payment Spark took fails with its own id, so a failure with another id is an earlier attempt's. attempt.ownId?.let { return id != it } attempt.earlierIds?.let { return id in it } @@ -2109,6 +2131,8 @@ class SparkRepo @Inject constructor( // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. payment.sendHash()?.let { uncertainSends.remove(it.lowercase()) + // A send call that returns after this keeps no hold for the outcome handled here. + inFlightAttempts.remove(it.lowercase()) takenAttempts.remove(it.lowercase()) restoredTakenAttempts.remove(it.lowercase()) cacheStore.removeSparkUncertainSend(it) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index d863e4133f..774fd42164 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -37,6 +37,7 @@ import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first @@ -4054,6 +4055,141 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(emptySet(), sut.attemptedLightningPaymentHashes()) } + @Test + fun `a taken attempt's late failure leaves the retry spark took after it failed`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val b = sentPayment(fees = 0).copy(id = "b", status = PaymentStatus.PENDING) + val (_, events) = retryAfterTakenFailure(store, retry = b) + + // The taken attempt's own failure event arrives only now. + sparkEvents.emit(SdkEvent.PaymentFailed(takenAttemptFailure)) + advanceUntilIdle() + + assertTrue(events.none { it is Event.PaymentFailed }, "the earlier attempt's failure ended the live retry") + val cache = store.data.first() + assertEquals("b", cache.sparkTakenSendIds["hash"]) + assertTrue("hash" in cache.sparkSendHashes) + } + + @Test + fun `a retry spark took after a taken attempt failed reports its success once past expiry`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val b = sentPayment(fees = 0).copy(id = "b", status = PaymentStatus.COMPLETED) + val (_, events) = retryAfterTakenFailure(store, retry = b) + + now += 2.hours + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals(1, events.count { it is Event.PaymentSuccessful }, "the expiry reported the retry's success again") + } + + @Test + fun `a spark send whose failure is handled before its pending response keeps no hold`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val b = sentPayment(fees = 0).copy(id = "b", status = PaymentStatus.PENDING) + val bFailed = b.copy(status = PaymentStatus.FAILED) + var listed = emptyList() + var isListUnavailable = false + whenever(sparkService.listPayments()).thenAnswer { + if (isListUnavailable) throw SdkException.Generic("down") else listed + } + // Spark reports the send's failure, while its list can't be read, before the send call returns pending. + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { + isListUnavailable = true + sparkEvents.emit(SdkEvent.PaymentFailed(bFailed)) + delay(1.seconds) + isListUnavailable = false + b + } + val sut = createSut(store) + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + sut.payInvoice("lnbc1", 100uL) + advanceUntilIdle() + + listed = listOf(bFailed) + now += 2.hours + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals(1, events.count { it is Event.PaymentFailed }, "the expiry reported the failure again") + } + + @Test + fun `a taken spark retry's own failure wins over an earlier failure in either order`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED) + val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) + whenever(sparkService.listPayments()).thenReturn(listOf(older)) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(retry) + val sut = createSut(store) + sut.start(0).getOrThrow() + sut.payInvoice("lnbc1", 100uL).getOrThrow() + runCurrent() + val ownFailure = retry.copy(status = PaymentStatus.FAILED) + + for (listed in listOf(listOf(older, ownFailure), listOf(ownFailure, older))) { + whenever(sparkService.listPayments()).thenReturn(listed) + val send = assertIs(sut.lightningSend("hash")) + assertEquals(PaymentStatus.FAILED, send.status, "an earlier failure hid the retry's own in $listed") + } + } + + private val takenAttemptFailure = + sentPayment(fees = 0).copy(id = "a", status = PaymentStatus.FAILED, timestamp = 0uL) + + /** + * Spark takes attempt "a", whose own failure it lists before its event arrives; the retry then goes out with its + * send call failing, and a sync finds it listed as [retry]. Returns the repository and its node events. + */ + private suspend fun TestScope.retryAfterTakenFailure( + store: CacheStore, + retry: Payment, + ): Pair> { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + var listed = emptyList() + whenever(sparkService.listPayments()).thenAnswer { listed } + val taken = takenAttemptFailure.copy(status = PaymentStatus.PENDING) + whenever(sparkService.send(any(), anyOrNull())) + .thenReturn(taken) + .thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut(store) + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + runCurrent() + + listed = listOf(takenAttemptFailure) + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + runCurrent() + + listed = listOf(takenAttemptFailure, retry) + now += 5.seconds + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + return sut to events + } + @Test fun `a taken spark retry keeps its expiry after a restart whose list shows only an earlier failure`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) From a7301d55cf0aa98425be01bc1acfd62da8b07a13 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 18:40:20 +0100 Subject: [PATCH 44/96] fix: end an unlisted taken spark retry after a grace past expiry A retry Spark took that it lists no outcome of, or only an earlier attempt's failure, stays held for 10 minutes past its invoice's expiry, as an unlisted withdrawal does, then fails its row and ends its hold. Verified: both new SparkRepoTest cases fail without the grace and pass with it; just compile, test and lint pass. --- .../java/to/bitkit/repositories/SparkRepo.kt | 15 +++++- .../to/bitkit/repositories/SparkRepoTest.kt | 46 +++++++++++++++---- 2 files changed, 49 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index b4702566cd..36651726e6 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -132,6 +132,12 @@ class SparkRepo @Inject constructor( /** How long a journaled withdrawal Spark doesn't list stays open before a sync closes it as never sent. */ private val UNLISTED_WITHDRAWAL_GRACE = 10.minutes + /** + * How long past its invoice's expiry a send Spark took stays held while Spark lists none of its own outcome, + * as with an unlisted withdrawal, before its row fails. + */ + private val UNLISTED_TAKEN_SEND_GRACE = 10.minutes + /** How many sent contact withdrawals stay recorded for a request proof to complete from. */ private const val MAX_SENT_WITHDRAWALS = 20 @@ -832,20 +838,25 @@ class SparkRepo @Inject constructor( /** * Drops the attempts of sends Spark took whose invoice expired, once their row is written from Spark's list, as a * failure the attempt held back may be the send's own. A send Spark still runs, or a list it can't read, keeps it. + * One Spark lists no outcome of, or only an earlier attempt's failure, fails its row once + * [UNLISTED_TAKEN_SEND_GRACE] past the expiry. */ private suspend fun dropExpiredTakenAttempts() { val expiries = cacheStore.data.first().sparkSendExpiries val now = clock.now().epochSeconds takenAttempts.keys.filter { (expiries[it] ?: Long.MAX_VALUE) <= now }.forEach { hash -> val attempt = takenAttempts[hash] ?: return@forEach + val expiresAt = expiries[hash] ?: return@forEach + // Spark may list a send it took only on a later sync, so an unlisted one stays held for a while. + val isPastGrace = now >= expiresAt + UNLISTED_TAKEN_SEND_GRACE.inWholeSeconds val (send, listed) = listedLightningSendPayment(hash) when (send) { SparkLightningSend.Unavailable -> return@forEach - SparkLightningSend.NotFound -> if (!failHeldRow(hash)) return@forEach + SparkLightningSend.NotFound -> if (!isPastGrace || !failHeldRow(hash)) return@forEach is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> return@forEach // A failure with another id than the attempt's own is an earlier attempt's, listed before the attempt. is SparkLightningSend.Found if send.status == PaymentStatus.FAILED && attempt.ownId != null && - listed?.id != attempt.ownId -> return@forEach + listed?.id != attempt.ownId -> if (!isPastGrace || !failHeldRow(hash)) return@forEach is SparkLightningSend.Found -> Unit } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 774fd42164..02f862641a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3997,16 +3997,32 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `an earlier attempt's failure at expiry leaves a taken spark retry spark still runs`() = test { + fun `a taken spark retry with only an earlier failure listed stays held until the grace past expiry`() = test { + assertTakenRetryHeldUntilGrace( + listed = listOf(sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED)) + ) + } + + @Test + fun `a taken spark retry spark never lists stays held until the grace past expiry`() = test { + assertTakenRetryHeldUntilGrace(listed = emptyList()) + } + + /** + * Spark takes a retry while it lists [listed], and keeps listing only that: the retry stays held past its invoice's + * expiry until the grace for an unlisted send ends, then its row fails. + */ + private suspend fun TestScope.assertTakenRetryHeldUntilGrace(listed: List) { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + whenever(activityRepo.getActivity(eq("hash"), any())).thenReturn(Result.success(pendingSendRow())) + whenever(activityRepo.upsertActivity(any())).thenReturn(Result.success(Unit)) val prepared = unexpiredPrepared() whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED) val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) - whenever(sparkService.listPayments()).thenReturn(listOf(older)) + whenever(sparkService.listPayments()).thenReturn(listed) whenever(sparkService.send(any(), anyOrNull())).thenReturn(retry) val sut = createSut(store) sut.start(0).getOrThrow() @@ -4014,15 +4030,25 @@ class SparkRepoTest : BaseUnitTest() { runCurrent() val events = mutableListOf() backgroundScope.launch { sut.nodeEvents.collect { events += it } } + val sync = suspend { + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + } - // The invoice expires while Spark's list still shows only the earlier attempt's failure. - now += 2.hours - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - - assertTrue(events.none { it is Event.PaymentFailed }, "the expiry ended a retry Spark still runs") + // Past the invoice's hour, within the 10 min Spark may take to list the retry. + now += 65.minutes + sync() + assertTrue(events.none { it is Event.PaymentFailed }, "the expiry ended a retry Spark may still list") assertTrue("hash" in store.data.first().sparkSendHashes) + + now += 10.minutes + sync() + assertTrue(events.any { it is Event.PaymentFailed }, "a retry Spark never listed stayed held past the grace") + verify(activityRepo, atLeastOnce()).upsertActivity( + argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } + ) + assertFalse("hash" in store.data.first().sparkSendHashes) } @Test From 59eff9d98088aea7cebea32a2c9f53684f02fef3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 19:14:41 +0100 Subject: [PATCH 45/96] fix: finish a pending spark send's hold when its caller is cancelled The send already went out, so taking its hold no longer gives up on cancellation while it waits for the release lock. Verified: just compile, test and lint pass; no unit test, as the case needs a cancellation while another holder has the lock. --- .../main/java/to/bitkit/repositories/SparkRepo.kt | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 36651726e6..58c9a31576 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -27,6 +27,7 @@ import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow @@ -613,11 +614,14 @@ class SparkRepo @Inject constructor( // A payment Spark took carries its own id, so its failure is never read as an earlier one's. val attempt = SendAttempt(sentAt.toULong(), earlierIds, result.getOrNull()?.id, attemptId) if (result.getOrNull()?.status == PaymentStatus.PENDING) { - // Taken only while its own outcome wasn't handled meanwhile, as its journal write is. - sendReleaseMutex.withLock { - if (inFlightAttempts[paymentHash.lowercase()]?.attemptId == attemptId) { - takenAttempts[paymentHash.lowercase()] = attempt - restoredTakenAttempts.remove(paymentHash.lowercase()) + // Taken only while its own outcome wasn't handled meanwhile, as its journal write is. Taken + // also when the caller is cancelled meanwhile, as the send already went out. + withContext(NonCancellable) { + sendReleaseMutex.withLock { + if (inFlightAttempts[paymentHash.lowercase()]?.attemptId == attemptId) { + takenAttempts[paymentHash.lowercase()] = attempt + restoredTakenAttempts.remove(paymentHash.lowercase()) + } } } } From 6d271e37116493d4d693a7af6bade550e317d471 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 20:23:40 +0100 Subject: [PATCH 46/96] fix: journal a taken spark send's id when its caller is cancelled The payment id now goes to the journal in the same NonCancellable block as the in-memory hold, so a restart after a cancellation no longer restores the send as in doubt. Verified: just compile, test and lint; the new SparkRepoTest case fails without the fix --- .../java/to/bitkit/repositories/SparkRepo.kt | 12 ++++---- .../to/bitkit/repositories/SparkRepoTest.kt | 30 +++++++++++++++++++ 2 files changed, 36 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 58c9a31576..203314bf16 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -613,9 +613,9 @@ class SparkRepo @Inject constructor( // Taken before the in-flight attempt is dropped, so an earlier failure never finds neither. // A payment Spark took carries its own id, so its failure is never read as an earlier one's. val attempt = SendAttempt(sentAt.toULong(), earlierIds, result.getOrNull()?.id, attemptId) - if (result.getOrNull()?.status == PaymentStatus.PENDING) { + result.getOrNull()?.takeIf { it.status == PaymentStatus.PENDING }?.let { payment -> // Taken only while its own outcome wasn't handled meanwhile, as its journal write is. Taken - // also when the caller is cancelled meanwhile, as the send already went out. + // and journaled also when the caller is cancelled meanwhile, as the send already went out. withContext(NonCancellable) { sendReleaseMutex.withLock { if (inFlightAttempts[paymentHash.lowercase()]?.attemptId == attemptId) { @@ -623,6 +623,9 @@ class SparkRepo @Inject constructor( restoredTakenAttempts.remove(paymentHash.lowercase()) } } + // A send Spark still runs keeps its earlier attempts' ids, so their late failures + // leave it alone. + cacheStore.keepSparkSendAttempt(paymentHash, payment.id, attemptId) } } // A send whose call failed may still have gone out, so it is in doubt before the in-flight @@ -669,10 +672,7 @@ class SparkRepo @Inject constructor( ) throw PaymentPendingException(paymentHash) } - // A send Spark still runs keeps its earlier attempts' ids, so their late failures leave it alone. - if (payment.status == PaymentStatus.PENDING) { - cacheStore.keepSparkSendAttempt(paymentHash, payment.id, attemptId) - } else { + if (payment.status != PaymentStatus.PENDING) { takenAttempts.remove(paymentHash.lowercase()) restoredTakenAttempts.remove(paymentHash.lowercase()) cacheStore.removeSparkUncertainSend(paymentHash) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 02f862641a..14480de706 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -33,8 +33,10 @@ import com.synonym.bitkitcore.PaykitEndpoint import com.synonym.bitkitcore.PaymentState import com.synonym.bitkitcore.ServiceRouteLeg import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.delay @@ -4081,6 +4083,34 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(emptySet(), sut.attemptedLightningPaymentHashes()) } + @Test + fun `a spark send whose caller is cancelled as spark takes it keeps its payment id`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(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() + runCurrent() + lateinit var caller: Job + // The caller is cancelled while Spark's send call returns the payment it took. + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { + caller.cancel() + sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) + } + + caller = backgroundScope.launch(start = CoroutineStart.LAZY) { sut.payInvoice("lnbc1", 100uL) } + caller.start() + advanceUntilIdle() + + val cache = store.data.first() + assertEquals("retry", cache.sparkTakenSendIds["hash"], "a restart would read the send as in doubt") + assertTrue("hash" !in cache.sparkUncertainSends) + } + @Test fun `a taken attempt's late failure leaves the retry spark took after it failed`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) From 640d72ac5d66a19545b236275e124266fce7b28b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 20:23:40 +0100 Subject: [PATCH 47/96] fix: hold an in-doubt spark retry past an older unlisted failure While a send is in doubt, a failure the pre-send list doesn't name counts as an earlier attempt's when Spark dates it at least 10 s before the send, as the list can leave an older attempt out. The send's own failure, dated at its start, still ends the hold. This matches bitkit-ios. Verified: just compile, test and lint --- .../main/java/to/bitkit/repositories/SparkRepo.kt | 12 ++++++++++-- .../java/to/bitkit/repositories/SparkRepoTest.kt | 7 +++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 203314bf16..d0b68d2612 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -2056,14 +2056,22 @@ class SparkRepo @Inject constructor( /** * Whether this failure is an earlier attempt's, of a retry still in Spark's send call or in doubt: one of the * attempts Spark listed before the retry went out, or, with none listed, one Spark dates before the retry plus its - * clock skew, so a failure that may be either never ends the retry's hold. + * clock skew, so a failure that may be either never ends the retry's hold. A retry in doubt also counts a failure + * that list doesn't name as earlier when Spark dates it before the retry minus that skew. */ private fun Payment.isEarlierFailureOfUncertainSend(): Boolean { val hash = sendHash(PaymentStatus.FAILED) ?: return false val attempt = heldAttempt(hash) ?: return false // A payment Spark took fails with its own id, so a failure with another id is an earlier attempt's. attempt.ownId?.let { return id != it } - attempt.earlierIds?.let { return id in it } + attempt.earlierIds?.let { ids -> + if (id in ids) return true + // Only a send in doubt has no id of its own, and the list read before it went out can lack an older + // attempt, so a failure that list doesn't name is earlier when Spark dates it clearly before the send. + val sentAt = attempt.sentAt + return sentAt != null && uncertainSends.containsKey(hash.lowercase()) && + timestamp + RAIL_CLOCK_SKEW_SECONDS <= sentAt + } // A send kept before start times were stored can't tell its own failure from an earlier one, so it stays held // until its invoice expires, when the expiry rule settles it and its row. val sentAt = attempt.sentAt ?: return true diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 14480de706..56ec182fa8 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3812,6 +3812,13 @@ class SparkRepoTest : BaseUnitTest() { assertFalse(retryHeldAfter(emptyList(), own.copy(timestamp = now.epochSeconds.toULong() - 5uL))) } + @Test + fun `an older failure the pre-send list left out keeps an uncertain retry held`() = test { + // Spark may leave an older attempt out of the list it gives before the retry goes out. + val omitted = sentPayment(fees = 0).copy(id = "omitted", status = PaymentStatus.FAILED) + assertTrue(retryHeldAfter(emptyList(), omitted.copy(timestamp = now.epochSeconds.toULong() - 10uL))) + } + @Test fun `a failure within the clock skew keeps an uncertain retry held while its earlier attempts are unknown`() = test { From 8935d0ba9cc3db3fd9f91f4e10b640628c6429fb Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 21:06:46 +0100 Subject: [PATCH 48/96] fix: end an unlisted taken spark retry only after a later sync A taken retry Spark doesn't list now ends past the grace only once Spark synced after the grace ended, so a list from an earlier, partial sync proves nothing. When Spark lists only an earlier attempt's failure, the retry's own row is failed instead of taking that attempt's amount, fee and time. This matches bitkit-ios. Verified: just compile, test and lint; both grace cases in SparkRepoTest fail without the fix --- .../java/to/bitkit/repositories/SparkRepo.kt | 19 ++++++++---- .../to/bitkit/repositories/SparkRepoTest.kt | 31 +++++++++++++++---- 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index d0b68d2612..7a41d4f302 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -851,16 +851,23 @@ class SparkRepo @Inject constructor( takenAttempts.keys.filter { (expiries[it] ?: Long.MAX_VALUE) <= now }.forEach { hash -> val attempt = takenAttempts[hash] ?: return@forEach val expiresAt = expiries[hash] ?: return@forEach - // Spark may list a send it took only on a later sync, so an unlisted one stays held for a while. - val isPastGrace = now >= expiresAt + UNLISTED_TAKEN_SEND_GRACE.inWholeSeconds - val (send, listed) = listedLightningSendPayment(hash) + // Spark may list a send it took only on a later sync, so an unlisted one stays held for a while, and its + // absence counts only in a list from a sync made after that. + val graceEndsAt = expiresAt + UNLISTED_TAKEN_SEND_GRACE.inWholeSeconds + val isPastGrace = suspend { now >= graceEndsAt && hasSyncedSince(graceEndsAt.toULong()) } + val (send, listedSend) = listedLightningSendPayment(hash) + var listed = listedSend when (send) { SparkLightningSend.Unavailable -> return@forEach - SparkLightningSend.NotFound -> if (!isPastGrace || !failHeldRow(hash)) return@forEach + SparkLightningSend.NotFound -> if (!isPastGrace() || !failHeldRow(hash)) return@forEach is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> return@forEach - // A failure with another id than the attempt's own is an earlier attempt's, listed before the attempt. + // A failure with another id than the attempt's own is an earlier attempt's, listed before the attempt, + // so the retry's own row is failed instead of taking that attempt's amount, fee and time. is SparkLightningSend.Found if send.status == PaymentStatus.FAILED && attempt.ownId != null && - listed?.id != attempt.ownId -> if (!isPastGrace || !failHeldRow(hash)) return@forEach + listed?.id != attempt.ownId -> { + if (!isPastGrace() || !failHeldRow(hash)) return@forEach + listed = null + } is SparkLightningSend.Found -> Unit } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 56ec182fa8..3385576965 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4007,9 +4007,11 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `a taken spark retry with only an earlier failure listed stays held until the grace past expiry`() = test { - assertTakenRetryHeldUntilGrace( - listed = listOf(sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED)) - ) + // The earlier attempt paid the amountless invoice at another amount and fee. + val older = sentPayment(fees = 7).copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger()) + val row = assertTakenRetryHeldUntilGrace(listed = listOf(older)) + assertEquals(PaymentState.FAILED, row.v1.status) + assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "the retry's row took the earlier attempt's payment") } @Test @@ -4021,13 +4023,17 @@ class SparkRepoTest : BaseUnitTest() { * Spark takes a retry while it lists [listed], and keeps listing only that: the retry stays held past its invoice's * expiry until the grace for an unlisted send ends, then its row fails. */ - private suspend fun TestScope.assertTakenRetryHeldUntilGrace(listed: List) { + private suspend fun TestScope.assertTakenRetryHeldUntilGrace(listed: List): Activity.Lightning { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - whenever(activityRepo.getActivity(eq("hash"), any())).thenReturn(Result.success(pendingSendRow())) - whenever(activityRepo.upsertActivity(any())).thenReturn(Result.success(Unit)) + var row = pendingSendRow() + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } val prepared = unexpiredPrepared() whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) @@ -4036,6 +4042,8 @@ class SparkRepoTest : BaseUnitTest() { val sut = createSut(store) sut.start(0).getOrThrow() assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + // Spark reports the retry it took, which writes its row. + sparkEvents.emit(SdkEvent.PaymentPending(retry)) runCurrent() val events = mutableListOf() backgroundScope.launch { sut.nodeEvents.collect { events += it } } @@ -4051,13 +4059,24 @@ class SparkRepoTest : BaseUnitTest() { assertTrue(events.none { it is Event.PaymentFailed }, "the expiry ended a retry Spark may still list") assertTrue("hash" in store.data.first().sparkSendHashes) + // Past the grace, while Spark's latest sync was made before it ended. now += 10.minutes + whenever( + sparkService.getInfo() + ).thenReturn(info(0uL).copy(lastSyncedAt = (now - 6.minutes).epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + assertTrue(events.none { it is Event.PaymentFailed }, "a list from before the grace ended failed the retry") + sync() assertTrue(events.any { it is Event.PaymentFailed }, "a retry Spark never listed stayed held past the grace") verify(activityRepo, atLeastOnce()).upsertActivity( argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } ) assertFalse("hash" in store.data.first().sparkSendHashes) + // Later syncs list the same payments. + sync() + return row } @Test From e97db950e6e1ead88b96253e04a85850731fd792 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 21:34:13 +0100 Subject: [PATCH 49/96] fix: keep a failed spark send's own amount against an earlier failure At its invoice's expiry, a send in doubt that Spark lists as failed now fails its own row in place, as the listed failure may be an earlier attempt's. A failed send row also keeps its amount, fee and time when a later launch lists another failure of its invoice. A send with no row yet still gets one from the listed payment. This matches bitkit-ios. Verified: just compile, test and lint; both new SparkRepoTest cases fail without the fix --- .../java/to/bitkit/repositories/SparkRepo.kt | 15 +++++- .../to/bitkit/repositories/SparkRepoTest.kt | 53 +++++++++++++++++++ 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 7a41d4f302..af4a89a6d5 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -735,6 +735,10 @@ class SparkRepo @Inject constructor( if (!isSettled) return false // A missing send's row is ended here, as no listed payment revisits it, so the hold stays until it is written. if (send == SparkLightningSend.NotFound && !failHeldRow(paymentHash)) return false + // A listed failure may be an earlier attempt's, so the send's own row is failed in place instead of taking + // that attempt's amount, fee and time. + val isFailed = send is SparkLightningSend.Found && send.status == PaymentStatus.FAILED + if (isFailed && !failHeldRow(paymentHash)) return false // A send Spark now runs keeps its earlier attempts' ids until it settles, taken over before the doubt ends. val isTaken = send is SparkLightningSend.Found && send.status == PaymentStatus.PENDING // Only the caller that takes the hash off settles it, so its outcome is reported once. The hand-over shares the @@ -764,8 +768,8 @@ class SparkRepo @Inject constructor( is SparkLightningSend.Found -> { if (send.status == PaymentStatus.FAILED) { cacheStore.removeSparkSendHash(paymentHash) - // An earlier attempt's failure was skipped while the hold lasted; a failed write is retried at the - // next refresh. + // Writes the row only when there was none to fail, as a failed row keeps its own payment; a + // failed write is retried at the next refresh. listed?.let { recordActivity(it) } } // The event comes from the read that settled it, so a failed later read can't leave the send pending. @@ -2222,6 +2226,13 @@ class SparkRepo @Inject constructor( } // Another attempt of the same invoice, on either rail, already paid it. if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) return true + // A failed send keeps its own attempt's amount, fee and time, as another failure of its invoice may be an + // earlier attempt's, listed again on a later launch once nothing holds the invoice. + if (existing?.status == PaymentState.FAILED && existing.txType == PaymentType.SENT && + payment.status == PaymentStatus.FAILED + ) { + return true + } val activity = LightningActivity.create( id = id, txType = when (payment.paymentType) { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 3385576965..00194b5215 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4005,6 +4005,59 @@ class SparkRepoTest : BaseUnitTest() { assertTakenRetryKeptPastEarlierFailure(restart = true) } + @Test + fun `an uncertain spark retry fails its own row at expiry when only an earlier failure is listed`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + var row = pendingSendRow() + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever(sparkService.listPayments()).thenReturn(emptyList()) + val sut = createSut() + sut.start(0).getOrThrow() + runCurrent() + // The earlier attempt paid the amountless invoice at another amount and fee, and failed. + val older = sentPayment(fees = 7).copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger()) + whenever(sparkService.listPayments()).thenReturn(listOf(older)) + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + runCurrent() + + // The invoice has expired, and Spark syncs after the retry went uncertain. + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL)) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals(PaymentState.FAILED, row.v1.status) + assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "the retry's row took the earlier attempt's payment") + } + + @Test + fun `a failed spark send row keeps its amount when a later launch lists an earlier attempt's failure`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED)) + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } + val older = sentPayment(fees = 7).copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger()) + whenever(sparkService.listPayments()).thenReturn(listOf(older)) + + createSut().start(0).getOrThrow() + advanceUntilIdle() + + assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "an earlier attempt's failure replaced the retry's row") + } + @Test fun `a taken spark retry with only an earlier failure listed stays held until the grace past expiry`() = test { // The earlier attempt paid the amountless invoice at another amount and fee. From af08c0905e2be26732b9d2be1c83976d4b4e61b1 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 22:01:10 +0100 Subject: [PATCH 50/96] fix: end a held spark send's row only while its hold stands The expiry check reads Spark's sync time before the list it ends a taken retry from, so a sync that ends between the two reads can't vouch for the older list. A held send's row is failed only while the caller still holds it, checked under the lock the row write takes, so a newer retry's row is left alone. A held attempt's own failure still updates a failed row, which may show an earlier attempt when the retry's own row was never saved. Verified: just compile, test and lint; the new SparkRepoTest steps fail without the fix, no unit test for the row ownership race --- .../java/to/bitkit/repositories/SparkRepo.kt | 28 +++++++---- .../to/bitkit/repositories/SparkRepoTest.kt | 46 +++++++++++++++++++ 2 files changed, 65 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index af4a89a6d5..42f9ecc24f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -734,11 +734,12 @@ class SparkRepo @Inject constructor( } if (!isSettled) return false // A missing send's row is ended here, as no listed payment revisits it, so the hold stays until it is written. - if (send == SparkLightningSend.NotFound && !failHeldRow(paymentHash)) return false + val holds = { uncertainSends[key] === uncertain } + if (send == SparkLightningSend.NotFound && !failHeldRow(paymentHash, holds)) return false // A listed failure may be an earlier attempt's, so the send's own row is failed in place instead of taking // that attempt's amount, fee and time. val isFailed = send is SparkLightningSend.Found && send.status == PaymentStatus.FAILED - if (isFailed && !failHeldRow(paymentHash)) return false + if (isFailed && !failHeldRow(paymentHash, holds)) return false // A send Spark now runs keeps its earlier attempts' ids until it settles, taken over before the doubt ends. val isTaken = send is SparkLightningSend.Found && send.status == PaymentStatus.PENDING // Only the caller that takes the hash off settles it, so its outcome is reported once. The hand-over shares the @@ -782,9 +783,15 @@ class SparkRepo @Inject constructor( /** * Marks the pending send row of [paymentHash] failed, as Spark lists no send of it; true once nothing is pending. - * Read and write share the lock Spark's own row writes take, so a settlement written meanwhile is not overwritten. + * Read and write share the lock Spark's own row writes take, so a settlement written meanwhile is not overwritten, + * and the write happens only while the caller still [holds] the send, so a newer retry's row is left alone. */ - private suspend fun failHeldRow(paymentHash: String): Boolean = sendReleaseMutex.withLock { + private suspend fun failHeldRow( + paymentHash: String, + holds: () -> Boolean, + ): Boolean = sendReleaseMutex.withLock { + // A hold that ended meanwhile is no longer the caller's to end, which its own removal then finds. + if (!holds()) return@withLock true val stored = activityRepo.get().getActivity(paymentHash).getOrElse { Logger.warn("Failed to read activity of Spark send '$paymentHash'", it, context = TAG) return@withLock false @@ -858,18 +865,20 @@ class SparkRepo @Inject constructor( // Spark may list a send it took only on a later sync, so an unlisted one stays held for a while, and its // absence counts only in a list from a sync made after that. val graceEndsAt = expiresAt + UNLISTED_TAKEN_SEND_GRACE.inWholeSeconds - val isPastGrace = suspend { now >= graceEndsAt && hasSyncedSince(graceEndsAt.toULong()) } + // Read before the list, so a sync that ends between the two reads can't vouch for an older list. + val isPastGrace = now >= graceEndsAt && hasSyncedSince(graceEndsAt.toULong()) + val holds = { takenAttempts[hash] === attempt } val (send, listedSend) = listedLightningSendPayment(hash) var listed = listedSend when (send) { SparkLightningSend.Unavailable -> return@forEach - SparkLightningSend.NotFound -> if (!isPastGrace() || !failHeldRow(hash)) return@forEach + SparkLightningSend.NotFound -> if (!isPastGrace || !failHeldRow(hash, holds)) return@forEach is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> return@forEach // A failure with another id than the attempt's own is an earlier attempt's, listed before the attempt, // so the retry's own row is failed instead of taking that attempt's amount, fee and time. is SparkLightningSend.Found if send.status == PaymentStatus.FAILED && attempt.ownId != null && listed?.id != attempt.ownId -> { - if (!isPastGrace() || !failHeldRow(hash)) return@forEach + if (!isPastGrace || !failHeldRow(hash, holds)) return@forEach listed = null } @@ -2227,9 +2236,10 @@ class SparkRepo @Inject constructor( // Another attempt of the same invoice, on either rail, already paid it. if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) return true // A failed send keeps its own attempt's amount, fee and time, as another failure of its invoice may be an - // earlier attempt's, listed again on a later launch once nothing holds the invoice. + // earlier attempt's, listed again on a later launch once nothing holds the invoice. The held attempt's own + // failure still writes it, as the row may show an earlier attempt when the retry's own row was never saved. if (existing?.status == PaymentState.FAILED && existing.txType == PaymentType.SENT && - payment.status == PaymentStatus.FAILED + payment.status == PaymentStatus.FAILED && payment.id != heldAttempt(id)?.ownId ) { return true } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 00194b5215..062b108761 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4038,6 +4038,39 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "the retry's row took the earlier attempt's payment") } + @Test + fun `a taken spark retry's own failure after a restart replaces an earlier attempt's failed row`() = test { + // The app closed before it saved the retry's pending row, so Activity still shows the earlier attempt. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to now.epochSeconds + 3_600), + sparkUncertainSendStarts = mapOf("hash" to now.epochSeconds), + sparkTakenSendIds = mapOf("hash" to "retry"), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, value = 999uL, fee = 7uL)) + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } + val older = sentPayment(fees = 7).copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger()) + val ownFailure = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(older, ownFailure)) + + createSut(store).start(0).getOrThrow() + advanceUntilIdle() + + assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "the retry's own failure left the earlier attempt's row") + } + @Test fun `a failed spark send row keeps its amount when a later launch lists an earlier attempt's failure`() = test { whenever(sparkService.isSupported).thenReturn(true) @@ -4121,6 +4154,19 @@ class SparkRepoTest : BaseUnitTest() { advanceUntilIdle() assertTrue(events.none { it is Event.PaymentFailed }, "a list from before the grace ended failed the retry") + // A sync past the grace ends while the expiry check reads Spark's list, so that list is still the older one. + var syncedAt = (now - 6.minutes).epochSeconds.toULong() + whenever(sparkService.getInfo()).thenAnswer { info(0uL).copy(lastSyncedAt = syncedAt) } + whenever(sparkService.listPayments()).thenAnswer { + val isSweep = Thread.currentThread().stackTrace.any { it.methodName.contains("dropExpiredTakenAttempts") } + if (isSweep) syncedAt = now.epochSeconds.toULong() + listed + } + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + assertTrue(events.none { it is Event.PaymentFailed }, "a sync after the list was read vouched for it") + whenever(sparkService.listPayments()).thenReturn(listed) + sync() assertTrue(events.any { it is Event.PaymentFailed }, "a retry Spark never listed stayed held past the grace") verify(activityRepo, atLeastOnce()).upsertActivity( From 9a672a03551f6ca580145217ad6461e0541c6c1c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 22:14:52 +0100 Subject: [PATCH 51/96] fix: let a spark send's failed row take its own and later failures A failed send row now keeps its amount, fee and time only against a failure Spark dates before it, an earlier attempt's, so the same attempt's fee correction and a later attempt's failure still update it. This matches bitkit-ios. Verified: just compile, test and lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 8 ++-- .../to/bitkit/repositories/SparkRepoTest.kt | 47 +++++++++++++++++-- 2 files changed, 46 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 545aab1d3c..37d520d580 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -2251,11 +2251,11 @@ class SparkRepo @Inject constructor( } // Another attempt of the same invoice, on either rail, already paid it. if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) return true - // A failed send keeps its own attempt's amount, fee and time, as another failure of its invoice may be an - // earlier attempt's, listed again on a later launch once nothing holds the invoice. The held attempt's own - // failure still writes it, as the row may show an earlier attempt when the retry's own row was never saved. + // A failed send keeps its own attempt's amount, fee and time against an earlier attempt's failure, listed again + // on a later launch once nothing holds the invoice; Spark dates an attempt at its start, so a failure dated + // before the row is that earlier attempt's, while the row's own or a later attempt's failure still writes it. if (existing?.status == PaymentState.FAILED && existing.txType == PaymentType.SENT && - payment.status == PaymentStatus.FAILED && payment.id != heldAttempt(id)?.ownId + payment.status == PaymentStatus.FAILED && payment.timestamp < existing.timestamp ) { return true } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 408da60b9a..b0ef74fd77 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4067,7 +4067,8 @@ class SparkRepoTest : BaseUnitTest() { sut.start(0).getOrThrow() runCurrent() // The earlier attempt paid the amountless invoice at another amount and fee, and failed. - val older = sentPayment(fees = 7).copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger()) + val older = sentPayment(fees = 7) + .copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger(), timestamp = 0uL) whenever(sparkService.listPayments()).thenReturn(listOf(older)) assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) runCurrent() @@ -4098,13 +4099,16 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, value = 999uL, fee = 7uL)) + var row = Activity.Lightning( + pendingSendRow().v1.copy(status = PaymentState.FAILED, value = 999uL, fee = 7uL, timestamp = 0uL) + ) whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { row = it.getArgument(0) as? Activity.Lightning ?: row Result.success(Unit) } - val older = sentPayment(fees = 7).copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger()) + val older = sentPayment(fees = 7) + .copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger(), timestamp = 0uL) val ownFailure = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED) whenever(sparkService.listPayments()).thenReturn(listOf(older, ownFailure)) @@ -4114,6 +4118,37 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "the retry's own failure left the earlier attempt's row") } + @Test + fun `a failed spark send row takes its own attempt's fee correction`() = test { + val corrected = sentPayment(fees = 3).copy(id = "retry", status = PaymentStatus.FAILED) + assertEquals(128uL to 3uL, failedRowAfterListing(corrected).let { it.v1.value to it.v1.fee }) + } + + @Test + fun `a failed spark send row takes a later attempt's failure`() = test { + val later = sentPayment(fees = 0) + .copy(id = "later", status = PaymentStatus.FAILED, amount = 200.toBigInteger(), timestamp = 9uL) + assertEquals(200uL, failedRowAfterListing(later).v1.value) + } + + /** The row of a send that failed, after a launch lists [payment] of its invoice. */ + private suspend fun TestScope.failedRowAfterListing(payment: Payment): Activity.Lightning { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED)) + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } + whenever(sparkService.listPayments()).thenReturn(listOf(payment)) + + createSut().start(0).getOrThrow() + advanceUntilIdle() + return row + } + @Test fun `a failed spark send row keeps its amount when a later launch lists an earlier attempt's failure`() = test { whenever(sparkService.isSupported).thenReturn(true) @@ -4125,7 +4160,8 @@ class SparkRepoTest : BaseUnitTest() { row = it.getArgument(0) as? Activity.Lightning ?: row Result.success(Unit) } - val older = sentPayment(fees = 7).copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger()) + val older = sentPayment(fees = 7) + .copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger(), timestamp = 0uL) whenever(sparkService.listPayments()).thenReturn(listOf(older)) createSut().start(0).getOrThrow() @@ -4137,7 +4173,8 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `a taken spark retry with only an earlier failure listed stays held until the grace past expiry`() = test { // The earlier attempt paid the amountless invoice at another amount and fee. - val older = sentPayment(fees = 7).copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger()) + val older = sentPayment(fees = 7) + .copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger(), timestamp = 0uL) val row = assertTakenRetryHeldUntilGrace(listed = listOf(older)) assertEquals(PaymentState.FAILED, row.v1.status) assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "the retry's row took the earlier attempt's payment") From cb6529a3eedd46a03633367bae347ab79ac76c59 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 22:40:44 +0100 Subject: [PATCH 52/96] fix: keep a failed spark send row against a same-second earlier failure Each Spark send's Activity row now remembers the payment that last wrote it, so an earlier attempt's failure dated the same second as a retry no longer overwrites the retry's amount and fee, while the row's own fee correction and a later attempt's failure still update it. This matches bitkit-ios. Verified: just compile, test and lint; the new SparkRepoTest case fails without the fix --- app/src/main/java/to/bitkit/data/CacheStore.kt | 15 +++++++++++++++ .../java/to/bitkit/repositories/BackupRepo.kt | 1 + .../main/java/to/bitkit/repositories/SparkRepo.kt | 12 ++++++++++-- .../test/java/to/bitkit/data/CacheStoreTest.kt | 11 +++++++++++ .../java/to/bitkit/repositories/SparkRepoTest.kt | 9 +++++++++ 5 files changed, 46 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 8435291076..55574e9995 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -166,6 +166,16 @@ class CacheStore internal constructor( } } + /** Keeps [paymentId] as the payment that last wrote the Activity row of Spark's send of [paymentHash]. */ + suspend fun keepSparkSendRowId(paymentHash: String, paymentId: String) { + val hash = paymentHash.lowercase() + if (store.data.first().sparkSendRowIds[hash] == paymentId) return + store.updateData { + val ids = (it.sparkSendRowIds - hash + (hash to paymentId)).entries.toList().takeLast(MAX_SPARK_SEND_HASHES) + it.copy(sparkSendRowIds = ids.associate { (key, id) -> key to id }) + } + } + suspend fun removeSparkSendHash(paymentHash: String) { val hash = paymentHash.lowercase() if (hash !in store.data.first().sparkSendHashes) return @@ -448,6 +458,11 @@ data class AppCacheData( val sparkTakenSendIds: Map = mapOf(), /** A random id of the attempt each of those sends' entries belongs to, so a stale attempt never writes over it. */ val sparkUncertainSendAttemptIds: Map = mapOf(), + /** + * Spark's id of the payment that last wrote each Spark send's Activity row, the latest [MAX_SPARK_SEND_HASHES], so + * an earlier attempt's failure dated the same second as the row never writes over it. + */ + val sparkSendRowIds: Map = mapOf(), /** * Payment hashes of the moves to Spark, kept across restarts so neither leg of a move is announced as a payment and * Activity shows the move as one. diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index f14ab299be..9a4f103a36 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1344,6 +1344,7 @@ class BackupRepo @Inject constructor( sparkUncertainSendEarlierIds = emptyMap(), sparkTakenSendIds = emptyMap(), sparkUncertainSendAttemptIds = emptyMap(), + sparkSendRowIds = emptyMap(), ) Logger.debug("Restored caches: ${jsonLogOf(logged)}", TAG) onCacheRestored() diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 37d520d580..ca46044f25 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -2083,6 +2083,11 @@ class SparkRepo @Inject constructor( .forEach { cacheStore.removeSparkSendHash(it) } } + /** Whether Spark dates this payment before the [row] of [paymentHash], or ties it as another payment. */ + private suspend fun Payment.isEarlierThan(row: LightningActivity, paymentHash: String): Boolean = + timestamp < row.timestamp || timestamp == row.timestamp && + cacheStore.data.first().sparkSendRowIds[paymentHash.lowercase()]?.let { it != id } == true + private fun recordedSince(records: Long): Set = sendRecordedAt.filterValues { it > records }.keys /** Whether this failure is an earlier attempt's, of a retry in doubt or one sent after [records] was read. */ @@ -2253,9 +2258,11 @@ class SparkRepo @Inject constructor( if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) return true // A failed send keeps its own attempt's amount, fee and time against an earlier attempt's failure, listed again // on a later launch once nothing holds the invoice; Spark dates an attempt at its start, so a failure dated - // before the row is that earlier attempt's, while the row's own or a later attempt's failure still writes it. + // before the row, or the same second by another payment than the one that wrote it, is that earlier attempt's, + // while the row's own or a later attempt's failure, and the held attempt's own, still write it. if (existing?.status == PaymentState.FAILED && existing.txType == PaymentType.SENT && - payment.status == PaymentStatus.FAILED && payment.timestamp < existing.timestamp + payment.status == PaymentStatus.FAILED && payment.id != heldAttempt(id)?.ownId && + payment.isEarlierThan(existing, id) ) { return true } @@ -2290,6 +2297,7 @@ class SparkRepo @Inject constructor( return false } unsavedPayments.remove(payment.id) + if (payment.paymentType == SparkPaymentType.SEND) cacheStore.keepSparkSendRowId(id, payment.id) if (payment.paymentType == SparkPaymentType.SEND && payment.fees.toLong() == 0L) { sendsRecordedWithoutFee.add(payment.id) } else { diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index bed23a8ec9..88a9a7c8ff 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -248,6 +248,17 @@ class CacheStoreTest : BaseUnitTest() { const val NOW = 1_800_000_000L } + @Test + fun `keepSparkSendRowId keeps the latest row writers up to the limit`() = test { + (0..MAX_SPARK_SEND_HASHES).forEach { sut.keepSparkSendRowId("hash$it", "id$it") } + sut.keepSparkSendRowId("HASH1", "newer") + + val ids = sut.data.first().sparkSendRowIds + assertEquals(MAX_SPARK_SEND_HASHES, ids.size) + assertFalse("hash0" in ids) + assertEquals("newer", ids["hash1"]) + } + @Test fun `keepSparkSendAttempt keeps the taken id of the attempt that still has its entry`() = test { sut.addSparkUncertainSend("hash", failedAt = 100, sentAt = 100, attemptId = "a") diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index b0ef74fd77..cb0d11990b 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4120,6 +4120,7 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `a failed spark send row takes its own attempt's fee correction`() = test { + cacheData.value = cacheData.value.copy(sparkSendRowIds = mapOf("hash" to "retry")) val corrected = sentPayment(fees = 3).copy(id = "retry", status = PaymentStatus.FAILED) assertEquals(128uL to 3uL, failedRowAfterListing(corrected).let { it.v1.value to it.v1.fee }) } @@ -4131,6 +4132,14 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(200uL, failedRowAfterListing(later).v1.value) } + @Test + fun `a failed spark send row keeps its amount against an earlier attempt's failure from the same second`() = test { + // The retry started in the same second as the earlier attempt, and its failure last wrote the row. + cacheData.value = cacheData.value.copy(sparkSendRowIds = mapOf("hash" to "retry")) + val older = sentPayment(fees = 7).copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger()) + assertEquals(128uL to 0uL, failedRowAfterListing(older).let { it.v1.value to it.v1.fee }) + } + /** The row of a send that failed, after a launch lists [payment] of its invoice. */ private suspend fun TestScope.failedRowAfterListing(payment: Payment): Activity.Lightning { whenever(sparkService.isSupported).thenReturn(true) From 50949469e1ab66853a53bd5b1568482a1fc5c5e0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 23:54:17 +0100 Subject: [PATCH 53/96] fix: spark send row ownership on retry and exit cleanup - A retry's own failure is judged against the attempt that wrote the row, so the sweep and the in-doubt expiry pass the attempt's own payment id. - An in-doubt send expires only after Spark syncs past its expiry, and an earlier attempt's failure is not written over a stored row at expiry. - A same-second tie keeps the row whose writer is not an earlier attempt. - Staged exit state is compared and deleted under the exit import lock. - A send cancelled after its failure was handled no longer holds the invoice. - A restored taken attempt's marker is cleared only by its own outcome. Verified: just compile, just test, just lint; the three new SparkRepoTest cases fail on the previous head and pass here; the exit-lock race has no unit test. --- .../java/to/bitkit/repositories/SparkRepo.kt | 105 ++++++++---- .../to/bitkit/repositories/BackupRepoTest.kt | 2 +- .../to/bitkit/repositories/SparkRepoTest.kt | 153 +++++++++++++++++- 3 files changed, 224 insertions(+), 36 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index ca46044f25..4ed6034e55 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -651,13 +651,19 @@ class SparkRepo @Inject constructor( } } } finally { - // A send cancelled inside Spark's call stays in doubt, as its journal entry does, so a sync settles it. + // A send cancelled inside Spark's call stays in doubt, as its journal entry does, so a sync settles it, + // unless its outcome was handled meanwhile, which dropped its in-flight attempt. if (isDispatched && !hasReturned) { val attempt = SendAttempt(sentAt.toULong(), earlierIds, attemptId = attemptId) - uncertainSends.putIfAbsent( - paymentHash.lowercase(), - UncertainSend(clock.now().epochSeconds.toULong(), expiresAt, attempt), - ) + withContext(NonCancellable) { + sendReleaseMutex.withLock { + if (inFlightAttempts[paymentHash.lowercase()]?.attemptId != attemptId) return@withLock + uncertainSends.putIfAbsent( + paymentHash.lowercase(), + UncertainSend(clock.now().epochSeconds.toULong(), expiresAt, attempt), + ) + } + } } inFlightAttempts.remove(paymentHash.lowercase()) sendsInFlight.remove(paymentHash.lowercase()) @@ -736,8 +742,10 @@ class SparkRepo @Inject constructor( val isSynced = hasSyncedSince(uncertain.failedAt) if (isSynced) _state.update { it.copy(hasSynced = true) } // Spark keeps a send it committed but didn't finish in a cache no call exposes, and a sync that reached Spark - // can still fail to resume it, so only an expired invoice shows a missing send will never go out. - val isFinal = isSynced && clock.now().epochSeconds.toULong() >= uncertain.expiresAt + // can still fail to resume it, so only an expired invoice shows a missing send will never go out, and only in a + // list from a sync made after it expired. + val isFinal = clock.now().epochSeconds.toULong() >= uncertain.expiresAt && + hasSyncedSince(maxOf(uncertain.failedAt, uncertain.expiresAt)) // The outcome and the payment its row is written from come from one read, so a later read can't miss it. val (send, listed) = listedLightningSendPayment(paymentHash) val isSettled = when (send) { @@ -760,6 +768,8 @@ class SparkRepo @Inject constructor( // lock a payment event's cleanup takes, so a send settled meanwhile keeps no attempt to report again at expiry. // The listed pending payment is the retry Spark now runs, so its id marks the retry's own failure. val taken = uncertain.attempt.copy(ownId = listed?.id ?: uncertain.attempt.ownId) + // Read while the attempt still holds the invoice, as its earlier ids tell a listed failure apart. + val isEarlierListed = listed?.isEarlierFailureOfUncertainSend() == true val isOwner = sendReleaseMutex.withLock { val isMarked = isTaken && takenAttempts.putIfAbsent(key, taken) == null // Only the attempt marked here is rolled back, as a retry may have replaced it meanwhile. @@ -783,9 +793,10 @@ class SparkRepo @Inject constructor( is SparkLightningSend.Found -> { if (send.status == PaymentStatus.FAILED) { cacheStore.removeSparkSendHash(paymentHash) - // Writes the row only when there was none to fail, as a failed row keeps its own payment; a - // failed write is retried at the next refresh. - listed?.let { recordActivity(it) } + // Writes the row only when there was none to fail or the failure is the send's own, as a failed row + // keeps its own payment; a failed write is retried at the next refresh. + listed?.takeUnless { isEarlierListed && hasStoredRow(paymentHash) } + ?.let { recordActivity(it, ownId = uncertain.attempt.ownId) } } // The event comes from the read that settled it, so a failed later read can't leave the send pending. listed?.toNodeEvent()?.let { _nodeEvents.emit(it) } @@ -795,6 +806,13 @@ class SparkRepo @Inject constructor( return true } + /** + * Whether Activity holds a row of [paymentHash], also when it can't be read, so a write is left to the next + * refresh. + */ + private suspend fun hasStoredRow(paymentHash: String): Boolean = + activityRepo.get().getActivity(paymentHash).fold(onSuccess = { it != null }, onFailure = { true }) + /** * Marks the pending send row of [paymentHash] failed, as Spark lists no send of it; true once nothing is pending. * Read and write share the lock Spark's own row writes take, so a settlement written meanwhile is not overwritten, @@ -904,9 +922,9 @@ class SparkRepo @Inject constructor( val isRestored = restoredTakenAttempts.remove(hash) cacheStore.removeSparkUncertainSend(hash) if (listed?.status != PaymentStatus.COMPLETED) cacheStore.removeSparkSendHash(hash) - // Written once the attempt is gone, so it no longer holds the row back; a failed write is retried at the - // next refresh. - listed?.let { recordActivity(it) } + // Written once the attempt is gone, so it no longer holds the row back, with the own id the attempt + // matched; a failed write is retried at the next refresh. + listed?.let { recordActivity(it, ownId = attempt.ownId) } if (isRestored) return@forEach // The send's own outcome event may have been held back with the attempt, so the send screen learns it here. val event = listed?.toNodeEvent() @@ -1418,9 +1436,8 @@ class SparkRepo @Inject constructor( * Stops merging stored exit data Spark can never import, which the caller kept apart, so the next upload replaces * it. A staged restore is dropped only when it holds that same [exitState]; other staged data still imports. */ - fun skipUnimportableRemoteExitState(exitState: String?) { - val staged = File(Env.sparkExitRestorePath(walletIndex)) - if (exitState != null && staged.exists() && staged.readText() == exitState) staged.delete() + suspend fun skipUnimportableRemoteExitState(exitState: String?) { + if (exitState != null) deleteStagedExitState(exitState) hasMergedRemoteExitState = true } @@ -1447,8 +1464,13 @@ class SparkRepo @Inject constructor( * Drops restored exit data Spark rejected, once the backup set a copy of it aside, unless newer data came. The * stored backup is merged again before the next upload, as that copy may be older than it. */ - fun discardStagedExitState(exitState: String) { + suspend fun discardStagedExitState(exitState: String) { hasMergedRemoteExitState = false + deleteStagedExitState(exitState) + } + + /** Deletes staged exit data that still holds [exitState], under the lock staging and import take. */ + private suspend fun deleteStagedExitState(exitState: String) = exitImportMutex.withLock { val staged = File(Env.sparkExitRestorePath(walletIndex)) if (staged.exists() && staged.readText() == exitState) staged.delete() } @@ -2083,10 +2105,26 @@ class SparkRepo @Inject constructor( .forEach { cacheStore.removeSparkSendHash(it) } } - /** Whether Spark dates this payment before the [row] of [paymentHash], or ties it as another payment. */ - private suspend fun Payment.isEarlierThan(row: LightningActivity, paymentHash: String): Boolean = - timestamp < row.timestamp || timestamp == row.timestamp && - cacheStore.data.first().sparkSendRowIds[paymentHash.lowercase()]?.let { it != id } == true + /** + * Whether this failure is an earlier attempt's than the failed send [row] of [paymentHash], so the row keeps its + * own attempt's amount, fee and time against it, listed again on a later launch once nothing holds the invoice. + * The row's own or a later attempt's failure, and that of the attempt [ownId] or the held one names, still write + * it. + */ + private suspend fun Payment.isEarlierFailureThan(row: LightningActivity, paymentHash: String, ownId: String?) = + row.status == PaymentState.FAILED && row.txType == PaymentType.SENT && status == PaymentStatus.FAILED && + id != (ownId ?: heldAttempt(paymentHash)?.ownId) && isEarlierThan(row, paymentHash) + + /** + * Whether Spark dates this payment before the [row] of [paymentHash], or ties it as another payment than the one + * that wrote the row, unless the row is an earlier attempt of the send held now and this payment is not. + */ + private suspend fun Payment.isEarlierThan(row: LightningActivity, paymentHash: String): Boolean { + if (timestamp != row.timestamp) return timestamp < row.timestamp + val rowId = cacheStore.data.first().sparkSendRowIds[paymentHash.lowercase()] ?: return false + val earlierIds = heldAttempt(paymentHash)?.earlierIds.orEmpty() + return rowId != id && !(rowId in earlierIds && id !in earlierIds) + } private fun recordedSince(records: Long): Set = sendRecordedAt.filterValues { it > records }.keys @@ -2214,17 +2252,27 @@ class SparkRepo @Inject constructor( payment.toNodeEvent()?.let { _nodeEvents.emit(it) } } - private fun Payment.heldBackOutcome() = sendHash()?.let { restoredTakenAttempts.remove(it.lowercase()) } + /** + * Marks the outcome of the restored retry of this payment's invoice as held back, unless this is another + * attempt's. + */ + private fun Payment.heldBackOutcome() = sendHash()?.lowercase()?.let { hash -> + val attempt = takenAttempts[hash] + val isOtherAttempt = attempt?.ownId?.let { it != id } ?: (attempt?.earlierIds?.contains(id) == true) + if (!isOtherAttempt) restoredTakenAttempts.remove(hash) + } /** * Records [payment] as activity and returns whether it is saved; a failed write is kept in [unsavedPayments]. Only * Spark's list or its send response [settlesJournal]: a payment event can come before the list holds the - * withdrawal, which recovery reads, so its journal stays open until the list shows it. + * withdrawal, which recovery reads, so its journal stays open until the list shows it. [ownId] is the Spark id + * of the attempt a caller that just ended its hold matched, so that attempt's own failure still writes the row. */ private suspend fun recordActivity( payment: Payment, settlesJournal: Boolean = true, records: Long = sendRecords.get(), + ownId: String? = null, ): Boolean { (payment.details as? PaymentDetails.Withdraw)?.let { return recordWithdrawal(payment, it, settlesJournal) } val lightning = payment.details as? PaymentDetails.Lightning ?: return true @@ -2256,16 +2304,7 @@ class SparkRepo @Inject constructor( } // Another attempt of the same invoice, on either rail, already paid it. if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) return true - // A failed send keeps its own attempt's amount, fee and time against an earlier attempt's failure, listed again - // on a later launch once nothing holds the invoice; Spark dates an attempt at its start, so a failure dated - // before the row, or the same second by another payment than the one that wrote it, is that earlier attempt's, - // while the row's own or a later attempt's failure, and the held attempt's own, still write it. - if (existing?.status == PaymentState.FAILED && existing.txType == PaymentType.SENT && - payment.status == PaymentStatus.FAILED && payment.id != heldAttempt(id)?.ownId && - payment.isEarlierThan(existing, id) - ) { - return true - } + if (existing != null && payment.isEarlierFailureThan(existing, id, ownId)) return true val activity = LightningActivity.create( id = id, txType = when (payment.paymentType) { diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index d29dd6a273..8ebe2f287b 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -3898,7 +3898,7 @@ class BackupRepoTest : BaseUnitTest() { private fun mergeFlagFollowsDiscard(hasMerged: Boolean) { var merged = hasMerged whenever(sparkRepo.hasMergedRemoteExitState).thenAnswer { merged } - whenever(sparkRepo.discardStagedExitState(any())).thenAnswer { merged = false } + whenever { sparkRepo.discardStagedExitState(any()) }.doSuspendableAnswer { merged = false } whenever { sparkRepo.mergeRemoteExitBackup(anyOrNull()) }.thenAnswer { merged = true Result.success(Unit) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index cb0d11990b..8d708bd34c 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4066,9 +4066,10 @@ class SparkRepoTest : BaseUnitTest() { val sut = createSut() sut.start(0).getOrThrow() runCurrent() - // The earlier attempt paid the amountless invoice at another amount and fee, and failed. + // The earlier attempt paid the amountless invoice at another amount and fee, and failed; Spark dates it after + // the retry's row, as the row was written from the device's clock. val older = sentPayment(fees = 7) - .copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger(), timestamp = 0uL) + .copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger(), timestamp = 5uL) whenever(sparkService.listPayments()).thenReturn(listOf(older)) assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) runCurrent() @@ -4140,6 +4141,74 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(128uL to 0uL, failedRowAfterListing(older).let { it.v1.value to it.v1.fee }) } + @Test + fun `an uncertain spark retry's own failure replaces an earlier attempt's row from the same second`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val sentAt = now.epochSeconds.toULong() + // The earlier attempt failed the second the retry starts, and its failure wrote the row. + cacheData.value = cacheData.value.copy(sparkSendRowIds = mapOf("hash" to "older")) + var row = Activity.Lightning( + pendingSendRow().v1.copy(status = PaymentState.FAILED, value = 999uL, fee = 7uL, timestamp = sentAt) + ) + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } + val older = sentPayment(fees = 7) + .copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger(), timestamp = sentAt) + whenever(sparkService.listPayments()).thenReturn(listOf(older)) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut() + sut.start(0).getOrThrow() + runCurrent() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + runCurrent() + + // The retry fails before Spark took it, so its own id was never known. + val ownFailure = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED, timestamp = sentAt) + whenever(sparkService.listPayments()).thenReturn(listOf(older, ownFailure)) + sparkEvents.emit(SdkEvent.PaymentFailed(ownFailure)) + advanceUntilIdle() + + assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "the retry's own failure kept the earlier row") + } + + @Test + fun `an expired spark send in doubt stays held until spark syncs after its expiry`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(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 SdkException.Generic("timeout") } + val failedAt = now.epochSeconds.toULong() + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + runCurrent() + + // Past the invoice's hour, while Spark's latest sync was made before it expired. + now += 2.hours + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = failedAt + 60uL)) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + assertTrue(events.none { it is Event.PaymentFailed }, "a list from before the expiry failed the send") + + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + assertTrue(events.any { it is Event.PaymentFailed }, "a send Spark never listed stayed held past its expiry") + } + /** The row of a send that failed, after a launch lists [payment] of its invoice. */ private suspend fun TestScope.failedRowAfterListing(payment: Payment): Activity.Lightning { whenever(sparkService.isSupported).thenReturn(true) @@ -4158,6 +4227,44 @@ class SparkRepoTest : BaseUnitTest() { return row } + @Test + fun `an expired taken spark retry's own failure replaces an earlier attempt's failed row from the same second`() = + test { + // The app closed before it saved the retry's pending row; the retry started the second the earlier one did. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to now.epochSeconds - 60), + sparkUncertainSendStarts = mapOf("hash" to now.epochSeconds - 3_660), + sparkTakenSendIds = mapOf("hash" to "retry"), + sparkSendRowIds = mapOf("hash" to "older"), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + var row = Activity.Lightning( + pendingSendRow().v1.copy(status = PaymentState.FAILED, value = 999uL, fee = 7uL) + ) + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } + val ownFailure = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(ownFailure)) + + createSut(store).start(0).getOrThrow() + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "the retry's own failure kept the earlier row") + assertFalse("hash" in store.data.first().sparkTakenSendIds) + } + @Test fun `a failed spark send row keeps its amount when a later launch lists an earlier attempt's failure`() = test { whenever(sparkService.isSupported).thenReturn(true) @@ -4297,6 +4404,34 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(emptySet(), sut.attemptedLightningPaymentHashes()) } + @Test + fun `a spark send cancelled after its failure was handled holds nothing`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + var listed = emptyList() + whenever(sparkService.listPayments()).thenAnswer { listed } + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) + // Spark reports the send's failure while its send call still runs, and the caller is cancelled after that. + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { + listed = listOf(failed) + sparkEvents.emit(SdkEvent.PaymentFailed(failed)) + awaitCancellation() + } + val sut = createSut() + sut.start(0).getOrThrow() + runCurrent() + val caller = backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } + advanceUntilIdle() + + caller.cancel() + advanceUntilIdle() + + assertNull(sut.earlierLightningSend("lnbc1", "hash"), "a handled failure still held the invoice") + } + @Test fun `a spark send whose caller is cancelled as spark takes it keeps its payment id`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) @@ -4536,6 +4671,15 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `a taken spark retry settled while closed reports no outcome when its invoice expires`() = test { + assertRestoredRetryReportsNoOutcome(earlierFailureFirst = false) + } + + @Test + fun `a taken spark retry settled while closed reports no outcome past an earlier attempt's late failure`() = test { + assertRestoredRetryReportsNoOutcome(earlierFailureFirst = true) + } + + private suspend fun TestScope.assertRestoredRetryReportsNoOutcome(earlierFailureFirst: Boolean) { val sentAt = now.epochSeconds // Spark took the retry, then the app closed; the retry completed while it was closed. val store = CacheStore( @@ -4565,6 +4709,11 @@ class SparkRepoTest : BaseUnitTest() { verify(activityRepo).upsertActivity( argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.SUCCEEDED } ) + if (earlierFailureFirst) { + val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED, timestamp = 1uL) + sparkEvents.emit(SdkEvent.PaymentFailed(older)) + advanceUntilIdle() + } now += 2.hours whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) From 02fa00ad86570c7b10647daefe1f4b31d2f758f6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 00:47:27 +0100 Subject: [PATCH 54/96] fix: spark retry row keeps its own failure past expiry - At expiry, the listed failure is read preferring a payment that is not one of the attempt's earlier ids, and one it didn't read as earlier is written as the attempt's own, also when the send call never returned its id. - Each send's earlier attempt ids are kept past its hold for the latest 100 sends, so after a restart an earlier attempt's failure never writes over the retry's row, whatever Spark's dates say. Verified: just compile, just test, just lint; the two changed SparkRepoTest cases fail on the previous head and pass here. --- .../main/java/to/bitkit/data/CacheStore.kt | 19 ++++++++ .../java/to/bitkit/repositories/BackupRepo.kt | 1 + .../java/to/bitkit/repositories/SparkRepo.kt | 46 +++++++++++++----- .../to/bitkit/repositories/SparkRepoTest.kt | 48 ++++++++++++++++++- 4 files changed, 100 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 55574e9995..53e807777b 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -176,6 +176,20 @@ class CacheStore internal constructor( } } + /** + * Keeps Spark's ids of the earlier attempts of the send of [paymentHash], [ids], with those kept before, past its + * hold and for the latest [MAX_SPARK_SEND_HASHES] sends, so their failures never write over a later attempt's row. + */ + suspend fun keepSparkSendEarlierIds(paymentHash: String, ids: Set) { + val hash = paymentHash.lowercase() + if (store.data.first().sparkSendEarlierIds[hash].orEmpty().containsAll(ids)) return + store.updateData { + val kept = (it.sparkSendEarlierIds[hash].orEmpty() + ids).distinct().sorted() + val all = (it.sparkSendEarlierIds - hash + (hash to kept)).entries.toList().takeLast(MAX_SPARK_SEND_HASHES) + it.copy(sparkSendEarlierIds = all.associate { (key, value) -> key to value }) + } + } + suspend fun removeSparkSendHash(paymentHash: String) { val hash = paymentHash.lowercase() if (hash !in store.data.first().sparkSendHashes) return @@ -463,6 +477,11 @@ data class AppCacheData( * an earlier attempt's failure dated the same second as the row never writes over it. */ val sparkSendRowIds: Map = mapOf(), + /** + * Spark's payment ids of each Spark send's earlier attempts, kept past its hold for the latest + * [MAX_SPARK_SEND_HASHES], so a failure of one never writes over a later attempt's Activity row after a restart. + */ + val sparkSendEarlierIds: Map> = mapOf(), /** * Payment hashes of the moves to Spark, kept across restarts so neither leg of a move is announced as a payment and * Activity shows the move as one. diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 9a4f103a36..6901c1522d 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1345,6 +1345,7 @@ class BackupRepo @Inject constructor( sparkTakenSendIds = emptyMap(), sparkUncertainSendAttemptIds = emptyMap(), sparkSendRowIds = emptyMap(), + sparkSendEarlierIds = emptyMap(), ) Logger.debug("Restored caches: ${jsonLogOf(logged)}", TAG) onCacheRestored() diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 4ed6034e55..5950180deb 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -608,6 +608,7 @@ class SparkRepo @Inject constructor( restoredTakenAttempts.remove(paymentHash.lowercase()) sendReleaseMutex.withLock { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() } cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) + earlierIds?.let { cacheStore.keepSparkSendEarlierIds(paymentHash, it) } spending { // Kept until the call returns, so a send cut off by process death or cancellation stays held. cacheStore.addSparkUncertainSend(paymentHash, sentAt, sentAt, earlierIds, attemptId) @@ -747,7 +748,7 @@ class SparkRepo @Inject constructor( val isFinal = clock.now().epochSeconds.toULong() >= uncertain.expiresAt && hasSyncedSince(maxOf(uncertain.failedAt, uncertain.expiresAt)) // The outcome and the payment its row is written from come from one read, so a later read can't miss it. - val (send, listed) = listedLightningSendPayment(paymentHash) + val (send, listed) = listedLightningSendPayment(paymentHash, uncertain.attempt.earlierIds) val isSettled = when (send) { SparkLightningSend.NotFound -> isFinal // A failed row may be an earlier attempt's, so it is final only when a missing one would be. @@ -795,8 +796,11 @@ class SparkRepo @Inject constructor( cacheStore.removeSparkSendHash(paymentHash) // Writes the row only when there was none to fail or the failure is the send's own, as a failed row // keeps its own payment; a failed write is retried at the next refresh. - listed?.takeUnless { isEarlierListed && hasStoredRow(paymentHash) } - ?.let { recordActivity(it, ownId = uncertain.attempt.ownId) } + // A failure the attempt didn't read as earlier is its own, also when its send call never + // returned its id. + listed?.takeUnless { isEarlierListed && hasStoredRow(paymentHash) }?.let { + recordActivity(it, ownId = uncertain.attempt.ownId ?: it.id.takeUnless { isEarlierListed }) + } } // The event comes from the read that settled it, so a failed later read can't leave the send pending. listed?.toNodeEvent()?.let { _nodeEvents.emit(it) } @@ -900,7 +904,7 @@ class SparkRepo @Inject constructor( // Read before the list, so a sync that ends between the two reads can't vouch for an older list. val isPastGrace = now >= graceEndsAt && hasSyncedSince(graceEndsAt.toULong()) val holds = { takenAttempts[hash] === attempt } - val (send, listedSend) = listedLightningSendPayment(hash) + val (send, listedSend) = listedLightningSendPayment(hash, attempt.earlierIds) var listed = listedSend when (send) { SparkLightningSend.Unavailable -> return@forEach @@ -924,7 +928,11 @@ class SparkRepo @Inject constructor( if (listed?.status != PaymentStatus.COMPLETED) cacheStore.removeSparkSendHash(hash) // Written once the attempt is gone, so it no longer holds the row back, with the own id the attempt // matched; a failed write is retried at the next refresh. - listed?.let { recordActivity(it, ownId = attempt.ownId) } + // Without its own id, a failure its earlier ids leave out is the attempt's own. + listed?.let { + val ownId = attempt.ownId ?: it.id.takeIf { id -> attempt.earlierIds?.contains(id) == false } + recordActivity(it, ownId = ownId) + } if (isRestored) return@forEach // The send's own outcome event may have been held back with the attempt, so the send screen learns it here. val event = listed?.toNodeEvent() @@ -1762,15 +1770,22 @@ class SparkRepo @Inject constructor( private suspend fun listedLightningSend(paymentHash: String): SparkLightningSend = listedLightningSendPayment(paymentHash).first - /** Spark's listed record of the Lightning send with [paymentHash] and the payment it was read from, in one read. */ - private suspend fun listedLightningSendPayment(paymentHash: String): Pair = + /** + * Spark's listed record of the Lightning send with [paymentHash] and the payment it was read from, in one read, + * preferring a payment that is not one of the attempt's [earlierIds], as Spark can date both in the same second. + */ + private suspend fun listedLightningSendPayment( + paymentHash: String, + earlierIds: Set? = null, + ): Pair = withContext(bgDispatcher) { if (!sparkService.isSupported) return@withContext SparkLightningSend.NotFound to null if (!canListPayments()) return@withContext SparkLightningSend.Unavailable to null val payments = runSuspendCatching { sparkService.listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrElse { return@withContext SparkLightningSend.Unavailable to null } - val latest = payments.latestSend(paymentHash) + val latest = earlierIds?.let { ids -> payments.filterNot { it.id in ids }.latestSend(paymentHash) } + ?: payments.latestSend(paymentHash) ?: return@withContext SparkLightningSend.NotFound to null val preimage = (latest.details as PaymentDetails.Lightning).htlcDetails.preimage SparkLightningSend.Found(latest.status, preimage) to latest @@ -2116,14 +2131,19 @@ class SparkRepo @Inject constructor( id != (ownId ?: heldAttempt(paymentHash)?.ownId) && isEarlierThan(row, paymentHash) /** - * Whether Spark dates this payment before the [row] of [paymentHash], or ties it as another payment than the one - * that wrote the row, unless the row is an earlier attempt of the send held now and this payment is not. + * Whether this payment is of an attempt a later one read as earlier before it went out, kept past its hold and a + * restart, or Spark dates it before the [row] of [paymentHash] or ties it as another payment than the one that + * wrote the row, unless that one is such an earlier attempt. */ private suspend fun Payment.isEarlierThan(row: LightningActivity, paymentHash: String): Boolean { + val cache = cacheStore.data.first() + val hash = paymentHash.lowercase() + val earlierIds = heldAttempt(paymentHash)?.earlierIds.orEmpty() + cache.sparkSendEarlierIds[hash].orEmpty() + // Spark's dates can put an earlier attempt's failure after the retry's row. + if (id in earlierIds) return true if (timestamp != row.timestamp) return timestamp < row.timestamp - val rowId = cacheStore.data.first().sparkSendRowIds[paymentHash.lowercase()] ?: return false - val earlierIds = heldAttempt(paymentHash)?.earlierIds.orEmpty() - return rowId != id && !(rowId in earlierIds && id !in earlierIds) + val rowId = cache.sparkSendRowIds[hash] ?: return false + return rowId != id && rowId !in earlierIds } private fun recordedSince(records: Long): Set = sendRecordedAt.filterValues { it > records }.keys diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 8d708bd34c..227e428b47 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4050,6 +4050,7 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `an uncertain spark retry fails its own row at expiry when only an earlier failure is listed`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) @@ -4063,7 +4064,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } whenever(sparkService.listPayments()).thenReturn(emptyList()) - val sut = createSut() + val sut = createSut(store) sut.start(0).getOrThrow() runCurrent() // The earlier attempt paid the amountless invoice at another amount and fee, and failed; Spark dates it after @@ -4081,8 +4082,53 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(PaymentState.FAILED, row.v1.status) assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "the retry's row took the earlier attempt's payment") + + // The next launch lists the same earlier failure once nothing holds the invoice. + createSut(store).start(0).getOrThrow() + advanceUntilIdle() + assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "a relaunch wrote the earlier attempt over the row") } + @Test + fun `an expired uncertain spark retry's own failure replaces an earlier attempt's row from the same second`() = + test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val sentAt = now.epochSeconds.toULong() + // The earlier attempt failed the second the retry starts, and its failure wrote the row. + store.keepSparkSendRowId("hash", "older") + var row = Activity.Lightning( + pendingSendRow().v1.copy(status = PaymentState.FAILED, value = 999uL, fee = 7uL, timestamp = sentAt) + ) + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } + val older = sentPayment(fees = 7) + .copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger(), timestamp = sentAt) + whenever(sparkService.listPayments()).thenReturn(listOf(older)) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut(store) + sut.start(0).getOrThrow() + runCurrent() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + runCurrent() + + // The send call timed out, so the retry's own id is known only from the list at its invoice's expiry. + val ownFailure = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED, timestamp = sentAt) + whenever(sparkService.listPayments()).thenReturn(listOf(older, ownFailure)) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = sentAt + 1uL)) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "the retry's own failure kept the earlier row") + } + @Test fun `a taken spark retry's own failure after a restart replaces an earlier attempt's failed row`() = test { // The app closed before it saved the retry's pending row, so Activity still shows the earlier attempt. From c38c4f3745b3e18377ead3f92d9f5e9738ca021c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 01:25:46 +0100 Subject: [PATCH 55/96] fix: spark row keeps its own fee correction after a refused retry - A kept earlier attempt id blocks a payment's failure only while another payment wrote the row, so a payment whose retry Spark refused keeps its fee corrections. - A held attempt failing its row in place drops the row's writer id, as the row is that attempt's from then on. Verified: just compile, just test, just lint; the new SparkRepoTest case fails on the previous head and passes here. --- app/src/main/java/to/bitkit/data/CacheStore.kt | 6 ++++++ .../main/java/to/bitkit/repositories/SparkRepo.kt | 14 +++++++++----- .../java/to/bitkit/repositories/SparkRepoTest.kt | 13 +++++++++++++ 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 53e807777b..7e7489ea54 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -190,6 +190,12 @@ class CacheStore internal constructor( } } + suspend fun removeSparkSendRowId(paymentHash: String) { + val hash = paymentHash.lowercase() + if (hash !in store.data.first().sparkSendRowIds) return + store.updateData { it.copy(sparkSendRowIds = it.sparkSendRowIds - hash) } + } + suspend fun removeSparkSendHash(paymentHash: String) { val hash = paymentHash.lowercase() if (hash !in store.data.first().sparkSendHashes) return diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 5950180deb..f186c4565c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -836,6 +836,8 @@ class SparkRepo @Inject constructor( if (send?.txType != PaymentType.SENT || send.status != PaymentState.PENDING) return@withLock true activityRepo.get().upsertActivity(Activity.Lightning(send.copy(status = PaymentState.FAILED))) .onFailure { Logger.warn("Failed to mark Spark send '$paymentHash' failed", it, context = TAG) } + // The row is the held attempt's now, so no earlier payment that wrote it before still owns it. + .onSuccess { cacheStore.removeSparkSendRowId(paymentHash) } .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } } @@ -2132,17 +2134,19 @@ class SparkRepo @Inject constructor( /** * Whether this payment is of an attempt a later one read as earlier before it went out, kept past its hold and a - * restart, or Spark dates it before the [row] of [paymentHash] or ties it as another payment than the one that - * wrote the row, unless that one is such an earlier attempt. + * restart, while it no longer wrote the [row] of [paymentHash], or Spark dates it before the row or ties it as + * another payment than the one that wrote the row, unless that one is such an earlier attempt. */ private suspend fun Payment.isEarlierThan(row: LightningActivity, paymentHash: String): Boolean { val cache = cacheStore.data.first() val hash = paymentHash.lowercase() val earlierIds = heldAttempt(paymentHash)?.earlierIds.orEmpty() + cache.sparkSendEarlierIds[hash].orEmpty() - // Spark's dates can put an earlier attempt's failure after the retry's row. - if (id in earlierIds) return true + val rowId = cache.sparkSendRowIds[hash] + // Spark's dates can put an earlier attempt's failure after the retry's row, while a retry Spark refused leaves + // the row, and its fee corrections, to that attempt. + if (id in earlierIds && rowId != id) return true if (timestamp != row.timestamp) return timestamp < row.timestamp - val rowId = cache.sparkSendRowIds[hash] ?: return false + rowId ?: return false return rowId != id && rowId !in earlierIds } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 227e428b47..b5f641af36 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4051,6 +4051,8 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `an uncertain spark retry fails its own row at expiry when only an earlier failure is listed`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + // The earlier attempt's failure wrote the invoice's row before the retry's replaced it. + store.keepSparkSendRowId("hash", "older") whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) @@ -4172,6 +4174,17 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(128uL to 3uL, failedRowAfterListing(corrected).let { it.v1.value to it.v1.fee }) } + @Test + fun `a failed spark send row takes its own fee correction after spark refused a retry`() = test { + // A retry read the payment as earlier, then Spark refused it before it went out, so the payment keeps the row. + cacheData.value = cacheData.value.copy( + sparkSendRowIds = mapOf("hash" to "older"), + sparkSendEarlierIds = mapOf("hash" to listOf("older")), + ) + val corrected = sentPayment(fees = 3).copy(id = "older", status = PaymentStatus.FAILED) + assertEquals(128uL to 3uL, failedRowAfterListing(corrected).let { it.v1.value to it.v1.fee }) + } + @Test fun `a failed spark send row takes a later attempt's failure`() = test { val later = sentPayment(fees = 0) From e2f968e5ec48410df7fcf0da07e0a265f042f8ce Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 02:01:20 +0100 Subject: [PATCH 56/96] fix: spark held row keeps its own writer when failed - Failing a held attempt's row sets its writer to the attempt's own id when known, and drops it only when the attempt read it as earlier, so the retry's saved id keeps protecting its row from an older same-second failure. - The writer is updated before the row is marked failed, so a restart between the two finds the row pending and does both again. Verified: just compile, just test, just lint; the new SparkRepoTest case fails on the previous head and passes here. --- .../java/to/bitkit/repositories/SparkRepo.kt | 21 ++++++--- .../to/bitkit/repositories/SparkRepoTest.kt | 44 +++++++++++++++++++ 2 files changed, 58 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index f186c4565c..b2333f2d2f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -758,11 +758,11 @@ class SparkRepo @Inject constructor( if (!isSettled) return false // A missing send's row is ended here, as no listed payment revisits it, so the hold stays until it is written. val holds = { uncertainSends[key] === uncertain } - if (send == SparkLightningSend.NotFound && !failHeldRow(paymentHash, holds)) return false + if (send == SparkLightningSend.NotFound && !failHeldRow(paymentHash, uncertain.attempt, holds)) return false // A listed failure may be an earlier attempt's, so the send's own row is failed in place instead of taking // that attempt's amount, fee and time. val isFailed = send is SparkLightningSend.Found && send.status == PaymentStatus.FAILED - if (isFailed && !failHeldRow(paymentHash, holds)) return false + if (isFailed && !failHeldRow(paymentHash, uncertain.attempt, holds)) return false // A send Spark now runs keeps its earlier attempts' ids until it settles, taken over before the doubt ends. val isTaken = send is SparkLightningSend.Found && send.status == PaymentStatus.PENDING // Only the caller that takes the hash off settles it, so its outcome is reported once. The hand-over shares the @@ -820,10 +820,13 @@ class SparkRepo @Inject constructor( /** * Marks the pending send row of [paymentHash] failed, as Spark lists no send of it; true once nothing is pending. * Read and write share the lock Spark's own row writes take, so a settlement written meanwhile is not overwritten, - * and the write happens only while the caller still [holds] the send, so a newer retry's row is left alone. + * and the write happens only while the caller still [holds] the send, so a newer retry's row is left alone. The + * row is the held [attempt]'s from then on, so its writer becomes that attempt before the write, kept across a + * restart that cuts the two apart. */ private suspend fun failHeldRow( paymentHash: String, + attempt: SendAttempt, holds: () -> Boolean, ): Boolean = sendReleaseMutex.withLock { // A hold that ended meanwhile is no longer the caller's to end, which its own removal then finds. @@ -834,10 +837,14 @@ class SparkRepo @Inject constructor( } val send = (stored as? Activity.Lightning)?.v1 if (send?.txType != PaymentType.SENT || send.status != PaymentState.PENDING) return@withLock true + // A writer the attempt read as earlier no longer owns the row, while the attempt's own one keeps protecting it. + val rowId = cacheStore.data.first().sparkSendRowIds[paymentHash.lowercase()] + when { + attempt.ownId != null -> cacheStore.keepSparkSendRowId(paymentHash, attempt.ownId) + rowId != null && attempt.earlierIds?.contains(rowId) == true -> cacheStore.removeSparkSendRowId(paymentHash) + } activityRepo.get().upsertActivity(Activity.Lightning(send.copy(status = PaymentState.FAILED))) .onFailure { Logger.warn("Failed to mark Spark send '$paymentHash' failed", it, context = TAG) } - // The row is the held attempt's now, so no earlier payment that wrote it before still owns it. - .onSuccess { cacheStore.removeSparkSendRowId(paymentHash) } .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } } @@ -910,13 +917,13 @@ class SparkRepo @Inject constructor( var listed = listedSend when (send) { SparkLightningSend.Unavailable -> return@forEach - SparkLightningSend.NotFound -> if (!isPastGrace || !failHeldRow(hash, holds)) return@forEach + SparkLightningSend.NotFound -> if (!isPastGrace || !failHeldRow(hash, attempt, holds)) return@forEach is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> return@forEach // A failure with another id than the attempt's own is an earlier attempt's, listed before the attempt, // so the retry's own row is failed instead of taking that attempt's amount, fee and time. is SparkLightningSend.Found if send.status == PaymentStatus.FAILED && attempt.ownId != null && listed?.id != attempt.ownId -> { - if (!isPastGrace || !failHeldRow(hash, holds)) return@forEach + if (!isPastGrace || !failHeldRow(hash, attempt, holds)) return@forEach listed = null } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index b5f641af36..059c846428 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4167,6 +4167,50 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "the retry's own failure left the earlier attempt's row") } + @Test + fun `a taken spark retry's row failed at expiry keeps its own writer against an older same-second failure`() = + test { + val sentAt = now.epochSeconds - 7_200 + // The pre-send list missed the older attempt, so only the retry's own id, as the row's writer, protects it. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to now.epochSeconds - 3_600), + sparkUncertainSendStarts = mapOf("hash" to sentAt), + sparkTakenSendIds = mapOf("hash" to "retry"), + sparkSendRowIds = mapOf("hash" to "retry"), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + var row = Activity.Lightning(pendingSendRow().v1.copy(timestamp = sentAt.toULong())) + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } + val older = sentPayment(fees = 7).copy( + id = "older", + status = PaymentStatus.FAILED, + amount = 999.toBigInteger(), + timestamp = sentAt.toULong(), + ) + whenever(sparkService.listPayments()).thenReturn(listOf(older)) + createSut(store).start(0).getOrThrow() + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + assertEquals(PaymentState.FAILED, row.v1.status, "the expired retry's row stayed pending") + + createSut(store).start(0).getOrThrow() + advanceUntilIdle() + + assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "a relaunch wrote the older attempt over the row") + } + @Test fun `a failed spark send row takes its own attempt's fee correction`() = test { cacheData.value = cacheData.value.copy(sparkSendRowIds = mapOf("hash" to "retry")) From 8f2d5e14aba8e34e38c2d0d8f01392fc50163e1f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 02:48:34 +0100 Subject: [PATCH 57/96] fix: spark held row checks kept earlier ids for its writer Failing a held attempt's row drops a writer that the earlier ids kept from past retries name, not only the attempt's own, as the attempt's pre-send read of them can have failed. Verified: just compile, just test, just lint; the new SparkRepoTest case fails on the previous head and passes here. --- .../java/to/bitkit/repositories/SparkRepo.kt | 7 ++- .../to/bitkit/repositories/SparkRepoTest.kt | 46 +++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index b2333f2d2f..afb7587349 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -838,10 +838,13 @@ class SparkRepo @Inject constructor( val send = (stored as? Activity.Lightning)?.v1 if (send?.txType != PaymentType.SENT || send.status != PaymentState.PENDING) return@withLock true // A writer the attempt read as earlier no longer owns the row, while the attempt's own one keeps protecting it. - val rowId = cacheStore.data.first().sparkSendRowIds[paymentHash.lowercase()] + // The ids kept from earlier retries count too, as this attempt's own read of them can have failed. + val cache = cacheStore.data.first() + val rowId = cache.sparkSendRowIds[paymentHash.lowercase()] + val earlierIds = attempt.earlierIds.orEmpty() + cache.sparkSendEarlierIds[paymentHash.lowercase()].orEmpty() when { attempt.ownId != null -> cacheStore.keepSparkSendRowId(paymentHash, attempt.ownId) - rowId != null && attempt.earlierIds?.contains(rowId) == true -> cacheStore.removeSparkSendRowId(paymentHash) + rowId != null && rowId in earlierIds -> cacheStore.removeSparkSendRowId(paymentHash) } activityRepo.get().upsertActivity(Activity.Lightning(send.copy(status = PaymentState.FAILED))) .onFailure { Logger.warn("Failed to mark Spark send '$paymentHash' failed", 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 059c846428..d880ed902d 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4211,6 +4211,52 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "a relaunch wrote the older attempt over the row") } + @Test + fun `an expired spark retry without earlier ids drops a writer kept as earlier before a relaunch`() = test { + val sentAt = now.epochSeconds - 7_200 + // The retry's pre-send read failed, while an earlier retry kept the older attempt's id; its pending row was + // saved, but not its writer. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to now.epochSeconds - 3_600), + sparkUncertainSends = mapOf("hash" to sentAt), + sparkUncertainSendStarts = mapOf("hash" to sentAt), + sparkSendRowIds = mapOf("hash" to "older"), + sparkSendEarlierIds = mapOf("hash" to listOf("older")), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + var row = Activity.Lightning(pendingSendRow().v1.copy(timestamp = sentAt.toULong())) + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } + whenever(sparkService.listPayments()).thenReturn(emptyList()) + createSut(store).start(0).getOrThrow() + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + assertEquals(PaymentState.FAILED, row.v1.status, "the expired retry's row stayed pending") + + val older = sentPayment(fees = 7).copy( + id = "older", + status = PaymentStatus.FAILED, + amount = 999.toBigInteger(), + timestamp = sentAt.toULong(), + ) + whenever(sparkService.listPayments()).thenReturn(listOf(older)) + createSut(store).start(0).getOrThrow() + advanceUntilIdle() + + assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "a relaunch wrote the older attempt over the row") + } + @Test fun `a failed spark send row takes its own attempt's fee correction`() = test { cacheData.value = cacheData.value.copy(sparkSendRowIds = mapOf("hash" to "retry")) From 31cce5e84081fb29effd67008f027f57f9c41aaf Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 03:43:22 +0100 Subject: [PATCH 58/96] fix: spark row writer cleared only once its row was written over Each Spark send row's writer id is kept with a stamp of the row it wrote (time, amount and fee) in one write. Failing a held row drops a writer read as earlier only when the row no longer matches that stamp, so a pending row an earlier payment still owns keeps its writer and takes that payment's final fee, while a row a retry wrote over without saving its writer still drops the stale one. Verified: just compile, just test, just lint; the new SparkRepoTest case fails on the previous head and passes here. --- .../main/java/to/bitkit/data/CacheStore.kt | 21 ++++++--- .../java/to/bitkit/repositories/BackupRepo.kt | 1 + .../java/to/bitkit/repositories/SparkRepo.kt | 21 ++++++--- .../java/to/bitkit/data/CacheStoreTest.kt | 13 ++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 44 +++++++++++++++++++ 5 files changed, 88 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 7e7489ea54..1b8cbff8e7 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -166,13 +166,20 @@ class CacheStore internal constructor( } } - /** Keeps [paymentId] as the payment that last wrote the Activity row of Spark's send of [paymentHash]. */ - suspend fun keepSparkSendRowId(paymentHash: String, paymentId: String) { + /** + * Keeps [paymentId] as the payment that last wrote the Activity row of Spark's send of [paymentHash], with the + * [stamp] of the row it wrote, in one write, so a row written over without its writer is told apart. + */ + suspend fun keepSparkSendRowId(paymentHash: String, paymentId: String, stamp: String? = null) { val hash = paymentHash.lowercase() - if (store.data.first().sparkSendRowIds[hash] == paymentId) return + val data = store.data.first() + if (data.sparkSendRowIds[hash] == paymentId && data.sparkSendRowStamps[hash] == stamp) return store.updateData { val ids = (it.sparkSendRowIds - hash + (hash to paymentId)).entries.toList().takeLast(MAX_SPARK_SEND_HASHES) - it.copy(sparkSendRowIds = ids.associate { (key, id) -> key to id }) + val stamps = stamp?.let { value -> it.sparkSendRowStamps + (hash to value) } + ?: (it.sparkSendRowStamps - hash) + val kept = ids.associate { (key, id) -> key to id } + it.copy(sparkSendRowIds = kept, sparkSendRowStamps = stamps.filterKeys { key -> key in kept }) } } @@ -193,7 +200,9 @@ class CacheStore internal constructor( suspend fun removeSparkSendRowId(paymentHash: String) { val hash = paymentHash.lowercase() if (hash !in store.data.first().sparkSendRowIds) return - store.updateData { it.copy(sparkSendRowIds = it.sparkSendRowIds - hash) } + store.updateData { + it.copy(sparkSendRowIds = it.sparkSendRowIds - hash, sparkSendRowStamps = it.sparkSendRowStamps - hash) + } } suspend fun removeSparkSendHash(paymentHash: String) { @@ -483,6 +492,8 @@ data class AppCacheData( * an earlier attempt's failure dated the same second as the row never writes over it. */ val sparkSendRowIds: Map = mapOf(), + /** The time, amount and fee of each of those rows as its writer wrote it, so a row written over is told apart. */ + val sparkSendRowStamps: Map = mapOf(), /** * Spark's payment ids of each Spark send's earlier attempts, kept past its hold for the latest * [MAX_SPARK_SEND_HASHES], so a failure of one never writes over a later attempt's Activity row after a restart. diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 6901c1522d..8dff903b2a 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1345,6 +1345,7 @@ class BackupRepo @Inject constructor( sparkTakenSendIds = emptyMap(), sparkUncertainSendAttemptIds = emptyMap(), sparkSendRowIds = emptyMap(), + sparkSendRowStamps = emptyMap(), sparkSendEarlierIds = emptyMap(), ) 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 afb7587349..331c25a3bc 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -837,14 +837,17 @@ class SparkRepo @Inject constructor( } val send = (stored as? Activity.Lightning)?.v1 if (send?.txType != PaymentType.SENT || send.status != PaymentState.PENDING) return@withLock true - // A writer the attempt read as earlier no longer owns the row, while the attempt's own one keeps protecting it. - // The ids kept from earlier retries count too, as this attempt's own read of them can have failed. + // A writer the attempt read as earlier no longer owns the row once the row differs from what it wrote, as a + // retry wrote over it, while the attempt's own one keeps protecting it. The ids kept from earlier retries count + // too, as this attempt's own read of them can have failed. val cache = cacheStore.data.first() - val rowId = cache.sparkSendRowIds[paymentHash.lowercase()] - val earlierIds = attempt.earlierIds.orEmpty() + cache.sparkSendEarlierIds[paymentHash.lowercase()].orEmpty() + val hash = paymentHash.lowercase() + val rowId = cache.sparkSendRowIds[hash] + val earlierIds = attempt.earlierIds.orEmpty() + cache.sparkSendEarlierIds[hash].orEmpty() + val isWrittenOver = cache.sparkSendRowStamps[hash] != send.sendRowStamp() when { - attempt.ownId != null -> cacheStore.keepSparkSendRowId(paymentHash, attempt.ownId) - rowId != null && rowId in earlierIds -> cacheStore.removeSparkSendRowId(paymentHash) + attempt.ownId != null -> cacheStore.keepSparkSendRowId(paymentHash, attempt.ownId, send.sendRowStamp()) + rowId != null && rowId in earlierIds && isWrittenOver -> cacheStore.removeSparkSendRowId(paymentHash) } activityRepo.get().upsertActivity(Activity.Lightning(send.copy(status = PaymentState.FAILED))) .onFailure { Logger.warn("Failed to mark Spark send '$paymentHash' failed", it, context = TAG) } @@ -2160,6 +2163,8 @@ class SparkRepo @Inject constructor( return rowId != id && rowId !in earlierIds } + private fun LightningActivity.sendRowStamp() = "$timestamp:$value:$fee" + private fun recordedSince(records: Long): Set = sendRecordedAt.filterValues { it > records }.keys /** Whether this failure is an earlier attempt's, of a retry in doubt or one sent after [records] was read. */ @@ -2370,7 +2375,9 @@ class SparkRepo @Inject constructor( return false } unsavedPayments.remove(payment.id) - if (payment.paymentType == SparkPaymentType.SEND) cacheStore.keepSparkSendRowId(id, payment.id) + if (payment.paymentType == SparkPaymentType.SEND) { + cacheStore.keepSparkSendRowId(id, payment.id, activity.sendRowStamp()) + } if (payment.paymentType == SparkPaymentType.SEND && payment.fees.toLong() == 0L) { sendsRecordedWithoutFee.add(payment.id) } else { diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index 88a9a7c8ff..77367dd583 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -248,6 +248,19 @@ class CacheStoreTest : BaseUnitTest() { const val NOW = 1_800_000_000L } + @Test + fun `keepSparkSendRowId keeps each writer's row stamp and drops it with the writer`() = test { + sut.keepSparkSendRowId("HASH", "id", "1:2:3") + assertEquals("1:2:3", sut.data.first().sparkSendRowStamps["hash"]) + + sut.keepSparkSendRowId("hash", "other") + assertFalse("hash" in sut.data.first().sparkSendRowStamps) + + sut.keepSparkSendRowId("hash", "id", "1:2:3") + sut.removeSparkSendRowId("hash") + assertTrue(sut.data.first().sparkSendRowStamps.isEmpty()) + } + @Test fun `keepSparkSendRowId keeps the latest row writers up to the limit`() = test { (0..MAX_SPARK_SEND_HASHES).forEach { sut.keepSparkSendRowId("hash$it", "id$it") } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index d880ed902d..c1ac9d4fbe 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4257,6 +4257,50 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "a relaunch wrote the older attempt over the row") } + @Test + fun `an expired spark retry that never wrote its row keeps an earlier payment's final fee`() = test { + val sentAt = now.epochSeconds - 7_200 + val pending = Activity.Lightning(pendingSendRow().v1.copy(timestamp = sentAt.toULong())) + // The earlier payment wrote the pending row and its failure never saved; a refused retry kept its id, and a + // later retry timed out without writing a row or reading earlier ids. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to now.epochSeconds - 3_600), + sparkUncertainSends = mapOf("hash" to sentAt), + sparkUncertainSendStarts = mapOf("hash" to sentAt), + sparkSendRowIds = mapOf("hash" to "older"), + sparkSendRowStamps = mapOf("hash" to pending.v1.let { "${it.timestamp}:${it.value}:${it.fee}" }), + sparkSendEarlierIds = mapOf("hash" to listOf("older")), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + var row = pending + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } + whenever(sparkService.listPayments()).thenReturn(emptyList()) + createSut(store).start(0).getOrThrow() + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + assertEquals(PaymentState.FAILED, row.v1.status, "the expired retry's row stayed pending") + + val final = sentPayment(fees = 3) + .copy(id = "older", status = PaymentStatus.FAILED, timestamp = sentAt.toULong()) + whenever(sparkService.listPayments()).thenReturn(listOf(final)) + createSut(store).start(0).getOrThrow() + advanceUntilIdle() + + assertEquals(3uL, row.v1.fee, "the earlier payment's final fee was dropped") + } + @Test fun `a failed spark send row takes its own attempt's fee correction`() = test { cacheData.value = cacheData.value.copy(sparkSendRowIds = mapOf("hash" to "retry")) From 7d91612a828ae0040aff300f7ac741458c42841b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 04:22:33 +0100 Subject: [PATCH 59/96] fix: spark send row writer kept before its row A Spark send row's writer id and stamp are kept before the row is written, under the same lock, and put back when the write fails, so a stop between the two never leaves a retry's row, alike in time, amount and fee, to an earlier writer. Verified: just compile, just test, just lint; the new SparkRepoTest case fails on the previous head and passes here. --- .../java/to/bitkit/repositories/SparkRepo.kt | 30 +++++++++++++----- .../to/bitkit/repositories/SparkRepoTest.kt | 31 +++++++++++++++++++ 2 files changed, 54 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 331c25a3bc..48fdc55f03 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -2165,6 +2165,28 @@ class SparkRepo @Inject constructor( private fun LightningActivity.sendRowStamp() = "$timestamp:$value:$fee" + /** + * Writes [activity], the row of [payment], unless a retry recorded after [records] outran it, then null. A send + * row's writer is kept before the row, so a stop between the two never leaves a retry's row, alike in time, amount + * and fee, to an earlier writer; a failed write puts the previous one back. + */ + private suspend fun saveLightningRow(payment: Payment, activity: LightningActivity, records: Long): Boolean? = + sendReleaseMutex.withLock { + if (payment.isOutrunByRetry(records)) return@withLock null + val hash = activity.id.lowercase() + val isSend = payment.paymentType == SparkPaymentType.SEND + val previous = cacheStore.data.first().let { it.sparkSendRowIds[hash] to it.sparkSendRowStamps[hash] } + if (isSend) cacheStore.keepSparkSendRowId(hash, payment.id, activity.sendRowStamp()) + val isSaved = activityRepo.get().upsertActivity(Activity.Lightning(activity)) + .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } + if (isSend && !isSaved) { + val (previousId, previousStamp) = previous + previousId?.let { cacheStore.keepSparkSendRowId(hash, it, previousStamp) } + ?: cacheStore.removeSparkSendRowId(hash) + } + isSaved + } + private fun recordedSince(records: Long): Set = sendRecordedAt.filterValues { it > records }.keys /** Whether this failure is an earlier attempt's, of a retry in doubt or one sent after [records] was read. */ @@ -2366,18 +2388,12 @@ class SparkRepo @Inject constructor( seenAt = existing?.seenAt, ) // The lookup above suspends, so a retry sent meanwhile is checked for again before the write. - val saved = sendReleaseMutex.withLock { - if (payment.isOutrunByRetry(records)) return true - activityRepo.get().upsertActivity(Activity.Lightning(activity)) - }.let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } + val saved = saveLightningRow(payment, activity, records) ?: return true if (!saved) { unsavedPayments.add(payment.id) return false } unsavedPayments.remove(payment.id) - if (payment.paymentType == SparkPaymentType.SEND) { - cacheStore.keepSparkSendRowId(id, payment.id, activity.sendRowStamp()) - } if (payment.paymentType == SparkPaymentType.SEND && payment.fees.toLong() == 0L) { sendsRecordedWithoutFee.add(payment.id) } else { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index c1ac9d4fbe..32ae1cc934 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4301,6 +4301,37 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(3uL, row.v1.fee, "the earlier payment's final fee was dropped") } + @Test + fun `a spark send row's writer is kept before its row and put back when the write fails`() = test { + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendRowIds = mapOf("hash" to "older"), + sparkSendRowStamps = mapOf("hash" to "0:128:0") + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + var writerAtWrite: String? = null + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + writerAtWrite = store.data.first().sparkSendRowIds["hash"] + Result.failure(IllegalStateException("write failed")) + } + // The retry's row is alike in time, amount and fee to the earlier attempt's. + val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING, timestamp = 0uL) + whenever(sparkService.listPayments()).thenReturn(listOf(retry)) + + createSut(store).start(0).getOrThrow() + advanceUntilIdle() + + assertEquals("retry", writerAtWrite, "the row was written before its writer was kept") + assertEquals("older", store.data.first().sparkSendRowIds["hash"], "a failed write kept its writer") + assertEquals("0:128:0", store.data.first().sparkSendRowStamps["hash"]) + } + @Test fun `a failed spark send row takes its own attempt's fee correction`() = test { cacheData.value = cacheData.value.copy(sparkSendRowIds = mapOf("hash" to "retry")) From 56be692dba91c46795b198b0fbf5292e3c4249d3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 05:18:56 +0100 Subject: [PATCH 60/96] fix: spark send row writer resolved by stamp after a cut write A writer kept ahead of its row keeps the previous writer and its stamp beside it until the row is saved. When a stop cut the row write short, the row still matches the previous stamp, so that writer is read as the row's and its final fee correction still lands. Verified: just compile, just test, just lint; the new SparkRepoTest case fails on the previous head and passes here. --- .../main/java/to/bitkit/data/CacheStore.kt | 42 ++++++++++++++++--- .../java/to/bitkit/repositories/BackupRepo.kt | 1 + .../java/to/bitkit/repositories/SparkRepo.kt | 25 +++++++++-- .../java/to/bitkit/data/CacheStoreTest.kt | 11 +++++ .../to/bitkit/repositories/SparkRepoTest.kt | 35 ++++++++++++++++ 5 files changed, 105 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 1b8cbff8e7..76cc8d76ee 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -168,21 +168,44 @@ class CacheStore internal constructor( /** * Keeps [paymentId] as the payment that last wrote the Activity row of Spark's send of [paymentHash], with the - * [stamp] of the row it wrote, in one write, so a row written over without its writer is told apart. + * [stamp] of the row it wrote, in one write, so a row written over without its writer is told apart. A writer + * kept [beforeRow] keeps the previous one beside it until [commitSparkSendRowId], so a stop before the row is + * written leaves the row to the writer whose stamp it still matches. */ - suspend fun keepSparkSendRowId(paymentHash: String, paymentId: String, stamp: String? = null) { + suspend fun keepSparkSendRowId( + paymentHash: String, + paymentId: String, + stamp: String? = null, + beforeRow: Boolean = false, + ) { val hash = paymentHash.lowercase() val data = store.data.first() - if (data.sparkSendRowIds[hash] == paymentId && data.sparkSendRowStamps[hash] == stamp) return + val isKept = data.sparkSendRowIds[hash] == paymentId && data.sparkSendRowStamps[hash] == stamp + if (isKept && !beforeRow && hash !in data.sparkSendPreviousRowWriters) return store.updateData { val ids = (it.sparkSendRowIds - hash + (hash to paymentId)).entries.toList().takeLast(MAX_SPARK_SEND_HASHES) val stamps = stamp?.let { value -> it.sparkSendRowStamps + (hash to value) } ?: (it.sparkSendRowStamps - hash) + val writer = it.sparkSendRowIds[hash]?.takeIf { beforeRow } + ?.let { id -> listOfNotNull(id, it.sparkSendRowStamps[hash]) } + val previous = writer?.let { value -> it.sparkSendPreviousRowWriters + (hash to value) } + ?: (it.sparkSendPreviousRowWriters - hash) val kept = ids.associate { (key, id) -> key to id } - it.copy(sparkSendRowIds = kept, sparkSendRowStamps = stamps.filterKeys { key -> key in kept }) + it.copy( + sparkSendRowIds = kept, + sparkSendRowStamps = stamps.filterKeys { key -> key in kept }, + sparkSendPreviousRowWriters = previous.filterKeys { key -> key in kept }, + ) } } + /** Ends the doubt over the writer of Spark's send row of [paymentHash], kept before its row, once it is saved. */ + suspend fun commitSparkSendRowId(paymentHash: String) { + val hash = paymentHash.lowercase() + if (hash !in store.data.first().sparkSendPreviousRowWriters) return + store.updateData { it.copy(sparkSendPreviousRowWriters = it.sparkSendPreviousRowWriters - hash) } + } + /** * Keeps Spark's ids of the earlier attempts of the send of [paymentHash], [ids], with those kept before, past its * hold and for the latest [MAX_SPARK_SEND_HASHES] sends, so their failures never write over a later attempt's row. @@ -201,7 +224,11 @@ class CacheStore internal constructor( val hash = paymentHash.lowercase() if (hash !in store.data.first().sparkSendRowIds) return store.updateData { - it.copy(sparkSendRowIds = it.sparkSendRowIds - hash, sparkSendRowStamps = it.sparkSendRowStamps - hash) + it.copy( + sparkSendRowIds = it.sparkSendRowIds - hash, + sparkSendRowStamps = it.sparkSendRowStamps - hash, + sparkSendPreviousRowWriters = it.sparkSendPreviousRowWriters - hash, + ) } } @@ -494,6 +521,11 @@ data class AppCacheData( val sparkSendRowIds: Map = mapOf(), /** The time, amount and fee of each of those rows as its writer wrote it, so a row written over is told apart. */ val sparkSendRowStamps: Map = mapOf(), + /** + * The writer, and its row's stamp, each of those rows had before a new writer was kept ahead of its row write, so + * a stop before the row was written leaves the row to the writer whose stamp it still matches. + */ + val sparkSendPreviousRowWriters: Map> = mapOf(), /** * Spark's payment ids of each Spark send's earlier attempts, kept past its hold for the latest * [MAX_SPARK_SEND_HASHES], so a failure of one never writes over a later attempt's Activity row after a restart. diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 8dff903b2a..1f51e2fba3 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1346,6 +1346,7 @@ class BackupRepo @Inject constructor( sparkUncertainSendAttemptIds = emptyMap(), sparkSendRowIds = emptyMap(), sparkSendRowStamps = emptyMap(), + sparkSendPreviousRowWriters = emptyMap(), sparkSendEarlierIds = emptyMap(), ) 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 48fdc55f03..87feb7729e 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -48,6 +48,7 @@ import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.PaymentFailureReason import org.lightningdevkit.ldknode.PaymentId import to.bitkit.async.appScope +import to.bitkit.data.AppCacheData import to.bitkit.data.CacheStore import to.bitkit.data.SettingsStore import to.bitkit.data.SparkPayoutChain @@ -842,9 +843,9 @@ class SparkRepo @Inject constructor( // too, as this attempt's own read of them can have failed. val cache = cacheStore.data.first() val hash = paymentHash.lowercase() - val rowId = cache.sparkSendRowIds[hash] + val rowId = cache.sendRowWriter(hash, send) val earlierIds = attempt.earlierIds.orEmpty() + cache.sparkSendEarlierIds[hash].orEmpty() - val isWrittenOver = cache.sparkSendRowStamps[hash] != send.sendRowStamp() + val isWrittenOver = !cache.isRowStampKept(hash, send) when { attempt.ownId != null -> cacheStore.keepSparkSendRowId(paymentHash, attempt.ownId, send.sendRowStamp()) rowId != null && rowId in earlierIds && isWrittenOver -> cacheStore.removeSparkSendRowId(paymentHash) @@ -2154,7 +2155,7 @@ class SparkRepo @Inject constructor( val cache = cacheStore.data.first() val hash = paymentHash.lowercase() val earlierIds = heldAttempt(paymentHash)?.earlierIds.orEmpty() + cache.sparkSendEarlierIds[hash].orEmpty() - val rowId = cache.sparkSendRowIds[hash] + val rowId = cache.sendRowWriter(hash, row) // Spark's dates can put an earlier attempt's failure after the retry's row, while a retry Spark refused leaves // the row, and its fee corrections, to that attempt. if (id in earlierIds && rowId != id) return true @@ -2165,6 +2166,21 @@ class SparkRepo @Inject constructor( private fun LightningActivity.sendRowStamp() = "$timestamp:$value:$fee" + /** + * The payment that wrote [row] of [hash]: the kept writer, unless a stop cut its row write short, when the row + * still matches the stamp of the writer it had before. + */ + private fun AppCacheData.sendRowWriter(hash: String, row: LightningActivity): String? { + val stamp = row.sendRowStamp() + val previous = sparkSendPreviousRowWriters[hash]?.takeIf { it.getOrNull(1) == stamp } + return if (sparkSendRowStamps[hash] != stamp && previous != null) previous.first() else sparkSendRowIds[hash] + } + + private fun AppCacheData.isRowStampKept(hash: String, row: LightningActivity): Boolean { + val stamp = row.sendRowStamp() + return sparkSendRowStamps[hash] == stamp || sparkSendPreviousRowWriters[hash]?.getOrNull(1) == stamp + } + /** * Writes [activity], the row of [payment], unless a retry recorded after [records] outran it, then null. A send * row's writer is kept before the row, so a stop between the two never leaves a retry's row, alike in time, amount @@ -2176,9 +2192,10 @@ class SparkRepo @Inject constructor( val hash = activity.id.lowercase() val isSend = payment.paymentType == SparkPaymentType.SEND val previous = cacheStore.data.first().let { it.sparkSendRowIds[hash] to it.sparkSendRowStamps[hash] } - if (isSend) cacheStore.keepSparkSendRowId(hash, payment.id, activity.sendRowStamp()) + if (isSend) cacheStore.keepSparkSendRowId(hash, payment.id, activity.sendRowStamp(), beforeRow = true) val isSaved = activityRepo.get().upsertActivity(Activity.Lightning(activity)) .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } + if (isSend && isSaved) cacheStore.commitSparkSendRowId(hash) if (isSend && !isSaved) { val (previousId, previousStamp) = previous previousId?.let { cacheStore.keepSparkSendRowId(hash, it, previousStamp) } diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index 77367dd583..ecd2363248 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -261,6 +261,17 @@ class CacheStoreTest : BaseUnitTest() { assertTrue(sut.data.first().sparkSendRowStamps.isEmpty()) } + @Test + fun `keepSparkSendRowId before a row keeps the previous writer until it is committed`() = test { + sut.keepSparkSendRowId("hash", "older", "1:2:3") + sut.keepSparkSendRowId("hash", "retry", "4:5:6", beforeRow = true) + assertEquals(listOf("older", "1:2:3"), sut.data.first().sparkSendPreviousRowWriters["hash"]) + + sut.commitSparkSendRowId("HASH") + assertFalse("hash" in sut.data.first().sparkSendPreviousRowWriters) + assertEquals("retry", sut.data.first().sparkSendRowIds["hash"]) + } + @Test fun `keepSparkSendRowId keeps the latest row writers up to the limit`() = test { (0..MAX_SPARK_SEND_HASHES).forEach { sut.keepSparkSendRowId("hash$it", "id$it") } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 32ae1cc934..c1529c6b6c 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4332,6 +4332,41 @@ class SparkRepoTest : BaseUnitTest() { assertEquals("0:128:0", store.data.first().sparkSendRowStamps["hash"]) } + @Test + fun `an earlier payment's row takes its final fee after a stop cut a retry's row write short`() = test { + var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 7uL)) + val olderStamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}" } + // The retry's writer was kept ahead of its row, and the app stopped before the row was written. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendRowIds = mapOf("hash" to "retry"), + sparkSendRowStamps = mapOf("hash" to "9:128:0"), + sparkSendPreviousRowWriters = mapOf("hash" to listOf("older", olderStamp)), + sparkSendEarlierIds = mapOf("hash" to listOf("older")), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } + val final = sentPayment(fees = 9) + .copy(id = "older", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp) + whenever(sparkService.listPayments()).thenReturn(listOf(final)) + + createSut(store).start(0).getOrThrow() + advanceUntilIdle() + + assertEquals(9uL, row.v1.fee, "the earlier payment's final fee was dropped") + assertTrue("hash" !in store.data.first().sparkSendPreviousRowWriters, "the row's writer stayed in doubt") + } + @Test fun `a failed spark send row takes its own attempt's fee correction`() = test { cacheData.value = cacheData.value.copy(sparkSendRowIds = mapOf("hash" to "retry")) From f329f0833b42e2b7d1f785056fa1dbd568bf27ab Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 05:34:36 +0100 Subject: [PATCH 61/96] fix: spark row without a writer keeps its stamp past a cut write A writer kept ahead of a row that had none keeps an empty previous writer with the replaced row's stamp, so after a stop that cut the row write short the row reads as having no known writer, not the retry's, as on iOS. Verified: just compile, just test, just lint; the new CacheStoreTest case covers the entry. --- .../main/java/to/bitkit/data/CacheStore.kt | 11 +++++++---- .../java/to/bitkit/repositories/SparkRepo.kt | 19 ++++++++++++++----- .../java/to/bitkit/data/CacheStoreTest.kt | 7 +++++++ 3 files changed, 28 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 76cc8d76ee..133a76987f 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -169,14 +169,16 @@ class CacheStore internal constructor( /** * Keeps [paymentId] as the payment that last wrote the Activity row of Spark's send of [paymentHash], with the * [stamp] of the row it wrote, in one write, so a row written over without its writer is told apart. A writer - * kept [beforeRow] keeps the previous one beside it until [commitSparkSendRowId], so a stop before the row is - * written leaves the row to the writer whose stamp it still matches. + * kept [beforeRow] keeps the previous one beside it until [commitSparkSendRowId], or an empty id with the stamp of + * the row it replaces, [rowStamp], when it had none, so a stop before the row is written leaves the row to the + * writer whose stamp it still matches. */ suspend fun keepSparkSendRowId( paymentHash: String, paymentId: String, stamp: String? = null, beforeRow: Boolean = false, + rowStamp: String? = null, ) { val hash = paymentHash.lowercase() val data = store.data.first() @@ -186,8 +188,9 @@ class CacheStore internal constructor( val ids = (it.sparkSendRowIds - hash + (hash to paymentId)).entries.toList().takeLast(MAX_SPARK_SEND_HASHES) val stamps = stamp?.let { value -> it.sparkSendRowStamps + (hash to value) } ?: (it.sparkSendRowStamps - hash) - val writer = it.sparkSendRowIds[hash]?.takeIf { beforeRow } - ?.let { id -> listOfNotNull(id, it.sparkSendRowStamps[hash]) } + val writer = it.sparkSendRowIds[hash]?.let { id -> listOfNotNull(id, it.sparkSendRowStamps[hash]) } + ?: rowStamp?.let { value -> listOf("", value) } + ?.takeIf { beforeRow } val previous = writer?.let { value -> it.sparkSendPreviousRowWriters + (hash to value) } ?: (it.sparkSendPreviousRowWriters - hash) val kept = ids.associate { (key, id) -> key to id } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 87feb7729e..007c9ee92b 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -2173,7 +2173,8 @@ class SparkRepo @Inject constructor( private fun AppCacheData.sendRowWriter(hash: String, row: LightningActivity): String? { val stamp = row.sendRowStamp() val previous = sparkSendPreviousRowWriters[hash]?.takeIf { it.getOrNull(1) == stamp } - return if (sparkSendRowStamps[hash] != stamp && previous != null) previous.first() else sparkSendRowIds[hash] + if (sparkSendRowStamps[hash] == stamp || previous == null) return sparkSendRowIds[hash] + return previous.first().ifEmpty { null } } private fun AppCacheData.isRowStampKept(hash: String, row: LightningActivity): Boolean { @@ -2184,15 +2185,23 @@ class SparkRepo @Inject constructor( /** * Writes [activity], the row of [payment], unless a retry recorded after [records] outran it, then null. A send * row's writer is kept before the row, so a stop between the two never leaves a retry's row, alike in time, amount - * and fee, to an earlier writer; a failed write puts the previous one back. + * and fee, to an earlier writer, and the stamp of the row it replaces, [rowStamp], tells a write a stop cut short; + * a failed write puts the previous one back. */ - private suspend fun saveLightningRow(payment: Payment, activity: LightningActivity, records: Long): Boolean? = + private suspend fun saveLightningRow( + payment: Payment, + activity: LightningActivity, + records: Long, + rowStamp: String?, + ): Boolean? = sendReleaseMutex.withLock { if (payment.isOutrunByRetry(records)) return@withLock null val hash = activity.id.lowercase() val isSend = payment.paymentType == SparkPaymentType.SEND val previous = cacheStore.data.first().let { it.sparkSendRowIds[hash] to it.sparkSendRowStamps[hash] } - if (isSend) cacheStore.keepSparkSendRowId(hash, payment.id, activity.sendRowStamp(), beforeRow = true) + if (isSend) { + cacheStore.keepSparkSendRowId(hash, payment.id, activity.sendRowStamp(), beforeRow = true, rowStamp) + } val isSaved = activityRepo.get().upsertActivity(Activity.Lightning(activity)) .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } if (isSend && isSaved) cacheStore.commitSparkSendRowId(hash) @@ -2405,7 +2414,7 @@ class SparkRepo @Inject constructor( seenAt = existing?.seenAt, ) // The lookup above suspends, so a retry sent meanwhile is checked for again before the write. - val saved = saveLightningRow(payment, activity, records) ?: return true + val saved = saveLightningRow(payment, activity, records, existing?.sendRowStamp()) ?: return true if (!saved) { unsavedPayments.add(payment.id) return false diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index ecd2363248..a68f347299 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -272,6 +272,13 @@ class CacheStoreTest : BaseUnitTest() { assertEquals("retry", sut.data.first().sparkSendRowIds["hash"]) } + @Test + fun `keepSparkSendRowId before a row without a writer keeps the replaced row's stamp`() = test { + sut.keepSparkSendRowId("hash", "retry", "4:5:6", beforeRow = true, rowStamp = "1:2:3") + + assertEquals(listOf("", "1:2:3"), sut.data.first().sparkSendPreviousRowWriters["hash"]) + } + @Test fun `keepSparkSendRowId keeps the latest row writers up to the limit`() = test { (0..MAX_SPARK_SEND_HASHES).forEach { sut.keepSparkSendRowId("hash$it", "id$it") } From c61222625f1d1b801518f0fd0a9c8f5e401c3cd7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 05:45:45 +0100 Subject: [PATCH 62/96] fix: spark failed row write restores both writers A failed Spark send row write puts back the writer, its stamp and the previous writer a stop left beside it in one write, so the row's own writer still takes its fee correction on the next refresh. Verified: just compile, just test, just lint; the new SparkRepoTest case fails on the previous head and passes here. --- .../main/java/to/bitkit/data/CacheStore.kt | 18 +++++++++ .../java/to/bitkit/repositories/SparkRepo.kt | 12 ++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 38 +++++++++++++++++++ 3 files changed, 64 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 133a76987f..2315e678fc 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -202,6 +202,24 @@ class CacheStore internal constructor( } } + /** + * Puts back the writer of Spark's send row of [paymentHash] as it was before a row write that failed: its [id], + * [stamp] and the [previous] writer a stop left beside it, each dropped when null. + */ + suspend fun restoreSparkSendRowWriter(paymentHash: String, id: String?, stamp: String?, previous: List?) { + val hash = paymentHash.lowercase() + store.updateData { + val ids = id?.let { value -> it.sparkSendRowIds + (hash to value) } ?: (it.sparkSendRowIds - hash) + val stamps = stamp?.takeIf { id != null } + ?.let { value -> it.sparkSendRowStamps + (hash to value) } + ?: (it.sparkSendRowStamps - hash) + val writers = previous?.takeIf { id != null } + ?.let { value -> it.sparkSendPreviousRowWriters + (hash to value) } + ?: (it.sparkSendPreviousRowWriters - hash) + it.copy(sparkSendRowIds = ids, sparkSendRowStamps = stamps, sparkSendPreviousRowWriters = writers) + } + } + /** Ends the doubt over the writer of Spark's send row of [paymentHash], kept before its row, once it is saved. */ suspend fun commitSparkSendRowId(paymentHash: String) { val hash = paymentHash.lowercase() diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 007c9ee92b..3e5a6032ad 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -2198,17 +2198,21 @@ class SparkRepo @Inject constructor( if (payment.isOutrunByRetry(records)) return@withLock null val hash = activity.id.lowercase() val isSend = payment.paymentType == SparkPaymentType.SEND - val previous = cacheStore.data.first().let { it.sparkSendRowIds[hash] to it.sparkSendRowStamps[hash] } + val before = cacheStore.data.first() if (isSend) { cacheStore.keepSparkSendRowId(hash, payment.id, activity.sendRowStamp(), beforeRow = true, rowStamp) } val isSaved = activityRepo.get().upsertActivity(Activity.Lightning(activity)) .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } if (isSend && isSaved) cacheStore.commitSparkSendRowId(hash) + // Both writers a stop left are put back, so the row's own writer still takes its correction later. if (isSend && !isSaved) { - val (previousId, previousStamp) = previous - previousId?.let { cacheStore.keepSparkSendRowId(hash, it, previousStamp) } - ?: cacheStore.removeSparkSendRowId(hash) + cacheStore.restoreSparkSendRowWriter( + hash, + before.sparkSendRowIds[hash], + before.sparkSendRowStamps[hash], + before.sparkSendPreviousRowWriters[hash], + ) } isSaved } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index c1529c6b6c..3e4321c6f9 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4367,6 +4367,44 @@ class SparkRepoTest : BaseUnitTest() { assertTrue("hash" !in store.data.first().sparkSendPreviousRowWriters, "the row's writer stayed in doubt") } + @Test + fun `an earlier payment's fee correction survives a failed write after a cut retry row write`() = test { + var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 7uL)) + val olderStamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}" } + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendRowIds = mapOf("hash" to "retry"), + sparkSendRowStamps = mapOf("hash" to "9:128:0"), + sparkSendPreviousRowWriters = mapOf("hash" to listOf("older", olderStamp)), + sparkSendEarlierIds = mapOf("hash" to listOf("older")), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + var isWritable = false + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + if (!isWritable) return@doSuspendableAnswer Result.failure(IllegalStateException("write failed")) + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } + val final = sentPayment(fees = 9) + .copy(id = "older", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp) + whenever(sparkService.listPayments()).thenReturn(listOf(final)) + createSut(store).start(0).getOrThrow() + advanceUntilIdle() + + isWritable = true + createSut(store).start(0).getOrThrow() + advanceUntilIdle() + + assertEquals(9uL, row.v1.fee, "a failed write dropped the earlier payment's writer") + } + @Test fun `a failed spark send row takes its own attempt's fee correction`() = test { cacheData.value = cacheData.value.copy(sparkSendRowIds = mapOf("hash" to "retry")) From ec4051d6d9f4f41467affd3d5023f515333abcd1 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 10:50:44 +0100 Subject: [PATCH 63/96] fix: spark skips writes for an unchanged send row Verified: CacheStoreTest unchanged-row test fails on c612226 and passes; just compile, test and lint pass. --- .../main/java/to/bitkit/data/CacheStore.kt | 2 +- .../java/to/bitkit/data/CacheStoreTest.kt | 24 +++++++++++++++++++ 2 files changed, 25 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 2315e678fc..789b60e0c0 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -183,7 +183,7 @@ class CacheStore internal constructor( val hash = paymentHash.lowercase() val data = store.data.first() val isKept = data.sparkSendRowIds[hash] == paymentId && data.sparkSendRowStamps[hash] == stamp - if (isKept && !beforeRow && hash !in data.sparkSendPreviousRowWriters) return + if (isKept && hash !in data.sparkSendPreviousRowWriters) return store.updateData { val ids = (it.sparkSendRowIds - hash + (hash to paymentId)).entries.toList().takeLast(MAX_SPARK_SEND_HASHES) val stamps = stamp?.let { value -> it.sparkSendRowStamps + (hash to value) } diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index a68f347299..4d62f12dc8 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -2,6 +2,7 @@ package to.bitkit.data import android.app.Application import android.content.Context +import androidx.datastore.core.DataStore import androidx.test.core.app.ApplicationProvider import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking @@ -321,4 +322,27 @@ class CacheStoreTest : BaseUnitTest() { assertFalse("hash" in data.sparkTakenSendIds) assertTrue("hash" in data.sparkUncertainSends) } + + @Test + fun `keepSparkSendRowId before an unchanged row writes nothing`() = test { + val store = CountingDataStore(InMemoryDataStore(AppCacheData())) + val cache = CacheStore(store) + cache.keepSparkSendRowId("hash", "id", "1:2:3", beforeRow = true) + cache.commitSparkSendRowId("hash") + val writes = store.writes + + cache.keepSparkSendRowId("hash", "id", "1:2:3", beforeRow = true, rowStamp = "1:2:3") + cache.commitSparkSendRowId("hash") + + assertEquals(0, store.writes - writes) + assertEquals("id", cache.data.first().sparkSendRowIds["hash"]) + assertFalse("hash" in cache.data.first().sparkSendPreviousRowWriters) + } + + private class CountingDataStore(private val inner: DataStore) : DataStore { + var writes = 0 + override val data = inner.data + override suspend fun updateData(transform: suspend (t: T) -> T): T = inner.updateData(transform) + .also { writes++ } + } } From 8e3da333d4831b3e2c4d3682101f4f51ed828fe8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 11:32:37 +0100 Subject: [PATCH 64/96] fix: spark keeps a retried send's row writer Verified: CacheStoreTest earlier-ids writer test fails on ec4051d and passes; just compile, test and lint pass. --- app/src/main/java/to/bitkit/data/CacheStore.kt | 12 +++++++++--- .../test/java/to/bitkit/data/CacheStoreTest.kt | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 789b60e0c0..a2e5f32eb7 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -185,7 +185,12 @@ class CacheStore internal constructor( val isKept = data.sparkSendRowIds[hash] == paymentId && data.sparkSendRowStamps[hash] == stamp if (isKept && hash !in data.sparkSendPreviousRowWriters) return store.updateData { - val ids = (it.sparkSendRowIds - hash + (hash to paymentId)).entries.toList().takeLast(MAX_SPARK_SEND_HASHES) + val all = (it.sparkSendRowIds - hash + (hash to paymentId)).entries.toList() + val dropped = all.map { (key) -> key } + .filter { key -> key !in it.sparkSendEarlierIds } + .take((all.size - MAX_SPARK_SEND_HASHES).coerceAtLeast(0)) + .toSet() + val ids = all.filter { (key) -> key !in dropped } val stamps = stamp?.let { value -> it.sparkSendRowStamps + (hash to value) } ?: (it.sparkSendRowStamps - hash) val writer = it.sparkSendRowIds[hash]?.let { id -> listOfNotNull(id, it.sparkSendRowStamps[hash]) } @@ -536,8 +541,9 @@ data class AppCacheData( /** A random id of the attempt each of those sends' entries belongs to, so a stale attempt never writes over it. */ val sparkUncertainSendAttemptIds: Map = mapOf(), /** - * Spark's id of the payment that last wrote each Spark send's Activity row, the latest [MAX_SPARK_SEND_HASHES], so - * an earlier attempt's failure dated the same second as the row never writes over it. + * Spark's id of the payment that last wrote each Spark send's Activity row, the latest [MAX_SPARK_SEND_HASHES] and + * those of sends with [sparkSendEarlierIds], so an earlier attempt's failure dated the same second as the row never + * writes over it. */ val sparkSendRowIds: Map = mapOf(), /** The time, amount and fee of each of those rows as its writer wrote it, so a row written over is told apart. */ diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index 4d62f12dc8..ba750e4986 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -339,6 +339,22 @@ class CacheStoreTest : BaseUnitTest() { assertFalse("hash" in cache.data.first().sparkSendPreviousRowWriters) } + @Test + fun `keepSparkSendRowId keeps the writer of a send with earlier ids past the latest sends`() = test { + sut.keepSparkSendEarlierIds("retried", setOf("earlier")) + sut.keepSparkSendRowId("retried", "original", "1:2:3") + sut.keepSparkSendRowId("plain", "id", "1:2:3") + + repeat(MAX_SPARK_SEND_HASHES) { sut.keepSparkSendRowId("later$it", "id$it", "1:2:3") } + + val data = sut.data.first() + assertEquals("original", data.sparkSendRowIds["retried"]) + assertEquals("1:2:3", data.sparkSendRowStamps["retried"]) + assertFalse("plain" in data.sparkSendRowIds) + assertFalse("later0" in data.sparkSendRowIds) + assertEquals(MAX_SPARK_SEND_HASHES, data.sparkSendRowIds.size) + } + private class CountingDataStore(private val inner: DataStore) : DataStore { var writes = 0 override val data = inner.data From 17286a8814f608c3dfc69503ddbcb7c0aaa39553 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 12:04:34 +0100 Subject: [PATCH 65/96] fix: spark keeps new send row writers at the cap Verified: CacheStoreTest new-writer test fails on 8e3da33 and passes; just compile, test and lint pass. --- .../main/java/to/bitkit/data/CacheStore.kt | 12 +++++------- .../java/to/bitkit/data/CacheStoreTest.kt | 19 +++++++++++++++++-- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index a2e5f32eb7..8950ace137 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -186,10 +186,8 @@ class CacheStore internal constructor( if (isKept && hash !in data.sparkSendPreviousRowWriters) return store.updateData { val all = (it.sparkSendRowIds - hash + (hash to paymentId)).entries.toList() - val dropped = all.map { (key) -> key } - .filter { key -> key !in it.sparkSendEarlierIds } - .take((all.size - MAX_SPARK_SEND_HASHES).coerceAtLeast(0)) - .toSet() + val unprotected = all.map { (key) -> key }.filter { key -> key !in it.sparkSendEarlierIds } + val dropped = unprotected.take((unprotected.size - MAX_SPARK_SEND_HASHES).coerceAtLeast(0)).toSet() val ids = all.filter { (key) -> key !in dropped } val stamps = stamp?.let { value -> it.sparkSendRowStamps + (hash to value) } ?: (it.sparkSendRowStamps - hash) @@ -541,9 +539,9 @@ data class AppCacheData( /** A random id of the attempt each of those sends' entries belongs to, so a stale attempt never writes over it. */ val sparkUncertainSendAttemptIds: Map = mapOf(), /** - * Spark's id of the payment that last wrote each Spark send's Activity row, the latest [MAX_SPARK_SEND_HASHES] and - * those of sends with [sparkSendEarlierIds], so an earlier attempt's failure dated the same second as the row never - * writes over it. + * Spark's id of the payment that last wrote each Spark send's Activity row, those of sends with + * [sparkSendEarlierIds] and the latest [MAX_SPARK_SEND_HASHES] of the others, so an earlier attempt's failure dated + * the same second as the row never writes over it. */ val sparkSendRowIds: Map = mapOf(), /** The time, amount and fee of each of those rows as its writer wrote it, so a row written over is told apart. */ diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index ba750e4986..7409100596 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -351,8 +351,23 @@ class CacheStoreTest : BaseUnitTest() { assertEquals("original", data.sparkSendRowIds["retried"]) assertEquals("1:2:3", data.sparkSendRowStamps["retried"]) assertFalse("plain" in data.sparkSendRowIds) - assertFalse("later0" in data.sparkSendRowIds) - assertEquals(MAX_SPARK_SEND_HASHES, data.sparkSendRowIds.size) + assertEquals("id0", data.sparkSendRowIds["later0"]) + assertEquals(MAX_SPARK_SEND_HASHES + 1, data.sparkSendRowIds.size) + } + + @Test + fun `keepSparkSendRowId keeps a new writer beside the latest sends with earlier ids`() = test { + repeat(MAX_SPARK_SEND_HASHES) { + sut.keepSparkSendEarlierIds("retried$it", setOf("earlier$it")) + sut.keepSparkSendRowId("retried$it", "original$it", "1:2:3") + } + + sut.keepSparkSendRowId("new", "id", "1:2:3") + + val data = sut.data.first() + assertEquals("id", data.sparkSendRowIds["new"]) + assertEquals("1:2:3", data.sparkSendRowStamps["new"]) + assertEquals("original0", data.sparkSendRowIds["retried0"]) } private class CountingDataStore(private val inner: DataStore) : DataStore { From b61d1216bcb99980ca7eb8bc8f0c629e9ff61321 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 14:54:11 +0100 Subject: [PATCH 66/96] fix: spark holds taken sends through the grace Verified: new SparkRepoTest and CacheStoreTest cases fail on 17286a8 and pass; just compile, test and lint pass. --- .../main/java/to/bitkit/data/CacheStore.kt | 7 +- .../java/to/bitkit/repositories/SparkRepo.kt | 22 ++++-- .../java/to/bitkit/data/CacheStoreTest.kt | 11 +++ .../to/bitkit/repositories/SparkRepoTest.kt | 69 ++++++++++++++++++- 4 files changed, 98 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 8950ace137..585b1cb869 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -191,9 +191,10 @@ class CacheStore internal constructor( val ids = all.filter { (key) -> key !in dropped } val stamps = stamp?.let { value -> it.sparkSendRowStamps + (hash to value) } ?: (it.sparkSendRowStamps - hash) - val writer = it.sparkSendRowIds[hash]?.let { id -> listOfNotNull(id, it.sparkSendRowStamps[hash]) } - ?: rowStamp?.let { value -> listOf("", value) } - ?.takeIf { beforeRow } + val writer = ( + it.sparkSendRowIds[hash]?.let { id -> listOfNotNull(id, it.sparkSendRowStamps[hash]) } + ?: rowStamp?.let { value -> listOf("", value) } + ).takeIf { beforeRow } val previous = writer?.let { value -> it.sparkSendPreviousRowWriters + (hash to value) } ?: (it.sparkSendPreviousRowWriters - hash) val kept = ids.associate { (key, id) -> key to id } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 3e5a6032ad..aeada211ff 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -846,11 +846,12 @@ class SparkRepo @Inject constructor( val rowId = cache.sendRowWriter(hash, send) val earlierIds = attempt.earlierIds.orEmpty() + cache.sparkSendEarlierIds[hash].orEmpty() val isWrittenOver = !cache.isRowStampKept(hash, send) + val failed = send.copy(status = PaymentState.FAILED) when { - attempt.ownId != null -> cacheStore.keepSparkSendRowId(paymentHash, attempt.ownId, send.sendRowStamp()) + attempt.ownId != null -> cacheStore.keepSparkSendRowId(paymentHash, attempt.ownId, failed.sendRowStamp()) rowId != null && rowId in earlierIds && isWrittenOver -> cacheStore.removeSparkSendRowId(paymentHash) } - activityRepo.get().upsertActivity(Activity.Lightning(send.copy(status = PaymentState.FAILED))) + activityRepo.get().upsertActivity(Activity.Lightning(failed)) .onFailure { Logger.warn("Failed to mark Spark send '$paymentHash' failed", it, context = TAG) } .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } } @@ -957,6 +958,17 @@ class SparkRepo @Inject constructor( } } + /** + * Sends Spark took whose attempts are kept past their invoice's expiry until [dropExpiredTakenAttempts] ends them, + * also ones kept from before a restart not yet taken back, so one Spark doesn't list yet still reads as pending. + */ + private suspend fun retainedSendHashes(): Set { + val cache = cacheStore.data.first() + val journaled = cache.sparkUncertainSendStarts.keys + cache.sparkUncertainSendEarlierIds.keys + + cache.sparkTakenSendIds.keys + return takenAttempts.keys + (journaled - cache.sparkUncertainSends.keys) + } + /** Sends whose outcome Spark didn't report, also ones kept from before a restart not yet taken back. */ private suspend fun uncertainSendHashes(): Set = uncertainSends.keys + cacheStore.data.first().sparkUncertainSends.keys @@ -1738,7 +1750,7 @@ class SparkRepo @Inject constructor( suspend fun lightningSendStatuses(): Map? = withContext(bgDispatcher) { if (!sparkService.isSupported) return@withContext emptyMap() if (!canListPayments()) return@withContext null - val unlisted = unexpiredStartedSends() + val unlisted = unexpiredStartedSends() + retainedSendHashes() val uncertain = uncertainSendHashes() val payments = runSuspendCatching { sparkService.listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } @@ -1769,7 +1781,7 @@ class SparkRepo @Inject constructor( */ suspend fun lightningSend(paymentHash: String): SparkLightningSend = withContext(bgDispatcher) { val hash = paymentHash.lowercase() - val isUnlistedHeld = hash in unexpiredStartedSends() + val isUnlistedHeld = hash in unexpiredStartedSends() || hash in retainedSendHashes() val (send, listed) = listedLightningSendPayment(paymentHash) val isUncertain = hash in uncertainSendHashes() val isHeld = when (send) { @@ -2164,7 +2176,7 @@ class SparkRepo @Inject constructor( return rowId != id && rowId !in earlierIds } - private fun LightningActivity.sendRowStamp() = "$timestamp:$value:$fee" + private fun LightningActivity.sendRowStamp() = "$timestamp:$value:$fee:$status" /** * The payment that wrote [row] of [hash]: the kept writer, unless a stop cut its row write short, when the row diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index 7409100596..ee40f19c6f 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -370,6 +370,17 @@ class CacheStoreTest : BaseUnitTest() { assertEquals("original0", data.sparkSendRowIds["retried0"]) } + @Test + fun `keepSparkSendRowId outside a row write keeps no previous writer`() = test { + sut.keepSparkSendRowId("hash", "older", "1:2:3") + + sut.keepSparkSendRowId("hash", "retry", "4:5:6") + + val data = sut.data.first() + assertEquals("retry", data.sparkSendRowIds["hash"]) + assertFalse("hash" in data.sparkSendPreviousRowWriters) + } + private class CountingDataStore(private val inner: DataStore) : DataStore { var writes = 0 override val data = inner.data diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 3e4321c6f9..6169063a61 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4271,7 +4271,9 @@ class SparkRepoTest : BaseUnitTest() { sparkUncertainSends = mapOf("hash" to sentAt), sparkUncertainSendStarts = mapOf("hash" to sentAt), sparkSendRowIds = mapOf("hash" to "older"), - sparkSendRowStamps = mapOf("hash" to pending.v1.let { "${it.timestamp}:${it.value}:${it.fee}" }), + sparkSendRowStamps = mapOf( + "hash" to pending.v1.let { "${it.timestamp}:${it.value}:${it.fee}:${it.status}" } + ), sparkSendEarlierIds = mapOf("hash" to listOf("older")), ) ), @@ -4335,7 +4337,7 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `an earlier payment's row takes its final fee after a stop cut a retry's row write short`() = test { var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 7uL)) - val olderStamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}" } + val olderStamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}:${it.status}" } // The retry's writer was kept ahead of its row, and the app stopped before the row was written. val store = CacheStore( InMemoryDataStore( @@ -4367,10 +4369,45 @@ class SparkRepoTest : BaseUnitTest() { assertTrue("hash" !in store.data.first().sparkSendPreviousRowWriters, "the row's writer stayed in doubt") } + @Test + fun `an earlier payment's failed row takes its final fee after a stop cut a retry alike in time amount and fee`() = + test { + var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 7uL)) + val stamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}" } + // The pending retry's writer was kept ahead of its row, alike in all but status to the earlier failed one. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendRowIds = mapOf("hash" to "retry"), + sparkSendRowStamps = mapOf("hash" to "$stamp:${PaymentState.PENDING}"), + sparkSendPreviousRowWriters = mapOf("hash" to listOf("older", "$stamp:${PaymentState.FAILED}")), + sparkSendEarlierIds = mapOf("hash" to listOf("older")), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } + val final = sentPayment(fees = 9) + .copy(id = "older", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp) + whenever(sparkService.listPayments()).thenReturn(listOf(final)) + + createSut(store).start(0).getOrThrow() + advanceUntilIdle() + + assertEquals(9uL, row.v1.fee, "the earlier payment's final fee was dropped") + } + @Test fun `an earlier payment's fee correction survives a failed write after a cut retry row write`() = test { var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 7uL)) - val olderStamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}" } + val olderStamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}:${it.status}" } val store = CacheStore( InMemoryDataStore( AppCacheData( @@ -4637,6 +4674,8 @@ class SparkRepoTest : BaseUnitTest() { sync() assertTrue(events.none { it is Event.PaymentFailed }, "the expiry ended a retry Spark may still list") assertTrue("hash" in store.data.first().sparkSendHashes) + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) + assertEquals(PaymentStatus.PENDING, sut.lightningSendStatuses()?.get("hash")) // Past the grace, while Spark's latest sync was made before it ended. now += 10.minutes @@ -4671,6 +4710,30 @@ class SparkRepoTest : BaseUnitTest() { return row } + @Test + fun `a taken spark retry kept from before a restart reads as pending within the grace past expiry`() = test { + val sentAt = now.epochSeconds + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to sentAt + 3_600), + sparkUncertainSendStarts = mapOf("hash" to sentAt), + sparkTakenSendIds = mapOf("hash" to "retry"), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.listPayments()).thenReturn(emptyList()) + now += 65.minutes + val sut = createSut(store) + + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) + sut.lightningSendStatuses()?.let { assertEquals(PaymentStatus.PENDING, it["hash"]) } + } + @Test fun `a taken spark retry's own failure listed after a restart frees its invoice for paykit`() = test { val sentAt = now.epochSeconds From f4f847eb5448d6e87ef6510ca9cc2200865d721a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 15:57:20 +0100 Subject: [PATCH 67/96] fix: spark keeps settled sends settled after a failed call Verified: new SparkRepoTest and CacheStoreTest cases fail on b61d121 and pass; just compile, test and lint pass. --- .../main/java/to/bitkit/data/CacheStore.kt | 5 +- .../java/to/bitkit/repositories/SparkRepo.kt | 58 +++++++--- .../java/to/bitkit/data/CacheStoreTest.kt | 10 ++ .../to/bitkit/repositories/SparkRepoTest.kt | 109 ++++++++++++++++++ 4 files changed, 163 insertions(+), 19 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 585b1cb869..dd0f02dc82 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -191,8 +191,11 @@ class CacheStore internal constructor( val ids = all.filter { (key) -> key !in dropped } val stamps = stamp?.let { value -> it.sparkSendRowStamps + (hash to value) } ?: (it.sparkSendRowStamps - hash) + // A writer a cut write left the row to stays its writer, as the row still matches its stamp. + val staged = it.sparkSendPreviousRowWriters[hash]?.takeIf { value -> value.getOrNull(1) == rowStamp } val writer = ( - it.sparkSendRowIds[hash]?.let { id -> listOfNotNull(id, it.sparkSendRowStamps[hash]) } + staged + ?: it.sparkSendRowIds[hash]?.let { id -> listOfNotNull(id, it.sparkSendRowStamps[hash]) } ?: rowStamp?.let { value -> listOf("", value) } ).takeIf { beforeRow } val previous = writer?.let { value -> it.sparkSendPreviousRowWriters + (hash to value) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index aeada211ff..0f7f601619 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -645,10 +645,17 @@ class SparkRepo @Inject constructor( } } // A send whose call failed may still have gone out, so it is in doubt before the in-flight - // attempt is dropped. + // attempt is dropped, unless its outcome was handled meanwhile, which dropped that attempt. if (result.isFailure) { - uncertainSends[paymentHash.lowercase()] = - UncertainSend(clock.now().epochSeconds.toULong(), expiresAt, attempt) + withContext(NonCancellable) { + sendReleaseMutex.withLock { + if (inFlightAttempts[paymentHash.lowercase()]?.attemptId != attemptId) { + return@withLock + } + uncertainSends[paymentHash.lowercase()] = + UncertainSend(clock.now().epochSeconds.toULong(), expiresAt, attempt) + } + } } } } @@ -711,15 +718,23 @@ class SparkRepo @Inject constructor( } private suspend fun settleUncertainSend(paymentHash: String, attempt: SendAttempt, expiresAt: ULong) { + val key = paymentHash.lowercase() val failedAt = clock.now().epochSeconds - uncertainSends[paymentHash.lowercase()] = UncertainSend(failedAt.toULong(), expiresAt, attempt) - cacheStore.addSparkUncertainSend( - paymentHash, - failedAt, - attempt.sentAt?.toLong(), - attempt.earlierIds, - attempt.attemptId, - ) + // Only while this attempt still holds the send, as a sync or payment event that settled it meanwhile keeps it + // settled, and under the lock their cleanup takes, so its journal entry is never written back after it. + val isHeld = sendReleaseMutex.withLock { + if (uncertainSends[key]?.attempt?.attemptId != attempt.attemptId) return@withLock false + uncertainSends[key] = UncertainSend(failedAt.toULong(), expiresAt, attempt) + cacheStore.addSparkUncertainSend( + paymentHash, + failedAt, + attempt.sentAt?.toLong(), + attempt.earlierIds, + attempt.attemptId, + ) + true + } + if (!isHeld) return scope.launch { // The send screen tracks the hash as pending only once the send returns, and resolves tracked ones. withTimeoutOrNull(PENDING_TRACK_WAIT) { @@ -969,6 +984,12 @@ class SparkRepo @Inject constructor( return takenAttempts.keys + (journaled - cache.sparkUncertainSends.keys) } + /** + * Sends in doubt or kept past their expiry by an attempt Spark took, read in the order a sync hands a send from the + * one to the other, so a send handed over meanwhile is found in either. + */ + private suspend fun heldSendHashes(): Set = uncertainSendHashes() + retainedSendHashes() + /** Sends whose outcome Spark didn't report, also ones kept from before a restart not yet taken back. */ private suspend fun uncertainSendHashes(): Set = uncertainSends.keys + cacheStore.data.first().sparkUncertainSends.keys @@ -1750,8 +1771,8 @@ class SparkRepo @Inject constructor( suspend fun lightningSendStatuses(): Map? = withContext(bgDispatcher) { if (!sparkService.isSupported) return@withContext emptyMap() if (!canListPayments()) return@withContext null - val unlisted = unexpiredStartedSends() + retainedSendHashes() val uncertain = uncertainSendHashes() + val unlisted = unexpiredStartedSends() + retainedSendHashes() val payments = runSuspendCatching { sparkService.listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrElse { return@withContext null } @@ -1781,11 +1802,12 @@ class SparkRepo @Inject constructor( */ suspend fun lightningSend(paymentHash: String): SparkLightningSend = withContext(bgDispatcher) { val hash = paymentHash.lowercase() - val isUnlistedHeld = hash in unexpiredStartedSends() || hash in retainedSendHashes() + val isUnlistedHeld = hash in unexpiredStartedSends() || hash in heldSendHashes() val (send, listed) = listedLightningSendPayment(paymentHash) val isUncertain = hash in uncertainSendHashes() val isHeld = when (send) { - SparkLightningSend.NotFound, SparkLightningSend.Unavailable -> isUncertain || isUnlistedHeld + // Read again after the list, as a sync can hand the send from its doubt to Spark meanwhile. + SparkLightningSend.NotFound, SparkLightningSend.Unavailable -> isUnlistedHeld || hash in heldSendHashes() // An earlier attempt's failure leaves a retry Spark took or still sends pending. is SparkLightningSend.Found -> send.status == PaymentStatus.FAILED && @@ -2180,12 +2202,12 @@ class SparkRepo @Inject constructor( /** * The payment that wrote [row] of [hash]: the kept writer, unless a stop cut its row write short, when the row - * still matches the stamp of the writer it had before. + * still matches the stamp of the writer it had before, also where both stamps match, as the row is then alike to + * either and the one it had before keeps its fee corrections. */ private fun AppCacheData.sendRowWriter(hash: String, row: LightningActivity): String? { - val stamp = row.sendRowStamp() - val previous = sparkSendPreviousRowWriters[hash]?.takeIf { it.getOrNull(1) == stamp } - if (sparkSendRowStamps[hash] == stamp || previous == null) return sparkSendRowIds[hash] + val previous = sparkSendPreviousRowWriters[hash]?.takeIf { it.getOrNull(1) == row.sendRowStamp() } + ?: return sparkSendRowIds[hash] return previous.first().ifEmpty { null } } diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index ee40f19c6f..d69ba83c57 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -381,6 +381,16 @@ class CacheStoreTest : BaseUnitTest() { assertFalse("hash" in data.sparkSendPreviousRowWriters) } + @Test + fun `keepSparkSendRowId keeps the writer a cut write left the row to across another cut write`() = test { + sut.keepSparkSendRowId("hash", "older", "1:2:3") + sut.keepSparkSendRowId("hash", "first", "4:5:6", beforeRow = true, rowStamp = "1:2:3") + + sut.keepSparkSendRowId("hash", "second", "7:8:9", beforeRow = true, rowStamp = "1:2:3") + + assertEquals(listOf("older", "1:2:3"), sut.data.first().sparkSendPreviousRowWriters["hash"]) + } + private class CountingDataStore(private val inner: DataStore) : DataStore { var writes = 0 override val data = inner.data diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 6169063a61..e74514ad79 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4404,6 +4404,40 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(9uL, row.v1.fee, "the earlier payment's final fee was dropped") } + @Test + fun `an earlier payment's failed row takes its final fee after a stop cut a retry's alike failed row`() = test { + var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 7uL)) + val stamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}:${it.status}" } + // The failed retry's writer was kept ahead of its row, alike in all to the earlier failed one. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendRowIds = mapOf("hash" to "retry"), + sparkSendRowStamps = mapOf("hash" to stamp), + sparkSendPreviousRowWriters = mapOf("hash" to listOf("older", stamp)), + sparkSendEarlierIds = mapOf("hash" to listOf("older")), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } + val final = sentPayment(fees = 9) + .copy(id = "older", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp) + whenever(sparkService.listPayments()).thenReturn(listOf(final)) + + createSut(store).start(0).getOrThrow() + advanceUntilIdle() + + assertEquals(9uL, row.v1.fee, "the earlier payment's final fee was dropped") + } + @Test fun `an earlier payment's fee correction survives a failed write after a cut retry row write`() = test { var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 7uL)) @@ -5409,6 +5443,81 @@ class SparkRepoTest : BaseUnitTest() { assertTrue(events.any { it is Event.PaymentFailed }, "the send screen never learned the send failed") } + @Test + fun `a spark send handed from its doubt to spark during a lookup's list read stays pending`() = test { + val sentAt = now.epochSeconds - 7_200 + // A retry in doubt from before a restart, whose invoice expired before Spark's last sync. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to sentAt + 3_600), + sparkUncertainSends = mapOf("hash" to sentAt), + sparkUncertainSendStarts = mapOf("hash" to sentAt), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = (sentAt + 60).toULong())) + val gate = CompletableDeferred() + var isLookup = false + var listed = emptyList() + whenever { sparkService.listPayments() }.doSuspendableAnswer { + if (!isLookup) return@doSuspendableAnswer listed + isLookup = false + gate.await() + emptyList() + } + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + // The lookup reads an empty list, and a sync hands the retry to Spark before the lookup goes on. + isLookup = true + val lookup = async { sut.lightningSend("hash") } + runCurrent() + listed = listOf(sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING)) + sparkEvents.emit(SdkEvent.Synced) + runCurrent() + assertEquals("retry", store.data.first().sparkTakenSendIds["hash"], "the sync didn't hand the retry to Spark") + gate.complete(Unit) + + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), lookup.await()) + } + + @Test + fun `a spark send whose success was handled before its call failed keeps no hold`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val completed = sentPayment(fees = 0).copy(status = PaymentStatus.COMPLETED) + var listed = emptyList() + whenever(sparkService.listPayments()).thenAnswer { listed } + // Spark reports the send's success while its call runs, and the call then fails. + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { + listed = listOf(completed) + sparkEvents.emit(SdkEvent.PaymentSucceeded(completed)) + delay(1) + throw SdkException.Generic("timeout") + } + val sut = createSut(store) + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + + sut.payInvoice("lnbc1", 100uL) + advanceUntilIdle() + + assertEquals(1, events.count { it is Event.PaymentSuccessful }, "the failed call reported the success again") + assertFalse("hash" in store.data.first().sparkUncertainSends, "the failed call held a settled send again") + } + @Test fun `a taken spark retry reads as pending while spark lists only an earlier attempt's failure`() = test { val sentAt = now.epochSeconds From baf9224c762390702e31d9da763615514e7a6d62 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 16:49:10 +0100 Subject: [PATCH 68/96] fix: spark returns a send outcome handled before its call failed Verified: SparkRepoTest handled-success case fails on f4f847e and passes; just compile, test and lint pass. --- .../main/java/to/bitkit/repositories/SparkRepo.kt | 14 ++++++++++---- .../java/to/bitkit/repositories/SparkRepoTest.kt | 5 +++-- 2 files changed, 13 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 0f7f601619..68b435ff67 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -694,12 +694,14 @@ class SparkRepo @Inject constructor( 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) - settleUncertainSend( + val isInDoubt = settleUncertainSend( paymentHash, SendAttempt(sentAt.toULong(), earlierIds, attemptId = attemptId), expiresAt ) - throw PaymentPendingException(paymentHash) + // An outcome handled meanwhile is known, so the caller reads it as it does after a returned send. + if (isInDoubt) throw PaymentPendingException(paymentHash) + return@runSuspendCatching paymentHash } if (payment.status != PaymentStatus.PENDING) { takenAttempts.remove(paymentHash.lowercase()) @@ -717,7 +719,10 @@ class SparkRepo @Inject constructor( } } - private suspend fun settleUncertainSend(paymentHash: String, attempt: SendAttempt, expiresAt: ULong) { + /** + * Holds [attempt]'s send in doubt and polls Spark for its outcome; false when that outcome was handled meanwhile. + */ + private suspend fun settleUncertainSend(paymentHash: String, attempt: SendAttempt, expiresAt: ULong): Boolean { val key = paymentHash.lowercase() val failedAt = clock.now().epochSeconds // Only while this attempt still holds the send, as a sync or payment event that settled it meanwhile keeps it @@ -734,7 +739,7 @@ class SparkRepo @Inject constructor( ) true } - if (!isHeld) return + if (!isHeld) return false scope.launch { // The send screen tracks the hash as pending only once the send returns, and resolves tracked ones. withTimeoutOrNull(PENDING_TRACK_WAIT) { @@ -749,6 +754,7 @@ class SparkRepo @Inject constructor( // Spark's next sync settles it, as a send it resumes then ends with its own payment event. Logger.warn("Stopped polling Spark send '$paymentHash' until Spark syncs again", context = TAG) } + return true } /** Settles an uncertain send once Spark shows its outcome; true once it is settled, also by another caller. */ diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index e74514ad79..b11bbc6191 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5488,7 +5488,7 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `a spark send whose success was handled before its call failed keeps no hold`() = test { + fun `a spark send whose success was handled before its call failed returns it and keeps no hold`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) @@ -5511,9 +5511,10 @@ class SparkRepoTest : BaseUnitTest() { backgroundScope.launch { sut.nodeEvents.collect { events += it } } runCurrent() - sut.payInvoice("lnbc1", 100uL) + val result = sut.payInvoice("lnbc1", 100uL) advanceUntilIdle() + assertEquals("hash", result.getOrNull(), "the failed call read a handled success as pending") assertEquals(1, events.count { it is Event.PaymentSuccessful }, "the failed call reported the success again") assertFalse("hash" in store.data.first().sparkUncertainSends, "the failed call held a settled send again") } From ec5f4ef5f1540a412122fe3ee1a3da13e2b529bc Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 17:27:34 +0100 Subject: [PATCH 69/96] fix: spark holds a retry in its send call past older failures Verified: SparkRepoTest older-failure-during-call case fails on baf9224 and passes; just compile, test and lint pass. --- .../java/to/bitkit/repositories/SparkRepo.kt | 8 +++-- .../to/bitkit/repositories/SparkRepoTest.kt | 34 +++++++++++++++++++ 2 files changed, 39 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 68b435ff67..d92bd3886d 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -2276,10 +2276,12 @@ class SparkRepo @Inject constructor( attempt.ownId?.let { return id != it } attempt.earlierIds?.let { ids -> if (id in ids) return true - // Only a send in doubt has no id of its own, and the list read before it went out can lack an older - // attempt, so a failure that list doesn't name is earlier when Spark dates it clearly before the send. + // Only a send in doubt or still in Spark's send call has no id of its own, and the list read before it went + // out can lack an older attempt, so a failure that list doesn't name is earlier when Spark dates it clearly + // before the send. + val key = hash.lowercase() val sentAt = attempt.sentAt - return sentAt != null && uncertainSends.containsKey(hash.lowercase()) && + return sentAt != null && (uncertainSends.containsKey(key) || inFlightAttempts.containsKey(key)) && timestamp + RAIL_CLOCK_SKEW_SECONDS <= sentAt } // A send kept before start times were stored can't tell its own failure from an earlier one, so it stays held diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index b11bbc6191..7d82391946 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5487,6 +5487,40 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), lookup.await()) } + @Test + fun `an older failure the pre-send list left out keeps a retry held while its send call runs`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + var listed = emptyList() + whenever(sparkService.listPayments()).thenAnswer { listed } + // An older attempt Spark didn't list before the retry went out fails while the retry's call runs, which then + // times out. + val older = sentPayment(fees = 0) + .copy(id = "older", status = PaymentStatus.FAILED, timestamp = (now - 1.minutes).epochSeconds.toULong()) + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { + listed = listOf(older) + sparkEvents.emit(SdkEvent.PaymentFailed(older)) + delay(1) + throw SdkException.Generic("timeout") + } + val sut = createSut(store) + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + + val result = sut.payInvoice("lnbc1", 100uL) + runCurrent() + + assertIs(result.exceptionOrNull(), "the older failure ended the retry's call") + assertTrue(events.none { it is Event.PaymentFailed }, "the older failure ended a retry Spark may finish") + assertTrue("hash" in store.data.first().sparkUncertainSends, "the older failure dropped the retry's hold") + } + @Test fun `a spark send whose success was handled before its call failed returns it and keeps no hold`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) From 0287a12f0a11a5c406d31d6af4b7428d309b2f3f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 17:36:18 +0100 Subject: [PATCH 70/96] fix: spark max funding caps the claim fee at the swiped one Verified: SparkFundingViewModelTest max-swipe claim fee case fails on ec5f4ef and passes; just compile, test and lint pass. --- .../screens/transfer/SparkFundingViewModel.kt | 4 ++- .../transfer/SparkFundingViewModelTest.kt | 27 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt index 232f3f352a..7aa7471eef 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SparkFundingViewModel.kt @@ -323,7 +323,9 @@ class SparkFundingViewModel @Inject constructor( } val walletId = shown.hwWalletId if (walletId == null) { - send(quote) + // A max transfer can reach spending with a higher Instant claim fee than the one swiped, so the early + // claim approves at most the fee shown, and asks first for more. + send(quote.copy(instantFeeSats = minOf(quote.instantFeeSats, shownQuote.instantFeeSats))) return@launch } _uiState.update { it.copy(isSending = false) } diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt index fc820e4d22..2b958f79a7 100644 --- a/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt @@ -315,6 +315,33 @@ class SparkFundingViewModelTest : BaseUnitTest() { assertEquals("Changed", toasts.single().title) } + @Test + fun `swipe on a max transfer approves no higher instant claim fee than the one shown`() = test { + whenever { + lightningRepo.sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), + ) + }.thenReturn(Result.success(OnchainSendOutcome.Accepted("txid", 99_700uL))) + val sut = createSut() + advanceUntilIdle() + sut.onAmountChange(sut.uiState.value.maxSats) + sut.onAmountContinue() + advanceUntilIdle() + // The network fee fell more than the claim fee rose, so more reaches spending and the swipe sends. + whenever { lightningRepo.estimateSendAllFee(any(), any(), any()) }.thenReturn(Result.success(300uL)) + whenever { sparkRepo.estimateDepositClaimFeeSats(any()) }.thenReturn(Result.success(1_400uL)) + + sut.onConfirm() + advanceUntilIdle() + + verify(sparkRepo).followDepositClaim("txid", SparkClaimSpeed.Instant, 1_350uL) + } + @Test fun `swipe refuses with real copy when savings no longer cover the transfer`() = test { val sut = createSut() From db0142d1b09a46d274ab9462453ad39c477cd014 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 17:45:42 +0100 Subject: [PATCH 71/96] fix: pending send resolves an outcome handled before tracking Verified: AppViewModelSendFlowTest handled-before-tracking case fails on 0287a12 and passes; just compile, test and lint pass. --- .../java/to/bitkit/viewmodels/AppViewModel.kt | 21 ++++++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 33 +++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index d8284d51b3..dc24e74a60 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -7988,6 +7988,7 @@ class AppViewModel @Inject constructor( if (incomingPaymentRequest != null) refreshIncomingPaykitPaymentRequests() setSendEffect(SendEffect.NavigateToPending(pendingHash, displayAmountSats.toLong())) lnurlComment?.let { activityRepo.setLightningMessageIfEmpty(paymentHash, it) } + resolveSettledPendingSend(pendingHash) return@onFailure } releasePrivatePaymentListIfNeeded(contactPaymentContext) @@ -8007,6 +8008,26 @@ class AppViewModel @Inject constructor( } } + /** Resolves a pending send whose outcome was handled before it was tracked, which no later event resolves. */ + private suspend fun resolveSettledPendingSend(paymentHash: String) { + val event = lightningRepo.settledSparkSendEvent(paymentHash) ?: return + if (!pendingPaymentRepo.isPending(paymentHash)) return + when (event) { + is Event.PaymentSuccessful if event.paymentHash == paymentHash -> { + syncContactForActivity(paymentHash) + pendingPaymentRepo.resolve(PendingPaymentResolution.Success(paymentHash, amountWithFeeSats = null)) + } + + is Event.PaymentFailed if event.paymentHash == paymentHash -> { + releaseFailedSwapHold(paymentHash) + clearPendingContactPaymentContext(paymentHash) + pendingPaymentRepo.resolve(PendingPaymentResolution.Failure(paymentHash, event.reason)) + } + + else -> Unit + } + } + private suspend fun savePendingLnurlComment(invoice: LightningInvoice, paymentHash: String): String? { val state = _sendUiState.value if (state.lnurl !is LnurlParams.LnurlPay || state.comment.isBlank()) return null diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 43b7a4a766..b0293ea190 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -18211,6 +18211,39 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(pendingPaymentRepo, never()).track(paymentHash) } + @Test + fun `pending spark send whose success was handled before it was tracked resolves as sent`() = test { + val bolt11 = "lnbcrt1sparkpending" + val paymentHash = "spark_hash" + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)) + .thenReturn(Result.failure(PaymentPendingException(paymentHash))) + // Spark's success was handled after the send returned pending, before the send screen tracked it. + whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + Event.PaymentSuccessful( + paymentId = paymentHash, + paymentHash = paymentHash, + paymentPreimage = "preimage", + feePaidMsat = 0uL, + ), + ) + whenever(pendingPaymentRepo.isPending(paymentHash)).thenReturn(true) + setSendState( + SendUiState( + address = bolt11, + amount = 1000u, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, amountSats = 1000u), + ), + ) + + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + verify(pendingPaymentRepo).track(paymentHash) + verify(pendingPaymentRepo).resolve(PendingPaymentResolution.Success(paymentHash)) + } + @Test fun `private lightning pending payment consumes private list`() = test { val bolt11 = "lnbcrt1pending" From 618cc1a0bddd3f15e52bca7bd2bfa10b8f11bd85 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 18:36:48 +0100 Subject: [PATCH 72/96] fix: hold spark sends through their call and wipe Verified: just format, compile, test, lint; new SparkRepoTest and AppViewModelSendFlowTest cases fail without the fix --- .../java/to/bitkit/repositories/SparkRepo.kt | 39 +++++--- .../java/to/bitkit/ui/sheets/SendSheet.kt | 2 + .../java/to/bitkit/viewmodels/AppViewModel.kt | 9 +- .../to/bitkit/repositories/SparkRepoTest.kt | 90 ++++++++++++++++++- .../viewmodels/AppViewModelSendFlowTest.kt | 41 +++++++++ 5 files changed, 163 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index d92bd3886d..8046535187 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -335,9 +335,13 @@ class SparkRepo @Inject constructor( sendsRecordedWithoutFee.clear() unsavedPayments.clear() sendsInFlight.clear() - uncertainSends.clear() - takenAttempts.clear() - restoredTakenAttempts.clear() + // Under the lock a send call's hand-over takes, so a call that returns after the wipe holds nothing. + sendReleaseMutex.withLock { + inFlightAttempts.clear() + uncertainSends.clear() + takenAttempts.clear() + restoredTakenAttempts.clear() + } hasSyncedActivities = false hasMergedRemoteExitState = false isLostForExit = false @@ -1755,11 +1759,19 @@ class SparkRepo @Inject constructor( */ suspend fun settledSendEvent(paymentHash: String): Event? = withContext(bgDispatcher) { if (!sparkService.isConnected) return@withContext null + val hash = paymentHash.lowercase() + // A failure leaves a send in doubt or in Spark's send call pending, as the other lookups read it, also one + // that a sync hands from the one to the other meanwhile. + val isHeldBefore = hash in uncertainSendHashes() || inFlightAttempts.containsKey(hash) runSuspendCatching { sparkService.listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrNull() ?.latestSend(paymentHash) ?.takeUnless { it.isEarlierFailureOfUncertainSend() } + ?.takeUnless { + it.status == PaymentStatus.FAILED && + (isHeldBefore || hash in uncertainSendHashes() || inFlightAttempts.containsKey(hash)) + } ?.toNodeEvent() } @@ -2264,25 +2276,26 @@ class SparkRepo @Inject constructor( isEarlierFailureOfUncertainSend() || hasRecordedSendSince(records, sendHash(PaymentStatus.FAILED)) /** - * Whether this failure is an earlier attempt's, of a retry still in Spark's send call or in doubt: one of the - * attempts Spark listed before the retry went out, or, with none listed, one Spark dates before the retry plus its - * clock skew, so a failure that may be either never ends the retry's hold. A retry in doubt also counts a failure - * that list doesn't name as earlier when Spark dates it before the retry minus that skew. + * Whether this failure may be an earlier attempt's, of a retry still in Spark's send call or in doubt, so it never + * ends the retry's hold: any failure while the call runs, one of the attempts Spark listed before the retry went + * out, or, with none listed, one Spark dates before the retry plus its clock skew. A retry in doubt also counts a + * failure that list doesn't name as earlier when Spark dates it before the retry minus that skew. */ private fun Payment.isEarlierFailureOfUncertainSend(): Boolean { val hash = sendHash(PaymentStatus.FAILED) ?: return false val attempt = heldAttempt(hash) ?: return false // A payment Spark took fails with its own id, so a failure with another id is an earlier attempt's. attempt.ownId?.let { return id != it } + // The call's own result, or its move into doubt, settles a send still in Spark's send call. + val key = hash.lowercase() + if (!uncertainSends.containsKey(key) && inFlightAttempts.containsKey(key)) return true attempt.earlierIds?.let { ids -> if (id in ids) return true - // Only a send in doubt or still in Spark's send call has no id of its own, and the list read before it went - // out can lack an older attempt, so a failure that list doesn't name is earlier when Spark dates it clearly - // before the send. - val key = hash.lowercase() + // The list read before a send in doubt went out can lack an older attempt, so a failure that list doesn't + // name is earlier when Spark dates it clearly before the send, while its own failure, dated at its start, + // ends its hold. val sentAt = attempt.sentAt - return sentAt != null && (uncertainSends.containsKey(key) || inFlightAttempts.containsKey(key)) && - timestamp + RAIL_CLOCK_SKEW_SECONDS <= sentAt + return sentAt != null && uncertainSends.containsKey(key) && timestamp + RAIL_CLOCK_SKEW_SECONDS <= sentAt } // A send kept before start times were stored can't tell its own failure from an earlier one, so it stays held // until its invoice expires, when the expiry rule settles it and its row. diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index a89ae3e49f..51cdac5b48 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -795,6 +795,7 @@ fun SendSheet( ) }, onPaymentSuccess = { paymentHash, amountWithFee -> + // A success shown before the send went pending is the same payment, so it shows again. appViewModel.onSendSuccess( NewTransactionSheetDetails( type = NewTransactionSheetType.LIGHTNING, @@ -802,6 +803,7 @@ fun SendSheet( paymentHashOrTxId = paymentHash, sats = amountWithFee, ), + allowDuplicateHash = true, ) }, onPaymentError = { failure -> diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index dc24e74a60..7ab6f964c6 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -8014,7 +8014,8 @@ class AppViewModel @Inject constructor( if (!pendingPaymentRepo.isPending(paymentHash)) return when (event) { is Event.PaymentSuccessful if event.paymentHash == paymentHash -> { - syncContactForActivity(paymentHash) + // The send screen may have moved on to another payment meanwhile, so only this send's contact counts. + syncContactForActivity(paymentHash, isPendingOnly = true) pendingPaymentRepo.resolve(PendingPaymentResolution.Success(paymentHash, amountWithFeeSats = null)) } @@ -9624,17 +9625,19 @@ class AppViewModel @Inject constructor( private fun syncContactForActivity( paymentHashOrTxId: String, walletId: String = WalletScope.default, + isPendingOnly: Boolean = false, ) { val contactContext = synchronized(contactPaymentContextLock) { val pendingContext = pendingContactPaymentContexts.remove(paymentHashOrTxId) - val context = pendingContext ?: activeContactPaymentContext + val context = pendingContext ?: activeContactPaymentContext.takeUnless { isPendingOnly } if (pendingContext == null && context != null) { activeContactPaymentContext = null } if (preparedContactPaymentContext == context) preparedContactPaymentContext = null context } - isSubmittingPaymentRequest = false + // A pending send settling later leaves the send under way alone. + if (!isPendingOnly) isSubmittingPaymentRequest = false contactContext ?: return viewModelScope.launch { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 7d82391946..8f3f6b1b8e 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4799,7 +4799,7 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `a spark send cancelled after its failure was handled holds nothing`() = test { + fun `a spark send cancelled after spark reported a failure during its call stays held`() = test { whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) @@ -4823,7 +4823,93 @@ class SparkRepoTest : BaseUnitTest() { caller.cancel() advanceUntilIdle() - assertNull(sut.earlierLightningSend("lnbc1", "hash"), "a handled failure still held the invoice") + // A failure reported during the call can't be told from an earlier attempt's, so the send stays in doubt. + assertEquals( + EarlierSend.Pending("hash"), + sut.earlierLightningSend("lnbc1", "hash"), + "a failure seen during the call ended the hold", + ) + } + + @Test + fun `a spark send whose call returns after a wipe holds nothing`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + whenever(sparkService.listPayments()).thenReturn(emptyList()) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val returns = CompletableDeferred() + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { returns.await() } + val sut = createSut(store) + sut.start(0).getOrThrow() + runCurrent() + backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } + advanceUntilIdle() + + // The wallet is wiped while Spark's send call runs, and the call then returns the payment it took. + sut.wipe(0).getOrThrow() + store.reset() + returns.complete(sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING)) + advanceUntilIdle() + + assertTrue(store.data.first().sparkTakenSendIds.isEmpty(), "the wiped wallet's send was journaled") + assertFalse( + "hash" in sut.attemptedLightningPaymentHashes().orEmpty(), + "the wiped wallet's send still held the invoice", + ) + } + + @Test + fun `a failure spark reports during a send call is no settled send event`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + var listed = emptyList() + whenever(sparkService.listPayments()).thenAnswer { listed } + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) + // An earlier attempt the pre-send list left out fails while the retry's send call runs. + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { + listed = listOf(failed) + awaitCancellation() + } + val sut = createSut() + sut.start(0).getOrThrow() + runCurrent() + backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } + advanceUntilIdle() + + assertNull(sut.settledSendEvent("hash"), "a failure seen during the call settled the send") + } + + @Test + fun `a spark send whose call returns its failure after spark reported it reads as failed`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + var listed = emptyList() + whenever(sparkService.listPayments()).thenAnswer { listed } + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) + // Spark reports the failure while its send call runs, and the call then returns it. + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { + listed = listOf(failed) + sparkEvents.emit(SdkEvent.PaymentFailed(failed)) + failed + } + val sut = createSut() + sut.start(0).getOrThrow() + runCurrent() + + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + advanceUntilIdle() + + assertIs(sut.settledSendEvent("hash"), "the returned failure wasn't reported") + assertNull(sut.earlierLightningSend("lnbc1", "hash"), "the failed send still held the invoice") } @Test diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index b0293ea190..6f313e3d07 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -18244,6 +18244,47 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(pendingPaymentRepo).resolve(PendingPaymentResolution.Success(paymentHash)) } + @Test + fun `pending spark send resolved as sent leaves the next send's contact alone`() = test { + val bolt11 = "lnbcrt1sparkpending" + val paymentHash = "spark_hash" + val nextContactKey = "pubkynext" + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)) + .thenReturn(Result.failure(PaymentPendingException(paymentHash))) + // The send screen moved on to a payment to a contact before the pending send's success was read. + whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenAnswer { + setActiveContactPaymentContext(nextContactKey) + Event.PaymentSuccessful( + paymentId = paymentHash, + paymentHash = paymentHash, + paymentPreimage = "preimage", + feePaidMsat = 0uL, + ) + } + whenever(pendingPaymentRepo.isPending(paymentHash)).thenReturn(true) + setSendState( + SendUiState( + address = bolt11, + amount = 1000u, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, amountSats = 1000u), + ), + ) + + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + verify(pendingPaymentRepo).resolve(PendingPaymentResolution.Success(paymentHash)) + assertEquals(nextContactKey, activeContactPaymentContext()?.publicKey) + verify(activityRepo, never()).setContact( + contactPublicKey = eq(nextContactKey), + forPaymentId = eq(paymentHash), + syncLdkPayments = any(), + walletId = any(), + ) + } + @Test fun `private lightning pending payment consumes private list`() = test { val bolt11 = "lnbcrt1pending" From cb2050433c0b4b2192d82cd946b2766234751f20 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 18:47:00 +0100 Subject: [PATCH 73/96] fix: spark orders two kept earlier attempts by date Verified: just format, compile, test, lint; the new SparkRepoTest case fails without the fix --- .../java/to/bitkit/repositories/SparkRepo.kt | 10 +++-- .../to/bitkit/repositories/SparkRepoTest.kt | 37 +++++++++++++++++++ 2 files changed, 43 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 8046535187..277fca69d8 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -2200,8 +2200,9 @@ class SparkRepo @Inject constructor( /** * Whether this payment is of an attempt a later one read as earlier before it went out, kept past its hold and a - * restart, while it no longer wrote the [row] of [paymentHash], or Spark dates it before the row or ties it as - * another payment than the one that wrote the row, unless that one is such an earlier attempt. + * restart, while it no longer wrote the [row] of [paymentHash] and the row's writer is no such attempt, or Spark + * dates it before the row or ties it as another payment than the one that wrote the row, unless that one is such an + * earlier attempt. */ private suspend fun Payment.isEarlierThan(row: LightningActivity, paymentHash: String): Boolean { val cache = cacheStore.data.first() @@ -2209,8 +2210,9 @@ class SparkRepo @Inject constructor( val earlierIds = heldAttempt(paymentHash)?.earlierIds.orEmpty() + cache.sparkSendEarlierIds[hash].orEmpty() val rowId = cache.sendRowWriter(hash, row) // Spark's dates can put an earlier attempt's failure after the retry's row, while a retry Spark refused leaves - // the row, and its fee corrections, to that attempt. - if (id in earlierIds && rowId != id) return true + // the row, and its fee corrections, to that attempt. Two attempts a later send both read as earlier aren't + // ordered by it, so their dates are. + if (id in earlierIds && rowId != id && rowId !in earlierIds) return true if (timestamp != row.timestamp) return timestamp < row.timestamp rowId ?: return false return rowId != id && rowId !in earlierIds diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 8f3f6b1b8e..b13c7fd5a8 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4404,6 +4404,43 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(9uL, row.v1.fee, "the earlier payment's final fee was dropped") } + @Test + fun `a later attempt's failure takes the row from an earlier one when a third send read both as earlier`() = test { + var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 1uL)) + val stamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}:${it.status}" } + // The first attempt wrote the row, the second's row write failed, and a third send that never wrote one read + // both as earlier. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendRowIds = mapOf("hash" to "first"), + sparkSendRowStamps = mapOf("hash" to stamp), + sparkSendEarlierIds = mapOf("hash" to listOf("first", "second")), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } + val first = sentPayment( + fees = 1 + ).copy(id = "first", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp) + val second = sentPayment(fees = 2) + .copy(id = "second", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp + 100uL) + whenever(sparkService.listPayments()).thenReturn(listOf(second, first)) + + createSut(store).start(0).getOrThrow() + advanceUntilIdle() + + assertEquals(2uL, row.v1.fee, "the first attempt's row stayed over the later second attempt's failure") + } + @Test fun `an earlier payment's failed row takes its final fee after a stop cut a retry's alike failed row`() = test { var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 7uL)) From 8ca2e4535d8bf02d3b6c478087cc349234dadfac Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 19:20:37 +0100 Subject: [PATCH 74/96] fix: spark reports a send failure seen during its call Verified: just format, compile, test, lint; the extended SparkRepoTest case fails without the fix --- .../java/to/bitkit/repositories/SparkRepo.kt | 20 +++++++++++++++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 7 ++++++- 2 files changed, 26 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 277fca69d8..350d4a23a3 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -198,6 +198,9 @@ class SparkRepo @Inject constructor( /** Each send still inside Spark's send call, by lowercase payment hash. */ private val inFlightAttempts = ConcurrentHashMap() + /** Failures Spark reported while a send call ran, by attempt and payment id, settled once the call returns one. */ + private val failuresDuringCall = ConcurrentHashMap>() + /** Counts sends recorded, so a listing drops a failed hash only when it was recorded before the listing. */ private val sendRecords = AtomicLong() private val sendRecordedAt = ConcurrentHashMap() @@ -341,6 +344,7 @@ class SparkRepo @Inject constructor( uncertainSends.clear() takenAttempts.clear() restoredTakenAttempts.clear() + failuresDuringCall.clear() } hasSyncedActivities = false hasMergedRemoteExitState = false @@ -603,6 +607,7 @@ class SparkRepo @Inject constructor( val attemptId = UUID.randomUUID().toString() var isDispatched = false var hasReturned = false + var failures: Map? = null val sent = try { inFlightAttempts[paymentHash.lowercase()] = SendAttempt(sentAt.toULong(), earlierIds, attemptId = attemptId) @@ -679,6 +684,7 @@ class SparkRepo @Inject constructor( } } inFlightAttempts.remove(paymentHash.lowercase()) + failures = failuresDuringCall.remove(attemptId) sendsInFlight.remove(paymentHash.lowercase()) } val payment = sent.getOrElse { @@ -712,6 +718,10 @@ class SparkRepo @Inject constructor( restoredTakenAttempts.remove(paymentHash.lowercase()) cacheStore.removeSparkUncertainSend(paymentHash) } + // A failure Spark reported during the call is this send's own once the call returns it, so it settles now. + failures?.get(payment.id) + ?.takeIf { payment.status == PaymentStatus.FAILED } + ?.let { onPayment(it) } Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) paymentHash }.onFailure { @@ -2370,6 +2380,7 @@ class SparkRepo @Inject constructor( // trySettleUncertainSend. if (payment.isOutrunByRetry(records)) { payment.heldBackOutcome() + payment.keepFailureDuringCall() Logger.info("Kept uncertain Spark send '${payment.sendHash()}' held past an older failure", context = TAG) return } @@ -2400,6 +2411,15 @@ class SparkRepo @Inject constructor( payment.toNodeEvent()?.let { _nodeEvents.emit(it) } } + /** Keeps a failure Spark reports while a send call of its invoice runs, kept with that call's attempt. */ + private fun Payment.keepFailureDuringCall() { + val hash = sendHash(PaymentStatus.FAILED)?.lowercase() ?: return + inFlightAttempts.computeIfPresent(hash) { _, attempt -> + attempt.attemptId?.let { failuresDuringCall.merge(it, mapOf(id to this)) { kept, new -> kept + new } } + attempt + } + } + /** * Marks the outcome of the restored retry of this payment's invoice as held back, unless this is another * attempt's. diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index b13c7fd5a8..4ff54dd02a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4923,7 +4923,7 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `a spark send whose call returns its failure after spark reported it reads as failed`() = test { + fun `a spark send whose call returns its failure after spark reported it reports it once`() = test { whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) @@ -4941,8 +4941,13 @@ class SparkRepoTest : BaseUnitTest() { val sut = createSut() sut.start(0).getOrThrow() runCurrent() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + // A watcher that started before the send, as a swap's hold payment does, learns the failure by its event. + assertEquals(1, events.count { it is Event.PaymentFailed }, "the failure's event was dropped or doubled") advanceUntilIdle() assertIs(sut.settledSendEvent("hash"), "the returned failure wasn't reported") From 73cc55efe24985bc7db182a66aff500889fdffd8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 19:59:22 +0100 Subject: [PATCH 75/96] fix: spark orders kept earlier attempts by send order Verified: just format, compile, test, lint; the new SparkRepoTest and CacheStoreTest cases fail without the fix --- .../main/java/to/bitkit/data/CacheStore.kt | 6 ++- .../java/to/bitkit/repositories/SparkRepo.kt | 12 +++--- .../java/to/bitkit/data/CacheStoreTest.kt | 8 ++++ .../to/bitkit/repositories/SparkRepoTest.kt | 39 +++++++++++++++++++ 4 files changed, 58 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index dd0f02dc82..180715d861 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -242,7 +242,9 @@ class CacheStore internal constructor( val hash = paymentHash.lowercase() if (store.data.first().sparkSendEarlierIds[hash].orEmpty().containsAll(ids)) return store.updateData { - val kept = (it.sparkSendEarlierIds[hash].orEmpty() + ids).distinct().sorted() + // In send order: a send's earlier attempts go after those an earlier send of the invoice kept. + val earlier = it.sparkSendEarlierIds[hash].orEmpty() + val kept = earlier + ids.filterNot { id -> id in earlier }.sorted() val all = (it.sparkSendEarlierIds - hash + (hash to kept)).entries.toList().takeLast(MAX_SPARK_SEND_HASHES) it.copy(sparkSendEarlierIds = all.associate { (key, value) -> key to value }) } @@ -556,7 +558,7 @@ data class AppCacheData( */ val sparkSendPreviousRowWriters: Map> = mapOf(), /** - * Spark's payment ids of each Spark send's earlier attempts, kept past its hold for the latest + * Spark's payment ids of each Spark send's earlier attempts, in send order, kept past its hold for the latest * [MAX_SPARK_SEND_HASHES], so a failure of one never writes over a later attempt's Activity row after a restart. */ val sparkSendEarlierIds: Map> = mapOf(), diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 350d4a23a3..dadefe74fd 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -2210,9 +2210,9 @@ class SparkRepo @Inject constructor( /** * Whether this payment is of an attempt a later one read as earlier before it went out, kept past its hold and a - * restart, while it no longer wrote the [row] of [paymentHash] and the row's writer is no such attempt, or Spark - * dates it before the row or ties it as another payment than the one that wrote the row, unless that one is such an - * earlier attempt. + * restart, while it no longer wrote the [row] of [paymentHash] and the row's writer is no such attempt, or kept + * before that writer when it is, or Spark dates it before the row or ties it as another payment than the one that + * wrote the row, unless that one is such an earlier attempt. */ private suspend fun Payment.isEarlierThan(row: LightningActivity, paymentHash: String): Boolean { val cache = cacheStore.data.first() @@ -2220,9 +2220,11 @@ class SparkRepo @Inject constructor( val earlierIds = heldAttempt(paymentHash)?.earlierIds.orEmpty() + cache.sparkSendEarlierIds[hash].orEmpty() val rowId = cache.sendRowWriter(hash, row) // Spark's dates can put an earlier attempt's failure after the retry's row, while a retry Spark refused leaves - // the row, and its fee corrections, to that attempt. Two attempts a later send both read as earlier aren't - // ordered by it, so their dates are. + // the row, and its fee corrections, to that attempt. Two attempts later sends read as earlier are ordered as + // those sends kept them. if (id in earlierIds && rowId != id && rowId !in earlierIds) return true + val order = cache.sparkSendEarlierIds[hash].orEmpty() + if (rowId != id && id in order && rowId in order) return order.indexOf(id) < order.indexOf(rowId) if (timestamp != row.timestamp) return timestamp < row.timestamp rowId ?: return false return rowId != id && rowId !in earlierIds diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index d69ba83c57..9ba979dedd 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -339,6 +339,14 @@ class CacheStoreTest : BaseUnitTest() { assertFalse("hash" in cache.data.first().sparkSendPreviousRowWriters) } + @Test + fun `keepSparkSendEarlierIds keeps a send's earlier attempts in send order`() = test { + sut.keepSparkSendEarlierIds("hash", setOf("zfirst")) + sut.keepSparkSendEarlierIds("hash", setOf("zfirst", "asecond")) + + assertEquals(listOf("zfirst", "asecond"), sut.data.first().sparkSendEarlierIds["hash"]) + } + @Test fun `keepSparkSendRowId keeps the writer of a send with earlier ids past the latest sends`() = test { sut.keepSparkSendEarlierIds("retried", setOf("earlier")) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 4ff54dd02a..5d38c8e634 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4441,6 +4441,45 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(2uL, row.v1.fee, "the first attempt's row stayed over the later second attempt's failure") } + @Test + fun `a later attempt's same-second failure keeps the row from an earlier one when a third send read both`() = + test { + var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 1uL)) + val stamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}:${it.status}" } + // The second attempt followed the first in the same second, and its row write failed. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendRowIds = mapOf("hash" to "zfirst"), + sparkSendRowStamps = mapOf("hash" to stamp), + sparkSendEarlierIds = mapOf("hash" to listOf("zfirst", "asecond")), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } + val first = sentPayment(fees = 1) + .copy(id = "zfirst", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp) + val second = sentPayment(fees = 2) + .copy(id = "asecond", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp) + + // Spark lists them in either order across launches. + listOf(listOf(second, first), listOf(first, second)).forEach { listed -> + whenever(sparkService.listPayments()).thenReturn(listed) + createSut(store).start(0).getOrThrow() + advanceUntilIdle() + + assertEquals(2uL, row.v1.fee, "the first attempt took the row back from the later second one") + } + } + @Test fun `an earlier payment's failed row takes its final fee after a stop cut a retry's alike failed row`() = test { var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 7uL)) From 33872084b8fd939e010f2148b9e1e3911c66acf4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 20:38:25 +0100 Subject: [PATCH 76/96] fix: spark lets dates order kept attempts before send order Verified: just format, compile, test, lint; the new SparkRepoTest case fails without the fix --- .../java/to/bitkit/repositories/SparkRepo.kt | 18 +++++----- .../to/bitkit/repositories/SparkRepoTest.kt | 35 +++++++++++++++++++ 2 files changed, 45 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 dadefe74fd..1583b391bd 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -2210,9 +2210,9 @@ class SparkRepo @Inject constructor( /** * Whether this payment is of an attempt a later one read as earlier before it went out, kept past its hold and a - * restart, while it no longer wrote the [row] of [paymentHash] and the row's writer is no such attempt, or kept - * before that writer when it is, or Spark dates it before the row or ties it as another payment than the one that - * wrote the row, unless that one is such an earlier attempt. + * restart, while it no longer wrote the [row] of [paymentHash] and the row's writer is no such attempt, or Spark + * dates it before the row or ties it as another payment than the one that wrote the row, kept before it when both + * are such earlier attempts. */ private suspend fun Payment.isEarlierThan(row: LightningActivity, paymentHash: String): Boolean { val cache = cacheStore.data.first() @@ -2220,14 +2220,16 @@ class SparkRepo @Inject constructor( val earlierIds = heldAttempt(paymentHash)?.earlierIds.orEmpty() + cache.sparkSendEarlierIds[hash].orEmpty() val rowId = cache.sendRowWriter(hash, row) // Spark's dates can put an earlier attempt's failure after the retry's row, while a retry Spark refused leaves - // the row, and its fee corrections, to that attempt. Two attempts later sends read as earlier are ordered as - // those sends kept them. + // the row, and its fee corrections, to that attempt. if (id in earlierIds && rowId != id && rowId !in earlierIds) return true - val order = cache.sparkSendEarlierIds[hash].orEmpty() - if (rowId != id && id in order && rowId in order) return order.indexOf(id) < order.indexOf(rowId) if (timestamp != row.timestamp) return timestamp < row.timestamp rowId ?: return false - return rowId != id && rowId !in earlierIds + if (rowId == id) return false + // Two attempts later sends read as earlier and Spark dates in the same second are ordered as those sends kept + // them. A read that left one out keeps it after later ones, so their dates come first. + val order = cache.sparkSendEarlierIds[hash].orEmpty() + if (id in order && rowId in order) return order.indexOf(id) < order.indexOf(rowId) + return rowId !in earlierIds } private fun LightningActivity.sendRowStamp() = "$timestamp:$value:$fee:$status" diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 5d38c8e634..081346e536 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4441,6 +4441,41 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(2uL, row.v1.fee, "the first attempt's row stayed over the later second attempt's failure") } + @Test + fun `an older attempt a pre-send read left out never takes a later attempt's row by its kept order`() = test { + var row = Activity.Lightning( + pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 2uL, timestamp = 1_000uL), + ) + val stamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}:${it.status}" } + // A read left the first attempt out, so it was kept after the second, which wrote the row. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendRowIds = mapOf("hash" to "second"), + sparkSendRowStamps = mapOf("hash" to stamp), + sparkSendEarlierIds = mapOf("hash" to listOf("second", "first")), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = it.getArgument(0) as? Activity.Lightning ?: row + Result.success(Unit) + } + val first = sentPayment(fees = 1) + .copy(id = "first", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp - 100uL) + whenever(sparkService.listPayments()).thenReturn(listOf(first)) + + createSut(store).start(0).getOrThrow() + advanceUntilIdle() + + assertEquals(2uL, row.v1.fee, "the older first attempt took the second one's row") + } + @Test fun `a later attempt's same-second failure keeps the row from an earlier one when a third send read both`() = test { From 1bf07803fce663c18bf825e520a2c39928b12ac4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 21:33:47 +0100 Subject: [PATCH 77/96] fix: spark settles a failure seen as the send call hands over Verified: just format, compile, test, lint; the new SparkRepoTest case fails without the fix --- .../java/to/bitkit/repositories/SparkRepo.kt | 5 +-- .../to/bitkit/repositories/SparkRepoTest.kt | 33 +++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 1583b391bd..18498e4a45 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -718,9 +718,10 @@ class SparkRepo @Inject constructor( restoredTakenAttempts.remove(paymentHash.lowercase()) cacheStore.removeSparkUncertainSend(paymentHash) } - // A failure Spark reported during the call is this send's own once the call returns it, so it settles now. + // A failure Spark reported during the call is this send's own once the call returns its payment, failed or + // still pending, so it settles now. failures?.get(payment.id) - ?.takeIf { payment.status == PaymentStatus.FAILED } + ?.takeIf { payment.status != PaymentStatus.COMPLETED } ?.let { onPayment(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 081346e536..5d28f3f444 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5028,6 +5028,39 @@ class SparkRepoTest : BaseUnitTest() { assertNull(sut.earlierLightningSend("lnbc1", "hash"), "the failed send still held the invoice") } + @Test + fun `a spark send whose call returns pending after spark reported its failure reports it once`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + var listed = emptyList() + whenever(sparkService.listPayments()).thenAnswer { listed } + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val taken = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) + val failed = taken.copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) + // Spark reports the failure while its send call hands the payment it took over, before the call ends. + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { + listed = listOf(failed) + sparkEvents.emit(SdkEvent.PaymentFailed(failed)) + taken + } + val sut = createSut(store) + sut.start(0).getOrThrow() + runCurrent() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + assertEquals(1, events.count { it is Event.PaymentFailed }, "the failure's event was dropped or doubled") + advanceUntilIdle() + + assertNull(sut.earlierLightningSend("lnbc1", "hash"), "the failed send still held the invoice") + assertTrue(store.data.first().sparkTakenSendIds.isEmpty(), "the failed send's attempt stayed journaled") + } + @Test fun `a spark send whose caller is cancelled as spark takes it keeps its payment id`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) From 8a609f8386b58756188bef6091fbc65a6105259c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 22:18:47 +0100 Subject: [PATCH 78/96] fix: spark reports a failure seen during its call once Verified: just format, compile, test, lint; the new SparkRepoTest race case fails without the fix --- .../java/to/bitkit/repositories/SparkRepo.kt | 35 ++++++++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 56 +++++++++++++++++++ 2 files changed, 85 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 18498e4a45..67783bea91 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -719,9 +719,11 @@ class SparkRepo @Inject constructor( cacheStore.removeSparkUncertainSend(paymentHash) } // A failure Spark reported during the call is this send's own once the call returns its payment, failed or - // still pending, so it settles now. + // still pending, so it settles now. A pending one is settled only while its attempt still holds it, taken + // off in one step, as the expiry sweep may have reported its outcome meanwhile. failures?.get(payment.id) ?.takeIf { payment.status != PaymentStatus.COMPLETED } + ?.takeIf { payment.status == PaymentStatus.FAILED || releaseTakenAttempt(paymentHash, attemptId) } ?.let { onPayment(it) } Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) paymentHash @@ -2375,6 +2377,13 @@ class SparkRepo @Inject constructor( } private suspend fun onPayment(payment: Payment) { + // A failure while a send call of its invoice runs waits for the call, which settles it once it returns that + // payment. + if (payment.keepFailureDuringCall()) { + payment.heldBackOutcome() + Logger.info("Kept Spark failure '${payment.id}' until its send call returns", context = TAG) + return + } // A retry of the invoice can start while this event is handled, so each step checks for one sent since now. val records = sendRecords.get() // The event carries its outcome, so a failed balance read never holds back its settlement. @@ -2385,7 +2394,6 @@ class SparkRepo @Inject constructor( // trySettleUncertainSend. if (payment.isOutrunByRetry(records)) { payment.heldBackOutcome() - payment.keepFailureDuringCall() Logger.info("Kept uncertain Spark send '${payment.sendHash()}' held past an older failure", context = TAG) return } @@ -2416,13 +2424,28 @@ class SparkRepo @Inject constructor( payment.toNodeEvent()?.let { _nodeEvents.emit(it) } } - /** Keeps a failure Spark reports while a send call of its invoice runs, kept with that call's attempt. */ - private fun Payment.keepFailureDuringCall() { - val hash = sendHash(PaymentStatus.FAILED)?.lowercase() ?: return + /** Takes [attemptId]'s taken attempt of [paymentHash] off; false when another caller settled it. */ + private fun releaseTakenAttempt(paymentHash: String, attemptId: String): Boolean { + val key = paymentHash.lowercase() + val attempt = takenAttempts[key]?.takeIf { it.attemptId == attemptId } ?: return false + return takenAttempts.remove(key, attempt) + } + + /** + * Keeps a failure Spark reports while a send call of its invoice runs and isn't in doubt, with that call's attempt; + * checked and kept in one step with the call's end, so the call either finds it or the event goes on. + */ + private fun Payment.keepFailureDuringCall(): Boolean { + val hash = sendHash(PaymentStatus.FAILED)?.lowercase() ?: return false + var isKept = false inFlightAttempts.computeIfPresent(hash) { _, attempt -> - attempt.attemptId?.let { failuresDuringCall.merge(it, mapOf(id to this)) { kept, new -> kept + new } } + attempt.attemptId?.takeUnless { uncertainSends.containsKey(hash) }?.let { + failuresDuringCall.merge(it, mapOf(id to this)) { kept, new -> kept + new } + isKept = true + } attempt } + return isKept } /** diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 5d28f3f444..55710a8456 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1,5 +1,6 @@ package to.bitkit.repositories +import androidx.datastore.core.DataStore import breez_sdk_spark.AutoOptimizationEvent import breez_sdk_spark.BitcoinAddressDetails import breez_sdk_spark.Bolt11InvoiceDetails @@ -5061,6 +5062,61 @@ class SparkRepoTest : BaseUnitTest() { assertTrue(store.data.first().sparkTakenSendIds.isEmpty(), "the failed send's attempt stayed journaled") } + @Test + fun `a failure seen during a spark send call that the expiry sweep reports first is reported once`() = test { + val inner = InMemoryDataStore(AppCacheData()) + val takenIdWritten = CompletableDeferred() + val resume = CompletableDeferred() + // The taken send's id write waits, so the expiry sweep runs while the send call hands its payment over. + val store = CacheStore( + object : DataStore { + override val data = inner.data + + override suspend fun updateData(transform: suspend (t: AppCacheData) -> AppCacheData): AppCacheData { + val before = inner.data.first() + if ("hash" !in before.sparkTakenSendIds && "hash" in transform(before).sparkTakenSendIds) { + takenIdWritten.complete(Unit) + resume.await() + } + return inner.updateData(transform) + } + }, + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenAnswer { info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) } + var listed = emptyList() + whenever(sparkService.listPayments()).thenAnswer { listed } + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val taken = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) + val failed = taken.copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { + listed = listOf(failed) + sparkEvents.emit(SdkEvent.PaymentFailed(failed)) + taken + } + val sut = createSut(store) + sut.start(0).getOrThrow() + runCurrent() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + val caller = backgroundScope.async { sut.payInvoice("lnbc1", 100uL) } + takenIdWritten.await() + + // The invoice expires and Spark syncs, so the sweep reports the failure while the call still runs. + now += 2.hours + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + resume.complete(Unit) + caller.await().getOrThrow() + advanceUntilIdle() + + assertEquals(1, events.count { it is Event.PaymentFailed }, "the failure was reported twice") + } + @Test fun `a spark send whose caller is cancelled as spark takes it keeps its payment id`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) From 904e62996ef9d56e7966307fdb5e0a72141dd992 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 23:27:11 +0100 Subject: [PATCH 79/96] fix: spark holds retries of unresolved sends A Lightning invoice is not sent again through Spark while an earlier attempt on it is in Spark's send call or in doubt; the payment shows as pending until Spark settles or fails it. A failure Spark dates no more than 10 s before the send's start ends it at once; an earlier attempt's failure is ignored. Removes the retry-hold layer and its saved journal. Verified: just format, just compile, just test, just lint --- .../main/java/to/bitkit/data/CacheStore.kt | 197 +- .../java/to/bitkit/repositories/BackupRepo.kt | 8 - .../to/bitkit/repositories/LightningRepo.kt | 4 +- .../java/to/bitkit/repositories/SparkRepo.kt | 800 +----- .../java/to/bitkit/data/CacheStoreTest.kt | 158 -- .../to/bitkit/repositories/SparkRepoTest.kt | 2426 ++--------------- 6 files changed, 342 insertions(+), 3251 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 180715d861..6b6930e6ba 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -166,102 +166,6 @@ class CacheStore internal constructor( } } - /** - * Keeps [paymentId] as the payment that last wrote the Activity row of Spark's send of [paymentHash], with the - * [stamp] of the row it wrote, in one write, so a row written over without its writer is told apart. A writer - * kept [beforeRow] keeps the previous one beside it until [commitSparkSendRowId], or an empty id with the stamp of - * the row it replaces, [rowStamp], when it had none, so a stop before the row is written leaves the row to the - * writer whose stamp it still matches. - */ - suspend fun keepSparkSendRowId( - paymentHash: String, - paymentId: String, - stamp: String? = null, - beforeRow: Boolean = false, - rowStamp: String? = null, - ) { - val hash = paymentHash.lowercase() - val data = store.data.first() - val isKept = data.sparkSendRowIds[hash] == paymentId && data.sparkSendRowStamps[hash] == stamp - if (isKept && hash !in data.sparkSendPreviousRowWriters) return - store.updateData { - val all = (it.sparkSendRowIds - hash + (hash to paymentId)).entries.toList() - val unprotected = all.map { (key) -> key }.filter { key -> key !in it.sparkSendEarlierIds } - val dropped = unprotected.take((unprotected.size - MAX_SPARK_SEND_HASHES).coerceAtLeast(0)).toSet() - val ids = all.filter { (key) -> key !in dropped } - val stamps = stamp?.let { value -> it.sparkSendRowStamps + (hash to value) } - ?: (it.sparkSendRowStamps - hash) - // A writer a cut write left the row to stays its writer, as the row still matches its stamp. - val staged = it.sparkSendPreviousRowWriters[hash]?.takeIf { value -> value.getOrNull(1) == rowStamp } - val writer = ( - staged - ?: it.sparkSendRowIds[hash]?.let { id -> listOfNotNull(id, it.sparkSendRowStamps[hash]) } - ?: rowStamp?.let { value -> listOf("", value) } - ).takeIf { beforeRow } - val previous = writer?.let { value -> it.sparkSendPreviousRowWriters + (hash to value) } - ?: (it.sparkSendPreviousRowWriters - hash) - val kept = ids.associate { (key, id) -> key to id } - it.copy( - sparkSendRowIds = kept, - sparkSendRowStamps = stamps.filterKeys { key -> key in kept }, - sparkSendPreviousRowWriters = previous.filterKeys { key -> key in kept }, - ) - } - } - - /** - * Puts back the writer of Spark's send row of [paymentHash] as it was before a row write that failed: its [id], - * [stamp] and the [previous] writer a stop left beside it, each dropped when null. - */ - suspend fun restoreSparkSendRowWriter(paymentHash: String, id: String?, stamp: String?, previous: List?) { - val hash = paymentHash.lowercase() - store.updateData { - val ids = id?.let { value -> it.sparkSendRowIds + (hash to value) } ?: (it.sparkSendRowIds - hash) - val stamps = stamp?.takeIf { id != null } - ?.let { value -> it.sparkSendRowStamps + (hash to value) } - ?: (it.sparkSendRowStamps - hash) - val writers = previous?.takeIf { id != null } - ?.let { value -> it.sparkSendPreviousRowWriters + (hash to value) } - ?: (it.sparkSendPreviousRowWriters - hash) - it.copy(sparkSendRowIds = ids, sparkSendRowStamps = stamps, sparkSendPreviousRowWriters = writers) - } - } - - /** Ends the doubt over the writer of Spark's send row of [paymentHash], kept before its row, once it is saved. */ - suspend fun commitSparkSendRowId(paymentHash: String) { - val hash = paymentHash.lowercase() - if (hash !in store.data.first().sparkSendPreviousRowWriters) return - store.updateData { it.copy(sparkSendPreviousRowWriters = it.sparkSendPreviousRowWriters - hash) } - } - - /** - * Keeps Spark's ids of the earlier attempts of the send of [paymentHash], [ids], with those kept before, past its - * hold and for the latest [MAX_SPARK_SEND_HASHES] sends, so their failures never write over a later attempt's row. - */ - suspend fun keepSparkSendEarlierIds(paymentHash: String, ids: Set) { - val hash = paymentHash.lowercase() - if (store.data.first().sparkSendEarlierIds[hash].orEmpty().containsAll(ids)) return - store.updateData { - // In send order: a send's earlier attempts go after those an earlier send of the invoice kept. - val earlier = it.sparkSendEarlierIds[hash].orEmpty() - val kept = earlier + ids.filterNot { id -> id in earlier }.sorted() - val all = (it.sparkSendEarlierIds - hash + (hash to kept)).entries.toList().takeLast(MAX_SPARK_SEND_HASHES) - it.copy(sparkSendEarlierIds = all.associate { (key, value) -> key to value }) - } - } - - suspend fun removeSparkSendRowId(paymentHash: String) { - val hash = paymentHash.lowercase() - if (hash !in store.data.first().sparkSendRowIds) return - store.updateData { - it.copy( - sparkSendRowIds = it.sparkSendRowIds - hash, - sparkSendRowStamps = it.sparkSendRowStamps - hash, - sparkSendPreviousRowWriters = it.sparkSendPreviousRowWriters - hash, - ) - } - } - suspend fun removeSparkSendHash(paymentHash: String) { val hash = paymentHash.lowercase() if (hash !in store.data.first().sparkSendHashes) return @@ -270,75 +174,16 @@ class CacheStore internal constructor( } } - /** - * Keeps Spark's send of [paymentHash] as one whose outcome Spark didn't report, since [failedAt] epoch seconds, - * with when it was sent, [sentAt], and Spark's ids of the invoice's earlier attempts, [earlierIds], once known; - * either left out drops an older attempt's. - */ - suspend fun addSparkUncertainSend( - paymentHash: String, - failedAt: Long, - sentAt: Long? = null, - earlierIds: Set? = null, - attemptId: String? = null, - ) { - val hash = paymentHash.lowercase() - store.updateData { - it.copy( - sparkUncertainSends = it.sparkUncertainSends + (hash to failedAt), - // Each write is one attempt's, so a value it lacks drops an older attempt's. - sparkUncertainSendStarts = sentAt?.let { start -> it.sparkUncertainSendStarts + (hash to start) } - ?: (it.sparkUncertainSendStarts - hash), - sparkUncertainSendEarlierIds = earlierIds - ?.let { ids -> it.sparkUncertainSendEarlierIds + (hash to ids.sorted()) } - ?: (it.sparkUncertainSendEarlierIds - hash), - sparkUncertainSendAttemptIds = attemptId?.let { id -> it.sparkUncertainSendAttemptIds + (hash to id) } - ?: (it.sparkUncertainSendAttemptIds - hash), - sparkTakenSendIds = it.sparkTakenSendIds - hash, - ) - } - } - - /** - * Ends the doubt over a send Spark took and still runs, keeping its start time and earlier attempts' ids, with - * Spark's id of the payment it took, [paymentId], so its own failure is told apart after a restart. Only the - * attempt [attemptId] that still has its entry changes it, so a send settled meanwhile is never kept again. - */ - suspend fun keepSparkSendAttempt(paymentHash: String, paymentId: String?, attemptId: String?) { + /** Keeps Spark's send of [paymentHash] as one whose outcome Spark didn't report, since [failedAt] epoch seconds. */ + suspend fun addSparkUncertainSend(paymentHash: String, failedAt: Long) { val hash = paymentHash.lowercase() - val data = store.data.first() - val isIdKept = paymentId == null || data.sparkTakenSendIds[hash] == paymentId - if (hash !in data.sparkUncertainSends && isIdKept) return - store.updateData { - // An entry kept before attempts had ids is one only an attempt without an id still owns. - val isOwn = attemptId?.let { id -> it.sparkUncertainSendAttemptIds[hash] == id } - ?: (hash in it.sparkUncertainSends && hash !in it.sparkUncertainSendAttemptIds) - if (!isOwn) return@updateData it - it.copy( - sparkUncertainSends = it.sparkUncertainSends - hash, - sparkTakenSendIds = paymentId - ?.let { id -> it.sparkTakenSendIds + (hash to id) } - ?: it.sparkTakenSendIds, - ) - } + store.updateData { it.copy(sparkUncertainSends = it.sparkUncertainSends + (hash to failedAt)) } } suspend fun removeSparkUncertainSend(paymentHash: String) { val hash = paymentHash.lowercase() - val data = store.data.first() - val isKept = hash in data.sparkUncertainSends || hash in data.sparkUncertainSendStarts || - hash in data.sparkUncertainSendEarlierIds || hash in data.sparkTakenSendIds || - hash in data.sparkUncertainSendAttemptIds - if (!isKept) return - store.updateData { - it.copy( - sparkUncertainSends = it.sparkUncertainSends - hash, - sparkUncertainSendStarts = it.sparkUncertainSendStarts - hash, - sparkUncertainSendEarlierIds = it.sparkUncertainSendEarlierIds - hash, - sparkUncertainSendAttemptIds = it.sparkUncertainSendAttemptIds - hash, - sparkTakenSendIds = it.sparkTakenSendIds - hash, - ) - } + if (hash !in store.data.first().sparkUncertainSends) return + store.updateData { it.copy(sparkUncertainSends = it.sparkUncertainSends - hash) } } suspend fun addMoveToSparkHash(paymentHash: String) { @@ -530,38 +375,6 @@ data class AppCacheData( * never reads a retry's earlier failed attempt as its outcome. */ val sparkUncertainSends: Map = mapOf(), - /** - * When each of those sends went out, in epoch seconds, so a failure Spark dates before it still reads as an earlier - * attempt's after a restart. Sends kept before this was have none. - */ - val sparkUncertainSendStarts: Map = mapOf(), - /** - * Spark's payment ids of each of those sends' earlier attempts, read before it went out, so only those attempts' - * failures read as earlier ones. Absent where Spark couldn't list them. - */ - val sparkUncertainSendEarlierIds: Map> = mapOf(), - /** Spark's id of the payment each send Spark took is, so its own failure never reads as an earlier attempt's. */ - val sparkTakenSendIds: Map = mapOf(), - /** A random id of the attempt each of those sends' entries belongs to, so a stale attempt never writes over it. */ - val sparkUncertainSendAttemptIds: Map = mapOf(), - /** - * Spark's id of the payment that last wrote each Spark send's Activity row, those of sends with - * [sparkSendEarlierIds] and the latest [MAX_SPARK_SEND_HASHES] of the others, so an earlier attempt's failure dated - * the same second as the row never writes over it. - */ - val sparkSendRowIds: Map = mapOf(), - /** The time, amount and fee of each of those rows as its writer wrote it, so a row written over is told apart. */ - val sparkSendRowStamps: Map = mapOf(), - /** - * The writer, and its row's stamp, each of those rows had before a new writer was kept ahead of its row write, so - * a stop before the row was written leaves the row to the writer whose stamp it still matches. - */ - val sparkSendPreviousRowWriters: Map> = mapOf(), - /** - * Spark's payment ids of each Spark send's earlier attempts, in send order, kept past its hold for the latest - * [MAX_SPARK_SEND_HASHES], so a failure of one never writes over a later attempt's Activity row after a restart. - */ - val sparkSendEarlierIds: Map> = mapOf(), /** * Payment hashes of the moves to Spark, kept across restarts so neither leg of a move is announced as a payment and * Activity shows the move as one. diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 1f51e2fba3..0011f3ce73 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1340,14 +1340,6 @@ class BackupRepo @Inject constructor( val logged = parsed.cache.copy( cachedRates = emptyList(), moveToSparkHashes = emptyList(), - sparkUncertainSendStarts = emptyMap(), - sparkUncertainSendEarlierIds = emptyMap(), - sparkTakenSendIds = emptyMap(), - sparkUncertainSendAttemptIds = emptyMap(), - sparkSendRowIds = emptyMap(), - sparkSendRowStamps = emptyMap(), - sparkSendPreviousRowWriters = emptyMap(), - sparkSendEarlierIds = emptyMap(), ) Logger.debug("Restored caches: ${jsonLogOf(logged)}", TAG) onCacheRestored() diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index cf9359dfae..17b271bee6 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1662,8 +1662,8 @@ class LightningRepo @Inject constructor( key: String, ldkRecordsBefore: Long, ): Result? { - // Read before the row too, so a send that ends while it is read still counts as live. The mark comes first, so - // a send it counts was admitted before liveness is read: still live then, or ended before the row is read. + // Read before the row too, so a send that ends while it is read still counts as live. The mark comes first, + // so a send it counts as recorded is already admitted or in flight when liveness is read. val sparkRecordsBefore = sparkRepo.sendRecordMark() val wasLive = isSendLive(paymentHash, key, ldkRecordsBefore) val send = sparkRepo.lightningSend(paymentHash) as? SparkLightningSend.Found ?: return null diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 67783bea91..612237efbc 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -27,7 +27,6 @@ import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job -import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow @@ -48,7 +47,6 @@ import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.PaymentFailureReason import org.lightningdevkit.ldknode.PaymentId import to.bitkit.async.appScope -import to.bitkit.data.AppCacheData import to.bitkit.data.CacheStore import to.bitkit.data.SettingsStore import to.bitkit.data.SparkPayoutChain @@ -111,12 +109,6 @@ class SparkRepo @Inject constructor( /** Looks for 5 minutes before telling the user Spark hasn't seen the deposit yet. */ private const val CLAIM_POLL_ATTEMPTS = 60 - /** - * How far Spark's clock may differ from the phone's: without the ids of a retry's earlier attempts, a failure - * Spark dates before the retry's start plus this may be an earlier attempt's, so it keeps the retry held. - */ - private const val RAIL_CLOCK_SKEW_SECONDS = 10uL - private val SEND_STATUS_PRIORITY = listOf(PaymentStatus.COMPLETED, PaymentStatus.PENDING, PaymentStatus.FAILED) /** How long the SDK leaves the counter-swap of a leaf swap cut short unclaimed (its 300 s), plus a margin. */ @@ -131,14 +123,14 @@ class SparkRepo @Inject constructor( /** Tries to learn the outcome of a send whose result was lost while Spark cannot list its payments. */ private const val SETTLE_ATTEMPTS = 10 - /** How long a journaled withdrawal Spark doesn't list stays open before a sync closes it as never sent. */ - private val UNLISTED_WITHDRAWAL_GRACE = 10.minutes - /** - * How long past its invoice's expiry a send Spark took stays held while Spark lists none of its own outcome, - * as with an unlisted withdrawal, before its row fails. + * How far before a send's start Spark may date its own failure, as Spark's clock can differ from the phone's. + * Shared with bitkit-ios. */ - private val UNLISTED_TAKEN_SEND_GRACE = 10.minutes + private const val OWN_FAILURE_CLOCK_MARGIN_SECS = 10uL + + /** How long a journaled withdrawal Spark doesn't list stays open before a sync closes it as never sent. */ + private val UNLISTED_WITHDRAWAL_GRACE = 10.minutes /** How many sent contact withdrawals stay recorded for a request proof to complete from. */ private const val MAX_SENT_WITHDRAWALS = 20 @@ -189,18 +181,9 @@ class SparkRepo @Inject constructor( private val refreshMutex = Mutex() - /** Orders recording a send against a payment event releasing its invoice, so an older event never releases it. */ - private val sendReleaseMutex = Mutex() - /** The invoice of each send still inside Spark's send call, by lowercase payment hash. */ private val sendsInFlight = ConcurrentHashMap() - /** Each send still inside Spark's send call, by lowercase payment hash. */ - private val inFlightAttempts = ConcurrentHashMap() - - /** Failures Spark reported while a send call ran, by attempt and payment id, settled once the call returns one. */ - private val failuresDuringCall = ConcurrentHashMap>() - /** Counts sends recorded, so a listing drops a failed hash only when it was recorded before the listing. */ private val sendRecords = AtomicLong() private val sendRecordedAt = ConcurrentHashMap() @@ -211,12 +194,6 @@ class SparkRepo @Inject constructor( /** Serialises the imports of staged exit data, so a restore and Spark's start never import it at once. */ private val exitImportMutex = Mutex() - /** Sends Spark took and still runs, by payment hash, until they settle or their invoice expires. */ - private val takenAttempts = ConcurrentHashMap() - - /** Taken attempts restored after a restart whose outcome no event held back, so their expiry reports none. */ - private val restoredTakenAttempts = ConcurrentHashMap.newKeySet() - @Volatile private var hasSyncedActivities = false @@ -338,14 +315,7 @@ class SparkRepo @Inject constructor( sendsRecordedWithoutFee.clear() unsavedPayments.clear() sendsInFlight.clear() - // Under the lock a send call's hand-over takes, so a call that returns after the wipe holds nothing. - sendReleaseMutex.withLock { - inFlightAttempts.clear() - uncertainSends.clear() - takenAttempts.clear() - restoredTakenAttempts.clear() - failuresDuringCall.clear() - } + uncertainSends.clear() hasSyncedActivities = false hasMergedRemoteExitState = false isLostForExit = false @@ -597,31 +567,17 @@ class SparkRepo @Inject constructor( expiresAt.toEpochSeconds(), ) } - val earlierIds = earlierAttemptIds(paymentHash) // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. if (!onBeforeSend()) throw PaymentAbortedBeforeSend() if (sendsInFlight.putIfAbsent(paymentHash.lowercase(), bolt11) != null) { throw PaymentPendingException(paymentHash) } - val sentAt = clock.now().epochSeconds - val attemptId = UUID.randomUUID().toString() - var isDispatched = false - var hasReturned = false - var failures: Map? = null val sent = try { - inFlightAttempts[paymentHash.lowercase()] = - SendAttempt(sentAt.toULong(), earlierIds, attemptId = attemptId) - // Its journal entry replaces an earlier attempt's, which only goes out once that one failed, so the - // earlier attempt no longer holds the invoice; dropped after this one holds it, so a reader never - // finds neither. - takenAttempts.remove(paymentHash.lowercase()) - restoredTakenAttempts.remove(paymentHash.lowercase()) - sendReleaseMutex.withLock { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() } + sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) - earlierIds?.let { cacheStore.keepSparkSendEarlierIds(paymentHash, it) } spending { // Kept until the call returns, so a send cut off by process death or cancellation stays held. - cacheStore.addSparkUncertainSend(paymentHash, sentAt, sentAt, earlierIds, attemptId) + cacheStore.addSparkUncertainSend(paymentHash, clock.now().epochSeconds) // The checks above and both writes suspend, so the deadline and an exit that started meanwhile // are checked last, before the send. runCatching { @@ -632,65 +588,14 @@ class SparkRepo @Inject constructor( cacheStore.removeSparkSendHash(paymentHash) throw it } - isDispatched = true - runSuspendCatching { sparkService.send(prepared) }.also { result -> - hasReturned = true - // Taken before the in-flight attempt is dropped, so an earlier failure never finds neither. - // A payment Spark took carries its own id, so its failure is never read as an earlier one's. - val attempt = SendAttempt(sentAt.toULong(), earlierIds, result.getOrNull()?.id, attemptId) - result.getOrNull()?.takeIf { it.status == PaymentStatus.PENDING }?.let { payment -> - // Taken only while its own outcome wasn't handled meanwhile, as its journal write is. Taken - // and journaled also when the caller is cancelled meanwhile, as the send already went out. - withContext(NonCancellable) { - sendReleaseMutex.withLock { - if (inFlightAttempts[paymentHash.lowercase()]?.attemptId == attemptId) { - takenAttempts[paymentHash.lowercase()] = attempt - restoredTakenAttempts.remove(paymentHash.lowercase()) - } - } - // A send Spark still runs keeps its earlier attempts' ids, so their late failures - // leave it alone. - cacheStore.keepSparkSendAttempt(paymentHash, payment.id, attemptId) - } - } - // A send whose call failed may still have gone out, so it is in doubt before the in-flight - // attempt is dropped, unless its outcome was handled meanwhile, which dropped that attempt. - if (result.isFailure) { - withContext(NonCancellable) { - sendReleaseMutex.withLock { - if (inFlightAttempts[paymentHash.lowercase()]?.attemptId != attemptId) { - return@withLock - } - uncertainSends[paymentHash.lowercase()] = - UncertainSend(clock.now().epochSeconds.toULong(), expiresAt, attempt) - } - } - } - } + runSuspendCatching { sparkService.send(prepared) } } } finally { - // A send cancelled inside Spark's call stays in doubt, as its journal entry does, so a sync settles it, - // unless its outcome was handled meanwhile, which dropped its in-flight attempt. - if (isDispatched && !hasReturned) { - val attempt = SendAttempt(sentAt.toULong(), earlierIds, attemptId = attemptId) - withContext(NonCancellable) { - sendReleaseMutex.withLock { - if (inFlightAttempts[paymentHash.lowercase()]?.attemptId != attemptId) return@withLock - uncertainSends.putIfAbsent( - paymentHash.lowercase(), - UncertainSend(clock.now().epochSeconds.toULong(), expiresAt, attempt), - ) - } - } - } - inFlightAttempts.remove(paymentHash.lowercase()) - failures = failuresDuringCall.remove(attemptId) sendsInFlight.remove(paymentHash.lowercase()) } val payment = sent.getOrElse { // The SDK checks the expiry again before anything goes out, so an expired invoice left nothing. if (it.isInvoiceExpired()) { - uncertainSends.remove(paymentHash.lowercase()) cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) throw SparkError.InvoiceExpired(it) @@ -698,33 +603,15 @@ class SparkRepo @Inject constructor( // 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) { - uncertainSends.remove(paymentHash.lowercase()) cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) 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) - val isInDoubt = settleUncertainSend( - paymentHash, - SendAttempt(sentAt.toULong(), earlierIds, attemptId = attemptId), - expiresAt - ) - // An outcome handled meanwhile is known, so the caller reads it as it does after a returned send. - if (isInDoubt) throw PaymentPendingException(paymentHash) - return@runSuspendCatching paymentHash - } - if (payment.status != PaymentStatus.PENDING) { - takenAttempts.remove(paymentHash.lowercase()) - restoredTakenAttempts.remove(paymentHash.lowercase()) - cacheStore.removeSparkUncertainSend(paymentHash) + settleUncertainSend(paymentHash, expiresAt) + throw PaymentPendingException(paymentHash) } - // A failure Spark reported during the call is this send's own once the call returns its payment, failed or - // still pending, so it settles now. A pending one is settled only while its attempt still holds it, taken - // off in one step, as the expiry sweep may have reported its outcome meanwhile. - failures?.get(payment.id) - ?.takeIf { payment.status != PaymentStatus.COMPLETED } - ?.takeIf { payment.status == PaymentStatus.FAILED || releaseTakenAttempt(paymentHash, attemptId) } - ?.let { onPayment(it) } + cacheStore.removeSparkUncertainSend(paymentHash) Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) paymentHash }.onFailure { @@ -736,27 +623,12 @@ class SparkRepo @Inject constructor( } } - /** - * Holds [attempt]'s send in doubt and polls Spark for its outcome; false when that outcome was handled meanwhile. - */ - private suspend fun settleUncertainSend(paymentHash: String, attempt: SendAttempt, expiresAt: ULong): Boolean { - val key = paymentHash.lowercase() + private suspend fun settleUncertainSend(paymentHash: String, expiresAt: ULong) { val failedAt = clock.now().epochSeconds - // Only while this attempt still holds the send, as a sync or payment event that settled it meanwhile keeps it - // settled, and under the lock their cleanup takes, so its journal entry is never written back after it. - val isHeld = sendReleaseMutex.withLock { - if (uncertainSends[key]?.attempt?.attemptId != attempt.attemptId) return@withLock false - uncertainSends[key] = UncertainSend(failedAt.toULong(), expiresAt, attempt) - cacheStore.addSparkUncertainSend( - paymentHash, - failedAt, - attempt.sentAt?.toLong(), - attempt.earlierIds, - attempt.attemptId, - ) - true - } - if (!isHeld) return false + // The time kept before the send went out stays its start, which tells its own failure from earlier ones. + val startedAt = cacheStore.data.first().sparkUncertainSends[paymentHash.lowercase()] ?: failedAt + uncertainSends[paymentHash.lowercase()] = UncertainSend(startedAt.toULong(), failedAt.toULong(), expiresAt) + cacheStore.addSparkUncertainSend(paymentHash, startedAt) scope.launch { // The send screen tracks the hash as pending only once the send returns, and resolves tracked ones. withTimeoutOrNull(PENDING_TRACK_WAIT) { @@ -771,58 +643,32 @@ class SparkRepo @Inject constructor( // Spark's next sync settles it, as a send it resumes then ends with its own payment event. Logger.warn("Stopped polling Spark send '$paymentHash' until Spark syncs again", context = TAG) } - return true } - /** Settles an uncertain send once Spark shows its outcome; true once it is settled, also by another caller. */ - private suspend fun trySettleUncertainSend(paymentHash: String): Boolean { + /** + * Settles an uncertain send once Spark shows its outcome; true once it is settled, also by another caller. A + * failure event for it [isFailureEvent] shows Spark reached the send, as a sync since would. + */ + private suspend fun trySettleUncertainSend(paymentHash: String, isFailureEvent: Boolean = false): Boolean { val key = paymentHash.lowercase() val uncertain = uncertainSends[key] ?: return true // Spark finishes an interrupted send only on a later sync, and a sync that never reached it still returns. val isSynced = hasSyncedSince(uncertain.failedAt) if (isSynced) _state.update { it.copy(hasSynced = true) } // Spark keeps a send it committed but didn't finish in a cache no call exposes, and a sync that reached Spark - // can still fail to resume it, so only an expired invoice shows a missing send will never go out, and only in a - // list from a sync made after it expired. - val isFinal = clock.now().epochSeconds.toULong() >= uncertain.expiresAt && - hasSyncedSince(maxOf(uncertain.failedAt, uncertain.expiresAt)) - // The outcome and the payment its row is written from come from one read, so a later read can't miss it. - val (send, listed) = listedLightningSendPayment(paymentHash, uncertain.attempt.earlierIds) + // can still fail to resume it, so only an expired invoice shows a missing send will never go out. + val isFinal = (isSynced || isFailureEvent) && clock.now().epochSeconds.toULong() >= uncertain.expiresAt + val send = listedLightningSend(paymentHash) val isSettled = when (send) { SparkLightningSend.NotFound -> isFinal - // A failed row may be an earlier attempt's, so it is final only when a missing one would be. - is SparkLightningSend.Found -> send.status != PaymentStatus.FAILED || isFinal + // A failure dated before the send started is an earlier attempt's, so it is final only when a missing + // send would be. + is SparkLightningSend.Found -> send.status != PaymentStatus.FAILED || isFinal || hasOwnFailure(paymentHash) SparkLightningSend.Unavailable -> false } - if (!isSettled) return false - // A missing send's row is ended here, as no listed payment revisits it, so the hold stays until it is written. - val holds = { uncertainSends[key] === uncertain } - if (send == SparkLightningSend.NotFound && !failHeldRow(paymentHash, uncertain.attempt, holds)) return false - // A listed failure may be an earlier attempt's, so the send's own row is failed in place instead of taking - // that attempt's amount, fee and time. - val isFailed = send is SparkLightningSend.Found && send.status == PaymentStatus.FAILED - if (isFailed && !failHeldRow(paymentHash, uncertain.attempt, holds)) return false - // A send Spark now runs keeps its earlier attempts' ids until it settles, taken over before the doubt ends. - val isTaken = send is SparkLightningSend.Found && send.status == PaymentStatus.PENDING - // Only the caller that takes the hash off settles it, so its outcome is reported once. The hand-over shares the - // lock a payment event's cleanup takes, so a send settled meanwhile keeps no attempt to report again at expiry. - // The listed pending payment is the retry Spark now runs, so its id marks the retry's own failure. - val taken = uncertain.attempt.copy(ownId = listed?.id ?: uncertain.attempt.ownId) - // Read while the attempt still holds the invoice, as its earlier ids tell a listed failure apart. - val isEarlierListed = listed?.isEarlierFailureOfUncertainSend() == true - val isOwner = sendReleaseMutex.withLock { - val isMarked = isTaken && takenAttempts.putIfAbsent(key, taken) == null - // Only the attempt marked here is rolled back, as a retry may have replaced it meanwhile. - val isRemoved = uncertainSends.remove(key, uncertain) - if (!isRemoved && isMarked) takenAttempts.remove(key, taken) - isRemoved - } - if (!isOwner) return true - if (isTaken) { - cacheStore.keepSparkSendAttempt(paymentHash, taken.ownId, taken.attemptId) - } else { - cacheStore.removeSparkUncertainSend(paymentHash) - } + // Only the caller that takes the hash off settles it, so its outcome is reported once. + if (!isSettled || !uncertainSends.remove(key, uncertain)) return isSettled + cacheStore.removeSparkUncertainSend(paymentHash) when (send) { SparkLightningSend.NotFound -> { cacheStore.removeSparkSendHash(paymentHash) @@ -833,186 +679,30 @@ class SparkRepo @Inject constructor( is SparkLightningSend.Found -> { if (send.status == PaymentStatus.FAILED) { cacheStore.removeSparkSendHash(paymentHash) - // Writes the row only when there was none to fail or the failure is the send's own, as a failed row - // keeps its own payment; a failed write is retried at the next refresh. - // A failure the attempt didn't read as earlier is its own, also when its send call never - // returned its id. - listed?.takeUnless { isEarlierListed && hasStoredRow(paymentHash) }?.let { - recordActivity(it, ownId = uncertain.attempt.ownId ?: it.id.takeUnless { isEarlierListed }) - } + // Its row stayed pending while held, so it takes the failure now. + runSuspendCatching { sparkService.listPayments() }.getOrNull() + ?.latestSend(paymentHash) + ?.let { recordActivity(it) } } - // The event comes from the read that settled it, so a failed later read can't leave the send pending. - listed?.toNodeEvent()?.let { _nodeEvents.emit(it) } + settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } } SparkLightningSend.Unavailable -> Unit } return true } - /** - * Whether Activity holds a row of [paymentHash], also when it can't be read, so a write is left to the next - * refresh. - */ - private suspend fun hasStoredRow(paymentHash: String): Boolean = - activityRepo.get().getActivity(paymentHash).fold(onSuccess = { it != null }, onFailure = { true }) - - /** - * Marks the pending send row of [paymentHash] failed, as Spark lists no send of it; true once nothing is pending. - * Read and write share the lock Spark's own row writes take, so a settlement written meanwhile is not overwritten, - * and the write happens only while the caller still [holds] the send, so a newer retry's row is left alone. The - * row is the held [attempt]'s from then on, so its writer becomes that attempt before the write, kept across a - * restart that cuts the two apart. - */ - private suspend fun failHeldRow( - paymentHash: String, - attempt: SendAttempt, - holds: () -> Boolean, - ): Boolean = sendReleaseMutex.withLock { - // A hold that ended meanwhile is no longer the caller's to end, which its own removal then finds. - if (!holds()) return@withLock true - val stored = activityRepo.get().getActivity(paymentHash).getOrElse { - Logger.warn("Failed to read activity of Spark send '$paymentHash'", it, context = TAG) - return@withLock false - } - val send = (stored as? Activity.Lightning)?.v1 - if (send?.txType != PaymentType.SENT || send.status != PaymentState.PENDING) return@withLock true - // A writer the attempt read as earlier no longer owns the row once the row differs from what it wrote, as a - // retry wrote over it, while the attempt's own one keeps protecting it. The ids kept from earlier retries count - // too, as this attempt's own read of them can have failed. - val cache = cacheStore.data.first() - val hash = paymentHash.lowercase() - val rowId = cache.sendRowWriter(hash, send) - val earlierIds = attempt.earlierIds.orEmpty() + cache.sparkSendEarlierIds[hash].orEmpty() - val isWrittenOver = !cache.isRowStampKept(hash, send) - val failed = send.copy(status = PaymentState.FAILED) - when { - attempt.ownId != null -> cacheStore.keepSparkSendRowId(paymentHash, attempt.ownId, failed.sendRowStamp()) - rowId != null && rowId in earlierIds && isWrittenOver -> cacheStore.removeSparkSendRowId(paymentHash) - } - activityRepo.get().upsertActivity(Activity.Lightning(failed)) - .onFailure { Logger.warn("Failed to mark Spark send '$paymentHash' failed", it, context = TAG) } - .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } - } - - /** - * A send whose outcome Spark didn't report: when it failed and when its invoice expires, in epoch seconds, and its - * [attempt], kept across a restart. - */ - private data class UncertainSend( - val failedAt: ULong, - val expiresAt: ULong, - val attempt: SendAttempt = SendAttempt() - ) - - /** - * When a send went out, in epoch seconds, and Spark's payment ids of its invoice's earlier attempts, read before it - * did; null where unknown, such as for a send kept before these were stored or one Spark couldn't list for. - */ - private data class SendAttempt( - val sentAt: ULong? = null, - val earlierIds: Set? = null, - val ownId: String? = null, - val attemptId: String? = null, - ) + /** A send whose outcome Spark didn't report: when it failed, and when its invoice expires, in epoch seconds. */ + private data class UncertainSend(val startedAt: ULong, val failedAt: ULong, val expiresAt: ULong) /** Takes back the sends whose outcome Spark didn't report before a restart, so a sync can still settle them. */ - private suspend fun restoreUncertainSends() = sendReleaseMutex.withLock { - // Read and installed under the lock a payment event's cleanup takes, so a hold it clears is never reloaded. + private suspend fun restoreUncertainSends() { val cache = cacheStore.data.first() cache.sparkUncertainSends.forEach { (hash, failedAt) -> val expiresAt = cache.sparkSendExpiries[hash]?.toULong() ?: ULong.MAX_VALUE - val attempt = SendAttempt( - sentAt = cache.sparkUncertainSendStarts[hash]?.toULong(), - earlierIds = cache.sparkUncertainSendEarlierIds[hash]?.toSet(), - attemptId = cache.sparkUncertainSendAttemptIds[hash], - ) - uncertainSends.putIfAbsent(hash, UncertainSend(failedAt.toULong(), expiresAt, attempt)) - } - (cache.sparkUncertainSendStarts.keys + cache.sparkUncertainSendEarlierIds.keys + cache.sparkTakenSendIds.keys) - .filter { it !in cache.sparkUncertainSends } - .forEach { hash -> - val attempt = SendAttempt( - sentAt = cache.sparkUncertainSendStarts[hash]?.toULong(), - earlierIds = cache.sparkUncertainSendEarlierIds[hash]?.toSet(), - ownId = cache.sparkTakenSendIds[hash], - attemptId = cache.sparkUncertainSendAttemptIds[hash], - ) - if (takenAttempts.putIfAbsent(hash, attempt) == null) restoredTakenAttempts.add(hash) - } - } - - /** - * Drops the attempts of sends Spark took whose invoice expired, once their row is written from Spark's list, as a - * failure the attempt held back may be the send's own. A send Spark still runs, or a list it can't read, keeps it. - * One Spark lists no outcome of, or only an earlier attempt's failure, fails its row once - * [UNLISTED_TAKEN_SEND_GRACE] past the expiry. - */ - private suspend fun dropExpiredTakenAttempts() { - val expiries = cacheStore.data.first().sparkSendExpiries - val now = clock.now().epochSeconds - takenAttempts.keys.filter { (expiries[it] ?: Long.MAX_VALUE) <= now }.forEach { hash -> - val attempt = takenAttempts[hash] ?: return@forEach - val expiresAt = expiries[hash] ?: return@forEach - // Spark may list a send it took only on a later sync, so an unlisted one stays held for a while, and its - // absence counts only in a list from a sync made after that. - val graceEndsAt = expiresAt + UNLISTED_TAKEN_SEND_GRACE.inWholeSeconds - // Read before the list, so a sync that ends between the two reads can't vouch for an older list. - val isPastGrace = now >= graceEndsAt && hasSyncedSince(graceEndsAt.toULong()) - val holds = { takenAttempts[hash] === attempt } - val (send, listedSend) = listedLightningSendPayment(hash, attempt.earlierIds) - var listed = listedSend - when (send) { - SparkLightningSend.Unavailable -> return@forEach - SparkLightningSend.NotFound -> if (!isPastGrace || !failHeldRow(hash, attempt, holds)) return@forEach - is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> return@forEach - // A failure with another id than the attempt's own is an earlier attempt's, listed before the attempt, - // so the retry's own row is failed instead of taking that attempt's amount, fee and time. - is SparkLightningSend.Found if send.status == PaymentStatus.FAILED && attempt.ownId != null && - listed?.id != attempt.ownId -> { - if (!isPastGrace || !failHeldRow(hash, attempt, holds)) return@forEach - listed = null - } - - is SparkLightningSend.Found -> Unit - } - // Only the attempt read here is dropped, as a retry may have replaced it meanwhile. - if (!takenAttempts.remove(hash, attempt)) return@forEach - // A restored attempt's outcome came while the app was closed and no event held it back, so none is sent. - val isRestored = restoredTakenAttempts.remove(hash) - cacheStore.removeSparkUncertainSend(hash) - if (listed?.status != PaymentStatus.COMPLETED) cacheStore.removeSparkSendHash(hash) - // Written once the attempt is gone, so it no longer holds the row back, with the own id the attempt - // matched; a failed write is retried at the next refresh. - // Without its own id, a failure its earlier ids leave out is the attempt's own. - listed?.let { - val ownId = attempt.ownId ?: it.id.takeIf { id -> attempt.earlierIds?.contains(id) == false } - recordActivity(it, ownId = ownId) - } - if (isRestored) return@forEach - // The send's own outcome event may have been held back with the attempt, so the send screen learns it here. - val event = listed?.toNodeEvent() - ?: Event.PaymentFailed(hash, hash, PaymentFailureReason.UNEXPECTED_ERROR) - _nodeEvents.emit(event) + uncertainSends.putIfAbsent(hash, UncertainSend(failedAt.toULong(), failedAt.toULong(), expiresAt)) } } - /** - * Sends Spark took whose attempts are kept past their invoice's expiry until [dropExpiredTakenAttempts] ends them, - * also ones kept from before a restart not yet taken back, so one Spark doesn't list yet still reads as pending. - */ - private suspend fun retainedSendHashes(): Set { - val cache = cacheStore.data.first() - val journaled = cache.sparkUncertainSendStarts.keys + cache.sparkUncertainSendEarlierIds.keys + - cache.sparkTakenSendIds.keys - return takenAttempts.keys + (journaled - cache.sparkUncertainSends.keys) - } - - /** - * Sends in doubt or kept past their expiry by an attempt Spark took, read in the order a sync hands a send from the - * one to the other, so a send handed over meanwhile is found in either. - */ - private suspend fun heldSendHashes(): Set = uncertainSendHashes() + retainedSendHashes() - /** Sends whose outcome Spark didn't report, also ones kept from before a restart not yet taken back. */ private suspend fun uncertainSendHashes(): Set = uncertainSends.keys + cacheStore.data.first().sparkUncertainSends.keys @@ -1586,7 +1276,7 @@ class SparkRepo @Inject constructor( private suspend fun connectForRestore(walletIndex: Int) { // Spark's listener drops events no one collects, and the wallet's start collects them only after the restore. - // The sends held before the restore are taken back first, so its events read their earlier attempts. + // The sends held before the restore are taken back first, so its events settle them. restoreUncertainSends() collectEvents() runSuspendCatching { sparkService.connect(walletIndex, exitStore(walletIndex).isActive()) } @@ -1619,8 +1309,6 @@ class SparkRepo @Inject constructor( val info = sparkService.getInfo() info.lastSyncError?.let { Logger.warn("Failed to sync Spark, balances may be stale: '$it'", context = TAG) } val unclaimed = sparkService.listUnclaimedDeposits() - // Read before the list, so a retry recorded after it keeps its row from a failure the list still shows. - val records = sendRecords.get() val payments = sparkService.listPayments() val claimedPayments = payments .filter { it.method == PaymentMethod.DEPOSIT && it.status == PaymentStatus.COMPLETED } @@ -1673,9 +1361,9 @@ class SparkRepo @Inject constructor( ).withBroadcastDeposits() } markClaimedDeposits(claimed) - payments + payments.decidingRows() .filter { it.id in unsavedPayments || (it.id in sendsRecordedWithoutFee && it.fees.toLong() > 0) } - .forEach { recordActivity(it, records = records) } + .forEach { recordActivity(it) } // Off the refresh, so a slow Electrum server never holds a send that waits for it. scope.launch { confirmMinedPayouts(payments) } markTransfers(payments) @@ -1772,22 +1460,36 @@ class SparkRepo @Inject constructor( */ suspend fun settledSendEvent(paymentHash: String): Event? = withContext(bgDispatcher) { if (!sparkService.isConnected) return@withContext null - val hash = paymentHash.lowercase() - // A failure leaves a send in doubt or in Spark's send call pending, as the other lookups read it, also one - // that a sync hands from the one to the other meanwhile. - val isHeldBefore = hash in uncertainSendHashes() || inFlightAttempts.containsKey(hash) runSuspendCatching { sparkService.listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrNull() ?.latestSend(paymentHash) - ?.takeUnless { it.isEarlierFailureOfUncertainSend() } - ?.takeUnless { - it.status == PaymentStatus.FAILED && - (isHeldBefore || hash in uncertainSendHashes() || inFlightAttempts.containsKey(hash)) - } + // A send in doubt or in Spark's send call is pending until Spark settles it, so a listed failure, which + // may be an earlier attempt's, settles nothing yet. + ?.takeUnless { it.status == PaymentStatus.FAILED && isHeldFrom(it) } ?.toNodeEvent() } + /** + * Whether [failure] leaves its send pending: while it is in Spark's send call, whose result settles it, or in doubt + * and Spark dates the failure more than [OWN_FAILURE_CLOCK_MARGIN_SECS] before the send started, as an earlier + * attempt's. + */ + private suspend fun isHeldFrom(failure: Payment): Boolean { + val hash = failure.sendHash()?.lowercase() ?: return false + if (sendsInFlight.containsKey(hash)) return true + val startedAt = uncertainSends[hash]?.startedAt + ?: cacheStore.data.first().sparkUncertainSends[hash]?.toULong() + ?: return false + return failure.timestamp.safe() + OWN_FAILURE_CLOCK_MARGIN_SECS.safe() < startedAt + } + + private suspend fun hasOwnFailure(paymentHash: String): Boolean { + val failure = runSuspendCatching { sparkService.listPayments() }.getOrNull()?.latestSend(paymentHash) + ?.takeIf { it.status == PaymentStatus.FAILED } ?: return false + return !isHeldFrom(failure) + } + /** * False while Spark is supported but not connected or not yet synced, since its payment list is read from local * storage that a restored wallet fills only on its first sync, so a missing payment proves nothing until then. @@ -1802,8 +1504,8 @@ class SparkRepo @Inject constructor( suspend fun lightningSendStatuses(): Map? = withContext(bgDispatcher) { if (!sparkService.isSupported) return@withContext emptyMap() if (!canListPayments()) return@withContext null + val unlisted = unexpiredStartedSends() val uncertain = uncertainSendHashes() - val unlisted = unexpiredStartedSends() + retainedSendHashes() val payments = runSuspendCatching { sparkService.listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrElse { return@withContext null } @@ -1815,10 +1517,9 @@ class SparkRepo @Inject constructor( } .distinct() .associateWith { hash -> - val latest = requireNotNull(payments.latestSend(hash)) - // A failed row may be an earlier attempt's, while Spark may still finish the uncertain or taken retry. - val isHeld = hash.lowercase() in uncertain || latest.isEarlierFailureOfUncertainSend() - if (latest.status == PaymentStatus.FAILED && isHeld) PaymentStatus.PENDING else latest.status + val status = requireNotNull(payments.latestSend(hash)).status + // A failed row may be an earlier attempt's, while Spark may still finish the uncertain retry. + if (status == PaymentStatus.FAILED && hash.lowercase() in uncertain) PaymentStatus.PENDING else status } val listedHashes = listed.keys.mapTo(mutableSetOf()) { it.lowercase() } listed + (unlisted + uncertain - listedHashes).associateWith { PaymentStatus.PENDING } @@ -1833,44 +1534,27 @@ class SparkRepo @Inject constructor( */ suspend fun lightningSend(paymentHash: String): SparkLightningSend = withContext(bgDispatcher) { val hash = paymentHash.lowercase() - val isUnlistedHeld = hash in unexpiredStartedSends() || hash in heldSendHashes() - val (send, listed) = listedLightningSendPayment(paymentHash) + val isUnlistedHeld = hash in unexpiredStartedSends() + val send = listedLightningSend(paymentHash) val isUncertain = hash in uncertainSendHashes() val isHeld = when (send) { - // Read again after the list, as a sync can hand the send from its doubt to Spark meanwhile. - SparkLightningSend.NotFound, SparkLightningSend.Unavailable -> isUnlistedHeld || hash in heldSendHashes() - // An earlier attempt's failure leaves a retry Spark took or still sends pending. - is SparkLightningSend.Found -> - send.status == PaymentStatus.FAILED && - (isUncertain || listed?.isEarlierFailureOfUncertainSend() == true) + SparkLightningSend.NotFound, SparkLightningSend.Unavailable -> isUncertain || isUnlistedHeld + is SparkLightningSend.Found -> isUncertain && send.status == PaymentStatus.FAILED } if (isHeld) SparkLightningSend.Found(PaymentStatus.PENDING, null) else send } /** Spark's listed record of the Lightning send with [paymentHash], as [lightningSend] reads it before its holds. */ - private suspend fun listedLightningSend(paymentHash: String): SparkLightningSend = - listedLightningSendPayment(paymentHash).first - - /** - * Spark's listed record of the Lightning send with [paymentHash] and the payment it was read from, in one read, - * preferring a payment that is not one of the attempt's [earlierIds], as Spark can date both in the same second. - */ - private suspend fun listedLightningSendPayment( - paymentHash: String, - earlierIds: Set? = null, - ): Pair = - withContext(bgDispatcher) { - if (!sparkService.isSupported) return@withContext SparkLightningSend.NotFound to null - if (!canListPayments()) return@withContext SparkLightningSend.Unavailable to null - val payments = runSuspendCatching { sparkService.listPayments() } - .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } - .getOrElse { return@withContext SparkLightningSend.Unavailable to null } - val latest = earlierIds?.let { ids -> payments.filterNot { it.id in ids }.latestSend(paymentHash) } - ?: payments.latestSend(paymentHash) - ?: return@withContext SparkLightningSend.NotFound to null - val preimage = (latest.details as PaymentDetails.Lightning).htlcDetails.preimage - SparkLightningSend.Found(latest.status, preimage) to latest - } + private suspend fun listedLightningSend(paymentHash: String): SparkLightningSend = withContext(bgDispatcher) { + if (!sparkService.isSupported) return@withContext SparkLightningSend.NotFound + if (!canListPayments()) return@withContext SparkLightningSend.Unavailable + val payments = runSuspendCatching { sparkService.listPayments() } + .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } + .getOrElse { return@withContext SparkLightningSend.Unavailable } + payments.latestSend(paymentHash) + ?.let { SparkLightningSend.Found(it.status, (it.details as PaymentDetails.Lightning).htlcDetails.preimage) } + ?: SparkLightningSend.NotFound + } /** * Spark's pending or paid send of [bolt11], matched by the invoice or its [paymentHash], so the node never pays it @@ -1918,7 +1602,7 @@ class SparkRepo @Inject constructor( } seedSendHashes(payments) val send = payments - .latestSend(paymentHash?.let { heldAttempt(it)?.ownId }) { + .latestSend { it.invoice.equals(bolt11, ignoreCase = true) || it.htlcDetails.paymentHash.equals(paymentHash, ignoreCase = true) } @@ -1930,9 +1614,6 @@ class SparkRepo @Inject constructor( } if (send.status == PaymentStatus.FAILED) { retried()?.let { return@withContext EarlierSend.Pending(it) } - // An earlier attempt's failure leaves a retry Spark took or still sends pending. - send.takeIf { it.isEarlierFailureOfUncertainSend() }?.sendHash() - ?.let { return@withContext EarlierSend.Pending(it) } refuseUnverifiedRestoredInvoice(bolt11, invoiceCreatedAt, invoiceExpiresAt) } val hash = (send.details as PaymentDetails.Lightning).htlcDetails.paymentHash @@ -2016,26 +1697,19 @@ class SparkRepo @Inject constructor( } private fun List.latestSend(paymentHash: String): Payment? = - latestSend( - heldAttempt(paymentHash)?.ownId - ) { it.htlcDetails.paymentHash.equals(paymentHash, ignoreCase = true) } + latestSend { it.htlcDetails.paymentHash.equals(paymentHash, ignoreCase = true) } - /** - * The send that settles the invoice [matches] picks: a retry of a failed send shares its hash, so the outcome that - * settles it wins, and between equal outcomes the held attempt's own payment, [ownId]. - */ - private fun List.latestSend( - ownId: String? = null, - matches: (PaymentDetails.Lightning) -> Boolean, - ): Payment? = filter { + private fun List.latestSend(matches: (PaymentDetails.Lightning) -> Boolean): Payment? = filter { val details = it.details as? PaymentDetails.Lightning it.paymentType == SparkPaymentType.SEND && details != null && matches(details) - }.minWithOrNull(compareBy({ SEND_STATUS_PRIORITY.indexOf(it.status) }, { it.id != ownId })) + } + // A retry of a failed send shares its hash, so the outcome that settles it wins, then the latest attempt. + .minWithOrNull(compareBy({ SEND_STATUS_PRIORITY.indexOf(it.status) }, { -it.timestamp.toLong() })) - /** The attempt that holds [paymentHash]: one in doubt, one in Spark's send call, or one Spark took. */ - private fun heldAttempt(paymentHash: String): SendAttempt? { - val key = paymentHash.lowercase() - return uncertainSends[key]?.attempt ?: inFlightAttempts[key] ?: takenAttempts[key] + /** Drops each send another attempt on its invoice decides, so one Activity row shows the deciding outcome. */ + private fun List.decidingRows(): List = filter { + val hash = (it.details as? PaymentDetails.Lightning)?.htlcDetails?.paymentHash + it.paymentType != SparkPaymentType.SEND || hash == null || latestSend(hash)?.id == it.id } /** Payment hashes of the Lightning payments Spark received. */ @@ -2051,21 +1725,27 @@ class SparkRepo @Inject constructor( if (!sparkService.isSupported) return emptySet() val unlisted = unexpiredStartedSends() val uncertain = uncertainSendHashes() - if (!sparkService.isConnected) return null - val payments = withContext(bgDispatcher) { runSuspendCatching { sparkService.listPayments() } } - .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } - .getOrNull() ?: return null - val sends = payments.mapNotNull { payment -> payment.sendHash()?.lowercase()?.let { it to payment } } - .groupBy({ it.first }, { it.second }) - // A retained attempt Spark lists as failed itself no longer holds its invoice; an earlier attempt's failure - // leaves it held. - val taken = takenAttempts.filter { (hash, attempt) -> - sends[hash].orEmpty().none { it.status == PaymentStatus.FAILED && it.id == attempt.ownId } - }.keys - return sends.filterValues { it.any { payment -> payment.status != PaymentStatus.FAILED } }.keys + - (unlisted - sends.keys) + uncertain + taken + val sends = lightningPaymentStatuses { it.paymentType == SparkPaymentType.SEND } ?: return null + return sends.filterValues { it.any { status -> status != PaymentStatus.FAILED } }.keys + + (unlisted - sends.keys) + uncertain } + /** The statuses of Spark's Lightning payments that match [filter], by lowercase payment hash. */ + private suspend fun lightningPaymentStatuses(filter: (Payment) -> Boolean): Map>? = + withContext(bgDispatcher) { + if (!sparkService.isConnected) return@withContext null + runSuspendCatching { sparkService.listPayments() } + .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } + .getOrNull() + ?.filter(filter) + ?.mapNotNull { payment -> + (payment.details as? PaymentDetails.Lightning)?.htlcDetails?.paymentHash?.lowercase() + ?.let { it to payment.status } + } + ?.groupBy({ it.first }, { it.second }) + ?.mapValues { it.value.toSet() } + } + private suspend fun lightningPaymentHashes(filter: (Payment) -> Boolean): Set? = withContext(bgDispatcher) { if (!sparkService.isConnected) return@withContext null runSuspendCatching { sparkService.listPayments() } @@ -2118,7 +1798,7 @@ class SparkRepo @Inject constructor( val isSynced = canListPayments() val payments = sparkService.listPayments() if (isSynced) seedSendHashes(payments) - val isSaved = payments.map { recordActivity(it, records = recordsBefore) }.all { it } + val isSaved = payments.decidingRows().map { recordActivity(it) }.all { it } releaseFailedSends(payments, recordsBefore, inFlightBefore) if (!settleJournal || wasWithdrawing || isWithdrawing || withdrawalSendsEnded.get() != sendsEndedBefore) { return isSaved @@ -2173,10 +1853,9 @@ class SparkRepo @Inject constructor( } // A send in flight, also one that ended while this list was read, or recorded after it was read while the // activities were recorded, may be missing from it or show only its earlier failed attempt, so it stays, as - // does one whose outcome Spark didn't report, also from before a restart, and one Spark took that keeps its - // attempt, until the expiry rule writes its row. + // does one whose outcome Spark didn't report, also from before a restart. val live = sendHashes(PaymentStatus.PENDING) + sendsInFlight.keys + inFlightBefore + - recordedSince(recordsBefore) + uncertainSendHashes() + takenAttempts.keys + recordedSince(recordsBefore) + uncertainSendHashes() val paid = sendHashes(PaymentStatus.COMPLETED) - live cacheStore.trimSparkSendHashes( paid = paid, @@ -2194,147 +1873,15 @@ class SparkRepo @Inject constructor( val inFlightBeforeCurrent = sendsInFlight.keys.toSet() val current = runSuspendCatching { sparkService.listPayments() }.getOrNull() ?: return val liveCurrent = sendsInFlight.keys + inFlightBeforeCurrent + recordedSince(recordsBeforeCurrent) + - uncertainSendHashes() + takenAttempts.keys + uncertainSendHashes() failed .filter { it.lowercase() !in liveCurrent } .filter { current.latestSend(it)?.status == PaymentStatus.FAILED } .forEach { cacheStore.removeSparkSendHash(it) } } - /** - * Whether this failure is an earlier attempt's than the failed send [row] of [paymentHash], so the row keeps its - * own attempt's amount, fee and time against it, listed again on a later launch once nothing holds the invoice. - * The row's own or a later attempt's failure, and that of the attempt [ownId] or the held one names, still write - * it. - */ - private suspend fun Payment.isEarlierFailureThan(row: LightningActivity, paymentHash: String, ownId: String?) = - row.status == PaymentState.FAILED && row.txType == PaymentType.SENT && status == PaymentStatus.FAILED && - id != (ownId ?: heldAttempt(paymentHash)?.ownId) && isEarlierThan(row, paymentHash) - - /** - * Whether this payment is of an attempt a later one read as earlier before it went out, kept past its hold and a - * restart, while it no longer wrote the [row] of [paymentHash] and the row's writer is no such attempt, or Spark - * dates it before the row or ties it as another payment than the one that wrote the row, kept before it when both - * are such earlier attempts. - */ - private suspend fun Payment.isEarlierThan(row: LightningActivity, paymentHash: String): Boolean { - val cache = cacheStore.data.first() - val hash = paymentHash.lowercase() - val earlierIds = heldAttempt(paymentHash)?.earlierIds.orEmpty() + cache.sparkSendEarlierIds[hash].orEmpty() - val rowId = cache.sendRowWriter(hash, row) - // Spark's dates can put an earlier attempt's failure after the retry's row, while a retry Spark refused leaves - // the row, and its fee corrections, to that attempt. - if (id in earlierIds && rowId != id && rowId !in earlierIds) return true - if (timestamp != row.timestamp) return timestamp < row.timestamp - rowId ?: return false - if (rowId == id) return false - // Two attempts later sends read as earlier and Spark dates in the same second are ordered as those sends kept - // them. A read that left one out keeps it after later ones, so their dates come first. - val order = cache.sparkSendEarlierIds[hash].orEmpty() - if (id in order && rowId in order) return order.indexOf(id) < order.indexOf(rowId) - return rowId !in earlierIds - } - - private fun LightningActivity.sendRowStamp() = "$timestamp:$value:$fee:$status" - - /** - * The payment that wrote [row] of [hash]: the kept writer, unless a stop cut its row write short, when the row - * still matches the stamp of the writer it had before, also where both stamps match, as the row is then alike to - * either and the one it had before keeps its fee corrections. - */ - private fun AppCacheData.sendRowWriter(hash: String, row: LightningActivity): String? { - val previous = sparkSendPreviousRowWriters[hash]?.takeIf { it.getOrNull(1) == row.sendRowStamp() } - ?: return sparkSendRowIds[hash] - return previous.first().ifEmpty { null } - } - - private fun AppCacheData.isRowStampKept(hash: String, row: LightningActivity): Boolean { - val stamp = row.sendRowStamp() - return sparkSendRowStamps[hash] == stamp || sparkSendPreviousRowWriters[hash]?.getOrNull(1) == stamp - } - - /** - * Writes [activity], the row of [payment], unless a retry recorded after [records] outran it, then null. A send - * row's writer is kept before the row, so a stop between the two never leaves a retry's row, alike in time, amount - * and fee, to an earlier writer, and the stamp of the row it replaces, [rowStamp], tells a write a stop cut short; - * a failed write puts the previous one back. - */ - private suspend fun saveLightningRow( - payment: Payment, - activity: LightningActivity, - records: Long, - rowStamp: String?, - ): Boolean? = - sendReleaseMutex.withLock { - if (payment.isOutrunByRetry(records)) return@withLock null - val hash = activity.id.lowercase() - val isSend = payment.paymentType == SparkPaymentType.SEND - val before = cacheStore.data.first() - if (isSend) { - cacheStore.keepSparkSendRowId(hash, payment.id, activity.sendRowStamp(), beforeRow = true, rowStamp) - } - val isSaved = activityRepo.get().upsertActivity(Activity.Lightning(activity)) - .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } - if (isSend && isSaved) cacheStore.commitSparkSendRowId(hash) - // Both writers a stop left are put back, so the row's own writer still takes its correction later. - if (isSend && !isSaved) { - cacheStore.restoreSparkSendRowWriter( - hash, - before.sparkSendRowIds[hash], - before.sparkSendRowStamps[hash], - before.sparkSendPreviousRowWriters[hash], - ) - } - isSaved - } - private fun recordedSince(records: Long): Set = sendRecordedAt.filterValues { it > records }.keys - /** Whether this failure is an earlier attempt's, of a retry in doubt or one sent after [records] was read. */ - private fun Payment.isOutrunByRetry(records: Long): Boolean = - isEarlierFailureOfUncertainSend() || hasRecordedSendSince(records, sendHash(PaymentStatus.FAILED)) - - /** - * Whether this failure may be an earlier attempt's, of a retry still in Spark's send call or in doubt, so it never - * ends the retry's hold: any failure while the call runs, one of the attempts Spark listed before the retry went - * out, or, with none listed, one Spark dates before the retry plus its clock skew. A retry in doubt also counts a - * failure that list doesn't name as earlier when Spark dates it before the retry minus that skew. - */ - private fun Payment.isEarlierFailureOfUncertainSend(): Boolean { - val hash = sendHash(PaymentStatus.FAILED) ?: return false - val attempt = heldAttempt(hash) ?: return false - // A payment Spark took fails with its own id, so a failure with another id is an earlier attempt's. - attempt.ownId?.let { return id != it } - // The call's own result, or its move into doubt, settles a send still in Spark's send call. - val key = hash.lowercase() - if (!uncertainSends.containsKey(key) && inFlightAttempts.containsKey(key)) return true - attempt.earlierIds?.let { ids -> - if (id in ids) return true - // The list read before a send in doubt went out can lack an older attempt, so a failure that list doesn't - // name is earlier when Spark dates it clearly before the send, while its own failure, dated at its start, - // ends its hold. - val sentAt = attempt.sentAt - return sentAt != null && uncertainSends.containsKey(key) && timestamp + RAIL_CLOCK_SKEW_SECONDS <= sentAt - } - // A send kept before start times were stored can't tell its own failure from an earlier one, so it stays held - // until its invoice expires, when the expiry rule settles it and its row. - val sentAt = attempt.sentAt ?: return true - return timestamp < sentAt + RAIL_CLOCK_SKEW_SECONDS - } - - /** Spark's payment ids of the earlier attempts to pay [paymentHash], or null while it can't list them all. */ - private suspend fun earlierAttemptIds(paymentHash: String): Set? { - if (!canListPayments()) return null - val payments = runSuspendCatching { sparkService.listPayments() } - .onFailure { Logger.warn("Failed to list Spark payments before send '$paymentHash'", it, context = TAG) } - .getOrNull() ?: return null - return payments.filter { - val details = it.details as? PaymentDetails.Lightning - it.paymentType == SparkPaymentType.SEND && - details?.htlcDetails?.paymentHash.equals(paymentHash, ignoreCase = true) - }.mapTo(mutableSetOf()) { it.id } - } - /** The payment hash of this send, at [status] when given. */ private fun Payment.sendHash(status: PaymentStatus? = null): String? = (details as? PaymentDetails.Lightning) ?.takeIf { paymentType == SparkPaymentType.SEND && (status == null || this.status == status) } @@ -2350,7 +1897,6 @@ class SparkRepo @Inject constructor( refresh() // A send whose outcome stayed unknown past its polling settles on a later sync. uncertainSends.keys.toList().forEach { trySettleUncertainSend(it) } - if (hasSyncedSince(null)) dropExpiredTakenAttempts() // A journal left open past its grace period would block every later withdrawal until a restart. // Spark emits Synced after a sync that never reached it too, so only one since the journal // drops it. @@ -2377,107 +1923,52 @@ class SparkRepo @Inject constructor( } private suspend fun onPayment(payment: Payment) { - // A failure while a send call of its invoice runs waits for the call, which settles it once it returns that - // payment. - if (payment.keepFailureDuringCall()) { - payment.heldBackOutcome() - Logger.info("Kept Spark failure '${payment.id}' until its send call returns", context = TAG) - return - } - // A retry of the invoice can start while this event is handled, so each step checks for one sent since now. - val records = sendRecords.get() // The event carries its outcome, so a failed balance read never holds back its settlement. runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after payment '${payment.id}'", it, context = TAG) } - // An earlier attempt's failure can arrive after a retry of its invoice went uncertain, and ends nothing of the - // retry's: Spark may still finish it, so its hold and its Activity row stay until the expiry rule of - // trySettleUncertainSend. - if (payment.isOutrunByRetry(records)) { - payment.heldBackOutcome() - Logger.info("Kept uncertain Spark send '${payment.sendHash()}' held past an older failure", context = TAG) + // An earlier attempt's failure, or one during Spark's send call, leaves the send pending until its own outcome, + // its call's result or its invoice's expiry settles it. + payment.sendHash(PaymentStatus.FAILED)?.takeIf { isHeldFrom(payment) }?.let { + trySettleUncertainSend(it, isFailureEvent = true) return } - recordActivity(payment, settlesJournal = false, records = records) - val failedHash = payment.sendHash(PaymentStatus.FAILED) - val latest = failedHash?.let { listedLightningSend(it) } - val isSettled = sendReleaseMutex.withLock { - if (payment.isOutrunByRetry(records)) return@withLock false - // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. - payment.sendHash()?.let { - uncertainSends.remove(it.lowercase()) - // A send call that returns after this keeps no hold for the outcome handled here. - inFlightAttempts.remove(it.lowercase()) - takenAttempts.remove(it.lowercase()) - restoredTakenAttempts.remove(it.lowercase()) - cacheStore.removeSparkUncertainSend(it) - } + // A failure of an earlier attempt settles nothing while Spark lists a later one pending or paid. + payment.sendHash(PaymentStatus.FAILED)?.let { hash -> + val deciding = runSuspendCatching { sparkService.listPayments() }.getOrNull()?.latestSend(hash) + if (deciding != null && deciding.id != payment.id && deciding.status != PaymentStatus.FAILED) return + } + recordActivity(payment, settlesJournal = false) + // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. + payment.sendHash()?.let { + uncertainSends.remove(it.lowercase()) + cacheStore.removeSparkUncertainSend(it) + } + payment.sendHash(PaymentStatus.FAILED)?.let { hash -> + val latest = listedLightningSend(hash) val isReleased = latest == SparkLightningSend.NotFound || (latest as? SparkLightningSend.Found)?.status == PaymentStatus.FAILED - if (failedHash != null && isReleased) cacheStore.removeSparkSendHash(failedHash) - true - } - if (!isSettled) { - payment.heldBackOutcome() - Logger.info("Kept Spark send '${payment.sendHash()}' held for a retry sent meanwhile", context = TAG) - return + if (isReleased) cacheStore.removeSparkSendHash(hash) } payment.toNodeEvent()?.let { _nodeEvents.emit(it) } } - /** Takes [attemptId]'s taken attempt of [paymentHash] off; false when another caller settled it. */ - private fun releaseTakenAttempt(paymentHash: String, attemptId: String): Boolean { - val key = paymentHash.lowercase() - val attempt = takenAttempts[key]?.takeIf { it.attemptId == attemptId } ?: return false - return takenAttempts.remove(key, attempt) - } - - /** - * Keeps a failure Spark reports while a send call of its invoice runs and isn't in doubt, with that call's attempt; - * checked and kept in one step with the call's end, so the call either finds it or the event goes on. - */ - private fun Payment.keepFailureDuringCall(): Boolean { - val hash = sendHash(PaymentStatus.FAILED)?.lowercase() ?: return false - var isKept = false - inFlightAttempts.computeIfPresent(hash) { _, attempt -> - attempt.attemptId?.takeUnless { uncertainSends.containsKey(hash) }?.let { - failuresDuringCall.merge(it, mapOf(id to this)) { kept, new -> kept + new } - isKept = true - } - attempt - } - return isKept - } - - /** - * Marks the outcome of the restored retry of this payment's invoice as held back, unless this is another - * attempt's. - */ - private fun Payment.heldBackOutcome() = sendHash()?.lowercase()?.let { hash -> - val attempt = takenAttempts[hash] - val isOtherAttempt = attempt?.ownId?.let { it != id } ?: (attempt?.earlierIds?.contains(id) == true) - if (!isOtherAttempt) restoredTakenAttempts.remove(hash) - } - /** * Records [payment] as activity and returns whether it is saved; a failed write is kept in [unsavedPayments]. Only * Spark's list or its send response [settlesJournal]: a payment event can come before the list holds the - * withdrawal, which recovery reads, so its journal stays open until the list shows it. [ownId] is the Spark id - * of the attempt a caller that just ended its hold matched, so that attempt's own failure still writes the row. + * withdrawal, which recovery reads, so its journal stays open until the list shows it. */ - private suspend fun recordActivity( - payment: Payment, - settlesJournal: Boolean = true, - records: Long = sendRecords.get(), - ownId: String? = null, - ): Boolean { + private suspend fun recordActivity(payment: Payment, settlesJournal: Boolean = true): Boolean { (payment.details as? PaymentDetails.Withdraw)?.let { return recordWithdrawal(payment, it, settlesJournal) } val lightning = payment.details as? PaymentDetails.Lightning ?: return true - // An earlier attempt's failure, listed or reported, leaves the row of a retry Spark may still finish. - if (payment.isOutrunByRetry(records)) return true if (payment.status == PaymentStatus.PENDING && payment.paymentType == SparkPaymentType.RECEIVE) { return true } val id = lightning.htlcDetails.paymentHash + // A send in doubt or in Spark's send call shows as pending until Spark settles it, whatever an earlier attempt + // on its invoice failed with. + if (payment.status == PaymentStatus.FAILED && isHeldFrom(payment)) { + return true + } // A failed read would drop the stored note, contact and seen time, so the write waits for the next refresh. val stored = activityRepo.get().getActivity(id).getOrElse { unsavedPayments.add(payment.id) @@ -2500,7 +1991,6 @@ class SparkRepo @Inject constructor( } // Another attempt of the same invoice, on either rail, already paid it. if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) return true - if (existing != null && payment.isEarlierFailureThan(existing, id, ownId)) return true val activity = LightningActivity.create( id = id, txType = when (payment.paymentType) { @@ -2522,8 +2012,8 @@ class SparkRepo @Inject constructor( contact = existing?.contact ?: receivedContact(payment, id), seenAt = existing?.seenAt, ) - // The lookup above suspends, so a retry sent meanwhile is checked for again before the write. - val saved = saveLightningRow(payment, activity, records, existing?.sendRowStamp()) ?: return true + val saved = activityRepo.get().upsertActivity(Activity.Lightning(activity)) + .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } if (!saved) { unsavedPayments.add(payment.id) return false diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index 9ba979dedd..ac07d41885 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -2,7 +2,6 @@ package to.bitkit.data import android.app.Application import android.content.Context -import androidx.datastore.core.DataStore import androidx.test.core.app.ApplicationProvider import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking @@ -248,161 +247,4 @@ class CacheStoreTest : BaseUnitTest() { private companion object { const val NOW = 1_800_000_000L } - - @Test - fun `keepSparkSendRowId keeps each writer's row stamp and drops it with the writer`() = test { - sut.keepSparkSendRowId("HASH", "id", "1:2:3") - assertEquals("1:2:3", sut.data.first().sparkSendRowStamps["hash"]) - - sut.keepSparkSendRowId("hash", "other") - assertFalse("hash" in sut.data.first().sparkSendRowStamps) - - sut.keepSparkSendRowId("hash", "id", "1:2:3") - sut.removeSparkSendRowId("hash") - assertTrue(sut.data.first().sparkSendRowStamps.isEmpty()) - } - - @Test - fun `keepSparkSendRowId before a row keeps the previous writer until it is committed`() = test { - sut.keepSparkSendRowId("hash", "older", "1:2:3") - sut.keepSparkSendRowId("hash", "retry", "4:5:6", beforeRow = true) - assertEquals(listOf("older", "1:2:3"), sut.data.first().sparkSendPreviousRowWriters["hash"]) - - sut.commitSparkSendRowId("HASH") - assertFalse("hash" in sut.data.first().sparkSendPreviousRowWriters) - assertEquals("retry", sut.data.first().sparkSendRowIds["hash"]) - } - - @Test - fun `keepSparkSendRowId before a row without a writer keeps the replaced row's stamp`() = test { - sut.keepSparkSendRowId("hash", "retry", "4:5:6", beforeRow = true, rowStamp = "1:2:3") - - assertEquals(listOf("", "1:2:3"), sut.data.first().sparkSendPreviousRowWriters["hash"]) - } - - @Test - fun `keepSparkSendRowId keeps the latest row writers up to the limit`() = test { - (0..MAX_SPARK_SEND_HASHES).forEach { sut.keepSparkSendRowId("hash$it", "id$it") } - sut.keepSparkSendRowId("HASH1", "newer") - - val ids = sut.data.first().sparkSendRowIds - assertEquals(MAX_SPARK_SEND_HASHES, ids.size) - assertFalse("hash0" in ids) - assertEquals("newer", ids["hash1"]) - } - - @Test - fun `keepSparkSendAttempt keeps the taken id of the attempt that still has its entry`() = test { - sut.addSparkUncertainSend("hash", failedAt = 100, sentAt = 100, attemptId = "a") - - sut.keepSparkSendAttempt("hash", "retry", attemptId = "a") - - val data = sut.data.first() - assertEquals("retry", data.sparkTakenSendIds["hash"]) - assertFalse("hash" in data.sparkUncertainSends) - } - - @Test - fun `keepSparkSendAttempt writes nothing for a send settled before it`() = test { - sut.addSparkUncertainSend("hash", failedAt = 100, sentAt = 100, attemptId = "a") - sut.removeSparkUncertainSend("hash") - - sut.keepSparkSendAttempt("hash", "retry", attemptId = "a") - - assertFalse("hash" in sut.data.first().sparkTakenSendIds) - } - - @Test - fun `keepSparkSendAttempt leaves a later attempt's entry from the same second alone`() = test { - sut.addSparkUncertainSend("hash", failedAt = 100, sentAt = 100, attemptId = "b") - - sut.keepSparkSendAttempt("hash", "retry", attemptId = "a") - - val data = sut.data.first() - assertFalse("hash" in data.sparkTakenSendIds) - assertTrue("hash" in data.sparkUncertainSends) - } - - @Test - fun `keepSparkSendRowId before an unchanged row writes nothing`() = test { - val store = CountingDataStore(InMemoryDataStore(AppCacheData())) - val cache = CacheStore(store) - cache.keepSparkSendRowId("hash", "id", "1:2:3", beforeRow = true) - cache.commitSparkSendRowId("hash") - val writes = store.writes - - cache.keepSparkSendRowId("hash", "id", "1:2:3", beforeRow = true, rowStamp = "1:2:3") - cache.commitSparkSendRowId("hash") - - assertEquals(0, store.writes - writes) - assertEquals("id", cache.data.first().sparkSendRowIds["hash"]) - assertFalse("hash" in cache.data.first().sparkSendPreviousRowWriters) - } - - @Test - fun `keepSparkSendEarlierIds keeps a send's earlier attempts in send order`() = test { - sut.keepSparkSendEarlierIds("hash", setOf("zfirst")) - sut.keepSparkSendEarlierIds("hash", setOf("zfirst", "asecond")) - - assertEquals(listOf("zfirst", "asecond"), sut.data.first().sparkSendEarlierIds["hash"]) - } - - @Test - fun `keepSparkSendRowId keeps the writer of a send with earlier ids past the latest sends`() = test { - sut.keepSparkSendEarlierIds("retried", setOf("earlier")) - sut.keepSparkSendRowId("retried", "original", "1:2:3") - sut.keepSparkSendRowId("plain", "id", "1:2:3") - - repeat(MAX_SPARK_SEND_HASHES) { sut.keepSparkSendRowId("later$it", "id$it", "1:2:3") } - - val data = sut.data.first() - assertEquals("original", data.sparkSendRowIds["retried"]) - assertEquals("1:2:3", data.sparkSendRowStamps["retried"]) - assertFalse("plain" in data.sparkSendRowIds) - assertEquals("id0", data.sparkSendRowIds["later0"]) - assertEquals(MAX_SPARK_SEND_HASHES + 1, data.sparkSendRowIds.size) - } - - @Test - fun `keepSparkSendRowId keeps a new writer beside the latest sends with earlier ids`() = test { - repeat(MAX_SPARK_SEND_HASHES) { - sut.keepSparkSendEarlierIds("retried$it", setOf("earlier$it")) - sut.keepSparkSendRowId("retried$it", "original$it", "1:2:3") - } - - sut.keepSparkSendRowId("new", "id", "1:2:3") - - val data = sut.data.first() - assertEquals("id", data.sparkSendRowIds["new"]) - assertEquals("1:2:3", data.sparkSendRowStamps["new"]) - assertEquals("original0", data.sparkSendRowIds["retried0"]) - } - - @Test - fun `keepSparkSendRowId outside a row write keeps no previous writer`() = test { - sut.keepSparkSendRowId("hash", "older", "1:2:3") - - sut.keepSparkSendRowId("hash", "retry", "4:5:6") - - val data = sut.data.first() - assertEquals("retry", data.sparkSendRowIds["hash"]) - assertFalse("hash" in data.sparkSendPreviousRowWriters) - } - - @Test - fun `keepSparkSendRowId keeps the writer a cut write left the row to across another cut write`() = test { - sut.keepSparkSendRowId("hash", "older", "1:2:3") - sut.keepSparkSendRowId("hash", "first", "4:5:6", beforeRow = true, rowStamp = "1:2:3") - - sut.keepSparkSendRowId("hash", "second", "7:8:9", beforeRow = true, rowStamp = "1:2:3") - - assertEquals(listOf("older", "1:2:3"), sut.data.first().sparkSendPreviousRowWriters["hash"]) - } - - private class CountingDataStore(private val inner: DataStore) : DataStore { - var writes = 0 - override val data = inner.data - override suspend fun updateData(transform: suspend (t: T) -> T): T = inner.updateData(transform) - .also { writes++ } - } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 55710a8456..c3b9034205 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1,6 +1,5 @@ package to.bitkit.repositories -import androidx.datastore.core.DataStore import breez_sdk_spark.AutoOptimizationEvent import breez_sdk_spark.BitcoinAddressDetails import breez_sdk_spark.Bolt11InvoiceDetails @@ -34,13 +33,10 @@ import com.synonym.bitkitcore.PaykitEndpoint import com.synonym.bitkitcore.PaymentState import com.synonym.bitkitcore.ServiceRouteLeg import kotlinx.coroutines.CompletableDeferred -import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation -import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first @@ -673,10 +669,9 @@ class SparkRepoTest : BaseUnitTest() { val retry = async { sut.payInvoice("lnbc1280n1send", 128uL) } runCurrent() - // Recorded, but its journal is not written yet; Spark's list still holds only the older attempt's failure, - // which reads as pending while the retry runs. + // Recorded, but its journal is not written yet, so Spark's list still reads the older attempt's failure. assertTrue(sut.hasRecordedSendSince(mark, "hash")) - assertEquals(PaymentStatus.PENDING, assertIs(sut.lightningSend("hash")).status) + assertEquals(PaymentStatus.FAILED, assertIs(sut.lightningSend("hash")).status) assertTrue(sut.isSendInFlight("hash"), "a paused retry read as settled") journaling.complete(Unit) assertEquals("hash", retry.await().getOrThrow()) @@ -869,39 +864,6 @@ class SparkRepoTest : BaseUnitTest() { assertTrue("hash" in store.data.first().sparkSendHashes, "A stale listing dropped a retry that ended") } - @Test - fun `a retry recorded while the activity sync reads spark's list keeps its row from an older failure`() = test { - val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) - val sut = retryDuringListRead(failed) { lists -> lists == 2 } - - // The refresh reads the list first, then the activity sync, whose read a retry outruns. - sut.start(0).getOrThrow() - - verify(activityRepo, never()).upsertActivity( - argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } - ) - } - - @Test - fun `a retry recorded while the refresh reads spark's list keeps its row from an older failure`() = test { - val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) - var isRetrying = false - val sut = retryDuringListRead(failed) { isRetrying } - // The activity sync can't read the row, so the next refresh records the failure. - whenever { activityRepo.getActivity(eq("hash"), any()) } - .thenReturn(Result.failure(IllegalStateException("db locked"))) - sut.start(0).getOrThrow() - whenever { activityRepo.getActivity(eq("hash"), any()) }.thenReturn(Result.success(pendingSendRow())) - - isRetrying = true - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - - verify(activityRepo, never()).upsertActivity( - argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } - ) - } - @Test fun `a retry in flight when the release reads spark's list again keeps its hash after it ends`() = test { cacheData.value = AppCacheData(sparkSendHashes = listOf("hash")) @@ -2718,40 +2680,6 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService).importExitState("new") } - @Test - fun `a restore that connects spark keeps a held retry past an earlier attempt's failure`() = test { - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendHashes = listOf("hash"), - sparkSendExpiries = mapOf("hash" to now.epochSeconds + 3_600), - sparkUncertainSendStarts = mapOf("hash" to now.epochSeconds), - sparkUncertainSendEarlierIds = mapOf("hash" to listOf("older")), - ) - ), - clock, - ) - var isConnected = false - whenever(sparkService.isConnected).thenAnswer { isConnected } - whenever { sparkService.connect(any(), any()) }.thenAnswer { - isConnected = true - true - } - whenever { sparkService.importExitState(any()) }.thenReturn(ImportUnilateralExitStateResponse(2u, 0u, 0u, 0u)) - val sut = createSut(store) - val events = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { events += it } } - sut.restoreExitBackup(SparkExitBackupV1(createdAt = 1, network = "regtest", exitState = "s"), 0).getOrThrow() - - val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED) - whenever { sparkService.listPayments() }.thenReturn(listOf(older)) - sparkEvents.emit(SdkEvent.PaymentFailed(older)) - advanceUntilIdle() - - assertTrue(events.none { it is Event.PaymentFailed }, "an earlier attempt's failure ended the held retry") - assertTrue("hash" in store.data.first().sparkUncertainSendStarts) - } - @Test fun `a restore that connects spark handles its events before the wallet starts`() = test { var isConnected = false @@ -3767,7 +3695,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val deadline = now + 1.seconds - whenever { cacheStore.addSparkUncertainSend(any(), any(), anyOrNull(), anyOrNull(), anyOrNull()) }.thenAnswer { + whenever { cacheStore.addSparkUncertainSend(any(), any()) }.thenAnswer { now = deadline + 1.seconds Unit } @@ -3808,2219 +3736,277 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `an older attempt's late failure event keeps an uncertain spark retry held`() = test { + fun `a failure spark reports during a send call is no settled send event`() = test { whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + var listed = emptyList() + whenever(sparkService.listPayments()).thenAnswer { listed } + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) + // An earlier attempt the pre-send list left out fails while the retry's send call runs. + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { + listed = listOf(failed) + awaitCancellation() + } + val sut = createSut() + sut.start(0).getOrThrow() + runCurrent() + backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } + advanceUntilIdle() + + assertNull(sut.settledSendEvent("hash"), "a failure seen during the call settled the send") + } + + @Test + fun `a failure listed while a spark send is in doubt is no settled send event`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } val sut = createSut() sut.start(0).getOrThrow() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + // An earlier attempt on the invoice, or the doubtful send itself, shows as failed. + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) + + assertNull(sut.settledSendEvent("hash"), "a send in doubt settled as failed") + } + + @Test + fun `an earlier attempt's late failure event leaves a spark send in doubt pending`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut() + sut.start(0).getOrThrow() val events = mutableListOf() backgroundScope.launch { sut.nodeEvents.collect { events += it } } - runCurrent() - val olderFailure = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) - whenever { sparkService.listPayments() }.thenReturn(listOf(olderFailure)) - whenever { sparkService.getInfo() }.thenReturn( - info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable"), lastSyncedAt = 1uL) - ) assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) - runCurrent() + advanceUntilIdle() + clearInvocations(activityRepo) - // The earlier attempt's failure, made before the retry started, arrives after the retry went uncertain. - sparkEvents.emit(SdkEvent.PaymentFailed(olderFailure)) + val earlier = sentPayment(fees = 0).copy(id = "earlier", status = PaymentStatus.FAILED, timestamp = 1uL) + whenever(sparkService.listPayments()).thenReturn(listOf(earlier)) + sparkEvents.emit(SdkEvent.PaymentFailed(earlier)) advanceUntilIdle() - assertTrue(events.none { it is Event.PaymentFailed }, "an older failure ended a send Spark may finish") assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + verify(sparkService, times(1)).send(any(), anyOrNull()) + assertTrue(events.none { it is Event.PaymentFailed }, "a send Spark may still finish was reported failed") verify(activityRepo, never()).upsertActivity( argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } ) } @Test - fun `an earlier attempt's failure dated just before an uncertain retry keeps it held`() = test { - val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED) - assertTrue(retryHeldAfter(listOf(older), older.copy(timestamp = now.epochSeconds.toULong() - 5uL))) - } - - @Test - fun `an earlier attempt's failure dated just after an uncertain retry keeps it held`() = test { - val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED) - assertTrue(retryHeldAfter(listOf(older), older.copy(timestamp = now.epochSeconds.toULong() + 5uL))) - } + fun `an earlier attempt's late failure event leaves a retry spark took pending`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING, timestamp = 5uL) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(retry) + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + sut.payInvoice("lnbc1", 100uL) + advanceUntilIdle() + clearInvocations(activityRepo) - @Test - fun `an uncertain retry's own failure dated before it by spark's clock ends its hold`() = test { - val own = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED) - assertFalse(retryHeldAfter(emptyList(), own.copy(timestamp = now.epochSeconds.toULong() - 5uL))) - } + val earlier = sentPayment(fees = 0).copy(id = "earlier", status = PaymentStatus.FAILED, timestamp = 1uL) + whenever(sparkService.listPayments()).thenReturn(listOf(retry, earlier)) + sparkEvents.emit(SdkEvent.PaymentFailed(earlier)) + advanceUntilIdle() - @Test - fun `an older failure the pre-send list left out keeps an uncertain retry held`() = test { - // Spark may leave an older attempt out of the list it gives before the retry goes out. - val omitted = sentPayment(fees = 0).copy(id = "omitted", status = PaymentStatus.FAILED) - assertTrue(retryHeldAfter(emptyList(), omitted.copy(timestamp = now.epochSeconds.toULong() - 10uL))) + assertTrue(events.none { it is Event.PaymentFailed }, "an earlier attempt's failure failed the retry") + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) } @Test - fun `a failure within the clock skew keeps an uncertain retry held while its earlier attempts are unknown`() = - test { - val failure = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED) - assertTrue(retryHeldAfter(null, failure.copy(timestamp = now.epochSeconds.toULong()))) - } - - @Test - fun `a failure past the clock skew ends an uncertain retry's hold while its earlier attempts are unknown`() = - test { - val failure = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED) - assertFalse(retryHeldAfter(null, failure.copy(timestamp = now.epochSeconds.toULong() + 10uL))) - } - - @Test - fun `a taken retry's own failure within the clock skew ends its hold while its earlier attempts are unknown`() = - test { - val taken = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) - val failure = taken.copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) - assertFalse(retryHeldAfter(null, failure, taken = taken)) - } - - @Test - fun `an earlier failure past the clock skew keeps a taken retry held while its earlier ids are unknown`() = - test { - val taken = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) - val older = sentPayment(fees = 0).copy( - id = "older", - status = PaymentStatus.FAILED, - timestamp = now.epochSeconds.toULong() + 60uL, - ) - assertTrue(retryHeldAfter(null, older, taken = taken)) - } - - @Test - fun `a taken retry's own failure within the clock skew ends its hold after a restart without earlier ids`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + fun `a spark send in doubt ends at once on its own failure`() = test { whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) - val prepared = prepared(feeSats = 0uL) - whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - val taken = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) - whenever(sparkService.send(any(), anyOrNull())).thenReturn(taken) - // Spark that never synced can't list every earlier attempt. - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncError = SyncError.Network("down"))) - val before = createSut(store) - before.start(0).getOrThrow() - val sentAt = now.epochSeconds.toULong() - before.payInvoice("lnbc1", 100uL).getOrThrow() - runCurrent() - - val restartedEvents = MutableSharedFlow() - whenever(sparkService.events).thenReturn(restartedEvents) whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - whenever(sparkService.listPayments()).thenReturn(listOf(taken)) - val after = createSut(store) - after.start(0).getOrThrow() + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut() + sut.start(0).getOrThrow() val events = mutableListOf() - backgroundScope.launch { after.nodeEvents.collect { events += it } } - runCurrent() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + val startedAt = now.epochSeconds.toULong() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() - val failure = taken.copy(status = PaymentStatus.FAILED, timestamp = sentAt) - whenever(sparkService.listPayments()).thenReturn(listOf(failure)) - restartedEvents.emit(SdkEvent.PaymentFailed(failure)) + // Spark dates a send's own failure at its start, by a clock that may run a few seconds behind the phone's. + val own = sentPayment(fees = 0).copy(id = "own", status = PaymentStatus.FAILED, timestamp = startedAt - 5uL) + whenever(sparkService.listPayments()).thenReturn(listOf(own)) + sparkEvents.emit(SdkEvent.PaymentFailed(own)) advanceUntilIdle() - assertTrue(events.any { it is Event.PaymentFailed }, "the retry's own failure stayed held after the restart") + assertEquals("hash", assertIs(events.single()).paymentHash) + verify(activityRepo).upsertActivity( + 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)) + sut.payInvoice("lnbc1", 100uL) + verify(sparkService, times(2)).send(any(), anyOrNull()) } - /** - * Sends a retry whose outcome stays unknown, or that Spark [taken] and still runs, with Spark listing - * [listedBeforeSend] before it goes out (null while it never synced, so it can't list), then delivers [failure]; - * true when the retry stays held. - */ - private suspend fun TestScope.retryHeldAfter( - listedBeforeSend: List?, - failure: Payment, - taken: Payment? = null, - ): Boolean { + @Test + fun `a spark send in doubt fails its row once its invoice expires with only an earlier failure listed`() = test { whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) - val prepared = prepared(feeSats = 0uL) + 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 { taken ?: throw SdkException.Generic("timeout") } - // Spark that never synced can't list every earlier attempt. - if (listedBeforeSend == null) { - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncError = SyncError.Network("down"))) - } + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } val sut = createSut() sut.start(0).getOrThrow() val events = mutableListOf() backgroundScope.launch { sut.nodeEvents.collect { events += it } } - runCurrent() - whenever(sparkService.listPayments()).thenReturn(listedBeforeSend.orEmpty()) - whenever(sparkService.getInfo()).thenReturn( - info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable"), lastSyncedAt = 1uL) - ) - val result = sut.payInvoice("lnbc1", 100uL) - if (taken == null) assertIs(result.exceptionOrNull()) else result.getOrThrow() - runCurrent() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + // Spark dates the failure before the send started, so it may be an earlier attempt's. + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = 1uL) + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) + advanceUntilIdle() - whenever(sparkService.listPayments()).thenReturn(listOf(failure)) - sparkEvents.emit(SdkEvent.PaymentFailed(failure)) + now += 2.hours + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) advanceUntilIdle() - return events.none { it is Event.PaymentFailed } + verify(activityRepo).upsertActivity( + argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } + ) + assertEquals("hash", assertIs(events.single()).paymentHash) + assertNull(sut.earlierLightningSend("lnbc1", "hash")) } @Test - fun `an uncertain spark retry's own failure after a restart ends its hold`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + fun `a spark send that failed lets a retry of its invoice send again`() = test { whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) - val prepared = prepared(feeSats = 0uL) - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - // The send call times out a while after Spark started the payment. - whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { - now += 5.seconds - throw SdkException.Generic("timeout") - } - // Spark lists no earlier attempt when the retry goes out, which the restart keeps. - whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = 1uL)) - val before = createSut(store) - before.start(0).getOrThrow() - whenever { sparkService.getInfo() }.thenReturn( - info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) - ) - val sentAt = now.epochSeconds.toULong() - assertIs(before.payInvoice("lnbc1", 100uL).exceptionOrNull()) - runCurrent() - now += 30.seconds - whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - val after = createSut(store) - after.start(0).getOrThrow() - runCurrent() - - // Spark resumes the retry after the restart and it fails, dated when Spark started it, before it was held. - val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = sentAt) - whenever { sparkService.listPayments() }.thenReturn(listOf(failed)) - sparkEvents.emit(SdkEvent.PaymentFailed(failed)) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(failed) + val sut = createSut() + sut.start(0).getOrThrow() + sut.payInvoice("lnbc1", 100uL) + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) advanceUntilIdle() - assertEquals(emptyList(), store.data.first().sparkUncertainSendEarlierIds["hash"].orEmpty()) - assertNull(after.earlierLightningSend("lnbc1", "hash"), "the retry's own failure still held the node off") + sut.payInvoice("lnbc1", 100uL) + + verify(sparkService, times(2)).send(any(), anyOrNull()) } @Test - fun `a spark send kept in doubt before start times were stored stays held past a failure`() = test { - val expiresAt = now.epochSeconds + 3_600 - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendHashes = listOf("hash"), - sparkSendExpiries = mapOf("hash" to expiresAt), - sparkUncertainSends = mapOf("hash" to now.epochSeconds), - ) - ), - clock, - ) + fun `a spark retry's success decides its activity row over an earlier attempt's failure`() = test { whenever(sparkService.isConnected).thenReturn(true) - val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) - whenever { sparkService.listPayments() }.thenReturn(listOf(failed)) - val sut = createSut(store) - sut.start(0).getOrThrow() - val events = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { events += it } } - runCurrent() + val success = sentPayment(fees = 0).copy(id = "retry", timestamp = 5uL) + val earlierFailure = sentPayment(fees = 0).copy(id = "earlier", status = PaymentStatus.FAILED, timestamp = 1uL) + whenever { sparkService.listPayments() }.thenReturn(listOf(success, earlierFailure)) + val sut = createSut() - // The failure may be its own or an earlier attempt's: without a start time, nothing tells them apart. - sparkEvents.emit(SdkEvent.PaymentFailed(failed)) - advanceUntilIdle() + sut.start(0).getOrThrow() - assertTrue(events.none { it is Event.PaymentFailed }, "a send Spark may still finish was reported failed") - assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + verify(activityRepo).upsertActivity( + argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.SUCCEEDED } + ) + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) } @Test - fun `an earlier attempt's late failure leaves a spark retry spark took and still runs`() = test { - assertTakenRetryKeptPastEarlierFailure(restart = false) + fun `an uncertain spark retry stays held after a restart while spark lists only its older failure`() = test { + assertUncertainRetryHeldAfterRestart(syncError = null) } @Test - fun `an earlier attempt's late failure after a restart leaves a spark retry spark still runs`() = test { - assertTakenRetryKeptPastEarlierFailure(restart = true) + fun `an uncertain spark retry stays held after a restart whose first sync fails`() = test { + assertUncertainRetryHeldAfterRestart(syncError = SyncError.Network("operators unreachable")) } - @Test - fun `an uncertain spark retry fails its own row at expiry when only an earlier failure is listed`() = test { + private suspend fun TestScope.assertUncertainRetryHeldAfterRestart(syncError: SyncError?) { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - // The earlier attempt's failure wrote the invoice's row before the retry's replaced it. - store.keepSparkSendRowId("hash", "older") - whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - var row = pendingSendRow() - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - val prepared = prepared(feeSats = 0uL) + val prepared = unexpiredPrepared() whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } - whenever(sparkService.listPayments()).thenReturn(emptyList()) - val sut = createSut(store) - sut.start(0).getOrThrow() - runCurrent() - // The earlier attempt paid the amountless invoice at another amount and fee, and failed; Spark dates it after - // the retry's row, as the row was written from the device's clock. - val older = sentPayment(fees = 7) - .copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger(), timestamp = 5uL) - whenever(sparkService.listPayments()).thenReturn(listOf(older)) - assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + // An earlier attempt of the invoice failed, and the retry's outcome is unknown when the app stops. + whenever { sparkService.listPayments() } + .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + ) + val before = createSut(store) + before.start(0).getOrThrow() + assertIs(before.payInvoice("lnbc1", 100uL).exceptionOrNull()) runCurrent() - // The invoice has expired, and Spark syncs after the retry went uncertain. - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL)) - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - - assertEquals(PaymentState.FAILED, row.v1.status) - assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "the retry's row took the earlier attempt's payment") - - // The next launch lists the same earlier failure once nothing holds the invoice. - createSut(store).start(0).getOrThrow() - advanceUntilIdle() - assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "a relaunch wrote the earlier attempt over the row") - } - - @Test - fun `an expired uncertain spark retry's own failure replaces an earlier attempt's row from the same second`() = - test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - val sentAt = now.epochSeconds.toULong() - // The earlier attempt failed the second the retry starts, and its failure wrote the row. - store.keepSparkSendRowId("hash", "older") - var row = Activity.Lightning( - pendingSendRow().v1.copy(status = PaymentState.FAILED, value = 999uL, fee = 7uL, timestamp = sentAt) - ) - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - val older = sentPayment(fees = 7) - .copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger(), timestamp = sentAt) - whenever(sparkService.listPayments()).thenReturn(listOf(older)) - val prepared = prepared(feeSats = 0uL) - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } - val sut = createSut(store) - sut.start(0).getOrThrow() - runCurrent() - assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) - runCurrent() - - // The send call timed out, so the retry's own id is known only from the list at its invoice's expiry. - val ownFailure = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED, timestamp = sentAt) - whenever(sparkService.listPayments()).thenReturn(listOf(older, ownFailure)) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = sentAt + 1uL)) - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - - assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "the retry's own failure kept the earlier row") - } - - @Test - fun `a taken spark retry's own failure after a restart replaces an earlier attempt's failed row`() = test { - // The app closed before it saved the retry's pending row, so Activity still shows the earlier attempt. - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendHashes = listOf("hash"), - sparkSendExpiries = mapOf("hash" to now.epochSeconds + 3_600), - sparkUncertainSendStarts = mapOf("hash" to now.epochSeconds), - sparkTakenSendIds = mapOf("hash" to "retry"), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - var row = Activity.Lightning( - pendingSendRow().v1.copy(status = PaymentState.FAILED, value = 999uL, fee = 7uL, timestamp = 0uL) - ) - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - val older = sentPayment(fees = 7) - .copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger(), timestamp = 0uL) - val ownFailure = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED) - whenever(sparkService.listPayments()).thenReturn(listOf(older, ownFailure)) - - createSut(store).start(0).getOrThrow() - advanceUntilIdle() - - assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "the retry's own failure left the earlier attempt's row") - } - - @Test - fun `a taken spark retry's row failed at expiry keeps its own writer against an older same-second failure`() = - test { - val sentAt = now.epochSeconds - 7_200 - // The pre-send list missed the older attempt, so only the retry's own id, as the row's writer, protects it. - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendHashes = listOf("hash"), - sparkSendExpiries = mapOf("hash" to now.epochSeconds - 3_600), - sparkUncertainSendStarts = mapOf("hash" to sentAt), - sparkTakenSendIds = mapOf("hash" to "retry"), - sparkSendRowIds = mapOf("hash" to "retry"), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - var row = Activity.Lightning(pendingSendRow().v1.copy(timestamp = sentAt.toULong())) - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - val older = sentPayment(fees = 7).copy( - id = "older", - status = PaymentStatus.FAILED, - amount = 999.toBigInteger(), - timestamp = sentAt.toULong(), - ) - whenever(sparkService.listPayments()).thenReturn(listOf(older)) - createSut(store).start(0).getOrThrow() - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - assertEquals(PaymentState.FAILED, row.v1.status, "the expired retry's row stayed pending") - - createSut(store).start(0).getOrThrow() - advanceUntilIdle() - - assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "a relaunch wrote the older attempt over the row") - } - - @Test - fun `an expired spark retry without earlier ids drops a writer kept as earlier before a relaunch`() = test { - val sentAt = now.epochSeconds - 7_200 - // The retry's pre-send read failed, while an earlier retry kept the older attempt's id; its pending row was - // saved, but not its writer. - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendHashes = listOf("hash"), - sparkSendExpiries = mapOf("hash" to now.epochSeconds - 3_600), - sparkUncertainSends = mapOf("hash" to sentAt), - sparkUncertainSendStarts = mapOf("hash" to sentAt), - sparkSendRowIds = mapOf("hash" to "older"), - sparkSendEarlierIds = mapOf("hash" to listOf("older")), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - var row = Activity.Lightning(pendingSendRow().v1.copy(timestamp = sentAt.toULong())) - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - whenever(sparkService.listPayments()).thenReturn(emptyList()) - createSut(store).start(0).getOrThrow() - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - assertEquals(PaymentState.FAILED, row.v1.status, "the expired retry's row stayed pending") - - val older = sentPayment(fees = 7).copy( - id = "older", - status = PaymentStatus.FAILED, - amount = 999.toBigInteger(), - timestamp = sentAt.toULong(), - ) - whenever(sparkService.listPayments()).thenReturn(listOf(older)) - createSut(store).start(0).getOrThrow() - advanceUntilIdle() - - assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "a relaunch wrote the older attempt over the row") - } - - @Test - fun `an expired spark retry that never wrote its row keeps an earlier payment's final fee`() = test { - val sentAt = now.epochSeconds - 7_200 - val pending = Activity.Lightning(pendingSendRow().v1.copy(timestamp = sentAt.toULong())) - // The earlier payment wrote the pending row and its failure never saved; a refused retry kept its id, and a - // later retry timed out without writing a row or reading earlier ids. - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendHashes = listOf("hash"), - sparkSendExpiries = mapOf("hash" to now.epochSeconds - 3_600), - sparkUncertainSends = mapOf("hash" to sentAt), - sparkUncertainSendStarts = mapOf("hash" to sentAt), - sparkSendRowIds = mapOf("hash" to "older"), - sparkSendRowStamps = mapOf( - "hash" to pending.v1.let { "${it.timestamp}:${it.value}:${it.fee}:${it.status}" } - ), - sparkSendEarlierIds = mapOf("hash" to listOf("older")), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - var row = pending - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - whenever(sparkService.listPayments()).thenReturn(emptyList()) - createSut(store).start(0).getOrThrow() - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - assertEquals(PaymentState.FAILED, row.v1.status, "the expired retry's row stayed pending") - - val final = sentPayment(fees = 3) - .copy(id = "older", status = PaymentStatus.FAILED, timestamp = sentAt.toULong()) - whenever(sparkService.listPayments()).thenReturn(listOf(final)) - createSut(store).start(0).getOrThrow() - advanceUntilIdle() - - assertEquals(3uL, row.v1.fee, "the earlier payment's final fee was dropped") - } - - @Test - fun `a spark send row's writer is kept before its row and put back when the write fails`() = test { - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendRowIds = mapOf("hash" to "older"), - sparkSendRowStamps = mapOf("hash" to "0:128:0") - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - var writerAtWrite: String? = null - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - writerAtWrite = store.data.first().sparkSendRowIds["hash"] - Result.failure(IllegalStateException("write failed")) - } - // The retry's row is alike in time, amount and fee to the earlier attempt's. - val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING, timestamp = 0uL) - whenever(sparkService.listPayments()).thenReturn(listOf(retry)) - - createSut(store).start(0).getOrThrow() - advanceUntilIdle() - - assertEquals("retry", writerAtWrite, "the row was written before its writer was kept") - assertEquals("older", store.data.first().sparkSendRowIds["hash"], "a failed write kept its writer") - assertEquals("0:128:0", store.data.first().sparkSendRowStamps["hash"]) - } - - @Test - fun `an earlier payment's row takes its final fee after a stop cut a retry's row write short`() = test { - var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 7uL)) - val olderStamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}:${it.status}" } - // The retry's writer was kept ahead of its row, and the app stopped before the row was written. - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendRowIds = mapOf("hash" to "retry"), - sparkSendRowStamps = mapOf("hash" to "9:128:0"), - sparkSendPreviousRowWriters = mapOf("hash" to listOf("older", olderStamp)), - sparkSendEarlierIds = mapOf("hash" to listOf("older")), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - val final = sentPayment(fees = 9) - .copy(id = "older", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp) - whenever(sparkService.listPayments()).thenReturn(listOf(final)) - - createSut(store).start(0).getOrThrow() - advanceUntilIdle() - - assertEquals(9uL, row.v1.fee, "the earlier payment's final fee was dropped") - assertTrue("hash" !in store.data.first().sparkSendPreviousRowWriters, "the row's writer stayed in doubt") - } - - @Test - fun `an earlier payment's failed row takes its final fee after a stop cut a retry alike in time amount and fee`() = - test { - var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 7uL)) - val stamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}" } - // The pending retry's writer was kept ahead of its row, alike in all but status to the earlier failed one. - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendRowIds = mapOf("hash" to "retry"), - sparkSendRowStamps = mapOf("hash" to "$stamp:${PaymentState.PENDING}"), - sparkSendPreviousRowWriters = mapOf("hash" to listOf("older", "$stamp:${PaymentState.FAILED}")), - sparkSendEarlierIds = mapOf("hash" to listOf("older")), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - val final = sentPayment(fees = 9) - .copy(id = "older", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp) - whenever(sparkService.listPayments()).thenReturn(listOf(final)) - - createSut(store).start(0).getOrThrow() - advanceUntilIdle() - - assertEquals(9uL, row.v1.fee, "the earlier payment's final fee was dropped") - } - - @Test - fun `a later attempt's failure takes the row from an earlier one when a third send read both as earlier`() = test { - var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 1uL)) - val stamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}:${it.status}" } - // The first attempt wrote the row, the second's row write failed, and a third send that never wrote one read - // both as earlier. - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendRowIds = mapOf("hash" to "first"), - sparkSendRowStamps = mapOf("hash" to stamp), - sparkSendEarlierIds = mapOf("hash" to listOf("first", "second")), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - val first = sentPayment( - fees = 1 - ).copy(id = "first", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp) - val second = sentPayment(fees = 2) - .copy(id = "second", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp + 100uL) - whenever(sparkService.listPayments()).thenReturn(listOf(second, first)) - - createSut(store).start(0).getOrThrow() - advanceUntilIdle() - - assertEquals(2uL, row.v1.fee, "the first attempt's row stayed over the later second attempt's failure") - } - - @Test - fun `an older attempt a pre-send read left out never takes a later attempt's row by its kept order`() = test { - var row = Activity.Lightning( - pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 2uL, timestamp = 1_000uL), - ) - val stamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}:${it.status}" } - // A read left the first attempt out, so it was kept after the second, which wrote the row. - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendRowIds = mapOf("hash" to "second"), - sparkSendRowStamps = mapOf("hash" to stamp), - sparkSendEarlierIds = mapOf("hash" to listOf("second", "first")), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - val first = sentPayment(fees = 1) - .copy(id = "first", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp - 100uL) - whenever(sparkService.listPayments()).thenReturn(listOf(first)) - - createSut(store).start(0).getOrThrow() - advanceUntilIdle() - - assertEquals(2uL, row.v1.fee, "the older first attempt took the second one's row") - } - - @Test - fun `a later attempt's same-second failure keeps the row from an earlier one when a third send read both`() = - test { - var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 1uL)) - val stamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}:${it.status}" } - // The second attempt followed the first in the same second, and its row write failed. - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendRowIds = mapOf("hash" to "zfirst"), - sparkSendRowStamps = mapOf("hash" to stamp), - sparkSendEarlierIds = mapOf("hash" to listOf("zfirst", "asecond")), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - val first = sentPayment(fees = 1) - .copy(id = "zfirst", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp) - val second = sentPayment(fees = 2) - .copy(id = "asecond", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp) - - // Spark lists them in either order across launches. - listOf(listOf(second, first), listOf(first, second)).forEach { listed -> - whenever(sparkService.listPayments()).thenReturn(listed) - createSut(store).start(0).getOrThrow() - advanceUntilIdle() - - assertEquals(2uL, row.v1.fee, "the first attempt took the row back from the later second one") - } - } - - @Test - fun `an earlier payment's failed row takes its final fee after a stop cut a retry's alike failed row`() = test { - var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 7uL)) - val stamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}:${it.status}" } - // The failed retry's writer was kept ahead of its row, alike in all to the earlier failed one. - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendRowIds = mapOf("hash" to "retry"), - sparkSendRowStamps = mapOf("hash" to stamp), - sparkSendPreviousRowWriters = mapOf("hash" to listOf("older", stamp)), - sparkSendEarlierIds = mapOf("hash" to listOf("older")), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - val final = sentPayment(fees = 9) - .copy(id = "older", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp) - whenever(sparkService.listPayments()).thenReturn(listOf(final)) - - createSut(store).start(0).getOrThrow() - advanceUntilIdle() - - assertEquals(9uL, row.v1.fee, "the earlier payment's final fee was dropped") - } - - @Test - fun `an earlier payment's fee correction survives a failed write after a cut retry row write`() = test { - var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED, fee = 7uL)) - val olderStamp = row.v1.let { "${it.timestamp}:${it.value}:${it.fee}:${it.status}" } - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendRowIds = mapOf("hash" to "retry"), - sparkSendRowStamps = mapOf("hash" to "9:128:0"), - sparkSendPreviousRowWriters = mapOf("hash" to listOf("older", olderStamp)), - sparkSendEarlierIds = mapOf("hash" to listOf("older")), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - var isWritable = false - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - if (!isWritable) return@doSuspendableAnswer Result.failure(IllegalStateException("write failed")) - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - val final = sentPayment(fees = 9) - .copy(id = "older", status = PaymentStatus.FAILED, timestamp = row.v1.timestamp) - whenever(sparkService.listPayments()).thenReturn(listOf(final)) - createSut(store).start(0).getOrThrow() - advanceUntilIdle() - - isWritable = true - createSut(store).start(0).getOrThrow() - advanceUntilIdle() - - assertEquals(9uL, row.v1.fee, "a failed write dropped the earlier payment's writer") - } - - @Test - fun `a failed spark send row takes its own attempt's fee correction`() = test { - cacheData.value = cacheData.value.copy(sparkSendRowIds = mapOf("hash" to "retry")) - val corrected = sentPayment(fees = 3).copy(id = "retry", status = PaymentStatus.FAILED) - assertEquals(128uL to 3uL, failedRowAfterListing(corrected).let { it.v1.value to it.v1.fee }) - } - - @Test - fun `a failed spark send row takes its own fee correction after spark refused a retry`() = test { - // A retry read the payment as earlier, then Spark refused it before it went out, so the payment keeps the row. - cacheData.value = cacheData.value.copy( - sparkSendRowIds = mapOf("hash" to "older"), - sparkSendEarlierIds = mapOf("hash" to listOf("older")), - ) - val corrected = sentPayment(fees = 3).copy(id = "older", status = PaymentStatus.FAILED) - assertEquals(128uL to 3uL, failedRowAfterListing(corrected).let { it.v1.value to it.v1.fee }) - } - - @Test - fun `a failed spark send row takes a later attempt's failure`() = test { - val later = sentPayment(fees = 0) - .copy(id = "later", status = PaymentStatus.FAILED, amount = 200.toBigInteger(), timestamp = 9uL) - assertEquals(200uL, failedRowAfterListing(later).v1.value) - } - - @Test - fun `a failed spark send row keeps its amount against an earlier attempt's failure from the same second`() = test { - // The retry started in the same second as the earlier attempt, and its failure last wrote the row. - cacheData.value = cacheData.value.copy(sparkSendRowIds = mapOf("hash" to "retry")) - val older = sentPayment(fees = 7).copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger()) - assertEquals(128uL to 0uL, failedRowAfterListing(older).let { it.v1.value to it.v1.fee }) - } - - @Test - fun `an uncertain spark retry's own failure replaces an earlier attempt's row from the same second`() = test { - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - val sentAt = now.epochSeconds.toULong() - // The earlier attempt failed the second the retry starts, and its failure wrote the row. - cacheData.value = cacheData.value.copy(sparkSendRowIds = mapOf("hash" to "older")) - var row = Activity.Lightning( - pendingSendRow().v1.copy(status = PaymentState.FAILED, value = 999uL, fee = 7uL, timestamp = sentAt) - ) - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - val older = sentPayment(fees = 7) - .copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger(), timestamp = sentAt) - whenever(sparkService.listPayments()).thenReturn(listOf(older)) - val prepared = prepared(feeSats = 0uL) - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } - val sut = createSut() - sut.start(0).getOrThrow() - runCurrent() - assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) - runCurrent() - - // The retry fails before Spark took it, so its own id was never known. - val ownFailure = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED, timestamp = sentAt) - whenever(sparkService.listPayments()).thenReturn(listOf(older, ownFailure)) - sparkEvents.emit(SdkEvent.PaymentFailed(ownFailure)) - advanceUntilIdle() - - assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "the retry's own failure kept the earlier row") - } - - @Test - fun `an expired spark send in doubt stays held until spark syncs after its expiry`() = test { - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(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 SdkException.Generic("timeout") } - val failedAt = now.epochSeconds.toULong() - val sut = createSut() - sut.start(0).getOrThrow() - val events = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { events += it } } - runCurrent() - assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) - runCurrent() - - // Past the invoice's hour, while Spark's latest sync was made before it expired. - now += 2.hours - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = failedAt + 60uL)) - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - assertTrue(events.none { it is Event.PaymentFailed }, "a list from before the expiry failed the send") - - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - assertTrue(events.any { it is Event.PaymentFailed }, "a send Spark never listed stayed held past its expiry") - } - - /** The row of a send that failed, after a launch lists [payment] of its invoice. */ - private suspend fun TestScope.failedRowAfterListing(payment: Payment): Activity.Lightning { - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED)) - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - whenever(sparkService.listPayments()).thenReturn(listOf(payment)) - - createSut().start(0).getOrThrow() - advanceUntilIdle() - return row - } - - @Test - fun `an expired taken spark retry's own failure replaces an earlier attempt's failed row from the same second`() = - test { - // The app closed before it saved the retry's pending row; the retry started the second the earlier one did. - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendHashes = listOf("hash"), - sparkSendExpiries = mapOf("hash" to now.epochSeconds - 60), - sparkUncertainSendStarts = mapOf("hash" to now.epochSeconds - 3_660), - sparkTakenSendIds = mapOf("hash" to "retry"), - sparkSendRowIds = mapOf("hash" to "older"), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - var row = Activity.Lightning( - pendingSendRow().v1.copy(status = PaymentState.FAILED, value = 999uL, fee = 7uL) - ) - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - val ownFailure = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED) - whenever(sparkService.listPayments()).thenReturn(listOf(ownFailure)) - - createSut(store).start(0).getOrThrow() - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - - assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "the retry's own failure kept the earlier row") - assertFalse("hash" in store.data.first().sparkTakenSendIds) - } - - @Test - fun `a failed spark send row keeps its amount when a later launch lists an earlier attempt's failure`() = test { - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - var row = Activity.Lightning(pendingSendRow().v1.copy(status = PaymentState.FAILED)) - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - val older = sentPayment(fees = 7) - .copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger(), timestamp = 0uL) - whenever(sparkService.listPayments()).thenReturn(listOf(older)) - - createSut().start(0).getOrThrow() - advanceUntilIdle() - - assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "an earlier attempt's failure replaced the retry's row") - } - - @Test - fun `a taken spark retry with only an earlier failure listed stays held until the grace past expiry`() = test { - // The earlier attempt paid the amountless invoice at another amount and fee. - val older = sentPayment(fees = 7) - .copy(id = "older", status = PaymentStatus.FAILED, amount = 999.toBigInteger(), timestamp = 0uL) - val row = assertTakenRetryHeldUntilGrace(listed = listOf(older)) - assertEquals(PaymentState.FAILED, row.v1.status) - assertEquals(128uL to 0uL, row.v1.value to row.v1.fee, "the retry's row took the earlier attempt's payment") - } - - @Test - fun `a taken spark retry spark never lists stays held until the grace past expiry`() = test { - assertTakenRetryHeldUntilGrace(listed = emptyList()) - } - - /** - * Spark takes a retry while it lists [listed], and keeps listing only that: the retry stays held past its invoice's - * expiry until the grace for an unlisted send ends, then its row fails. - */ - private suspend fun TestScope.assertTakenRetryHeldUntilGrace(listed: List): Activity.Lightning { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - var row = pendingSendRow() - whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { Result.success(row) } - whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { - row = it.getArgument(0) as? Activity.Lightning ?: row - Result.success(Unit) - } - val prepared = unexpiredPrepared() - whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) - whenever(sparkService.listPayments()).thenReturn(listed) - whenever(sparkService.send(any(), anyOrNull())).thenReturn(retry) - val sut = createSut(store) - sut.start(0).getOrThrow() - assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) - // Spark reports the retry it took, which writes its row. - sparkEvents.emit(SdkEvent.PaymentPending(retry)) - runCurrent() - val events = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { events += it } } - val sync = suspend { - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - } - - // Past the invoice's hour, within the 10 min Spark may take to list the retry. - now += 65.minutes - sync() - assertTrue(events.none { it is Event.PaymentFailed }, "the expiry ended a retry Spark may still list") - assertTrue("hash" in store.data.first().sparkSendHashes) - assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) - assertEquals(PaymentStatus.PENDING, sut.lightningSendStatuses()?.get("hash")) - - // Past the grace, while Spark's latest sync was made before it ended. - now += 10.minutes - whenever( - sparkService.getInfo() - ).thenReturn(info(0uL).copy(lastSyncedAt = (now - 6.minutes).epochSeconds.toULong())) - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - assertTrue(events.none { it is Event.PaymentFailed }, "a list from before the grace ended failed the retry") - - // A sync past the grace ends while the expiry check reads Spark's list, so that list is still the older one. - var syncedAt = (now - 6.minutes).epochSeconds.toULong() - whenever(sparkService.getInfo()).thenAnswer { info(0uL).copy(lastSyncedAt = syncedAt) } - whenever(sparkService.listPayments()).thenAnswer { - val isSweep = Thread.currentThread().stackTrace.any { it.methodName.contains("dropExpiredTakenAttempts") } - if (isSweep) syncedAt = now.epochSeconds.toULong() - listed - } - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - assertTrue(events.none { it is Event.PaymentFailed }, "a sync after the list was read vouched for it") - whenever(sparkService.listPayments()).thenReturn(listed) - - sync() - assertTrue(events.any { it is Event.PaymentFailed }, "a retry Spark never listed stayed held past the grace") - verify(activityRepo, atLeastOnce()).upsertActivity( - argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } - ) - assertFalse("hash" in store.data.first().sparkSendHashes) - // Later syncs list the same payments. - sync() - return row - } - - @Test - fun `a taken spark retry kept from before a restart reads as pending within the grace past expiry`() = test { - val sentAt = now.epochSeconds - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendHashes = listOf("hash"), - sparkSendExpiries = mapOf("hash" to sentAt + 3_600), - sparkUncertainSendStarts = mapOf("hash" to sentAt), - sparkTakenSendIds = mapOf("hash" to "retry"), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.listPayments()).thenReturn(emptyList()) - now += 65.minutes - val sut = createSut(store) - - assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) - sut.lightningSendStatuses()?.let { assertEquals(PaymentStatus.PENDING, it["hash"]) } - } - - @Test - fun `a taken spark retry's own failure listed after a restart frees its invoice for paykit`() = test { - val sentAt = now.epochSeconds - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendHashes = listOf("hash"), - sparkSendExpiries = mapOf("hash" to sentAt + 3_600), - sparkUncertainSendStarts = mapOf("hash" to sentAt), - sparkTakenSendIds = mapOf("hash" to "retry"), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED) - whenever(sparkService.listPayments()).thenReturn(listOf(older)) - val sut = createSut(store) - sut.start(0).getOrThrow() - advanceUntilIdle() - assertEquals(setOf("hash"), sut.attemptedLightningPaymentHashes(), "an earlier failure freed a taken retry") - - // The retry failed while the app was closed, so Spark lists its own failure. - val ownFailure = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.FAILED) - whenever(sparkService.listPayments()).thenReturn(listOf(older, ownFailure)) - - assertEquals(emptySet(), sut.attemptedLightningPaymentHashes()) - } - - @Test - fun `a spark send cancelled after spark reported a failure during its call stays held`() = test { - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - var listed = emptyList() - whenever(sparkService.listPayments()).thenAnswer { listed } - val prepared = unexpiredPrepared() - whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) - // Spark reports the send's failure while its send call still runs, and the caller is cancelled after that. - whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { - listed = listOf(failed) - sparkEvents.emit(SdkEvent.PaymentFailed(failed)) - awaitCancellation() - } - val sut = createSut() - sut.start(0).getOrThrow() - runCurrent() - val caller = backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } - advanceUntilIdle() - - caller.cancel() - advanceUntilIdle() - - // A failure reported during the call can't be told from an earlier attempt's, so the send stays in doubt. - assertEquals( - EarlierSend.Pending("hash"), - sut.earlierLightningSend("lnbc1", "hash"), - "a failure seen during the call ended the hold", - ) - } - - @Test - fun `a spark send whose call returns after a wipe holds nothing`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - whenever(sparkService.listPayments()).thenReturn(emptyList()) - val prepared = unexpiredPrepared() - whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - val returns = CompletableDeferred() - whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { returns.await() } - val sut = createSut(store) - sut.start(0).getOrThrow() - runCurrent() - backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } - advanceUntilIdle() - - // The wallet is wiped while Spark's send call runs, and the call then returns the payment it took. - sut.wipe(0).getOrThrow() - store.reset() - returns.complete(sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING)) - advanceUntilIdle() - - assertTrue(store.data.first().sparkTakenSendIds.isEmpty(), "the wiped wallet's send was journaled") - assertFalse( - "hash" in sut.attemptedLightningPaymentHashes().orEmpty(), - "the wiped wallet's send still held the invoice", - ) - } - - @Test - fun `a failure spark reports during a send call is no settled send event`() = test { - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - var listed = emptyList() - whenever(sparkService.listPayments()).thenAnswer { listed } - val prepared = unexpiredPrepared() - whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) - // An earlier attempt the pre-send list left out fails while the retry's send call runs. - whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { - listed = listOf(failed) - awaitCancellation() - } - val sut = createSut() - sut.start(0).getOrThrow() - runCurrent() - backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } - advanceUntilIdle() - - assertNull(sut.settledSendEvent("hash"), "a failure seen during the call settled the send") - } - - @Test - fun `a spark send whose call returns its failure after spark reported it reports it once`() = test { - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - var listed = emptyList() - whenever(sparkService.listPayments()).thenAnswer { listed } - val prepared = unexpiredPrepared() - whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) - // Spark reports the failure while its send call runs, and the call then returns it. - whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { - listed = listOf(failed) - sparkEvents.emit(SdkEvent.PaymentFailed(failed)) - failed - } - val sut = createSut() - sut.start(0).getOrThrow() - runCurrent() - val events = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { events += it } } - runCurrent() - - assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) - // A watcher that started before the send, as a swap's hold payment does, learns the failure by its event. - assertEquals(1, events.count { it is Event.PaymentFailed }, "the failure's event was dropped or doubled") - advanceUntilIdle() - - assertIs(sut.settledSendEvent("hash"), "the returned failure wasn't reported") - assertNull(sut.earlierLightningSend("lnbc1", "hash"), "the failed send still held the invoice") - } - - @Test - fun `a spark send whose call returns pending after spark reported its failure reports it once`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - var listed = emptyList() - whenever(sparkService.listPayments()).thenAnswer { listed } - val prepared = unexpiredPrepared() - whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - val taken = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) - val failed = taken.copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) - // Spark reports the failure while its send call hands the payment it took over, before the call ends. - whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { - listed = listOf(failed) - sparkEvents.emit(SdkEvent.PaymentFailed(failed)) - taken - } - val sut = createSut(store) - sut.start(0).getOrThrow() - runCurrent() - val events = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { events += it } } - runCurrent() - - assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) - assertEquals(1, events.count { it is Event.PaymentFailed }, "the failure's event was dropped or doubled") - advanceUntilIdle() - - assertNull(sut.earlierLightningSend("lnbc1", "hash"), "the failed send still held the invoice") - assertTrue(store.data.first().sparkTakenSendIds.isEmpty(), "the failed send's attempt stayed journaled") - } - - @Test - fun `a failure seen during a spark send call that the expiry sweep reports first is reported once`() = test { - val inner = InMemoryDataStore(AppCacheData()) - val takenIdWritten = CompletableDeferred() - val resume = CompletableDeferred() - // The taken send's id write waits, so the expiry sweep runs while the send call hands its payment over. - val store = CacheStore( - object : DataStore { - override val data = inner.data - - override suspend fun updateData(transform: suspend (t: AppCacheData) -> AppCacheData): AppCacheData { - val before = inner.data.first() - if ("hash" !in before.sparkTakenSendIds && "hash" in transform(before).sparkTakenSendIds) { - takenIdWritten.complete(Unit) - resume.await() - } - return inner.updateData(transform) - } - }, - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenAnswer { info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) } - var listed = emptyList() - whenever(sparkService.listPayments()).thenAnswer { listed } - val prepared = unexpiredPrepared() - whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - val taken = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) - val failed = taken.copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) - whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { - listed = listOf(failed) - sparkEvents.emit(SdkEvent.PaymentFailed(failed)) - taken - } - val sut = createSut(store) - sut.start(0).getOrThrow() - runCurrent() - val events = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { events += it } } - runCurrent() - val caller = backgroundScope.async { sut.payInvoice("lnbc1", 100uL) } - takenIdWritten.await() - - // The invoice expires and Spark syncs, so the sweep reports the failure while the call still runs. - now += 2.hours - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - resume.complete(Unit) - caller.await().getOrThrow() - advanceUntilIdle() - - assertEquals(1, events.count { it is Event.PaymentFailed }, "the failure was reported twice") - } - - @Test - fun `a spark send whose caller is cancelled as spark takes it keeps its payment id`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(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() - runCurrent() - lateinit var caller: Job - // The caller is cancelled while Spark's send call returns the payment it took. - whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { - caller.cancel() - sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) - } - - caller = backgroundScope.launch(start = CoroutineStart.LAZY) { sut.payInvoice("lnbc1", 100uL) } - caller.start() - advanceUntilIdle() - - val cache = store.data.first() - assertEquals("retry", cache.sparkTakenSendIds["hash"], "a restart would read the send as in doubt") - assertTrue("hash" !in cache.sparkUncertainSends) - } - - @Test - fun `a taken attempt's late failure leaves the retry spark took after it failed`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - val b = sentPayment(fees = 0).copy(id = "b", status = PaymentStatus.PENDING) - val (_, events) = retryAfterTakenFailure(store, retry = b) - - // The taken attempt's own failure event arrives only now. - sparkEvents.emit(SdkEvent.PaymentFailed(takenAttemptFailure)) - advanceUntilIdle() - - assertTrue(events.none { it is Event.PaymentFailed }, "the earlier attempt's failure ended the live retry") - val cache = store.data.first() - assertEquals("b", cache.sparkTakenSendIds["hash"]) - assertTrue("hash" in cache.sparkSendHashes) - } - - @Test - fun `a retry spark took after a taken attempt failed reports its success once past expiry`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - val b = sentPayment(fees = 0).copy(id = "b", status = PaymentStatus.COMPLETED) - val (_, events) = retryAfterTakenFailure(store, retry = b) - - now += 2.hours - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - - assertEquals(1, events.count { it is Event.PaymentSuccessful }, "the expiry reported the retry's success again") - } - - @Test - fun `a spark send whose failure is handled before its pending response keeps no hold`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - val prepared = unexpiredPrepared() - whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - val b = sentPayment(fees = 0).copy(id = "b", status = PaymentStatus.PENDING) - val bFailed = b.copy(status = PaymentStatus.FAILED) - var listed = emptyList() - var isListUnavailable = false - whenever(sparkService.listPayments()).thenAnswer { - if (isListUnavailable) throw SdkException.Generic("down") else listed - } - // Spark reports the send's failure, while its list can't be read, before the send call returns pending. - whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { - isListUnavailable = true - sparkEvents.emit(SdkEvent.PaymentFailed(bFailed)) - delay(1.seconds) - isListUnavailable = false - b - } - val sut = createSut(store) - sut.start(0).getOrThrow() - val events = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { events += it } } - sut.payInvoice("lnbc1", 100uL) - advanceUntilIdle() - - listed = listOf(bFailed) - now += 2.hours - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - - assertEquals(1, events.count { it is Event.PaymentFailed }, "the expiry reported the failure again") - } - - @Test - fun `a taken spark retry's own failure wins over an earlier failure in either order`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - val prepared = unexpiredPrepared() - whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED) - val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) - whenever(sparkService.listPayments()).thenReturn(listOf(older)) - whenever(sparkService.send(any(), anyOrNull())).thenReturn(retry) - val sut = createSut(store) - sut.start(0).getOrThrow() - sut.payInvoice("lnbc1", 100uL).getOrThrow() - runCurrent() - val ownFailure = retry.copy(status = PaymentStatus.FAILED) - - for (listed in listOf(listOf(older, ownFailure), listOf(ownFailure, older))) { - whenever(sparkService.listPayments()).thenReturn(listed) - val send = assertIs(sut.lightningSend("hash")) - assertEquals(PaymentStatus.FAILED, send.status, "an earlier failure hid the retry's own in $listed") - } - } - - private val takenAttemptFailure = - sentPayment(fees = 0).copy(id = "a", status = PaymentStatus.FAILED, timestamp = 0uL) - - /** - * Spark takes attempt "a", whose own failure it lists before its event arrives; the retry then goes out with its - * send call failing, and a sync finds it listed as [retry]. Returns the repository and its node events. - */ - private suspend fun TestScope.retryAfterTakenFailure( - store: CacheStore, - retry: Payment, - ): Pair> { - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - val prepared = unexpiredPrepared() - whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - var listed = emptyList() - whenever(sparkService.listPayments()).thenAnswer { listed } - val taken = takenAttemptFailure.copy(status = PaymentStatus.PENDING) - whenever(sparkService.send(any(), anyOrNull())) - .thenReturn(taken) - .thenAnswer { throw SdkException.Generic("timeout") } - val sut = createSut(store) - sut.start(0).getOrThrow() - val events = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { events += it } } - assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) - runCurrent() - - listed = listOf(takenAttemptFailure) - assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) - runCurrent() - - listed = listOf(takenAttemptFailure, retry) - now += 5.seconds - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - return sut to events - } - - @Test - fun `a taken spark retry keeps its expiry after a restart whose list shows only an earlier failure`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isConnected).thenReturn(true) - val prepared = unexpiredPrepared() - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED) - val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) - whenever { sparkService.listPayments() }.thenReturn(listOf(older)) - whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(retry) - val before = createSut(store) - before.start(0).getOrThrow() - assertEquals("hash", before.payInvoice("lnbc1", 100uL).getOrThrow()) - runCurrent() - assertTrue("hash" in store.data.first().sparkSendExpiries) - - // Spark's list after the relaunch doesn't show the retry yet, only its earlier failed attempt. - whenever(sparkService.events).thenReturn(MutableSharedFlow()) - createSut(store).start(0).getOrThrow() - advanceUntilIdle() - - val cache = store.data.first() - assertTrue("hash" in cache.sparkSendHashes, "the startup sync released a retry Spark took") - assertTrue("hash" in cache.sparkSendExpiries, "the startup sync dropped a taken retry's expiry") - } - - @Test - fun `a taken spark retry without earlier ids ends its row and send once its invoice expires`() = test { - val sentAt = now.epochSeconds - // Spark took the retry before a restart, while its earlier attempts' ids couldn't be read. - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendHashes = listOf("hash"), - sparkSendExpiries = mapOf("hash" to sentAt + 3_600), - sparkUncertainSendStarts = mapOf("hash" to sentAt), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - whenever(activityRepo.getActivity(eq("hash"), any())).thenReturn(Result.success(pendingSendRow())) - whenever(activityRepo.upsertActivity(any())).thenReturn(Result.success(Unit)) - val ownFailure = sentPayment(fees = 0).copy( - id = "retry", - status = PaymentStatus.FAILED, - timestamp = sentAt.toULong() + 1uL, - ) - whenever(sparkService.listPayments()).thenReturn(listOf(ownFailure)) - val sut = createSut(store) - sut.start(0).getOrThrow() - val events = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { events += it } } - // Its own failure, dated within the 10 s a clock difference may account for, can't be told from an earlier one. - sparkEvents.emit(SdkEvent.PaymentFailed(ownFailure)) - advanceUntilIdle() - verify(activityRepo, never()).upsertActivity( - argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } - ) - - now += 2.hours - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - - verify(activityRepo).upsertActivity( - argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } - ) - assertFalse("hash" in store.data.first().sparkUncertainSendStarts) - assertTrue(events.any { it is Event.PaymentFailed }, "the send screen never learned the send failed") - } - - @Test - fun `a taken spark retry settled while closed reports no outcome when its invoice expires`() = test { - assertRestoredRetryReportsNoOutcome(earlierFailureFirst = false) - } - - @Test - fun `a taken spark retry settled while closed reports no outcome past an earlier attempt's late failure`() = test { - assertRestoredRetryReportsNoOutcome(earlierFailureFirst = true) - } - - private suspend fun TestScope.assertRestoredRetryReportsNoOutcome(earlierFailureFirst: Boolean) { - val sentAt = now.epochSeconds - // Spark took the retry, then the app closed; the retry completed while it was closed. - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendHashes = listOf("hash"), - sparkSendExpiries = mapOf("hash" to sentAt + 3_600), - sparkUncertainSendStarts = mapOf("hash" to sentAt), - sparkUncertainSendEarlierIds = mapOf("hash" to listOf("older")), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - whenever(activityRepo.getActivity(eq("hash"), any())).thenReturn(Result.success(pendingSendRow())) - whenever(activityRepo.upsertActivity(any())).thenReturn(Result.success(Unit)) - val completed = sentPayment(fees = 0).copy(id = "retry", timestamp = sentAt.toULong() + 5uL) - whenever(sparkService.listPayments()).thenReturn(listOf(completed)) - val sut = createSut(store) - sut.start(0).getOrThrow() - val events = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { events += it } } - advanceUntilIdle() - // The startup sync already wrote the completed row; Spark's event for it fired before the listener existed. - verify(activityRepo).upsertActivity( - argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.SUCCEEDED } - ) - if (earlierFailureFirst) { - val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED, timestamp = 1uL) - sparkEvents.emit(SdkEvent.PaymentFailed(older)) - advanceUntilIdle() - } - - now += 2.hours - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - - assertFalse("hash" in store.data.first().sparkUncertainSendStarts) - assertEquals( - emptyList(), - events.filter { it is Event.PaymentSuccessful || it is Event.PaymentFailed }, - "a payment settled hours earlier was reported again, opening the Sent sheet", - ) - } - - @Test - fun `a spark retry whose earlier ids went unread keeps none of an older attempt`() = test { - val aSentAt = now.epochSeconds - // Spark took attempt "a" of the invoice before a restart, while it listed only "older" for it. - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendHashes = listOf("hash"), - sparkSendExpiries = mapOf("hash" to aSentAt + 3_600), - sparkUncertainSendStarts = mapOf("hash" to aSentAt), - sparkUncertainSendEarlierIds = mapOf("hash" to listOf("older")), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(activityRepo.getActivity(eq("hash"), any())).thenReturn(Result.success(pendingSendRow())) - whenever(activityRepo.upsertActivity(any())).thenReturn(Result.success(Unit)) - // Attempt "a" failed while the app was closed; after the restart the user pays the invoice again. - now += 60.seconds - val aFailed = sentPayment(fees = 0).copy( - id = "a", - status = PaymentStatus.FAILED, - timestamp = aSentAt.toULong() + 30uL, - ) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - whenever(sparkService.listPayments()).thenReturn(listOf(aFailed)) - val prepared = unexpiredPrepared() - whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) - whenever(sparkService.send(any(), anyOrNull())).thenReturn(retry) - val second = createSut(store) - second.start(0).getOrThrow() - advanceUntilIdle() - // The retry's read of its earlier attempts fails right after the status read before it succeeded. - var reads = 0 - whenever(sparkService.listPayments()).thenAnswer { - if (reads++ == 1) throw SdkException.Generic("read") - listOf(aFailed) - } - val bSentAt = now.epochSeconds - assertEquals("hash", second.payInvoice("lnbc1", 100uL).getOrThrow()) - runCurrent() - - // The app restarts again while Spark still runs the retry. - now += 60.seconds - whenever(sparkService.listPayments()).thenReturn(listOf(aFailed, retry.copy(timestamp = bSentAt.toULong()))) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - val events = MutableSharedFlow() - whenever(sparkService.events).thenReturn(events) - clearInvocations(activityRepo) - createSut(store).start(0).getOrThrow() - advanceUntilIdle() - - verify(activityRepo, never()).upsertActivity( - argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } - ) - } - - private suspend fun TestScope.assertTakenRetryKeptPastEarlierFailure(restart: Boolean) { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isConnected).thenReturn(true) - val prepared = unexpiredPrepared() - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - // Dated well after the retry went out, past the 10 s a clock difference may account for. - val older = sentPayment(fees = 0).copy( - id = "older", - status = PaymentStatus.FAILED, - timestamp = now.epochSeconds.toULong() + 60uL, - ) - val retry = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING) - whenever { sparkService.listPayments() }.thenReturn(listOf(older)) - whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(retry) - val before = createSut(store) - before.start(0).getOrThrow() - assertEquals("hash", before.payInvoice("lnbc1", 100uL).getOrThrow()) - runCurrent() - whenever { sparkService.listPayments() }.thenReturn(listOf(older, retry)) - clearInvocations(activityRepo) - val events = MutableSharedFlow() - val sut = if (restart) { - whenever(sparkService.events).thenReturn(events) - createSut(store).also { it.start(0).getOrThrow() } - } else { - before - } - val nodeEvents = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { nodeEvents += it } } - runCurrent() - - (if (restart) events else sparkEvents).emit(SdkEvent.PaymentFailed(older)) - advanceUntilIdle() - - assertTrue(nodeEvents.none { it is Event.PaymentFailed }, "an earlier failure ended a send Spark still runs") - verify(activityRepo, never()).upsertActivity( - argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } - ) - } - - @Test - fun `an older attempt's failure after a restart keeps an uncertain spark retry held`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - val prepared = prepared(feeSats = 0uL) - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } - whenever { sparkService.getInfo() }.thenReturn( - info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) - ) - val before = createSut(store) - before.start(0).getOrThrow() - assertIs(before.payInvoice("lnbc1", 100uL).exceptionOrNull()) - runCurrent() - val after = createSut(store) - after.start(0).getOrThrow() - val events = mutableListOf() - backgroundScope.launch { after.nodeEvents.collect { events += it } } - runCurrent() - - // The earlier attempt's failure, made long before the retry went out, arrives after the restart. - val olderFailure = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) - whenever { sparkService.listPayments() }.thenReturn(listOf(olderFailure)) - sparkEvents.emit(SdkEvent.PaymentFailed(olderFailure)) - advanceUntilIdle() - - assertTrue(events.none { it is Event.PaymentFailed }, "an older failure ended a send Spark may finish") - assertEquals(EarlierSend.Pending("hash"), after.earlierLightningSend("lnbc1", "hash")) - verify(activityRepo, never()).upsertActivity( - argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } - ) - } - - @Test - fun `an uncertain spark retry stays held after a restart while spark lists only its older failure`() = test { - assertUncertainRetryHeldAfterRestart(syncError = null) - } - - @Test - fun `an uncertain spark retry stays held after a restart whose first sync fails`() = test { - assertUncertainRetryHeldAfterRestart(syncError = SyncError.Network("operators unreachable")) - } - - private suspend fun TestScope.assertUncertainRetryHeldAfterRestart(syncError: SyncError?) { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isConnected).thenReturn(true) - val prepared = prepared(feeSats = 0uL) - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } - // An earlier attempt of the invoice failed, and the retry's outcome is unknown when the app stops. - whenever { sparkService.listPayments() } - .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) - whenever { sparkService.getInfo() }.thenReturn( - info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) - ) - val before = createSut(store) - before.start(0).getOrThrow() - assertIs(before.payInvoice("lnbc1", 100uL).exceptionOrNull()) - runCurrent() - - whenever { sparkService.getInfo() }.thenReturn( - info(0uL).copy(lastSyncError = syncError, lastSyncedAt = now.epochSeconds.toULong() + 1uL) - ) - clearInvocations(activityRepo) - val after = createSut(store) - after.start(0).getOrThrow() - - verify(activityRepo, never()).upsertActivity( - argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } - ) - assertTrue("hash" in store.data.first().sparkSendHashes, "A restart released a retry Spark may resume") - assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), after.lightningSend("hash")) - assertEquals(EarlierSend.Pending("hash"), after.earlierLightningSend("lnbc1", "hash")) - } - - @Test - fun `a spark retry cut off by process death stays held after a restart while spark lists only its older failure`() = - test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isConnected).thenReturn(true) - val prepared = unexpiredPrepared() - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - // The process dies inside Spark's send call, so the call never returns. - whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { awaitCancellation() } - whenever { sparkService.listPayments() } - .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) - val before = createSut(store) - before.start(0).getOrThrow() - backgroundScope.launch { before.payInvoice("lnbc1", 100uL) } - runCurrent() - - whenever { sparkService.getInfo() }.thenReturn( - info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) - ) - assertEquals(now.epochSeconds, store.data.first().sparkUncertainSendStarts["hash"]) - clearInvocations(activityRepo) - // A new process: only the restarted repo hears Spark's events. - val restartedEvents = MutableSharedFlow() - whenever(sparkService.events).thenReturn(restartedEvents) - val after = createSut(store) - after.start(0).getOrThrow() - val events = mutableListOf() - backgroundScope.launch { after.nodeEvents.collect { events += it } } - runCurrent() - // The earlier attempt's failure arrives again as an event after the restart. - restartedEvents.emit(SdkEvent.PaymentFailed(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) - advanceUntilIdle() - - assertEquals( - EarlierSend.Pending("hash"), - after.earlierLightningSend("lnbc1", "hash"), - "A restart released a retry Spark may resume to the node", - ) - assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), after.lightningSend("hash")) - assertTrue(events.none { it is Event.PaymentFailed }, "an older failure ended a send Spark may finish") - verify(activityRepo, never()).upsertActivity( - argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } - ) - } - - @Test - fun `an uncertain spark retry held past an older failure ends its row as failed once its invoice expires`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isConnected).thenReturn(true) - val prepared = unexpiredPrepared() - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } - val olderFailure = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) - whenever { sparkService.listPayments() }.thenReturn(listOf(olderFailure)) - whenever { sparkService.getInfo() }.thenReturn( - info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) - ) - val before = createSut(store) - before.start(0).getOrThrow() - assertIs(before.payInvoice("lnbc1", 100uL).exceptionOrNull()) - runCurrent() - whenever { sparkService.getInfo() }.thenReturn( - info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) - ) - clearInvocations(activityRepo) - val restartedEvents = MutableSharedFlow() - whenever(sparkService.events).thenReturn(restartedEvents) - val after = createSut(store) - after.start(0).getOrThrow() - val events = mutableListOf() - backgroundScope.launch { after.nodeEvents.collect { events += it } } - runCurrent() - verify(activityRepo, never()).upsertActivity( - argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } - ) - - // The invoice expires and Spark syncs, still listing only the older failure. - now += 2.hours - whenever { sparkService.getInfo() }.thenReturn( - info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) - ) - restartedEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - - assertTrue(events.any { it is Event.PaymentFailed }, "the expired retry was never reported failed") - verify(activityRepo, atLeastOnce()).upsertActivity( - argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } - ) - } - - @Test - fun `an expired spark retry listed as failed writes its row from the read that ends its hold`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isConnected).thenReturn(true) - val prepared = unexpiredPrepared() - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } - val olderFailure = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) - whenever { sparkService.listPayments() }.thenReturn(listOf(olderFailure)) - whenever { sparkService.getInfo() }.thenReturn( - info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) - ) - val before = createSut(store) - before.start(0).getOrThrow() - assertIs(before.payInvoice("lnbc1", 100uL).exceptionOrNull()) - runCurrent() - whenever { sparkService.getInfo() }.thenReturn( - info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) - ) - // The restarted repository writes to its own Activity, so the first one's poll can't stand in for it. - val restartedActivity = mock() - whenever { restartedActivity.getActivity(any(), any()) }.thenReturn(Result.success(null)) - whenever { restartedActivity.upsertActivity(any()) }.thenReturn(Result.success(Unit)) - val restartedEvents = MutableSharedFlow() - whenever(sparkService.events).thenReturn(restartedEvents) - val after = createSut(store, restartedActivity) - after.start(0).getOrThrow() - val events = mutableListOf() - backgroundScope.launch { after.nodeEvents.collect { events += it } } - runCurrent() - verify(restartedActivity, never()).upsertActivity( - argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } - ) - - // The invoice expires and Spark syncs, still listing only the older failure. - now += 2.hours whenever { sparkService.getInfo() }.thenReturn( - info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) - ) - // Every read of Spark's list after the one that settles the hold fails. - var isSettled = false - whenever { sparkService.listPayments() }.thenAnswer { - if (isSettled) throw SdkException.Generic("operators unreachable") - isSettled = Thread.currentThread().stackTrace.any { it.methodName.contains("trySettleUncertainSend") } - listOf(olderFailure) - } - restartedEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - - verify(restartedActivity, atLeastOnce()).upsertActivity( - argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } - ) - assertTrue(events.any { it is Event.PaymentFailed }, "the send screen never learned the send failed") - } - - @Test - fun `a spark send handed from its doubt to spark during a lookup's list read stays pending`() = test { - val sentAt = now.epochSeconds - 7_200 - // A retry in doubt from before a restart, whose invoice expired before Spark's last sync. - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendHashes = listOf("hash"), - sparkSendExpiries = mapOf("hash" to sentAt + 3_600), - sparkUncertainSends = mapOf("hash" to sentAt), - sparkUncertainSendStarts = mapOf("hash" to sentAt), - ) - ), - clock, - ) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = (sentAt + 60).toULong())) - val gate = CompletableDeferred() - var isLookup = false - var listed = emptyList() - whenever { sparkService.listPayments() }.doSuspendableAnswer { - if (!isLookup) return@doSuspendableAnswer listed - isLookup = false - gate.await() - emptyList() - } - val sut = createSut(store) - sut.start(0).getOrThrow() - advanceUntilIdle() - - // The lookup reads an empty list, and a sync hands the retry to Spark before the lookup goes on. - isLookup = true - val lookup = async { sut.lightningSend("hash") } - runCurrent() - listed = listOf(sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING)) - sparkEvents.emit(SdkEvent.Synced) - runCurrent() - assertEquals("retry", store.data.first().sparkTakenSendIds["hash"], "the sync didn't hand the retry to Spark") - gate.complete(Unit) - - assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), lookup.await()) - } - - @Test - fun `an older failure the pre-send list left out keeps a retry held while its send call runs`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - val prepared = unexpiredPrepared() - whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - var listed = emptyList() - whenever(sparkService.listPayments()).thenAnswer { listed } - // An older attempt Spark didn't list before the retry went out fails while the retry's call runs, which then - // times out. - val older = sentPayment(fees = 0) - .copy(id = "older", status = PaymentStatus.FAILED, timestamp = (now - 1.minutes).epochSeconds.toULong()) - whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { - listed = listOf(older) - sparkEvents.emit(SdkEvent.PaymentFailed(older)) - delay(1) - throw SdkException.Generic("timeout") - } - val sut = createSut(store) - sut.start(0).getOrThrow() - val events = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { events += it } } - runCurrent() - - val result = sut.payInvoice("lnbc1", 100uL) - runCurrent() - - assertIs(result.exceptionOrNull(), "the older failure ended the retry's call") - assertTrue(events.none { it is Event.PaymentFailed }, "the older failure ended a retry Spark may finish") - assertTrue("hash" in store.data.first().sparkUncertainSends, "the older failure dropped the retry's hold") - } - - @Test - fun `a spark send whose success was handled before its call failed returns it and keeps no hold`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isSupported).thenReturn(true) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - val prepared = unexpiredPrepared() - whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - val completed = sentPayment(fees = 0).copy(status = PaymentStatus.COMPLETED) - var listed = emptyList() - whenever(sparkService.listPayments()).thenAnswer { listed } - // Spark reports the send's success while its call runs, and the call then fails. - whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { - listed = listOf(completed) - sparkEvents.emit(SdkEvent.PaymentSucceeded(completed)) - delay(1) - throw SdkException.Generic("timeout") - } - val sut = createSut(store) - sut.start(0).getOrThrow() - val events = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { events += it } } - runCurrent() - - val result = sut.payInvoice("lnbc1", 100uL) - advanceUntilIdle() - - assertEquals("hash", result.getOrNull(), "the failed call read a handled success as pending") - assertEquals(1, events.count { it is Event.PaymentSuccessful }, "the failed call reported the success again") - assertFalse("hash" in store.data.first().sparkUncertainSends, "the failed call held a settled send again") - } - - @Test - fun `a taken spark retry reads as pending while spark lists only an earlier attempt's failure`() = test { - val sentAt = now.epochSeconds - // Spark took a retry before a restart, while it listed only the earlier attempt "older" of the invoice. - val store = CacheStore( - InMemoryDataStore( - AppCacheData( - sparkSendHashes = listOf("hash"), - sparkSendExpiries = mapOf("hash" to sentAt + 3_600), - sparkUncertainSendStarts = mapOf("hash" to sentAt), - sparkUncertainSendEarlierIds = mapOf("hash" to listOf("older")), - ) - ), - clock, + info(0uL).copy(lastSyncError = syncError, lastSyncedAt = now.epochSeconds.toULong() + 1uL) ) - whenever(sparkService.isConnected).thenReturn(true) - whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - val older = sentPayment(fees = 0).copy(id = "older", status = PaymentStatus.FAILED) - whenever(sparkService.listPayments()).thenReturn(listOf(older)) - val sut = createSut(store) - sut.start(0).getOrThrow() - advanceUntilIdle() - - assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) - assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) - assertEquals(PaymentStatus.PENDING, sut.lightningSendStatuses()?.get("hash")) - assertTrue("hash" in sut.attemptedLightningPaymentHashes().orEmpty()) - assertNull(sut.settledSendEvent("hash")) - } - - @Test - fun `an older attempt's failure after a spark retry was cancelled inside its send keeps its hold`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isConnected).thenReturn(true) - val prepared = unexpiredPrepared() - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { awaitCancellation() } - val olderFailure = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) - whenever { sparkService.listPayments() }.thenReturn(listOf(olderFailure)) - val sut = createSut(store) - sut.start(0).getOrThrow() clearInvocations(activityRepo) - val events = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { events += it } } - val send = backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } - runCurrent() - - // The send screen goes away while Spark's send call runs, and the older failure arrives after. - send.cancel() - runCurrent() - sparkEvents.emit(SdkEvent.PaymentFailed(olderFailure)) - runCurrent() + val after = createSut(store) + after.start(0).getOrThrow() - assertTrue( - events.none { it is Event.PaymentFailed }, - "an older failure ended a cancelled send Spark may finish" - ) - assertTrue( - "hash" in store.data.first().sparkUncertainSends, - "an older failure dropped the cancelled send's hold" - ) - assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) verify(activityRepo, never()).upsertActivity( argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } ) + assertTrue("hash" in store.data.first().sparkSendHashes, "A restart released a retry Spark may resume") + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), after.lightningSend("hash")) + assertEquals(EarlierSend.Pending("hash"), after.earlierLightningSend("lnbc1", "hash")) } @Test - fun `an expired spark send missing from spark keeps its hold until its row is marked failed`() = test { - whenever(sparkService.isConnected).thenReturn(true) - val prepared = unexpiredPrepared() - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } - val pending = LightningActivity.create( - id = "hash", - txType = ActivityPaymentType.SENT, - status = PaymentState.PENDING, - value = 100uL, - invoice = "lnbc1", - timestamp = 1uL, - ) - whenever { activityRepo.getActivity(eq("hash"), any()) }.thenReturn(Result.success(Activity.Lightning(pending))) - whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.failure(IllegalStateException("disk full"))) - val sut = createSut() - sut.start(0).getOrThrow() - val events = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { events += it } } - assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) - advanceUntilIdle() - - // The invoice expires and Spark syncs, listing no such send, while Activity can't be written. - now += 2.hours - whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - - assertTrue(events.none { it is Event.PaymentFailed }, "a send was reported failed while its row stayed pending") - assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) - - // The next sync writes the row, which ends the hold. - whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.success(Unit)) - clearInvocations(activityRepo) - sparkEvents.emit(SdkEvent.Synced) - advanceUntilIdle() - - assertTrue(events.any { it is Event.PaymentFailed }, "the expired send was never reported failed") - verify(activityRepo, atLeastOnce()).upsertActivity( - argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } - ) - } - - @Test - fun `an older attempt's failure during a spark retry's send keeps its hold`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isConnected).thenReturn(true) - val prepared = unexpiredPrepared() - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - // Spark's send call is still running when the earlier attempt's failure arrives. - whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { awaitCancellation() } - val olderFailure = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) - whenever { sparkService.listPayments() }.thenReturn(listOf(olderFailure)) - val sut = createSut(store) - sut.start(0).getOrThrow() - // The start recorded the older attempt's failure, before the retry. - clearInvocations(activityRepo) - val events = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { events += it } } - backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } - runCurrent() - - sparkEvents.emit(SdkEvent.PaymentFailed(olderFailure)) - runCurrent() + fun `a spark retry cut off by process death stays held after a restart while spark lists only its older failure`() = + test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + // The process dies inside Spark's send call, so the call never returns. + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { awaitCancellation() } + whenever { sparkService.listPayments() } + .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + val before = createSut(store) + before.start(0).getOrThrow() + backgroundScope.launch { before.payInvoice("lnbc1", 100uL) } + runCurrent() - val cache = store.data.first() - assertTrue("hash" in cache.sparkUncertainSends, "an older failure dropped the in-flight send's hold") - assertTrue("hash" in cache.sparkSendHashes, "an older failure released the in-flight send's invoice") - assertTrue(events.none { it is Event.PaymentFailed }, "an older failure ended a send Spark may finish") - verify(activityRepo, never()).upsertActivity( - argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } - ) - } + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) + ) + val after = createSut(store) + after.start(0).getOrThrow() - @Test - fun `an older failure handled across a retry's start leaves the retry's hold`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isConnected).thenReturn(true) - val prepared = unexpiredPrepared() - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { awaitCancellation() } - val sut = createSut(store) - sut.start(0).getOrThrow() - val events = mutableListOf() - backgroundScope.launch { sut.nodeEvents.collect { events += it } } - val olderFailure = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED) - whenever { sparkService.listPayments() }.thenReturn(listOf(olderFailure)) - // The older failure's handler waits on its Activity lookup while the retry starts. - val lookup = CompletableDeferred() - whenever { activityRepo.getActivity(any(), any()) }.doSuspendableAnswer { - lookup.await() - Result.success(null) + assertEquals( + EarlierSend.Pending("hash"), + after.earlierLightningSend("lnbc1", "hash"), + "A restart released a retry Spark may resume to the node", + ) + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), after.lightningSend("hash")) } - sparkEvents.emit(SdkEvent.PaymentFailed(olderFailure)) - runCurrent() - backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } - runCurrent() - - lookup.complete(Unit) - runCurrent() - - val cache = store.data.first() - assertTrue("hash" in cache.sparkUncertainSends, "an older failure dropped the retry's hold") - assertTrue("hash" in cache.sparkSendHashes, "an older failure released the retry's invoice") - assertTrue(events.none { it is Event.PaymentFailed }, "an older failure ended a send Spark may finish") - verify(activityRepo, never()).upsertActivity( - argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } - ) - } @Test fun `a cancelled spark retry stays held while spark lists only its older failure`() = test { @@ -6070,38 +4056,6 @@ class SparkRepoTest : BaseUnitTest() { ) } - /** Runs a retry of the invoice to its end inside the first list read [isRetryRead] picks, which lists [failed]. */ - private fun retryDuringListRead(failed: Payment, isRetryRead: (Int) -> Boolean): SparkRepo { - whenever(sparkService.isConnected).thenReturn(true) - val prepared = prepared(feeSats = 0uL) - whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0).copy(id = "retry")) - whenever { activityRepo.getActivity(eq("hash"), any()) }.thenReturn(Result.success(pendingSendRow())) - whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.success(Unit)) - val sut = createSut() - var lists = 0 - var hasRetried = false - whenever { sparkService.listPayments() }.doSuspendableAnswer { - if (!hasRetried && isRetryRead(++lists)) { - hasRetried = true - sut.payInvoice("lnbc1280n1send", 128uL).getOrThrow() - } - listOf(failed) - } - return sut - } - - private fun pendingSendRow() = Activity.Lightning( - LightningActivity.create( - id = "hash", - txType = ActivityPaymentType.SENT, - status = PaymentState.PENDING, - value = 128uL, - invoice = "lnbc1280n1send", - timestamp = 1uL, - ) - ) - private fun unexpiredPrepared(): PrepareSendPaymentResponse { val details = mock { on { paymentHash } doReturn "hash" From d8e1de5c77f3eb6f5e8fbb019983747018a4089c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 23:47:48 +0100 Subject: [PATCH 80/96] fix: spark holds a taken send until it settles A send Spark took keeps its hold until Spark settles it or its invoice expires, so a list that does not show it yet never lets a retry through. Verified: just format, just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 15 ++++++++--- .../to/bitkit/repositories/SparkRepoTest.kt | 25 +++++++++++++++++++ 2 files changed, 37 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 612237efbc..09a5e95ad6 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -611,7 +611,13 @@ class SparkRepo @Inject constructor( settleUncertainSend(paymentHash, expiresAt) throw PaymentPendingException(paymentHash) } - cacheStore.removeSparkUncertainSend(paymentHash) + // A send Spark took stays held until Spark settles it or its invoice expires, as Spark's list may not show + // it yet. + if (payment.status == PaymentStatus.PENDING) { + settleUncertainSend(paymentHash, expiresAt) + } else { + cacheStore.removeSparkUncertainSend(paymentHash) + } Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) paymentHash }.onFailure { @@ -663,7 +669,10 @@ class SparkRepo @Inject constructor( SparkLightningSend.NotFound -> isFinal // A failure dated before the send started is an earlier attempt's, so it is final only when a missing // send would be. - is SparkLightningSend.Found -> send.status != PaymentStatus.FAILED || isFinal || hasOwnFailure(paymentHash) + is SparkLightningSend.Found if send.status == PaymentStatus.COMPLETED -> true + // A pending send ends with its own payment event, or at its invoice's expiry. + is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> isFinal + is SparkLightningSend.Found -> isFinal || hasOwnFailure(paymentHash) SparkLightningSend.Unavailable -> false } // Only the caller that takes the hash off settles it, so its outcome is reported once. @@ -674,7 +683,7 @@ class SparkRepo @Inject constructor( cacheStore.removeSparkSendHash(paymentHash) _nodeEvents.emit(Event.PaymentFailed(paymentHash, paymentHash, PaymentFailureReason.UNEXPECTED_ERROR)) } - // A pending send ends with its own payment event. + // Spark still runs a pending send past its invoice's expiry, so its own payment event reports it. is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> Unit is SparkLightningSend.Found -> { if (send.status == PaymentStatus.FAILED) { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index c3b9034205..f704cba980 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3836,6 +3836,31 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) } + @Test + fun `a retry spark took stays held while spark lists only an earlier attempt's failure`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val taken = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING, timestamp = 5uL) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(taken) + val sut = createSut() + sut.start(0).getOrThrow() + sut.payInvoice("lnbc1", 100uL) + advanceUntilIdle() + + // Spark's list doesn't show the send it took yet, only the invoice's earlier failed attempt. + val earlier = sentPayment(fees = 0).copy(id = "earlier", status = PaymentStatus.FAILED, timestamp = 1uL) + whenever(sparkService.listPayments()).thenReturn(listOf(earlier)) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + verify(sparkService, times(1)).send(any(), anyOrNull()) + } + @Test fun `a spark send in doubt ends at once on its own failure`() = test { whenever(sparkService.isSupported).thenReturn(true) From 63135ae1ef0b0d8a52ba0abac629e262b0198e3b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 00:16:00 +0100 Subject: [PATCH 81/96] fix: spark settles a cancelled send at expiry The sync sweep also reads holds only saved, as when a caller was cancelled inside the send call, so one never stays held until a restart. Verified: just format, just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 6 ++++- .../to/bitkit/repositories/SparkRepoTest.kt | 27 +++++++++++++++++++ 2 files changed, 32 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 09a5e95ad6..e6ab1ee0ac 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -707,6 +707,8 @@ class SparkRepo @Inject constructor( private suspend fun restoreUncertainSends() { val cache = cacheStore.data.first() cache.sparkUncertainSends.forEach { (hash, failedAt) -> + // A send still in Spark's send call is settled by its result. + if (sendsInFlight.containsKey(hash)) return@forEach val expiresAt = cache.sparkSendExpiries[hash]?.toULong() ?: ULong.MAX_VALUE uncertainSends.putIfAbsent(hash, UncertainSend(failedAt.toULong(), failedAt.toULong(), expiresAt)) } @@ -1904,7 +1906,9 @@ class SparkRepo @Inject constructor( if (hasSyncedSince(null)) _state.update { it.copy(hasSynced = true) } seedRestoredSendHashes() refresh() - // A send whose outcome stayed unknown past its polling settles on a later sync. + // A send whose outcome stayed unknown past its polling settles on a later sync, also one only + // saved, as when its caller was cancelled inside Spark's send call. + restoreUncertainSends() uncertainSends.keys.toList().forEach { trySettleUncertainSend(it) } // A journal left open past its grace period would block every later withdrawal until a restart. // Spark emits Synced after a sync that never reached it too, so only one since the journal diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index f704cba980..fbc33677ce 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3861,6 +3861,33 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, times(1)).send(any(), anyOrNull()) } + @Test + fun `a spark send whose caller was cancelled inside the send call ends at its invoice's expiry`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { awaitCancellation() } + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) + sut.start(0).getOrThrow() + val send = launch { sut.payInvoice("lnbc1", 100uL) } + runCurrent() + send.cancel() + advanceUntilIdle() + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + + // Spark never lists the send, and syncs after its invoice expired. + now += 2.hours + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertFalse("hash" in store.data.first().sparkUncertainSends, "a cancelled send stayed held past expiry") + assertNull(sut.earlierLightningSend("lnbc1", "hash")) + } + @Test fun `a spark send in doubt ends at once on its own failure`() = test { whenever(sparkService.isSupported).thenReturn(true) From 7444b24786341013d9ce5c01b6bd9d702a82eb58 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 00:25:42 +0100 Subject: [PATCH 82/96] fix: spark ignores an older attempt failure event A failure event of an attempt Spark lists another attempt deciding no longer replaces that attempt amount, fee and time in Activity. Verified: just format, just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 5 +++-- .../to/bitkit/repositories/SparkRepoTest.kt | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index e6ab1ee0ac..45bc590369 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1945,10 +1945,11 @@ class SparkRepo @Inject constructor( trySettleUncertainSend(it, isFailureEvent = true) return } - // A failure of an earlier attempt settles nothing while Spark lists a later one pending or paid. + // A failure of an attempt that Spark's list shows another attempt deciding, as pending, paid or a later + // failure, settles nothing. payment.sendHash(PaymentStatus.FAILED)?.let { hash -> val deciding = runSuspendCatching { sparkService.listPayments() }.getOrNull()?.latestSend(hash) - if (deciding != null && deciding.id != payment.id && deciding.status != PaymentStatus.FAILED) return + if (deciding != null && deciding.id != payment.id) return } recordActivity(payment, settlesJournal = false) // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index fbc33677ce..3d594aed4a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3888,6 +3888,24 @@ class SparkRepoTest : BaseUnitTest() { assertNull(sut.earlierLightningSend("lnbc1", "hash")) } + @Test + fun `an older failure event leaves the row of a later failed attempt`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + val later = sentPayment(fees = 0).copy(id = "later", status = PaymentStatus.FAILED, timestamp = 20uL) + val older = sentPayment(fees = 7).copy(id = "older", status = PaymentStatus.FAILED, timestamp = 1uL) + whenever(sparkService.listPayments()).thenReturn(listOf(later, older)) + val sut = createSut() + sut.start(0).getOrThrow() + advanceUntilIdle() + clearInvocations(activityRepo) + + sparkEvents.emit(SdkEvent.PaymentFailed(older)) + advanceUntilIdle() + + verify(activityRepo, never()).upsertActivity(argThat { this is Activity.Lightning && v1.fee == 7uL }) + } + @Test fun `a spark send in doubt ends at once on its own failure`() = test { whenever(sparkService.isSupported).thenReturn(true) From d45d99727eb527beece42de8aa97da0e5d1c405f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 00:57:52 +0100 Subject: [PATCH 83/96] fix: spark keeps a send in flight until its result is handled A sync that runs as a send returns no longer takes back its saved hold before the result clears it, as when Spark refuses it for its balance. Verified: just format, just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 85 ++++++++++--------- .../to/bitkit/repositories/SparkRepoTest.kt | 38 +++++++++ 2 files changed, 82 insertions(+), 41 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 45bc590369..e53cd0632f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -572,54 +572,57 @@ class SparkRepo @Inject constructor( if (sendsInFlight.putIfAbsent(paymentHash.lowercase(), bolt11) != null) { throw PaymentPendingException(paymentHash) } - val sent = try { - sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() - cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) - spending { - // Kept until the call returns, so a send cut off by process death or cancellation stays held. - cacheStore.addSparkUncertainSend(paymentHash, clock.now().epochSeconds) - // The checks above and both writes suspend, so the deadline and an exit that started meanwhile - // are checked last, before the send. - runCatching { - ensurePaymentDeadline(paymentDeadlineAt) - ensureNotExiting() - }.onFailure { + // Kept in flight until its result is handled, so a sync meanwhile never takes back its saved hold. + try { + val sent = run { + sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() + cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) + spending { + // Kept until the call returns, so a send cut off by process death or cancellation stays held. + cacheStore.addSparkUncertainSend(paymentHash, clock.now().epochSeconds) + // The checks above and both writes suspend, so the deadline and an exit that started meanwhile + // are checked last, before the send. + runCatching { + ensurePaymentDeadline(paymentDeadlineAt) + ensureNotExiting() + }.onFailure { + cacheStore.removeSparkUncertainSend(paymentHash) + cacheStore.removeSparkSendHash(paymentHash) + throw it + } + runSuspendCatching { sparkService.send(prepared) } + } + } + val payment = sent.getOrElse { + // The SDK checks the expiry again before anything goes out, so an expired invoice left nothing. + if (it.isInvoiceExpired()) { cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) - throw it + throw SparkError.InvoiceExpired(it) } - runSuspendCatching { sparkService.send(prepared) } - } - } finally { - sendsInFlight.remove(paymentHash.lowercase()) - } - val payment = sent.getOrElse { - // The SDK checks the expiry again before anything goes out, so an expired invoice left nothing. - if (it.isInvoiceExpired()) { - cacheStore.removeSparkUncertainSend(paymentHash) - 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. + if (it is SdkException.InsufficientFunds) { + cacheStore.removeSparkUncertainSend(paymentHash) + cacheStore.removeSparkSendHash(paymentHash) + 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) + settleUncertainSend(paymentHash, expiresAt) + throw PaymentPendingException(paymentHash) } - // 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) { + // A send Spark took stays held until Spark settles it or its invoice expires, as Spark's list may not + // show it yet. + if (payment.status == PaymentStatus.PENDING) { + settleUncertainSend(paymentHash, expiresAt) + } else { cacheStore.removeSparkUncertainSend(paymentHash) - cacheStore.removeSparkSendHash(paymentHash) - 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) - settleUncertainSend(paymentHash, expiresAt) - throw PaymentPendingException(paymentHash) - } - // A send Spark took stays held until Spark settles it or its invoice expires, as Spark's list may not show - // it yet. - if (payment.status == PaymentStatus.PENDING) { - settleUncertainSend(paymentHash, expiresAt) - } else { - cacheStore.removeSparkUncertainSend(paymentHash) + Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) + paymentHash + } finally { + sendsInFlight.remove(paymentHash.lowercase()) } - Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) - paymentHash }.onFailure { if (it is PaymentAbortedBeforeSend) { Logger.debug("Aborted Spark invoice pay before send", 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 3d594aed4a..36753ac22e 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1,5 +1,6 @@ package to.bitkit.repositories +import androidx.datastore.core.DataStore import breez_sdk_spark.AutoOptimizationEvent import breez_sdk_spark.BitcoinAddressDetails import breez_sdk_spark.Bolt11InvoiceDetails @@ -3906,6 +3907,43 @@ class SparkRepoTest : BaseUnitTest() { verify(activityRepo, never()).upsertActivity(argThat { this is Activity.Lightning && v1.fee == 7uL }) } + @Test + fun `a spark send refused for its balance stays in flight until its hold is cleared`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.InsufficientFunds(null) } + val backing = InMemoryDataStore(AppCacheData()) + lateinit var sut: SparkRepo + val inFlightAtClear = mutableListOf() + // A sync's sweep skips a send in flight, so the saved hold must be cleared before the send leaves it. + val store = CacheStore( + object : DataStore { + override val data = backing.data + + override suspend fun updateData(transform: suspend (t: AppCacheData) -> AppCacheData): AppCacheData { + val wasHeld = "hash" in backing.data.first().sparkUncertainSends + val updated = backing.updateData(transform) + if (wasHeld && "hash" !in updated.sparkUncertainSends) { + inFlightAtClear += sut.isSendInFlight("hash") + } + return updated + } + }, + clock, + ) + sut = createSut(store) + sut.start(0).getOrThrow() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + assertTrue(inFlightAtClear.isNotEmpty() && inFlightAtClear.all { it }, "a sync could take back the hold") + assertFalse(sut.isSendInFlight("hash")) + assertNull(sut.earlierLightningSend("lnbc1", "hash")) + } + @Test fun `a spark send in doubt ends at once on its own failure`() = test { whenever(sparkService.isSupported).thenReturn(true) From 50fae11ea275acad515379b598630c9dcc600a17 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 01:38:20 +0100 Subject: [PATCH 84/96] fix: spark restores saved holds under the send lock A sync takes back saved holds under the same lock a send leaves flight with, so it never restores a hold a refused send just cleared. Verified: just format, just compile, just test, just lint --- app/src/main/java/to/bitkit/repositories/SparkRepo.kt | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index e53cd0632f..78f1208c6e 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -27,6 +27,7 @@ import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow @@ -194,6 +195,9 @@ class SparkRepo @Inject constructor( /** Serialises the imports of staged exit data, so a restore and Spark's start never import it at once. */ private val exitImportMutex = Mutex() + /** Held while saved holds are taken back and while a send leaves flight, so neither reads the other halfway. */ + private val holdRestoreMutex = Mutex() + @Volatile private var hasSyncedActivities = false @@ -621,7 +625,9 @@ class SparkRepo @Inject constructor( Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) paymentHash } finally { - sendsInFlight.remove(paymentHash.lowercase()) + withContext(NonCancellable) { + holdRestoreMutex.withLock { sendsInFlight.remove(paymentHash.lowercase()) } + } } }.onFailure { if (it is PaymentAbortedBeforeSend) { @@ -707,7 +713,7 @@ class SparkRepo @Inject constructor( private data class UncertainSend(val startedAt: ULong, val failedAt: ULong, val expiresAt: ULong) /** Takes back the sends whose outcome Spark didn't report before a restart, so a sync can still settle them. */ - private suspend fun restoreUncertainSends() { + private suspend fun restoreUncertainSends() = holdRestoreMutex.withLock { val cache = cacheStore.data.first() cache.sparkUncertainSends.forEach { (hash, failedAt) -> // A send still in Spark's send call is settled by its result. From 1ea4fdd183f0ba8daa8c8e3073c1abe3c148bcf4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 02:31:27 +0100 Subject: [PATCH 85/96] fix: spark settles a hold under the restore lock Settling a send takes its hold and clears the saved copy under the lock a sync restores holds with, so its failure is reported once. Verified: just format, just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 14 ++++-- .../to/bitkit/repositories/SparkRepoTest.kt | 47 +++++++++++++++++++ 2 files changed, 57 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 78f1208c6e..2c14977c52 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -685,8 +685,12 @@ class SparkRepo @Inject constructor( SparkLightningSend.Unavailable -> false } // Only the caller that takes the hash off settles it, so its outcome is reported once. - if (!isSettled || !uncertainSends.remove(key, uncertain)) return isSettled - cacheStore.removeSparkUncertainSend(paymentHash) + if (!isSettled) return false + // Both copies go under the restore lock, so a sync never takes back a hold settled here. + val isTaken = holdRestoreMutex.withLock { + uncertainSends.remove(key, uncertain).also { if (it) cacheStore.removeSparkUncertainSend(paymentHash) } + } + if (!isTaken) return true when (send) { SparkLightningSend.NotFound -> { cacheStore.removeSparkSendHash(paymentHash) @@ -1963,8 +1967,10 @@ class SparkRepo @Inject constructor( recordActivity(payment, settlesJournal = false) // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. payment.sendHash()?.let { - uncertainSends.remove(it.lowercase()) - cacheStore.removeSparkUncertainSend(it) + holdRestoreMutex.withLock { + uncertainSends.remove(it.lowercase()) + cacheStore.removeSparkUncertainSend(it) + } } payment.sendHash(PaymentStatus.FAILED)?.let { hash -> val latest = listedLightningSend(hash) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 36753ac22e..0504cfc920 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -38,6 +38,7 @@ import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first @@ -3944,6 +3945,52 @@ class SparkRepoTest : BaseUnitTest() { assertNull(sut.earlierLightningSend("lnbc1", "hash")) } + @Test + fun `a sync while the poll settles a spark send in doubt reports its failure once`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } + val own = sentPayment(fees = 0).copy( + id = "own", + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong(), + ) + whenever(sparkService.listPayments()).thenReturn(listOf(own)) + val backing = InMemoryDataStore(AppCacheData()) + var isArmed = false + // Spark syncs while the poll clears the saved hold. + val store = CacheStore( + object : DataStore { + override val data = backing.data + + override suspend fun updateData(transform: suspend (t: AppCacheData) -> AppCacheData): AppCacheData { + val isClearing = "hash" in backing.data.first().sparkUncertainSends && + "hash" !in transform(backing.data.first()).sparkUncertainSends + if (isArmed && isClearing) { + isArmed = false + sparkEvents.emit(SdkEvent.Synced) + delay(1.seconds) + } + return backing.updateData(transform) + } + }, + clock, + ) + val sut = createSut(store) + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + isArmed = true + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + + assertEquals(1, events.count { it is Event.PaymentFailed }, "the failure was reported twice") + } + @Test fun `a spark send in doubt ends at once on its own failure`() = test { whenever(sparkService.isSupported).thenReturn(true) From 2c948200831dec78f107d5c1218a2a76eda824d6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 03:04:21 +0100 Subject: [PATCH 86/96] fix: spark reports a send outcome once per payment The poll and Spark payment event claim the payment id before reporting, so a failure the poll settled first is not reported again. Verified: just format, just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 14 +++++++--- .../to/bitkit/repositories/SparkRepoTest.kt | 28 +++++++++++++++++++ 2 files changed, 38 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 2c14977c52..04a578b9b2 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -185,6 +185,9 @@ class SparkRepo @Inject constructor( /** The invoice of each send still inside Spark's send call, by lowercase payment hash. */ private val sendsInFlight = ConcurrentHashMap() + /** Spark payment ids of the sends whose outcome was reported, so the poll and Spark's event report it once. */ + private val reportedSendIds = ConcurrentHashMap.newKeySet() + /** Counts sends recorded, so a listing drops a failed hash only when it was recorded before the listing. */ private val sendRecords = AtomicLong() private val sendRecordedAt = ConcurrentHashMap() @@ -699,14 +702,15 @@ class SparkRepo @Inject constructor( // Spark still runs a pending send past its invoice's expiry, so its own payment event reports it. is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> Unit is SparkLightningSend.Found -> { + val listed = runSuspendCatching { sparkService.listPayments() }.getOrNull()?.latestSend(paymentHash) if (send.status == PaymentStatus.FAILED) { cacheStore.removeSparkSendHash(paymentHash) // Its row stayed pending while held, so it takes the failure now. - runSuspendCatching { sparkService.listPayments() }.getOrNull() - ?.latestSend(paymentHash) - ?.let { recordActivity(it) } + listed?.let { recordActivity(it) } + } + if (listed?.let { reportedSendIds.add(it.id) } != false) { + settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } } - settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } } SparkLightningSend.Unavailable -> Unit } @@ -1978,6 +1982,8 @@ class SparkRepo @Inject constructor( (latest as? SparkLightningSend.Found)?.status == PaymentStatus.FAILED if (isReleased) cacheStore.removeSparkSendHash(hash) } + // The poll may have reported this payment's outcome already. + if (payment.sendHash() != null && !reportedSendIds.add(payment.id)) return payment.toNodeEvent()?.let { _nodeEvents.emit(it) } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 0504cfc920..782fd0cb8d 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3991,6 +3991,34 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(1, events.count { it is Event.PaymentFailed }, "the failure was reported twice") } + @Test + fun `a spark send's own failure the poll settled first is reported once`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } + val own = sentPayment(fees = 0).copy( + id = "own", + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong(), + ) + whenever(sparkService.listPayments()).thenReturn(listOf(own)) + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + + // Spark's callback for the same payment arrives after the poll settled it. + sparkEvents.emit(SdkEvent.PaymentFailed(own)) + advanceUntilIdle() + + assertEquals(1, events.count { it is Event.PaymentFailed }, "the failure was reported twice") + } + @Test fun `a spark send in doubt ends at once on its own failure`() = test { whenever(sparkService.isSupported).thenReturn(true) From a5094aa547ba4bad09f656dde246a896f2c6609e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 03:55:02 +0100 Subject: [PATCH 87/96] fix: spark reports a settled send from the payment it read The poll builds the event from the payment it read and claims its id only for the send own final outcome, so a retry read as pending keeps its success and an expiry past an earlier failure is still reported. Verified: just format, just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 12 +++- .../to/bitkit/repositories/SparkRepoTest.kt | 63 +++++++++++++++++++ 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 04a578b9b2..ad28d5a8d5 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -708,8 +708,16 @@ class SparkRepo @Inject constructor( // Its row stayed pending while held, so it takes the failure now. listed?.let { recordActivity(it) } } - if (listed?.let { reportedSendIds.add(it.id) } != false) { - settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } + val isOwn = listed != null && + listed.timestamp.safe() + OWN_FAILURE_CLOCK_MARGIN_SECS.safe() >= uncertain.startedAt + when { + listed == null -> settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } + // A retry started after the hold was taken reads as pending, and its own event reports it. + listed.status == PaymentStatus.PENDING -> Unit + // The send's own outcome is claimed, so Spark's event for the same payment reports nothing more. + isOwn -> if (reportedSendIds.add(listed.id)) listed.toNodeEvent()?.let { _nodeEvents.emit(it) } + // An earlier attempt's failure ends the send at its expiry, so it claims no payment. + else -> listed.toNodeEvent()?.let { _nodeEvents.emit(it) } } } SparkLightningSend.Unavailable -> Unit diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 782fd0cb8d..b70c944bb7 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4019,6 +4019,69 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(1, events.count { it is Event.PaymentFailed }, "the failure was reported twice") } + @Test + fun `a spark retry spark never lists reports its failure at expiry past a reported earlier failure`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } + val earlier = sentPayment(fees = 0).copy(id = "earlier", status = PaymentStatus.FAILED, timestamp = 1uL) + whenever(sparkService.listPayments()).thenReturn(listOf(earlier)) + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + sparkEvents.emit(SdkEvent.PaymentFailed(earlier)) + advanceUntilIdle() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + + now += 2.hours + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals(2, events.count { it is Event.PaymentFailed }, "the retry's failure was never reported") + } + + @Test + fun `a retry read as pending while the poll settles a send keeps its own success event`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + val own = sentPayment(fees = 0).copy( + id = "own", + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong(), + ) + val retry = sentPayment(fees = 0).copy( + id = "retry", + status = PaymentStatus.PENDING, + timestamp = now.epochSeconds.toULong() + 1uL, + ) + // The poll reads the send's own failure, then a retry started meanwhile. + val reads = ArrayDeque(listOf(listOf(own), listOf(own))) + whenever(sparkService.listPayments()).thenAnswer { reads.removeFirstOrNull() ?: listOf(own, retry) } + advanceUntilIdle() + + val paid = retry.copy(status = PaymentStatus.COMPLETED) + whenever(sparkService.listPayments()).thenReturn(listOf(own, paid)) + sparkEvents.emit(SdkEvent.PaymentSucceeded(paid)) + advanceUntilIdle() + + assertTrue(events.any { it is Event.PaymentSuccessful }, "the retry's success was never reported") + } + @Test fun `a spark send in doubt ends at once on its own failure`() = test { whenever(sparkService.isSupported).thenReturn(true) From 53066372f154524b7d14afcc39faf8ccef7365f9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 04:46:32 +0100 Subject: [PATCH 88/96] fix: spark keeps a settled failure off a retry in flight Verified: just format, just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 9 +++- .../to/bitkit/repositories/SparkRepoTest.kt | 42 +++++++++++++++++++ 2 files changed, 50 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 ad28d5a8d5..ce8278a315 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -697,7 +697,12 @@ class SparkRepo @Inject constructor( when (send) { SparkLightningSend.NotFound -> { cacheStore.removeSparkSendHash(paymentHash) - _nodeEvents.emit(Event.PaymentFailed(paymentHash, paymentHash, PaymentFailureReason.UNEXPECTED_ERROR)) + // A retry that entered Spark's send call since the hold was taken reports its own outcome. + if (!sendsInFlight.containsKey(key)) { + _nodeEvents.emit( + Event.PaymentFailed(paymentHash, paymentHash, PaymentFailureReason.UNEXPECTED_ERROR) + ) + } } // Spark still runs a pending send past its invoice's expiry, so its own payment event reports it. is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> Unit @@ -714,6 +719,8 @@ class SparkRepo @Inject constructor( listed == null -> settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } // A retry started after the hold was taken reads as pending, and its own event reports it. listed.status == PaymentStatus.PENDING -> Unit + // A retry that entered Spark's send call since the hold was taken reports its own outcome. + listed.status == PaymentStatus.FAILED && isHeldFrom(listed) -> Unit // The send's own outcome is claimed, so Spark's event for the same payment reports nothing more. isOwn -> if (reportedSendIds.add(listed.id)) listed.toNodeEvent()?.let { _nodeEvents.emit(it) } // An earlier attempt's failure ends the send at its expiry, so it claims no payment. diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index b70c944bb7..ead51396f9 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -51,6 +51,7 @@ import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.withTimeoutOrNull +import kotlinx.coroutines.yield import org.junit.Before import org.junit.Rule import org.junit.Test @@ -4082,6 +4083,47 @@ class SparkRepoTest : BaseUnitTest() { assertTrue(events.any { it is Event.PaymentSuccessful }, "the retry's success was never reported") } + @Test + fun `a retry that enters spark's send call as the poll settles a send keeps its screen off the failure`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val retrySending = CompletableDeferred() + var sends = 0 + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { + if (++sends == 1) throw SdkException.Generic("timeout") + retrySending.await() + } + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + var isArmed = false + // The retry enters Spark's send call right after the poll takes the hold. + whenever { cacheStore.removeSparkUncertainSend(any()) }.doSuspendableAnswer { + if (isArmed) { + isArmed = false + backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } + while (!sut.isSendInFlight("hash")) yield() + } + } + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + val own = sentPayment(fees = 0).copy( + id = "own", + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong(), + ) + // Spark lists only the earlier send's failure while the retry runs. + whenever(sparkService.listPayments()).thenReturn(listOf(own)) + isArmed = true + advanceUntilIdle() + + assertTrue(sut.isSendInFlight("hash"), "the retry never entered Spark's send call") + assertTrue(events.none { it is Event.PaymentFailed }, "the earlier send's failure reached the retry's screen") + } + @Test fun `a spark send in doubt ends at once on its own failure`() = test { whenever(sparkService.isSupported).thenReturn(true) From 5f79ba25c1c9d2effcb0645e8453764d06b2a6df Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 05:57:01 +0100 Subject: [PATCH 89/96] fix: spark keeps a retry's saved send through the poll Verified: just format, just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 32 +++++++++---- .../to/bitkit/repositories/SparkRepoTest.kt | 46 +++++++++++++++---- 2 files changed, 60 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index ce8278a315..c21fd78aae 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -576,9 +576,10 @@ class SparkRepo @Inject constructor( } // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. if (!onBeforeSend()) throw PaymentAbortedBeforeSend() - if (sendsInFlight.putIfAbsent(paymentHash.lowercase(), bolt11) != null) { - throw PaymentPendingException(paymentHash) + val isEntered = holdRestoreMutex.withLock { + sendsInFlight.putIfAbsent(paymentHash.lowercase(), bolt11) == null } + if (!isEntered) throw PaymentPendingException(paymentHash) // Kept in flight until its result is handled, so a sync meanwhile never takes back its saved hold. try { val sent = run { @@ -689,14 +690,9 @@ class SparkRepo @Inject constructor( } // Only the caller that takes the hash off settles it, so its outcome is reported once. if (!isSettled) return false - // Both copies go under the restore lock, so a sync never takes back a hold settled here. - val isTaken = holdRestoreMutex.withLock { - uncertainSends.remove(key, uncertain).also { if (it) cacheStore.removeSparkUncertainSend(paymentHash) } - } - if (!isTaken) return true + if (!takeUncertainSend(paymentHash, uncertain, send)) return true when (send) { SparkLightningSend.NotFound -> { - cacheStore.removeSparkSendHash(paymentHash) // A retry that entered Spark's send call since the hold was taken reports its own outcome. if (!sendsInFlight.containsKey(key)) { _nodeEvents.emit( @@ -709,7 +705,6 @@ class SparkRepo @Inject constructor( is SparkLightningSend.Found -> { val listed = runSuspendCatching { sparkService.listPayments() }.getOrNull()?.latestSend(paymentHash) if (send.status == PaymentStatus.FAILED) { - cacheStore.removeSparkSendHash(paymentHash) // Its row stayed pending while held, so it takes the failure now. listed?.let { recordActivity(it) } } @@ -732,6 +727,25 @@ class SparkRepo @Inject constructor( return true } + private suspend fun takeUncertainSend( + paymentHash: String, + uncertain: UncertainSend, + send: SparkLightningSend, + ): Boolean { + val key = paymentHash.lowercase() + val isFailed = send == SparkLightningSend.NotFound || + send is SparkLightningSend.Found && send.status == PaymentStatus.FAILED + // Both copies go under the restore lock, so a sync never takes back a hold settled here. A send enters Spark's + // send call under the same lock, so a retry's saved send is never dropped here. + return holdRestoreMutex.withLock { + uncertainSends.remove(key, uncertain).also { + if (!it) return@also + cacheStore.removeSparkUncertainSend(paymentHash) + if (isFailed && !sendsInFlight.containsKey(key)) cacheStore.removeSparkSendHash(paymentHash) + } + } + } + /** A send whose outcome Spark didn't report: when it failed, and when its invoice expires, in epoch seconds. */ private data class UncertainSend(val startedAt: ULong, val failedAt: ULong, val expiresAt: ULong) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index ead51396f9..b3d39fbecb 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -113,6 +113,9 @@ import com.synonym.bitkitcore.PaymentType as ActivityPaymentType class SparkRepoTest : BaseUnitTest() { private companion object { const val ADDRESS = "bcrt1qsavings" + + /** How many turns a Spark list read yields to a retry starting its send. */ + const val RETRY_TURNS = 100 } private val sparkService = mock() @@ -4085,6 +4088,22 @@ class SparkRepoTest : BaseUnitTest() { @Test fun `a retry that enters spark's send call as the poll settles a send keeps its screen off the failure`() = test { + val events = settleWithRetryEntering(mutableListOf()) + + assertTrue(events.none { it is Event.PaymentFailed }, "the earlier send's failure reached the retry's screen") + } + + @Test + fun `a retry that enters spark's send call as the poll settles a send keeps its saved expiry`() = test { + val records = mutableListOf() + + settleWithRetryEntering(records) + + assertEquals("add", records.last(), "the poll dropped the retry's saved send: $records") + } + + /** Settles a send in doubt on its own failure while a retry starts right after the poll takes the hold. */ + private suspend fun TestScope.settleWithRetryEntering(records: MutableList): List { whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) @@ -4096,18 +4115,19 @@ class SparkRepoTest : BaseUnitTest() { if (++sends == 1) throw SdkException.Generic("timeout") retrySending.await() } + whenever { cacheStore.addSparkSendHash(any(), anyOrNull()) }.doSuspendableAnswer { records += "add" } + whenever { cacheStore.removeSparkSendHash(any()) }.doSuspendableAnswer { records += "remove" } val sut = createSut() sut.start(0).getOrThrow() val events = mutableListOf() backgroundScope.launch { sut.nodeEvents.collect { events += it } } var isArmed = false - // The retry enters Spark's send call right after the poll takes the hold. + var isRetrying = false whenever { cacheStore.removeSparkUncertainSend(any()) }.doSuspendableAnswer { - if (isArmed) { - isArmed = false - backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } - while (!sut.isSendInFlight("hash")) yield() - } + if (!isArmed) return@doSuspendableAnswer + isArmed = false + isRetrying = true + backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } } assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) val own = sentPayment(fees = 0).copy( @@ -4115,13 +4135,21 @@ class SparkRepoTest : BaseUnitTest() { status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong(), ) - // Spark lists only the earlier send's failure while the retry runs. - whenever(sparkService.listPayments()).thenReturn(listOf(own)) + // Spark lists only the earlier send's failure while the retry runs, and the poll's read after the take gives + // the retry the first chance to enter Spark's send call. + whenever { sparkService.listPayments() }.doSuspendableAnswer { + if (isRetrying) { + isRetrying = false + var turns = 0 + while (!sut.isSendInFlight("hash") && turns++ < RETRY_TURNS) yield() + } + listOf(own) + } isArmed = true advanceUntilIdle() assertTrue(sut.isSendInFlight("hash"), "the retry never entered Spark's send call") - assertTrue(events.none { it is Event.PaymentFailed }, "the earlier send's failure reached the retry's screen") + return events } @Test From cc0cc6cacbdae6077674b6b5c47310d83b9b4dcc Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 06:16:04 +0100 Subject: [PATCH 90/96] fix: spark failure event keeps a retry's hold Verified: just format, just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 22 +++++---- .../to/bitkit/repositories/SparkRepoTest.kt | 48 +++++++++++++++++++ 2 files changed, 60 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index c21fd78aae..5df3ffbfb0 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1998,19 +1998,21 @@ class SparkRepo @Inject constructor( if (deciding != null && deciding.id != payment.id) return } recordActivity(payment, settlesJournal = false) - // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. - payment.sendHash()?.let { + payment.sendHash()?.let { hash -> + val isFailed = payment.status == PaymentStatus.FAILED + val isReleased = isFailed && listedLightningSend(hash).let { + it == SparkLightningSend.NotFound || (it as? SparkLightningSend.Found)?.status == PaymentStatus.FAILED + } + // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. A send + // enters Spark's send call under the same lock, so a retry started since the checks above keeps its hold + // and saved send. holdRestoreMutex.withLock { - uncertainSends.remove(it.lowercase()) - cacheStore.removeSparkUncertainSend(it) + if (isFailed && isHeldFrom(payment)) return@withLock + uncertainSends.remove(hash.lowercase()) + cacheStore.removeSparkUncertainSend(hash) + if (isReleased) cacheStore.removeSparkSendHash(hash) } } - payment.sendHash(PaymentStatus.FAILED)?.let { hash -> - val latest = listedLightningSend(hash) - val isReleased = latest == SparkLightningSend.NotFound || - (latest as? SparkLightningSend.Found)?.status == PaymentStatus.FAILED - if (isReleased) cacheStore.removeSparkSendHash(hash) - } // The poll may have reported this payment's outcome already. if (payment.sendHash() != null && !reportedSendIds.add(payment.id)) return payment.toNodeEvent()?.let { _nodeEvents.emit(it) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index b3d39fbecb..496c1eb284 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4102,6 +4102,54 @@ class SparkRepoTest : BaseUnitTest() { assertEquals("add", records.last(), "the poll dropped the retry's saved send: $records") } + @Test + fun `a retry that enters spark's send call while a failure event is handled keeps its hold and saved send`() = + test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val failed = sentPayment(fees = 0).copy( + id = "failed", + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong(), + ) + val retrySending = CompletableDeferred() + var sends = 0 + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { + if (++sends == 1) failed else retrySending.await() + } + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) + val records = mutableListOf() + whenever { cacheStore.addSparkSendHash(any(), anyOrNull()) }.doSuspendableAnswer { records += "add" } + whenever { cacheStore.removeSparkSendHash(any()) }.doSuspendableAnswer { records += "remove" } + whenever { cacheStore.addSparkUncertainSend(any(), any()) }.doSuspendableAnswer { records += "hold" } + whenever { cacheStore.removeSparkUncertainSend(any()) }.doSuspendableAnswer { records += "unhold" } + val sut = createSut() + sut.start(0).getOrThrow() + sut.payInvoice("lnbc1", 100uL) + advanceUntilIdle() + var isArmed = true + // The retry enters Spark's send call while the failure event writes its row. + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + if (isArmed) { + isArmed = false + backgroundScope.launch { sut.payInvoice("lnbc1", 100uL) } + var turns = 0 + while (!sut.isSendInFlight("hash") && turns++ < RETRY_TURNS) yield() + } + Result.success(Unit) + } + records.clear() + + sparkEvents.emit(SdkEvent.PaymentFailed(failed)) + advanceUntilIdle() + + assertTrue(sut.isSendInFlight("hash"), "the retry never entered Spark's send call") + assertEquals(listOf("add", "hold"), records, "the failure event dropped the retry's hold or saved send") + } + /** Settles a send in doubt on its own failure while a retry starts right after the poll takes the hold. */ private suspend fun TestScope.settleWithRetryEntering(records: MutableList): List { whenever(sparkService.isSupported).thenReturn(true) From d20d1c727d7fa694bbc093d5eec8e6d624e1ee65 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 06:43:46 +0100 Subject: [PATCH 91/96] fix: spark failure event leaves a retry's screen alone Verified: just format, just compile, just test, just lint --- app/src/main/java/to/bitkit/repositories/SparkRepo.kt | 10 ++++++---- .../test/java/to/bitkit/repositories/SparkRepoTest.kt | 5 ++++- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 5df3ffbfb0..450c8bc9a1 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1998,21 +1998,23 @@ class SparkRepo @Inject constructor( if (deciding != null && deciding.id != payment.id) return } recordActivity(payment, settlesJournal = false) - payment.sendHash()?.let { hash -> + val isRetried = payment.sendHash()?.let { hash -> val isFailed = payment.status == PaymentStatus.FAILED val isReleased = isFailed && listedLightningSend(hash).let { it == SparkLightningSend.NotFound || (it as? SparkLightningSend.Found)?.status == PaymentStatus.FAILED } // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. A send // enters Spark's send call under the same lock, so a retry started since the checks above keeps its hold - // and saved send. + // and saved send, and reports its own outcome. holdRestoreMutex.withLock { - if (isFailed && isHeldFrom(payment)) return@withLock + if (isFailed && isHeldFrom(payment)) return@withLock true uncertainSends.remove(hash.lowercase()) cacheStore.removeSparkUncertainSend(hash) if (isReleased) cacheStore.removeSparkSendHash(hash) + false } - } + } ?: false + if (isRetried) return // The poll may have reported this payment's outcome already. if (payment.sendHash() != null && !reportedSendIds.add(payment.id)) return payment.toNodeEvent()?.let { _nodeEvents.emit(it) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 496c1eb284..b1d368d5c8 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4103,7 +4103,7 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `a retry that enters spark's send call while a failure event is handled keeps its hold and saved send`() = + fun `a retry entering spark's send call during a failure event keeps its hold and its screen`() = test { whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) @@ -4142,12 +4142,15 @@ class SparkRepoTest : BaseUnitTest() { Result.success(Unit) } records.clear() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } sparkEvents.emit(SdkEvent.PaymentFailed(failed)) advanceUntilIdle() assertTrue(sut.isSendInFlight("hash"), "the retry never entered Spark's send call") assertEquals(listOf("add", "hold"), records, "the failure event dropped the retry's hold or saved send") + assertTrue(events.none { it is Event.PaymentFailed }, "the earlier failure reached the retry's screen") } /** Settles a send in doubt on its own failure while a retry starts right after the poll takes the hold. */ From 237275212530182b3c1b27d5f3761532b47bfb16 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 12:14:32 +0100 Subject: [PATCH 92/96] fix: spark launch sync settles a held send it lists The sync that records Spark's list now settles each held send from that same list, so a send whose own failure Spark lists frees its invoice at launch even when the next read of Spark's list fails. Verified: just format, just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 31 ++++++++++----- .../to/bitkit/repositories/SparkRepoTest.kt | 38 +++++++++++++++++++ 2 files changed, 60 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 450c8bc9a1..02f9db38f6 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -666,9 +666,14 @@ class SparkRepo @Inject constructor( /** * Settles an uncertain send once Spark shows its outcome; true once it is settled, also by another caller. A - * failure event for it [isFailureEvent] shows Spark reached the send, as a sync since would. + * failure event for it [isFailureEvent] shows Spark reached the send, as a sync since would. A [listing] just + * read from Spark is used instead of reading it again. */ - private suspend fun trySettleUncertainSend(paymentHash: String, isFailureEvent: Boolean = false): Boolean { + private suspend fun trySettleUncertainSend( + paymentHash: String, + isFailureEvent: Boolean = false, + listing: List? = null, + ): Boolean { val key = paymentHash.lowercase() val uncertain = uncertainSends[key] ?: return true // Spark finishes an interrupted send only on a later sync, and a sync that never reached it still returns. @@ -677,7 +682,7 @@ class SparkRepo @Inject constructor( // Spark keeps a send it committed but didn't finish in a cache no call exposes, and a sync that reached Spark // can still fail to resume it, so only an expired invoice shows a missing send will never go out. val isFinal = (isSynced || isFailureEvent) && clock.now().epochSeconds.toULong() >= uncertain.expiresAt - val send = listedLightningSend(paymentHash) + val send = listedLightningSend(paymentHash, listing) val isSettled = when (send) { SparkLightningSend.NotFound -> isFinal // A failure dated before the send started is an earlier attempt's, so it is final only when a missing @@ -685,7 +690,7 @@ class SparkRepo @Inject constructor( is SparkLightningSend.Found if send.status == PaymentStatus.COMPLETED -> true // A pending send ends with its own payment event, or at its invoice's expiry. is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> isFinal - is SparkLightningSend.Found -> isFinal || hasOwnFailure(paymentHash) + is SparkLightningSend.Found -> isFinal || hasOwnFailure(paymentHash, listing) SparkLightningSend.Unavailable -> false } // Only the caller that takes the hash off settles it, so its outcome is reported once. @@ -703,7 +708,8 @@ class SparkRepo @Inject constructor( // Spark still runs a pending send past its invoice's expiry, so its own payment event reports it. is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> Unit is SparkLightningSend.Found -> { - val listed = runSuspendCatching { sparkService.listPayments() }.getOrNull()?.latestSend(paymentHash) + val listed = (listing ?: runSuspendCatching { sparkService.listPayments() }.getOrNull()) + ?.latestSend(paymentHash) if (send.status == PaymentStatus.FAILED) { // Its row stayed pending while held, so it takes the failure now. listed?.let { recordActivity(it) } @@ -1541,8 +1547,9 @@ class SparkRepo @Inject constructor( return failure.timestamp.safe() + OWN_FAILURE_CLOCK_MARGIN_SECS.safe() < startedAt } - private suspend fun hasOwnFailure(paymentHash: String): Boolean { - val failure = runSuspendCatching { sparkService.listPayments() }.getOrNull()?.latestSend(paymentHash) + private suspend fun hasOwnFailure(paymentHash: String, listing: List? = null): Boolean { + val failure = (listing ?: runSuspendCatching { sparkService.listPayments() }.getOrNull()) + ?.latestSend(paymentHash) ?.takeIf { it.status == PaymentStatus.FAILED } ?: return false return !isHeldFrom(failure) } @@ -1602,10 +1609,13 @@ class SparkRepo @Inject constructor( } /** Spark's listed record of the Lightning send with [paymentHash], as [lightningSend] reads it before its holds. */ - private suspend fun listedLightningSend(paymentHash: String): SparkLightningSend = withContext(bgDispatcher) { + private suspend fun listedLightningSend( + paymentHash: String, + listing: List? = null, + ): SparkLightningSend = withContext(bgDispatcher) { if (!sparkService.isSupported) return@withContext SparkLightningSend.NotFound if (!canListPayments()) return@withContext SparkLightningSend.Unavailable - val payments = runSuspendCatching { sparkService.listPayments() } + val payments = listing ?: runSuspendCatching { sparkService.listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrElse { return@withContext SparkLightningSend.Unavailable } payments.latestSend(paymentHash) @@ -1856,6 +1866,9 @@ class SparkRepo @Inject constructor( val payments = sparkService.listPayments() if (isSynced) seedSendHashes(payments) val isSaved = payments.decidingRows().map { recordActivity(it) }.all { it } + // A held send that this list shows settled, as by its own failure, ends here, so its hold never waits on + // another read of Spark's list. + if (isSynced) uncertainSends.keys.toList().forEach { trySettleUncertainSend(it, listing = payments) } releaseFailedSends(payments, recordsBefore, inFlightBefore) if (!settleJournal || wasWithdrawing || isWithdrawing || withdrawalSendsEnded.get() != sendsEndedBefore) { return isSaved diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index b1d368d5c8..d9bdf257e9 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4345,6 +4345,44 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(EarlierSend.Pending("hash"), after.earlierLightningSend("lnbc1", "hash")) } + @Test + fun `a held spark send whose own failure a restart's sync lists frees its invoice without another read`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever { sparkService.listPayments() }.thenReturn(emptyList()) + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + ) + val before = createSut(store) + before.start(0).getOrThrow() + assertIs(before.payInvoice("lnbc1", 100uL).exceptionOrNull()) + runCurrent() + assertTrue("hash" in store.data.first().sparkUncertainSends) + + whenever { sparkService.getInfo() }.thenReturn( + info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) + ) + // Spark lists the send's own failure to the restart's sync, and every read after it fails. + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) + var isListed = true + whenever { sparkService.listPayments() }.doSuspendableAnswer { + if (isListed) listOf(failed) else throw SdkException.Generic("offline") + } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + isListed = false + Result.success(Unit) + } + val after = createSut(store) + after.start(0).getOrThrow() + + val cache = store.data.first() + assertFalse("hash" in cache.sparkUncertainSends, "A restart kept the hold of a send Spark listed as failed") + assertFalse("hash" in cache.sparkSendHashes, "A restart kept a failed send's invoice from the node") + } + @Test fun `a spark retry cut off by process death stays held after a restart while spark lists only its older failure`() = test { From 8573bafc718da0db4fe2846af807eab98cf42502 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 12:34:18 +0100 Subject: [PATCH 93/96] fix: spark retry start clears earlier failures A retry's saved start is floored 11 s past every failure Spark dated for its invoice, or past now when Spark's list can't be read, so an earlier attempt's failure inside the clock margin never reads as the retry's own. A failure only fails an existing send row in place, so at expiry the retry's row keeps its own amount and fee. Verified: just format, just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 72 ++++++++++----- .../to/bitkit/repositories/SparkRepoTest.kt | 87 ++++++++++++++++++- 2 files changed, 137 insertions(+), 22 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 02f9db38f6..4b998af094 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -185,6 +185,9 @@ class SparkRepo @Inject constructor( /** The invoice of each send still inside Spark's send call, by lowercase payment hash. */ private val sendsInFlight = ConcurrentHashMap() + /** The latest failure Spark dated for each send seen this process, by payment hash, in epoch seconds. */ + private val sendFailedAt = ConcurrentHashMap() + /** Spark payment ids of the sends whose outcome was reported, so the poll and Spark's event report it once. */ private val reportedSendIds = ConcurrentHashMap.newKeySet() @@ -323,6 +326,7 @@ class SparkRepo @Inject constructor( unsavedPayments.clear() sendsInFlight.clear() uncertainSends.clear() + sendFailedAt.clear() hasSyncedActivities = false hasMergedRemoteExitState = false isLostForExit = false @@ -582,12 +586,13 @@ 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 { + val startedAt = sendStartedAt(paymentHash) val sent = run { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) spending { // Kept until the call returns, so a send cut off by process death or cancellation stays held. - cacheStore.addSparkUncertainSend(paymentHash, clock.now().epochSeconds) + cacheStore.addSparkUncertainSend(paymentHash, startedAt) // The checks above and both writes suspend, so the deadline and an exit that started meanwhile // are checked last, before the send. runCatching { @@ -601,6 +606,7 @@ class SparkRepo @Inject constructor( runSuspendCatching { sparkService.send(prepared) } } } + sent.onSuccess { noteFailure(it) } val payment = sent.getOrElse { // The SDK checks the expiry again before anything goes out, so an expired invoice left nothing. if (it.isInvoiceExpired()) { @@ -708,14 +714,14 @@ class SparkRepo @Inject constructor( // Spark still runs a pending send past its invoice's expiry, so its own payment event reports it. is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> Unit is SparkLightningSend.Found -> { - val listed = (listing ?: runSuspendCatching { sparkService.listPayments() }.getOrNull()) + val listed = (listing ?: runSuspendCatching { listPayments() }.getOrNull()) ?.latestSend(paymentHash) + val isOwn = listed != null && + listed.timestamp.safe() + OWN_FAILURE_CLOCK_MARGIN_SECS.safe() >= uncertain.startedAt if (send.status == PaymentStatus.FAILED) { // Its row stayed pending while held, so it takes the failure now. listed?.let { recordActivity(it) } } - val isOwn = listed != null && - listed.timestamp.safe() + OWN_FAILURE_CLOCK_MARGIN_SECS.safe() >= uncertain.startedAt when { listed == null -> settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } // A retry started after the hold was taken reads as pending, and its own event reports it. @@ -1041,7 +1047,7 @@ class SparkRepo @Inject constructor( * its own withdrawal apart, also while Spark's list lacks one after a restart. */ suspend fun withdrawalTxidsTo(address: String): Set = withContext(bgDispatcher) { - val listed = sparkService.listPayments().mapNotNull { payment -> + val listed = listPayments().mapNotNull { payment -> (payment.details as? PaymentDetails.Withdraw)?.takeIf { it.destinationAddress == address }?.txId } val recorded = cacheStore.data.first().sentSparkWithdrawals.filter { it.address == address }.map { it.txid } @@ -1056,7 +1062,7 @@ class SparkRepo @Inject constructor( if (!isSent) return@withContext false if (cacheStore.data.first().sentSparkWithdrawals.any { it.txid == txid }) return@withContext true if (!_state.value.isReady) return@withContext false - runSuspendCatching { sparkService.listPayments() } + runSuspendCatching { listPayments() } .onFailure { Logger.warn("Failed to list Spark payments for '$txid'", it, context = TAG) } .getOrDefault(emptyList()) .any { (it.details as? PaymentDetails.Withdraw)?.txId == txid } @@ -1077,7 +1083,7 @@ class SparkRepo @Inject constructor( it.address == address && it.amountSats == amountSats && it.txid !in earlierTxids }?.let { return@withContext SparkWithdrawalOutcome.Sent(it.txid) } if (!_state.value.hasSynced || isWithdrawing) return@withContext SparkWithdrawalOutcome.Unknown - val attempts = sparkService.listPayments().filter { payment -> + val attempts = listPayments().filter { payment -> val withdraw = payment.details as? PaymentDetails.Withdraw ?: return@filter false withdraw.destinationAddress == address && payment.amount.toLong().toULong() == amountSats && withdraw.txId !in earlierTxids @@ -1372,7 +1378,7 @@ class SparkRepo @Inject constructor( val info = sparkService.getInfo() info.lastSyncError?.let { Logger.warn("Failed to sync Spark, balances may be stale: '$it'", context = TAG) } val unclaimed = sparkService.listUnclaimedDeposits() - val payments = sparkService.listPayments() + val payments = listPayments() val claimedPayments = payments .filter { it.method == PaymentMethod.DEPOSIT && it.status == PaymentStatus.COMPLETED } val claimed = claimedPayments @@ -1523,7 +1529,7 @@ class SparkRepo @Inject constructor( */ suspend fun settledSendEvent(paymentHash: String): Event? = withContext(bgDispatcher) { if (!sparkService.isConnected) return@withContext null - runSuspendCatching { sparkService.listPayments() } + runSuspendCatching { listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrNull() ?.latestSend(paymentHash) @@ -1548,7 +1554,7 @@ class SparkRepo @Inject constructor( } private suspend fun hasOwnFailure(paymentHash: String, listing: List? = null): Boolean { - val failure = (listing ?: runSuspendCatching { sparkService.listPayments() }.getOrNull()) + val failure = (listing ?: runSuspendCatching { listPayments() }.getOrNull()) ?.latestSend(paymentHash) ?.takeIf { it.status == PaymentStatus.FAILED } ?: return false return !isHeldFrom(failure) @@ -1570,7 +1576,7 @@ class SparkRepo @Inject constructor( if (!canListPayments()) return@withContext null val unlisted = unexpiredStartedSends() val uncertain = uncertainSendHashes() - val payments = runSuspendCatching { sparkService.listPayments() } + val payments = runSuspendCatching { listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrElse { return@withContext null } val listed = payments @@ -1615,7 +1621,7 @@ class SparkRepo @Inject constructor( ): SparkLightningSend = withContext(bgDispatcher) { if (!sparkService.isSupported) return@withContext SparkLightningSend.NotFound if (!canListPayments()) return@withContext SparkLightningSend.Unavailable - val payments = listing ?: runSuspendCatching { sparkService.listPayments() } + val payments = listing ?: runSuspendCatching { listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrElse { return@withContext SparkLightningSend.Unavailable } payments.latestSend(paymentHash) @@ -1656,7 +1662,7 @@ class SparkRepo @Inject constructor( val unlisted = unexpiredStartedSends() // Before Spark's first sync its local list can be empty although a restored send is live. val payments = if (sparkService.isSupported && canListPayments()) { - runSuspendCatching { sparkService.listPayments() } + runSuspendCatching { listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrNull() } else { @@ -1801,7 +1807,7 @@ class SparkRepo @Inject constructor( private suspend fun lightningPaymentStatuses(filter: (Payment) -> Boolean): Map>? = withContext(bgDispatcher) { if (!sparkService.isConnected) return@withContext null - runSuspendCatching { sparkService.listPayments() } + runSuspendCatching { listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrNull() ?.filter(filter) @@ -1815,7 +1821,7 @@ class SparkRepo @Inject constructor( private suspend fun lightningPaymentHashes(filter: (Payment) -> Boolean): Set? = withContext(bgDispatcher) { if (!sparkService.isConnected) return@withContext null - runSuspendCatching { sparkService.listPayments() } + runSuspendCatching { listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrNull() ?.filter(filter) @@ -1829,7 +1835,7 @@ class SparkRepo @Inject constructor( */ private suspend fun seedRestoredSendHashes() { if (cacheStore.data.first().sparkHistoryUnseededSince == null || !canListPayments()) return - runSuspendCatching { sparkService.listPayments() } + runSuspendCatching { listPayments() } .onSuccess { seedSendHashes(it) } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } } @@ -1863,7 +1869,7 @@ class SparkRepo @Inject constructor( val wasWithdrawing = isWithdrawing // Read before the list, as one read before Spark's first sync can lack its restored sends. val isSynced = canListPayments() - val payments = sparkService.listPayments() + val payments = listPayments() if (isSynced) seedSendHashes(payments) val isSaved = payments.decidingRows().map { recordActivity(it) }.all { it } // A held send that this list shows settled, as by its own failure, ends here, so its hold never waits on @@ -1941,7 +1947,7 @@ class SparkRepo @Inject constructor( // A retry can start while the list is recorded, so the release reads Spark's sends again first. val recordsBeforeCurrent = sendRecords.get() val inFlightBeforeCurrent = sendsInFlight.keys.toSet() - val current = runSuspendCatching { sparkService.listPayments() }.getOrNull() ?: return + val current = runSuspendCatching { listPayments() }.getOrNull() ?: return val liveCurrent = sendsInFlight.keys + inFlightBeforeCurrent + recordedSince(recordsBeforeCurrent) + uncertainSendHashes() failed @@ -1952,6 +1958,28 @@ class SparkRepo @Inject constructor( private fun recordedSince(records: Long): Set = sendRecordedAt.filterValues { it > records }.keys + private suspend fun listPayments(): List = sparkService.listPayments().onEach { noteFailure(it) } + + private fun noteFailure(payment: Payment) { + val hash = payment.sendHash(PaymentStatus.FAILED)?.lowercase() ?: return + sendFailedAt.merge(hash, payment.timestamp) { old, new -> maxOf(old, new) } + } + + /** + * When a send of [paymentHash] starting now counts as started: past every failure Spark dated for it by more than + * [OWN_FAILURE_CLOCK_MARGIN_SECS], so an earlier attempt's failure never reads as this send's own. Past now too + * when Spark's list can't be read, as a failure unknown to this process may be dated up to now. + */ + private suspend fun sendStartedAt(paymentHash: String): Long { + val now = clock.now().epochSeconds.toULong() + val isListed = runSuspendCatching { listPayments() } + .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } + .isSuccess + val known = sendFailedAt[paymentHash.lowercase()] + val failedAt = (if (isListed) known else maxOf(now, known ?: 0uL)) ?: return now.toLong() + return maxOf(now, failedAt.safe() + (OWN_FAILURE_CLOCK_MARGIN_SECS + 1uL).safe()).toLong() + } + /** The payment hash of this send, at [status] when given. */ private fun Payment.sendHash(status: PaymentStatus? = null): String? = (details as? PaymentDetails.Lightning) ?.takeIf { paymentType == SparkPaymentType.SEND && (status == null || this.status == status) } @@ -1995,6 +2023,7 @@ class SparkRepo @Inject constructor( } private suspend fun onPayment(payment: Payment) { + noteFailure(payment) // The event carries its outcome, so a failed balance read never holds back its settlement. runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after payment '${payment.id}'", it, context = TAG) } @@ -2007,7 +2036,7 @@ class SparkRepo @Inject constructor( // A failure of an attempt that Spark's list shows another attempt deciding, as pending, paid or a later // failure, settles nothing. payment.sendHash(PaymentStatus.FAILED)?.let { hash -> - val deciding = runSuspendCatching { sparkService.listPayments() }.getOrNull()?.latestSend(hash) + val deciding = runSuspendCatching { listPayments() }.getOrNull()?.latestSend(hash) if (deciding != null && deciding.id != payment.id) return } recordActivity(payment, settlesJournal = false) @@ -2072,7 +2101,10 @@ class SparkRepo @Inject constructor( } // Another attempt of the same invoice, on either rail, already paid it. if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) return true - val activity = LightningActivity.create( + // A failure, possibly an earlier attempt's, only fails the send's row, which keeps its own details. + val failedRow = existing?.takeIf { payment.status == PaymentStatus.FAILED && it.txType == PaymentType.SENT } + if (failedRow?.status == PaymentState.FAILED) return true + val activity = failedRow?.copy(status = PaymentState.FAILED) ?: LightningActivity.create( id = id, txType = when (payment.paymentType) { SparkPaymentType.SEND -> PaymentType.SENT diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index d9bdf257e9..f75107ed69 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3956,13 +3956,18 @@ 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 SdkException.Generic("timeout") } val own = sentPayment(fees = 0).copy( id = "own", status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong(), ) - whenever(sparkService.listPayments()).thenReturn(listOf(own)) + // Spark lists the send's own failure once the send went out. + var listed = emptyList() + whenever(sparkService.listPayments()).thenAnswer { listed } + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { + listed = listOf(own) + throw SdkException.Generic("timeout") + } val backing = InMemoryDataStore(AppCacheData()) var isArmed = false // Spark syncs while the poll clears the saved hold. @@ -4265,6 +4270,84 @@ class SparkRepoTest : BaseUnitTest() { assertNull(sut.earlierLightningSend("lnbc1", "hash")) } + @Test + fun `a spark retry started within the clock margin of an earlier failure stays held while only that is listed`() = + test { + val (sut, events) = startRetryInMarginOfEarlierFailure() + + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL)) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) + assertTrue(events.none { it is Event.PaymentFailed }, "An earlier attempt's failure ended the retry") + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status != PaymentState.PENDING } + ) + } + + @Test + fun `a spark retry in the clock margin of an earlier failure fails its own row in place at expiry`() = test { + val (_, events, store) = startRetryInMarginOfEarlierFailure() + val retryRow = storedSend(PaymentState.PENDING) + .copy(value = 200uL, fee = 7uL, timestamp = now.epochSeconds.toULong()) + var row = retryRow + whenever { activityRepo.getActivity(eq("hash"), any()) }.doSuspendableAnswer { + Result.success(Activity.Lightning(row)) + } + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + row = (it.getArgument(0) as Activity.Lightning).v1 + Result.success(Unit) + } + + now += 2.hours + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals("hash", assertIs(events.single()).paymentHash) + assertEquals(retryRow.copy(status = PaymentState.FAILED), row) + + // The next start's sync lists only the earlier attempt's failure. + createSut(store).start(0).getOrThrow() + + assertEquals(retryRow.copy(status = PaymentState.FAILED), row, "A sync copied the earlier attempt's details") + } + + /** + * Attempt A fails, as Spark reports at once, and retry B starts 5 s later, within the clock margin of A's failure, + * with an unknown outcome while Spark lists only A's failure. + */ + private suspend fun TestScope.startRetryInMarginOfEarlierFailure(): Triple, CacheStore> { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + val earlier = sentPayment(fees = 0).copy( + id = "earlier", + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong(), + ) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(earlier) + val sut = createSut(store) + sut.start(0).getOrThrow() + sut.payInvoice("lnbc1", 100uL).getOrThrow() + whenever { sparkService.listPayments() }.thenReturn(listOf(earlier)) + advanceUntilIdle() + + now += 5.seconds + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + clearInvocations(activityRepo) + return Triple(sut, events, store) + } + @Test fun `a spark send that failed lets a retry of its invoice send again`() = test { whenever(sparkService.isSupported).thenReturn(true) From 844626fc450f98c63645c18385b64c3b711710ff Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 13:16:18 +0100 Subject: [PATCH 94/96] fix: spark sync settles only holds from before its list The sync settles only the holds taken before it read Spark's list, so a send held while it writes activity is never settled from that older list. A send whose start can't be dated because Spark can't list its payments is refused before anything goes out, instead of saving a start past now that made its own failure read as an earlier attempt's. Verified: just format, just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 36 ++++++++----- .../bitkit/repositories/LightningRepoTest.kt | 1 + .../to/bitkit/repositories/SparkRepoTest.kt | 53 +++++++++++++++++++ 3 files changed, 78 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 4b998af094..d775737f57 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -530,9 +530,10 @@ 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 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 + * payment or list its payments, 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 * dispatched, and its event decides it. An invoice this wallet already sends is not sent again: one in flight or * pending fails with [PaymentPendingException], and one Spark completed returns its hash. After a restore, a * still-valid invoice created before it that the Spark operators can't show unsent fails with @@ -673,15 +674,17 @@ class SparkRepo @Inject constructor( /** * Settles an uncertain send once Spark shows its outcome; true once it is settled, also by another caller. A * failure event for it [isFailureEvent] shows Spark reached the send, as a sync since would. A [listing] just - * read from Spark is used instead of reading it again. + * read from Spark is used instead of reading it again, and then only for the hold [held] taken before it was read. */ private suspend fun trySettleUncertainSend( paymentHash: String, isFailureEvent: Boolean = false, listing: List? = null, + held: UncertainSend? = null, ): Boolean { val key = paymentHash.lowercase() val uncertain = uncertainSends[key] ?: return true + if (held != null && uncertain !== held) return false // Spark finishes an interrupted send only on a later sync, and a sync that never reached it still returns. val isSynced = hasSyncedSince(uncertain.failedAt) if (isSynced) _state.update { it.copy(hasSynced = true) } @@ -1867,6 +1870,8 @@ class SparkRepo @Inject constructor( // A list read while a withdrawal was in flight, or before one ended, may lack it, so it settles no journal. val sendsEndedBefore = withdrawalSendsEnded.get() val wasWithdrawing = isWithdrawing + // A send held after the list was read may be missing from it, so only the holds before it settle from it. + val heldBefore = uncertainSends.toMap() // Read before the list, as one read before Spark's first sync can lack its restored sends. val isSynced = canListPayments() val payments = listPayments() @@ -1874,7 +1879,15 @@ class SparkRepo @Inject constructor( val isSaved = payments.decidingRows().map { recordActivity(it) }.all { it } // A held send that this list shows settled, as by its own failure, ends here, so its hold never waits on // another read of Spark's list. - if (isSynced) uncertainSends.keys.toList().forEach { trySettleUncertainSend(it, listing = payments) } + if (isSynced) { + heldBefore.forEach { (hash, held) -> + trySettleUncertainSend( + hash, + listing = payments, + held = held + ) + } + } releaseFailedSends(payments, recordsBefore, inFlightBefore) if (!settleJournal || wasWithdrawing || isWithdrawing || withdrawalSendsEnded.get() != sendsEndedBefore) { return isSaved @@ -1967,16 +1980,15 @@ class SparkRepo @Inject constructor( /** * When a send of [paymentHash] starting now counts as started: past every failure Spark dated for it by more than - * [OWN_FAILURE_CLOCK_MARGIN_SECS], so an earlier attempt's failure never reads as this send's own. Past now too - * when Spark's list can't be read, as a failure unknown to this process may be dated up to now. + * [OWN_FAILURE_CLOCK_MARGIN_SECS], so an earlier attempt's failure never reads as this send's own. Refused when + * Spark's list can't be read, as it may hold a failure unknown to this process; nothing has gone out yet. */ private suspend fun sendStartedAt(paymentHash: String): Long { + runSuspendCatching { listPayments() }.onFailure { + throw SparkError.SendRefused("Spark could not list its payments to date the send", it) + } val now = clock.now().epochSeconds.toULong() - val isListed = runSuspendCatching { listPayments() } - .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } - .isSuccess - val known = sendFailedAt[paymentHash.lowercase()] - val failedAt = (if (isListed) known else maxOf(now, known ?: 0uL)) ?: return now.toLong() + val failedAt = sendFailedAt[paymentHash.lowercase()] ?: return now.toLong() return maxOf(now, failedAt.safe() + (OWN_FAILURE_CLOCK_MARGIN_SECS + 1uL).safe()).toLong() } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 625724b33f..2e60238226 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1986,6 +1986,7 @@ class LightningRepoTest : BaseUnitTest() { feePolicy = FeePolicy.FEES_EXCLUDED, ) whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.listPayments()).thenReturn(emptyList()) val sending = CompletableDeferred() whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { sending.await() } val spark = SparkRepo( diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index f75107ed69..02ea839a05 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4348,6 +4348,59 @@ class SparkRepoTest : BaseUnitTest() { return Triple(sut, events, store) } + @Test + fun `a spark send is refused before it goes out while spark can't list its payments`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val sut = createSut(store) + sut.start(0).getOrThrow() + whenever(sparkService.listPayments()).thenAnswer { throw SdkException.Generic("storage") } + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + verify(sparkService, never()).send(any(), anyOrNull()) + assertFalse("hash" in store.data.first().sparkUncertainSends) + assertFalse("hash" in store.data.first().sparkSendHashes) + } + + @Test + fun `a spark send held while a sync writes its list is not settled from that list`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenAnswer { info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) } + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + // The sync's list has no send of the invoice; Spark lists the send as pending once it went out. + var listed = listOf(receivedPayment()) + whenever(sparkService.listPayments()).thenAnswer { listed } + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { + listed = listed + sentPayment(fees = 0).copy(status = PaymentStatus.PENDING) + throw SdkException.Generic("timeout") + } + val sut = createSut(store) + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + var isArmed = true + // The send starts while the sync writes its list, and its invoice expires before the sync settles holds. + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + if (isArmed) { + isArmed = false + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + now += 2.hours + } + Result.success(Unit) + } + + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertFalse(isArmed) + assertTrue(events.none { it is Event.PaymentFailed }, "A sync's older list failed a send Spark is paying") + } + @Test fun `a spark send that failed lets a retry of its invoice send again`() = test { whenever(sparkService.isSupported).thenReturn(true) From ff2687ee9151ba9b2ffe32a922d0ac157cf69196 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 13:33:26 +0100 Subject: [PATCH 95/96] fix: unsynced spark refuses an operator-failed send After a restore, before Spark syncs, its list can't date an earlier attempt the operators show failed, and a send must start past that failure, so a Spark send of such an invoice is refused until Spark syncs. An invoice the operators show no send of still sends. Verified: just format, just compile, just test, just lint --- .../java/to/bitkit/repositories/SparkRepo.kt | 14 +++++--- .../to/bitkit/repositories/SparkRepoTest.kt | 33 +++++++++++++++++++ 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index d775737f57..1199588238 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -572,11 +572,13 @@ class SparkRepo @Inject constructor( is SparkLightningSend.Found if earlier.status == PaymentStatus.PENDING -> 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. + // path, so the operators decide. Before Spark syncs, its list can't date an earlier attempt they show + // failed, which a send must start past, so that one is refused too. else -> refuseUnverifiedRestoredInvoice( bolt11, invoice.timestamp.toEpochSeconds(), expiresAt.toEpochSeconds(), + isFailedUnsent = canListPayments(), ) } // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. @@ -1714,12 +1716,13 @@ class SparkRepo @Inject constructor( bolt11: String, invoiceCreatedAt: Long?, invoiceExpiresAt: Long?, + isFailedUnsent: Boolean = true, ) { val restoredAt = cacheStore.data.first().sparkRestoredAt ?: return val isHeld = sparkService.isSupported && (invoiceCreatedAt ?: 0L) < restoredAt && (invoiceExpiresAt == null || clock.now().epochSeconds < invoiceExpiresAt) - if (!isHeld || isUnsentPerOperators(bolt11)) return + if (!isHeld || isUnsentPerOperators(bolt11, isFailedUnsent)) return Logger.warn("Refused a send of a pre-restore invoice the Spark operators can't show unsent", context = TAG) throw SparkError.RestoredInvoiceUnverified() } @@ -1727,14 +1730,15 @@ class SparkRepo @Inject constructor( /** * Whether the Spark operators confirm this wallet never sent [bolt11] over Lightning, and it can't have been paid * by a direct Spark transfer, which they don't see: false when they show a send completed or pending, or can't be - * asked. A failed one counts as unsent, as they show it failed only once every attempt at the hash was returned. + * asked. A failed one counts as unsent when [isFailedUnsent], as they show it failed only once every attempt at the + * hash was returned. */ - private suspend fun isUnsentPerOperators(bolt11: String): Boolean { + private suspend fun isUnsentPerOperators(bolt11: String, isFailedUnsent: Boolean = true): Boolean { if (!sparkService.isConnected) return false val status = runSuspendCatching { sparkService.lightningSendStatus(bolt11) } .onFailure { Logger.warn("Failed to fetch Spark's send status", it, context = TAG) } .getOrElse { return false } - if (status != null && status != PaymentStatus.FAILED) { + if (status != null && (status != PaymentStatus.FAILED || !isFailedUnsent)) { Logger.info("Found a '$status' Spark operator send of the pre-restore invoice", context = TAG) return false } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 02ea839a05..8810dedc0c 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -433,6 +433,39 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any(), anyOrNull()) } + @Test + fun `an unsynced spark refuses a pre-restore invoice the operators show failed`() = test { + assertUnsyncedRestoredSend(operatorStatus = PaymentStatus.FAILED, isSent = false) + } + + @Test + fun `an unsynced spark sends a pre-restore invoice the operators show no send of`() = test { + assertUnsyncedRestoredSend(operatorStatus = null, isSent = true) + } + + private suspend fun TestScope.assertUnsyncedRestoredSend(operatorStatus: PaymentStatus?, isSent: Boolean) { + val restored = AppCacheData(sparkHistoryUnseededSince = now.epochSeconds, sparkRestoredAt = now.epochSeconds) + val store = CacheStore(InMemoryDataStore(restored), clock) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL).copy(lastSyncedAt = null)) + val prepared = prepared(feeSats = 0uL, createdAt = (now.epochSeconds - 600).toULong(), expirySecs = 3_600uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) + sendStatus = { operatorStatus } + val sut = createSut(store) + sut.start(0).getOrThrow() + + val result = sut.payInvoice("lnbc1280n1send", 128uL) + + if (isSent) { + assertTrue(result.isSuccess) + verify(sparkService).send(any(), anyOrNull()) + } else { + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any(), anyOrNull()) + } + } + @Test fun `a synced spark refuses a pre-restore invoice its list lacks while operators can't be asked`() = test { val restoredAt = now.epochSeconds - 60 From 33f1958c778e299a24171bc04c12b3789febe5ef Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 23 Nov 2026 13:11:12 +0100 Subject: [PATCH 96/96] fix: spark retry success during a list read stays pending A retry's success event could end its hold while Spark's list was read, with the list holding only an earlier attempt's failure, so the send read as failed until the next read: Paykit could remove the paid request's proof and the send screen could show the paid send as failed. Both lookups now take the hold before the list, so a send held then stays pending unless that same list shows its own outcome, and Paykit settles a proof the node failed from its one Spark read instead of reading Spark again. Verified: just format, just compile, just test, just lint --- .../repositories/PaykitPaymentProofRepo.kt | 12 ++-- .../java/to/bitkit/repositories/SparkRepo.kt | 17 ++++-- .../PaykitPaymentProofRepoTest.kt | 24 ++++++++ .../to/bitkit/repositories/SparkRepoTest.kt | 61 +++++++++++++++++++ 4 files changed, 104 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index 44bedac639..b8fe69b490 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -1486,8 +1486,8 @@ class PaykitPaymentProofRepo @Inject constructor( when (payment.status) { PaymentStatus.PENDING -> Unit // A Spark retry of an invoice the node failed shares its hash and decides the payment. - PaymentStatus.FAILED -> when (lightningRepo.sparkLightningSend(paymentHash)) { - is SparkLightningSend.Found -> reconcileSparkLightningProof(proof, paymentHash) + PaymentStatus.FAILED -> when (val send = lightningRepo.sparkLightningSend(paymentHash)) { + is SparkLightningSend.Found -> reconcileSparkLightningProof(proof, paymentHash, send) SparkLightningSend.Unavailable -> Unit SparkLightningSend.NotFound -> removeLightningProofsLocked(paymentHash) } @@ -1499,8 +1499,12 @@ class PaykitPaymentProofRepo @Inject constructor( } } - private suspend fun reconcileSparkLightningProof(proof: PendingPaykitPaymentProof, paymentHash: String) { - val send = lightningRepo.sparkLightningSend(paymentHash) as? SparkLightningSend.Found ?: return + private suspend fun reconcileSparkLightningProof( + proof: PendingPaykitPaymentProof, + paymentHash: String, + read: SparkLightningSend.Found? = null, + ) { + val send = read ?: lightningRepo.sparkLightningSend(paymentHash) as? SparkLightningSend.Found ?: return when (send.status) { SparkPaymentStatus.PENDING -> Unit SparkPaymentStatus.FAILED -> removeLightningProofsLocked(paymentHash) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 1199588238..9733315ad4 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1534,13 +1534,15 @@ class SparkRepo @Inject constructor( */ suspend fun settledSendEvent(paymentHash: String): Event? = withContext(bgDispatcher) { if (!sparkService.isConnected) return@withContext null + // Read before the list, so a hold its success event ends while the list is read still keeps it pending. + val heldStart = sendHoldStart(paymentHash.lowercase()) runSuspendCatching { listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrNull() ?.latestSend(paymentHash) // A send in doubt or in Spark's send call is pending until Spark settles it, so a listed failure, which // may be an earlier attempt's, settles nothing yet. - ?.takeUnless { it.status == PaymentStatus.FAILED && isHeldFrom(it) } + ?.takeUnless { it.status == PaymentStatus.FAILED && isHeldFrom(it, heldStart) } ?.toNodeEvent() } @@ -1549,12 +1551,10 @@ class SparkRepo @Inject constructor( * and Spark dates the failure more than [OWN_FAILURE_CLOCK_MARGIN_SECS] before the send started, as an earlier * attempt's. */ - private suspend fun isHeldFrom(failure: Payment): Boolean { + private suspend fun isHeldFrom(failure: Payment, heldStart: ULong? = null): Boolean { val hash = failure.sendHash()?.lowercase() ?: return false if (sendsInFlight.containsKey(hash)) return true - val startedAt = uncertainSends[hash]?.startedAt - ?: cacheStore.data.first().sparkUncertainSends[hash]?.toULong() - ?: return false + val startedAt = listOfNotNull(heldStart, sendHoldStart(hash)).maxOrNull() ?: return false return failure.timestamp.safe() + OWN_FAILURE_CLOCK_MARGIN_SECS.safe() < startedAt } @@ -1610,8 +1610,10 @@ class SparkRepo @Inject constructor( suspend fun lightningSend(paymentHash: String): SparkLightningSend = withContext(bgDispatcher) { val hash = paymentHash.lowercase() val isUnlistedHeld = hash in unexpiredStartedSends() + // Read before the list, so a hold its success event ends while the list is read still keeps it pending. + val wasUncertain = sendHoldStart(hash) != null val send = listedLightningSend(paymentHash) - val isUncertain = hash in uncertainSendHashes() + val isUncertain = wasUncertain || sendHoldStart(hash) != null val isHeld = when (send) { SparkLightningSend.NotFound, SparkLightningSend.Unavailable -> isUncertain || isUnlistedHeld is SparkLightningSend.Found -> isUncertain && send.status == PaymentStatus.FAILED @@ -1619,6 +1621,9 @@ class SparkRepo @Inject constructor( if (isHeld) SparkLightningSend.Found(PaymentStatus.PENDING, null) else send } + private suspend fun sendHoldStart(hash: String): ULong? = + uncertainSends[hash]?.startedAt ?: cacheStore.data.first().sparkUncertainSends[hash]?.toULong() + /** Spark's listed record of the Lightning send with [paymentHash], as [lightningSend] reads it before its holds. */ private suspend fun listedLightningSend( paymentHash: String, diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index 5f0b45f337..eaefc24e54 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -1194,6 +1194,30 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { assertTrue(storedProofs.isEmpty()) } + @Test + fun `a lightning proof the node failed is kept while spark reads its retry pending`() = test { + val failed = mock { + on { id } doReturn PAYMENT_HASH + on { direction } doReturn PaymentDirection.OUTBOUND + on { status } doReturn PaymentStatus.FAILED + } + whenever(lightningRepo.getPayments()).thenReturn(Result.success(listOf(failed))) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(paymentRequestRecord())) + 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() + // Spark reads the retry pending, then, once its success event ended the hold, only the earlier failure. + whenever(lightningRepo.sparkLightningSend(PAYMENT_HASH)).thenReturn( + SparkLightningSend.Found(SparkPaymentStatus.PENDING, null), + SparkLightningSend.Found(SparkPaymentStatus.FAILED, null), + ) + + paymentProofRepo().reconcile() + + assertEquals(PAYMENT_HASH, storedProofs.single().paymentIdentifier) + } + @Test fun `lightning proof is removed when spark failed the send`() = test { whenever(lightningRepo.getPayments()).thenReturn(Result.success(emptyList())) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 8810dedc0c..3d6dc9e827 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -104,6 +104,7 @@ import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant @@ -3900,6 +3901,54 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, times(1)).send(any(), anyOrNull()) } + @Test + fun `a spark retry whose success ends its hold while spark's list is read stays pending`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val taken = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING, timestamp = 5uL) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(taken) + val earlier = sentPayment(fees = 0).copy(id = "earlier", status = PaymentStatus.FAILED, timestamp = 1uL) + whenever(sparkService.listPayments()).thenReturn(listOf(earlier)) + val sut = createSut() + sut.start(0).getOrThrow() + sut.payInvoice("lnbc1", 100uL) + advanceUntilIdle() + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) + + // The retry's success event ends its hold while the list is read, and the list lists only the earlier failure. + stubListEndingHoldWithSuccess(taken.copy(status = PaymentStatus.COMPLETED), earlier) + + val send = sut.lightningSend("hash") + + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), send, "a paid retry read as failed") + } + + @Test + fun `a spark retry whose success ends its hold while spark's list is read settles no send screen`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val taken = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING, timestamp = 5uL) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(taken) + val earlier = sentPayment(fees = 0).copy(id = "earlier", status = PaymentStatus.FAILED, timestamp = 1uL) + whenever(sparkService.listPayments()).thenReturn(listOf(earlier)) + val sut = createSut() + sut.start(0).getOrThrow() + sut.payInvoice("lnbc1", 100uL) + advanceUntilIdle() + assertNull(sut.settledSendEvent("hash")) + + // The retry's success event ends its hold while the list is read, and the list lists only the earlier failure. + stubListEndingHoldWithSuccess(taken.copy(status = PaymentStatus.COMPLETED), earlier) + + assertNull(sut.settledSendEvent("hash"), "a paid retry settled the send screen as failed") + } + @Test fun `a spark send whose caller was cancelled inside the send call ends at its invoice's expiry`() = test { whenever(sparkService.isSupported).thenReturn(true) @@ -4630,6 +4679,18 @@ class SparkRepoTest : BaseUnitTest() { ) } + private fun stubListEndingHoldWithSuccess(completed: Payment, earlier: Payment) { + var isEnded = false + whenever { sparkService.listPayments() }.doSuspendableAnswer { + if (!isEnded) { + isEnded = true + sparkEvents.emit(SdkEvent.PaymentSucceeded(completed)) + delay(1.milliseconds) + } + listOf(earlier) + } + } + private fun unexpiredPrepared(): PrepareSendPaymentResponse { val details = mock { on { paymentHash } doReturn "hash"