From 5f22319900930520b55359fdd6c15651ab0a6718 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 12:37:26 +0100 Subject: [PATCH 1/2] fix: find a restored wallet's exit funding before quoting the next exit --- .../java/to/bitkit/repositories/BackupRepo.kt | 3 +- .../bitkit/repositories/SparkExitFunding.kt | 7 ++- .../to/bitkit/repositories/SparkExitRepo.kt | 19 ++++--- .../repositories/SparkExitFundingTest.kt | 14 +++++ .../bitkit/repositories/SparkExitRepoTest.kt | 54 +++++++++++++++++++ 5 files changed, 88 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 86601183b0..3fde33b58a 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1256,7 +1256,8 @@ class BackupRepo @Inject constructor( it.sparkExitNextFundingIndexes, cleanCache.sparkExitNextFundingIndexes, ), - // The exit then looks once for funding addresses that still hold coins and nothing watches. + // 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, ) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index 445530cdd9..ff89a10f76 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -513,7 +513,7 @@ object SparkExitMath { /** Unused funding addresses a scan reads past the last used one before it stops. */ const val FUNDING_SCAN_GAP_LIMIT = 20 - /** The most funding addresses one scan reads, even when a host reports every one used. */ + /** The most funding addresses one scan reads from where it starts, even when a host reports every one used. */ const val FUNDING_SCAN_MAX_ADDRESSES = 1_000 /** @@ -524,7 +524,10 @@ object SparkExitMath { suspend fun scanNextFundingIndex(from: UInt = 0u, isUsed: suspend (UInt) -> Boolean): UInt { var next = from var index = from - while (index < next + FUNDING_SCAN_GAP_LIMIT.toUInt() && index < FUNDING_SCAN_MAX_ADDRESSES.toUInt()) { + val limit = (from.toULong() + FUNDING_SCAN_MAX_ADDRESSES.toULong()) + .coerceAtMost(UInt.MAX_VALUE.toULong()) + .toUInt() + while (index < next + FUNDING_SCAN_GAP_LIMIT.toUInt() && index < limit) { if (isUsed(index)) next = index + 1u index++ } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 9f0ed4c8b2..01d3c840a1 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -811,7 +811,9 @@ class SparkExitRepo @Inject constructor( // Spark on Lightning with its leaf optimization on, and nothing would drive or fund it. withContext(NonCancellable) { cacheStore.update { - val next = it.sparkExitNextFundingIndexes + (fundingIndexKey to pending.fundingIndex.toInt() + 1) + // Never lowers an index a restore's scan moved past this quote's. + val past = maxOf(it.sparkExitNextFundingIndexes[fundingIndexKey] ?: 0, pending.fundingIndex.toInt() + 1) + val next = it.sparkExitNextFundingIndexes + (fundingIndexKey to past) it.copy(sparkExitNextFundingIndexes = next) } // A cancelled exit's address this exit funds again is this exit's now, not an earlier exit's. @@ -1128,14 +1130,15 @@ class SparkExitRepo @Inject constructor( } /** - * With no index kept and no record, as after a restore from the phrase or from a backup older than the index, the - * funding addresses are scanned first. A scan the chain fails keeps nothing. + * While a restore is pending, as after a restore from the phrase or from a backup, the funding addresses are + * scanned first: a restored index can predate the last exit's funding. A scan the chain fails throws and keeps + * nothing, so no quote reuses that funding address. */ private suspend fun nextFundingIndex(): UInt { + val scanned = chain?.let { recoverFunding(it) }?.toInt() val kept = cacheStore.data.first().sparkExitNextFundingIndexes[fundingIndexKey] val stored = runSuspendCatching { store.load() }.getOrNull() - if (kept != null || stored != null) return SparkExitMath.nextFundingIndex(kept, stored) - return chain?.let { recoverFunding(it) } ?: 0u + return SparkExitMath.nextFundingIndex(listOfNotNull(kept, scanned).maxOrNull(), stored) } /** @@ -1162,7 +1165,11 @@ class SparkExitRepo @Inject constructor( chain.isAddressUsed(address(index)).also { if (it) used += index } } val candidates = if (kept == null) used else (0u until kept.toUInt()).toList() + used - val listed = runCatching { earlierAddressStore.load() }.getOrDefault(emptyList()).map { it.address } + // A forgotten exit's funding address is no longer watched once the scan moves the index past it, so one that + // holds coins is listed again, as kept change. + val listed = runCatching { earlierAddressStore.load() }.getOrDefault(emptyList()) + .filter { it.kind != SparkExitEarlierAddress.Kind.CANCELLED_FUNDING } + .map { it.address } val watched = listed + stored?.funding?.map { it.address }.orEmpty() for (index in candidates.filter { address(it) !in watched }) { val address = address(index) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index ec062e76bc..b7a7b56ea9 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -740,6 +740,20 @@ class SparkExitFundingTest { assertEquals((0u..(5u + SparkExitMath.FUNDING_SCAN_GAP_LIMIT.toUInt())).toList(), reads) } + @Test + fun `a funding scan from past its ceiling still reads forward`() = runTest { + val from = SparkExitMath.FUNDING_SCAN_MAX_ADDRESSES.toUInt() + val reads = mutableListOf() + + val next = SparkExitMath.scanNextFundingIndex(from) { + reads += it + it == from + } + + assertEquals(from + 1u, next) + assertEquals((from..(from + SparkExitMath.FUNDING_SCAN_GAP_LIMIT.toUInt())).toList(), reads) + } + @Test fun `a funding scan stops at its ceiling when every address reads as used`() = runTest { var reads = 0 diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 3307dd0d23..e5de08901b 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -903,6 +903,60 @@ class SparkExitRepoTest : BaseUnitTest() { ) } + @Test + fun `a quote while a restore is pending scans past the restored funding index first`() = test { + // The backup carrying index 4 never landed: address 3 still holds the lost exit's coins. + val key = "${Env.network.name.lowercase()}/wallet0" + val restored = AppCacheData( + sparkExitNextFundingIndexes = mapOf(key to 3), + sparkExitFundingRecoveryPending = setOf(key), + ) + whenever(cacheStore.data).thenReturn(flowOf(restored)) + val sut = scannedSut(scanChain(used = setOf(0, 1, 2, 3), reads = mutableListOf(), coins = mapOf(3 to 7_000))) + + sut.loadQuote().getOrThrow() + + assertEquals(4u, sut.state.value.pending?.fundingIndex, "the next exit funds from the lost exit's address") + assertEquals(listOf(keptCoins(3, 7_000uL)), sut.state.value.earlierAddresses) + assertTrue(keptCache(restored).sparkExitFundingRecoveryPending.isEmpty()) + } + + @Test + fun `a quote while a restore is pending fails when the scan fails`() = test { + val key = "${Env.network.name.lowercase()}/wallet0" + val restored = AppCacheData( + sparkExitNextFundingIndexes = mapOf(key to 3), + sparkExitFundingRecoveryPending = setOf(key), + ) + whenever(cacheStore.data).thenReturn(flowOf(restored)) + val sut = scannedSut(scanChain(used = emptySet(), reads = mutableListOf(), isDown = true)) + + assertTrue(sut.loadQuote().isFailure, "a quote could fund from the address a lost exit used") + + assertNull(sut.state.value.pending) + verify(cacheStore, never()).update(any()) + } + + @Test + fun `a restored funding index at a forgotten exit's address lists its late payment as kept change`() = test { + // The exit at address 3 was forgotten before funding, so the index went back to 3; a payment came late. + val key = "${Env.network.name.lowercase()}/wallet0" + val restored = AppCacheData( + sparkExitNextFundingIndexes = mapOf(key to 3), + sparkExitFundingRecoveryPending = setOf(key), + ) + whenever(cacheStore.data).thenReturn(flowOf(restored)) + val earlier = SparkExitEarlierAddressStore(File(Env.sparkExitEarlierAddressesPath(0))) + earlier.add(keptCoins(3, 0uL).copy(kind = SparkExitEarlierAddress.Kind.CANCELLED_FUNDING, sats = null)) + val sut = scannedSut(scanChain(used = setOf(0, 1, 2, 3), reads = mutableListOf(), coins = mapOf(3 to 4_000))) + sut.load(0).getOrThrow() + + sut.refreshEarlierAddresses() + + assertEquals(listOf(keptCoins(3, 4_000uL)), earlier.load(), "watched only until its cancel expires") + assertEquals(mapOf(key to 4), keptCache(restored).sparkExitNextFundingIndexes) + } + @Test fun `a kept funding index with no restore pending reads no funding address`() = test { val key = "${Env.network.name.lowercase()}/wallet0" From 286930cf98e307a014b912c28f6d0bf541272205 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 13:01:50 +0100 Subject: [PATCH 2/2] fix: end the exit funding scan at the top of the index range --- .../to/bitkit/repositories/SparkExitFunding.kt | 7 +++---- .../to/bitkit/repositories/SparkExitFundingTest.kt | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index ff89a10f76..cd060cb18e 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -524,10 +524,9 @@ object SparkExitMath { suspend fun scanNextFundingIndex(from: UInt = 0u, isUsed: suspend (UInt) -> Boolean): UInt { var next = from var index = from - val limit = (from.toULong() + FUNDING_SCAN_MAX_ADDRESSES.toULong()) - .coerceAtMost(UInt.MAX_VALUE.toULong()) - .toUInt() - while (index < next + FUNDING_SCAN_GAP_LIMIT.toUInt() && index < limit) { + // In 64 bits, so an index near the top of its range ends the scan instead of wrapping around. + val limit = (from.toULong() + FUNDING_SCAN_MAX_ADDRESSES.toULong()).coerceAtMost(UInt.MAX_VALUE.toULong()) + while (index.toULong() < next.toULong() + FUNDING_SCAN_GAP_LIMIT.toULong() && index.toULong() < limit) { if (isUsed(index)) next = index + 1u index++ } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index b7a7b56ea9..8f650e2f35 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -754,6 +754,20 @@ class SparkExitFundingTest { assertEquals((from..(from + SparkExitMath.FUNDING_SCAN_GAP_LIMIT.toUInt())).toList(), reads) } + @Test + fun `a funding scan from the top of the index range ends instead of wrapping around`() = runTest { + val from = UInt.MAX_VALUE - 5u + val reads = mutableListOf() + + val next = SparkExitMath.scanNextFundingIndex(from) { + reads += it + true + } + + assertEquals(UInt.MAX_VALUE, next) + assertEquals((from until UInt.MAX_VALUE).toList(), reads) + } + @Test fun `a funding scan stops at its ceiling when every address reads as used`() = runTest { var reads = 0