Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion app/src/main/java/to/bitkit/repositories/BackupRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
}
Expand Down
6 changes: 4 additions & 2 deletions app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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

/**
Expand All @@ -524,7 +524,9 @@ 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()) {
// 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++
}
Expand Down
19 changes: 13 additions & 6 deletions app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment thread
ovitrif marked this conversation as resolved.
Resolved
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.
Expand Down Expand Up @@ -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)
}

/**
Expand All @@ -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)
Expand Down
28 changes: 28 additions & 0 deletions app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -740,6 +740,34 @@ 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<UInt>()

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 from the top of the index range ends instead of wrapping around`() = runTest {
val from = UInt.MAX_VALUE - 5u
val reads = mutableListOf<UInt>()

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
Expand Down
54 changes: 54 additions & 0 deletions app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading