From 777a7e88f380caf77cd535d8b3f44c3e8719c74f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 27 Nov 2026 12:19:27 +0100 Subject: [PATCH 1/2] fix: keep the force transfer's fee request in step with the savings send Release the savings-send hold when the exit wallet's journal holds no attempt and the funding address was never used; keep the fee request a partial payment reduced across marking and a failed top-up; send no fee request when unconfirmed funding already covers the fees. Verified: gradlew testDevDebugUnitTest SparkExitRepoTest, PaykitPaymentProofRepoTest, SendPendingViewModelTest (pass; the three new tests fail with the main-code changes reverted), gradlew detekt --- .../to/bitkit/repositories/LightningRepo.kt | 3 + .../to/bitkit/repositories/SparkExitRepo.kt | 43 ++++++++-- .../bitkit/repositories/SparkExitRepoTest.kt | 78 ++++++++++++++++++- changelog.d/next/2151.fixed.md | 1 + 4 files changed, 118 insertions(+), 7 deletions(-) create mode 100644 changelog.d/next/2151.fixed.md diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 55d8e16096..847727c6fd 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -2585,6 +2585,9 @@ class LightningRepo @Inject constructor( suspend fun currentOnchainSendAttempt(): OnchainSendAttempt? = onchainSendAttemptStore.current() + /** The wallet whose send journal [currentOnchainSendAttempt] reads. */ + val currentWalletIndex: Int get() = lightningService.currentWalletIndex + /** Syncs the on-chain wallet, then checks that none of the attempt's candidates reached the mempool or chain. */ override suspend fun onchainCandidatesNeverReachedNetwork(attempt: OnchainSendAttempt): Boolean = onchainCandidatesNeverReachedNetwork(attempt, ABANDON_SYNC_TIMEOUT) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index c1639d9257..3a178e1b12 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -100,6 +100,10 @@ class SparkExitRepo @Inject constructor( @Volatile private var walletIndex = 0 + /** The last read of a funding address and what it held, so an ask a held payment hid can show again. */ + @Volatile + private var lastFundingRead: Pair>? = null + @Volatile private var isLoaded = false @@ -456,6 +460,8 @@ class SparkExitRepo @Inject constructor( val seen = utxos?.let { SparkExitMath.newFunding(it, record) }?.fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } + val address = record.funding.firstOrNull()?.address + if (utxos != null && address != null) lastFundingRead = address to utxos _state.update { it.copy( fundingSeenSats = seen ?: it.fundingSeenSats, @@ -495,7 +501,9 @@ class SparkExitRepo @Inject constructor( deadlineAtMillis = clock.nowMs() + deadline.deadlineIn.inWholeMilliseconds ) } - if (SparkExitAlerts.isFundingAskBack(record, previous)) work.notify(SparkExitAlert.Funding) + // Funding at the address that covers the fees only waits to confirm: there is nothing to ask for. + val isCovered = _state.value.fundingState == SparkExitFundingState.Seen + if (SparkExitAlerts.isFundingAskBack(record, previous) && !isCovered) work.notify(SparkExitAlert.Funding) if (SparkExitAlerts.isFundingAskWithdrawn(record, previous)) work.dismissFundingAsk() when (record.phase) { // Waiting on the operators for a week needs nothing from the user, so nothing reminds them. @@ -1008,18 +1016,23 @@ class SparkExitRepo @Inject constructor( val started = SparkExitRecord.SavingsSendStarted(address, atHeight = null, earlierAttemptId) val marked = record.copy(savingsSendStarted = started) saveRecord(marked) - _state.update { it.copy(record = marked, fundingState = SparkExitMath.fundingState(marked, utxos = null)) } + _state.update { it.copy(record = marked, fundingState = SparkExitMath.fundingState(marked, lastRead(marked))) } } + private fun lastRead(record: SparkExitRecord): List? = + lastFundingRead?.takeIf { it.first == record.funding.firstOrNull()?.address }?.second + private fun clearSavingsSend() { val record = _state.value.record?.takeIf { it.savingsSendStarted != null } ?: return val cleared = record.copy(savingsSendStarted = null) // Kept in memory even when the save fails; a later tick saves it. runCatching { saveRecord(cleared) } .onFailure { Logger.warn("Failed to clear the started Spark exit savings payment", it, context = TAG) } - // The hold ends: the ask shows until the next read of the address. + // The hold ends: the ask the last read of the address found shows again, reduced by a partial payment, or the + // full ask until the next read when there was none. val isHeld = _state.value.fundingState == SparkExitFundingState.Paid && !cleared.isAwaitingOwnPayment - _state.update { it.copy(record = cleared, fundingState = it.fundingState.takeUnless { isHeld }) } + val asked = lastRead(cleared)?.let { SparkExitMath.fundingState(cleared, it) } + _state.update { it.copy(record = cleared, fundingState = if (isHeld) asked else it.fundingState) } } /** @@ -1148,9 +1161,28 @@ class SparkExitRepo @Inject constructor( if (!canKeepAcceptedSavingsSend(record)) return record // The journal's attempt to any address: one elsewhere says the journal moved on, not that nothing went out. val attempt = runSuspendCatching { lightningRepo.currentOnchainSendAttempt() }.getOrElse { return record } + if (attempt == null && isStartedSendNeverSent(record)) { + Logger.info("Forgetting the started Spark exit savings payment the journal never sent", context = TAG) + clearSavingsSend() + return _state.value.record ?: record + } return keepAcceptedSavingsSend(record, attempt) } + /** + * Whether the started savings payment of [record] never went out, once the send journal holds no attempt: the + * journal is the exit wallet's, which saves a send before it goes out, and no transaction ever reached the started + * payment's address. The address read covers a payment the journal no longer holds: one a later send replaced + * before that send was dropped, or one from a journal a restore did not bring back. Called under the tick lock, + * so it never runs between marking a payment and its admission to the journal. + */ + private suspend fun isStartedSendNeverSent(record: SparkExitRecord): Boolean { + val address = record.savingsSendStarted?.address ?: return false + if (lightningRepo.currentWalletIndex != walletIndex) return false + val chain = chain ?: return false + return runSuspendCatching { !chain.isAddressUsed(address) }.getOrDefault(false) + } + private fun canKeepAcceptedSavingsSend(record: SparkExitRecord): Boolean = record.isActive && record.phase is SparkExitRecord.Phase.AwaitingFunding && record.fundingPaymentTxid == null && (record.savingsRefusal != null || record.savingsSendStarted != null) @@ -1165,7 +1197,8 @@ class SparkExitRepo @Inject constructor( val txid = own?.takeIf { it.hasPositiveEvidence || (started != null && isNoAnswer) }?.txid if (txid == null) { // Only the earlier attempt: nothing was admitted, so nothing went out. One a node refused is paid again by - // its own retry. No attempt at all proves nothing: the journal may be another wallet's. + // its own retry. No attempt at all proves nothing here: the journal may be another wallet's, which only + // the journal's wallet and an unused address rule out. val isNotSent = (attempt != null && attempt.attemptId == started?.earlierAttemptId) || own?.evidence == OnchainSendEvidence.Rejected if (started != null && isNotSent) { diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 890cf308a1..45fec89e58 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -747,14 +747,18 @@ class SparkExitRepoTest : BaseUnitTest() { } // On the test's own dispatcher, so no tick a start or payment launches runs on after the test. - private fun fundingChain(utxos: String? = "[]", readUtxos: () -> String? = { utxos }) = HttpClient( + private fun fundingChain( + utxos: String? = "[]", + txCount: Int = 0, + readUtxos: () -> String? = { utxos }, + ) = HttpClient( MockEngine.create { dispatcher = testDispatcher addHandler { request -> val url = request.url.toString() when { url.endsWith("/address/$funding/utxo") && readUtxos() != null -> respond(readUtxos().orEmpty()) - url.endsWith("/address/$funding") -> respond(addressStats(txCount = 0)) + url.endsWith("/address/$funding") -> respond(addressStats(txCount)) url.endsWith("/blocks/tip/height") -> respond("1000") url.endsWith("/fee-estimates") -> respond("""{"1":9,"3":6,"144":1}""") else -> throw IOException("unreachable '$url'") @@ -2015,6 +2019,76 @@ class SparkExitRepoTest : BaseUnitTest() { assertIs(sut.state.value.fundingState) } + @Test + fun `a started savings payment the journal never sent frees the ask once its address shows nothing`() = test { + // Stopped before the payment was admitted, or restart dropped an attempt that never went out: no attempt. + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(startedRecord(earlierAttemptId = null)) + whenever(lightning.currentOnchainSendAttempt()).thenReturn(null) + val used = quotedSut(FakeSparkExitRecovering(), fundingChain(txCount = 1)) + used.load().getOrThrow() + used.tick().getOrThrow() + used.onAppBackgrounded() + assertNotNull(assertNotNull(store.load()).savingsSendStarted, "a transaction reached the address") + + val sut = quotedSut(FakeSparkExitRecovering(), fundingChain()) + sut.load().getOrThrow() + sut.tick().getOrThrow() + sut.onAppBackgrounded() + + assertNull(assertNotNull(store.load()).savingsSendStarted) + assertIs(sut.state.value.fundingState) + assertTrue(sut.canCancel) + } + + @Test + fun `a started savings payment that expires sends no fee request while covering funding confirms`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + val elsewhere = refusedSavingsPayment().copy( + address = "bcrt1qelsewhere", + evidence = OnchainSendEvidence.Accepted, + ) + whenever(lightning.currentOnchainSendAttempt()).thenReturn(elsewhere) + // The chain's tip is 1000. + store.save(startedRecord(atHeight = 1000u - SparkExitRecord.OWN_PAYMENT_TIMEOUT_BLOCKS)) + val covering = """[{"txid":"${"e1".repeat(32)}","vout":0,"value":100000,"status":{"confirmed":false}}]""" + val sut = quotedSut(FakeSparkExitRecovering(), fundingChain(utxos = covering)) + sut.load().getOrThrow() + sut.tick().getOrThrow() + sut.onAppBackgrounded() + + assertNull(assertNotNull(store.load()).savingsSendStarted) + assertIs(sut.state.value.fundingState) + verify(work, never()).notify(eq(SparkExitAlert.Funding), anyOrNull(), anyOrNull(), anyOrNull()) + } + + @Test + fun `a savings payment that fails keeps the fee request another wallet's payment reduced`() = test { + var heldAtSend: SparkExitFundingState? = null + lateinit var sut: SparkExitRepo + stubFunding { + heldAtSend = sut.state.value.fundingState + Result.failure(OnchainSendNotDispatchedError(IOException("journal write failed"))) + } + val paid = """[{"txid":"${"e1".repeat(32)}","vout":0,"value":8000,"status":{"confirmed":false}}]""" + sut = quotedSut(FakeSparkExitRecovering(), fundingChain(utxos = paid)) + sut.loadQuote().getOrThrow() + sut.refreshFundingAddress().getOrThrow() + whenever(lightning.getFeeRates()).thenReturn(Result.success(FeeRates(fast = 7u, mid = 4u, slow = 1u))) + whenever(lightning.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success(300uL)) + whenever(lightning.getBalancesAsync()).thenReturn(Result.success(balances(100_000uL))) + sut.savingsFundingFee().getOrThrow() + + assertTrue(sut.start(fundFromSavings = true).isFailure) + sut.onAppBackgrounded() + + assertIs(heldAtSend, "the ask is held while the payment goes out") + assertNull(sut.state.value.record?.savingsSendStarted) + val ask = assertIs(sut.state.value.fundingState) + assertEquals(8000uL, ask.receivedSats, "the partial payment still counts") + } + @Test fun `a start's savings payment is saved on the exit before it goes out`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) diff --git a/changelog.d/next/2151.fixed.md b/changelog.d/next/2151.fixed.md new file mode 100644 index 0000000000..5dad105d95 --- /dev/null +++ b/changelog.d/next/2151.fixed.md @@ -0,0 +1 @@ +Fixed the force transfer's fee request staying hidden or too large after a savings payment that never went out or failed, and a fee reminder sent while funding already covered the fees. From 14c105b2c7335afc3af2df5d431f534c6daea41d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 27 Nov 2026 12:29:22 +0100 Subject: [PATCH 2/2] fix: keep the last funding read from the start and wallet checks The start's read of the funding address keeps the last read too, a wipe forgets it, and the release checks the journal's wallet before and after reading it. Verified: gradlew testDevDebugUnitTest SparkExitRepoTest, PaykitPaymentProofRepoTest, SendPendingViewModelTest (pass), gradlew detekt --- app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt | 5 ++++- .../test/java/to/bitkit/repositories/SparkExitRepoTest.kt | 8 ++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 3a178e1b12..d41d677f29 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -132,6 +132,7 @@ class SparkExitRepo @Inject constructor( .onFailure { e -> Logger.warn("Failed to delete the wiped exit addresses", e, context = TAG) } work.cancelAll() _state.update { SparkExitState() } + lastFundingRead = null isLoaded = false // A later exit, of a new or restored wallet, writes again. isWriteClosed = false @@ -788,6 +789,7 @@ class SparkExitRepo @Inject constructor( val chain = requireNotNull(chain) { "No chain host for this network" } val address = requireNotNull(_state.value.fundingAddress) { "No Spark exit funding address" } val utxos = chain.utxos(address) + lastFundingRead = address to utxos val seen = utxos.fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } _state.update { it.copy(fundingSeenSats = seen, fundingSeenCount = utxos.size) } seen @@ -1160,8 +1162,9 @@ class SparkExitRepo @Inject constructor( private suspend fun keepAcceptedSavingsSend(record: SparkExitRecord): SparkExitRecord { if (!canKeepAcceptedSavingsSend(record)) return record // The journal's attempt to any address: one elsewhere says the journal moved on, not that nothing went out. + val journalWallet = lightningRepo.currentWalletIndex val attempt = runSuspendCatching { lightningRepo.currentOnchainSendAttempt() }.getOrElse { return record } - if (attempt == null && isStartedSendNeverSent(record)) { + if (attempt == null && journalWallet == walletIndex && isStartedSendNeverSent(record)) { Logger.info("Forgetting the started Spark exit savings payment the journal never sent", context = TAG) clearSavingsSend() return _state.value.record ?: record diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 45fec89e58..502e835e29 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -2031,6 +2031,14 @@ class SparkExitRepoTest : BaseUnitTest() { used.onAppBackgrounded() assertNotNull(assertNotNull(store.load()).savingsSendStarted, "a transaction reached the address") + whenever(lightning.currentWalletIndex).thenReturn(1) + val elsewhere = quotedSut(FakeSparkExitRecovering(), fundingChain()) + elsewhere.load().getOrThrow() + elsewhere.tick().getOrThrow() + elsewhere.onAppBackgrounded() + assertNotNull(assertNotNull(store.load()).savingsSendStarted, "the journal read is another wallet's") + + whenever(lightning.currentWalletIndex).thenReturn(0) val sut = quotedSut(FakeSparkExitRecovering(), fundingChain()) sut.load().getOrThrow() sut.tick().getOrThrow()