From 4125b72d128c24fde0b35b6a8a4b3cb135d2b274 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 16:41:33 +0100 Subject: [PATCH 1/3] fix: hold a redo spark exit rebuild over a waiting leaf --- .../to/bitkit/repositories/SparkExitDriver.kt | 17 +++ .../to/bitkit/repositories/SparkExitRecord.kt | 9 ++ .../repositories/SparkExitDriverTest.kt | 119 ++++++++++++++++++ .../repositories/SparkExitRecordTest.kt | 2 + .../bitkit/repositories/SparkExitRepoTest.kt | 24 ++++ 5 files changed, 171 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 2c73014c26..0ec03679b8 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -126,6 +126,9 @@ class SparkExitDriver( /** The least time between two builds, so a divergence that persists does not rebuild every tick. */ val REBUILD_INTERVAL = 10.minutes + /** Blocks a Redo rebuild waits for a skipped leaf the diverged generation recovers, about an hour. */ + const val REDO_HOLD_BLOCKS = 6u + const val LOST_REASON = "Claimed by an older state" const val NO_LEAF_REASON = "No leaf can be exited" @@ -340,6 +343,7 @@ class SparkExitDriver( // Adopted, it would drop the signed steps of the leaf it could not read for the week the failed // leaves are retried, past the window in which they are ours to publish. if (record.keepsValidGenerationOver(waiting)) return record.keepingValidGeneration() + holdingRedo(record, waiting)?.let { return it } val adopted = record.adopt(built, nowMillis()).copy(waitingLeafIds = waiting) save(adopted) Logger.info("Built Spark exit of only '${built.failed.size}' failed cooperative leaves", context = TAG) @@ -355,6 +359,9 @@ class SparkExitDriver( // A rebuild of other leaves would drop the signed steps of a waiting leaf the valid generation recovers, until // the other leaves' chains confirm: the valid generation stays, rebuilt over once a block. if (record.keepsValidGenerationOver(waiting)) return record.keepingValidGeneration() + // A diverged generation is never sent again, so a Redo rebuild that leaves out a waiting leaf it recovers would + // leave that leaf unsent until the rest of the exit is done: it tries again at its usual pace for a few blocks. + holdingRedo(record, waiting)?.let { return it } val adopted = record.adopt(built, nowMillis()).copy(waitingLeafIds = waiting) // Saved before any of it is broadcast, so a crash never leaves broadcast transactions without their record. save(adopted) @@ -365,6 +372,16 @@ class SparkExitDriver( return broadcastReady(adopted) } + private fun holdingRedo(record: SparkExitRecord, waiting: List): SparkExitRecord? { + if (!record.isRedoRebuild || record.recovery?.leaves?.none { it.leafId in waiting } != false) return null + // Without a tip the hold goes on uncounted: the failed read that skipped the leaf often fails the tip too. + val height = tip + val since = record.redoHeldSince ?: height + if (height != null && since != null && height >= since && height - since >= REDO_HOLD_BLOCKS) return null + Logger.info("Holding the Spark exit's Redo rebuild for waiting leaves '$waiting'", context = TAG) + return record.copy(redoHeldSince = since, lastBuildAt = nowMillis()) + } + private suspend fun withExitState(record: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { record.exitStateSnapshot?.let { snapshot -> runSuspendCatching { sdk.importExitState(snapshot) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 01cbe6e701..eef2309ff3 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -116,6 +116,12 @@ data class SparkExitRecord( val isRebuiltFromChain: Boolean = false, /** The rebuild in progress started from a Redo verdict, the only one whose reproduced spent steps strike. */ val isRedoRebuild: Boolean = false, + /** + * The tip at which a Redo rebuild first left out a waiting leaf the diverged generation recovers. The rebuild is + * not adopted for [SparkExitDriver.REDO_HOLD_BLOCKS] from then, so a leaf one failed read skipped is not left + * unsent until the rest of the exit is done. + */ + val redoHeldSince: UInt? = null, /** The fee funding asked for came from a rebuild over unverified steps, while the generation out there is valid. */ val isUnverifiedAsk: Boolean = false, /** @@ -427,6 +433,7 @@ data class SparkExitRecord( fun adopt(built: RecoverFundsResponse, atMillis: Long): SparkExitRecord = copy( spentStepStrikes = if (isRedoRebuild) spentStepStrikes(built) else spentStepStrikes, isRedoRebuild = false, + redoHeldSince = null, isUnverifiedAsk = false, isFeeBumpPending = false, feeBumpBuiltAtHeight = null, @@ -967,6 +974,7 @@ object SparkExitJson { r.exitStateSnapshot?.let { put("exitStateSnapshot", it) } if (r.isRebuiltFromChain) put("isRebuiltFromChain", true) if (r.isRedoRebuild) put("isRedoRebuild", true) + r.redoHeldSince?.let { put("redoHeldSince", it.toLong()) } if (r.isUnverifiedAsk) put("isUnverifiedAsk", true) putFeeBumpState(r) r.fundingStrategy?.let { put("fundingStrategy", it) } @@ -1108,6 +1116,7 @@ object SparkExitJson { exitStateSnapshot = o.stringOrNull("exitStateSnapshot"), isRebuiltFromChain = o.booleanOrNull("isRebuiltFromChain") ?: false, isRedoRebuild = o.booleanOrNull("isRedoRebuild") ?: false, + redoHeldSince = o.ulongOrNull("redoHeldSince")?.toUInt(), isUnverifiedAsk = o.booleanOrNull("isUnverifiedAsk") ?: false, isFeeBumpPending = o.booleanOrNull("isFeeBumpPending") ?: false, feeBumpBuiltAtHeight = o.ulongOrNull("feeBumpBuiltAtHeight")?.toUInt(), diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 8c64977836..18cb585043 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1761,6 +1761,79 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(Race.rebuiltSecond, chain.broadcasts.last().cpfpTxHex) } + private val redoLeaves = listOf( + RecoverFundsLeaf("leaf-1", 100_000uL, RecoveryMethod.UNILATERAL), + RecoverFundsLeaf("leaf-2", 100_000uL, RecoveryMethod.UNILATERAL), + ) + + /** A generation recovering leaf-1 and leaf-2 whose check returned Redo, its rebuild due. */ + private fun divergedOverTwoLeaves(): SparkExitRecord { + val old = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))).copy(leaves = redoLeaves) + sdk.checks += check(old, redo) + return running(old, builtAt = now - interval).copy(leafIds = listOf("leaf-1", "leaf-2")) + } + + private val leaf2Unread = SparkExitFixtures.prepared(funding = null, leaves = listOf("leaf-1")).copy( + skipped = listOf(SkippedLeaf("leaf-2", 100_000uL, SkippedLeafReason.Unverified)), + ) + + @Test + fun `a redo rebuild beside a waiting leaf holds until the leaf reads`() = test { + var record = divergedOverTwoLeaves() + sdk.preparedResponse = leaf2Unread + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("a1"))) + + record = driver(tip = 1_000u).tick(record) + + assertEquals(1, record.generation, "a rebuild left out leaf-2's steps the diverged generation recovers") + assertTrue(record.isRebuilding) + assertEquals(1_000u, record.redoHeldSince) + assertEquals(1, sdk.recoverRequests.size) + assertTrue(chain.broadcasts.isEmpty(), "the diverged generation was sent again") + + // leaf-2 reads on the next build: both leaves are rebuilt together. + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null, leaves = listOf("leaf-1", "leaf-2")) + .copy(skipped = emptyList()) + sdk.builds += SparkExitFixtures.recovery( + listOf(SparkExitFixtures.tx("a1"), SparkExitFixtures.tx("b1")), + ).copy(leaves = redoLeaves) + now += interval + record = driver(tip = 1_001u).tick(record) + + assertEquals(2, record.generation) + assertFalse(record.isRebuilding) + assertEquals(listOf("leaf-1", "leaf-2"), record.recovery?.leaves?.map { it.leafId }) + assertNull(record.redoHeldSince) + assertTrue(record.waitingLeafIds.isEmpty()) + assertEquals(listOf("a1", "b1"), chain.broadcasts.map { it.txid }) + } + + @Test + fun `a redo rebuild beside a leaf that stays unread adopts after the hold`() = test { + var record = divergedOverTwoLeaves() + sdk.preparedResponse = leaf2Unread + repeat(SparkExitDriver.REDO_HOLD_BLOCKS.toInt() + 1) { + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("a1"))) + } + + record = driver(tip = 1_000u).tick(record) + for (height in 1_001u until 1_000u + SparkExitDriver.REDO_HOLD_BLOCKS) { + now += interval + record = driver(tip = height).tick(record) + assertEquals(1, record.generation, "adopted at '$height' before the hold ended") + assertEquals(1_000u, record.redoHeldSince, "the hold restarted at '$height'") + } + assertTrue(chain.broadcasts.isEmpty()) + + now += interval + record = driver(tip = 1_000u + SparkExitDriver.REDO_HOLD_BLOCKS).tick(record) + + assertEquals(2, record.generation, "the rebuild waited past the hold") + assertEquals(listOf("leaf-2"), record.waitingLeafIds) + assertNull(record.redoHeldSince) + assertEquals(listOf("a1"), chain.broadcasts.map { it.txid }) + } + @Test fun `a rebuild from the chain keeps its note until one of its steps confirms`() = test { val built = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) @@ -2446,6 +2519,52 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(Phase.Running, record.phase) } + @Test + fun `a redo after a refund sent spent strikes it once and not again once its rebuild is accepted`() = test { + // A lost CPFP race comes back as Redo: the refund was refused as spent because its child's funding was. + val recovery = lostLeafRecovery() + var record = running(recovery, builtAt = 0L).copy( + funding = listOf( + SparkExitRecord.Funding(0u, SparkExitFixtures.FUNDING_ADDRESS, "02ab", "f0", 1u, 20_000uL), + ), + broadcastLog = listOf( + SparkExitRecord.BroadcastAttempt(1, "refund", 1, 0, now, "inputs missing", false, isInputSpent = true), + ), + ) + sdk.preparedResponse = SparkExitFixtures.prepared() + // The rebuild reproduces the refund with a new child on the funding that is left. + val rebuilt = SparkExitFixtures.recovery( + recovery.transactions.map { if (it.txid == "refund") it.copy(cpfpTxHex = "03c2") else it }, + ) + sdk.checks += check(recovery, redo) + sdk.builds += rebuilt + + record = driver().tick(record) + + assertEquals(2, record.generation) + assertEquals(mapOf("refund" to 1), record.spentStepStrikes) + assertTrue(record.lostLeaves.isEmpty()) + assertEquals( + listOf(CpfpInput.P2wpkh("f0", 1u, 20_000uL, "02ab")), + sdk.recoverRequests.single().fundingInputs, + ) + assertEquals(listOf("03c2"), chain.broadcasts.map { it.cpfpTxHex }) + val sent = record.broadcastLog.single { it.txid == "refund" } + assertTrue(sent.isAccepted) + assertFalse(sent.isInputSpent) + + // Diverged again: the refund was accepted this generation, so its strike drops out instead of reaching two. + sdk.checks += check(rebuilt, redo) + sdk.builds += rebuilt + now += interval + record = driver().tick(record) + + assertEquals(3, record.generation) + assertTrue(record.spentStepStrikes.isEmpty(), "the refund was struck a second time in a row") + assertTrue(record.lostLeaves.isEmpty()) + assertEquals(Phase.Running, record.phase) + } + @Test fun `the first build keeps the sdk's exit data and every rebuild imports it first`() = test { chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("f0", 1u, 25_000uL)) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt index efa5b2c6ae..3294c2fba5 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt @@ -122,6 +122,7 @@ class SparkExitRecordTest { exitStateSnapshot = "exit-state", isRebuiltFromChain = true, isRedoRebuild = true, + redoHeldSince = 1_005u, isFeeBumpPending = true, feeBumpBuiltAtHeight = 1_004u, earlierReceivedSats = mapOf("sweep-0" to 90_000uL), @@ -229,6 +230,7 @@ class SparkExitRecordTest { "exitStateSnapshot", "isRebuiltFromChain", "isRedoRebuild", + "redoHeldSince", "isFeeBumpPending", "feeBumpBuiltAtHeight", "earlierReceivedSats", diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index eaddeb1b52..1966b6962a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -1023,6 +1023,30 @@ class SparkExitRepoTest : BaseUnitTest() { assertTrue(reads.isEmpty(), "a backed-up index needs no scan") } + @Test + fun `a start never lowers a funding index a scan moved past its quote`() = test { + val key = "${Env.network.name.lowercase()}/wallet0" + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(sparkExitNextFundingIndexes = mapOf(key to 3)))) + val sut = quotedSut(FakeSparkExitRecovering()) + sut.loadQuote().getOrThrow() + assertEquals(3u, sut.state.value.pending?.fundingIndex) + + sut.start(fundFromSavings = false).getOrThrow() + sut.onAppBackgrounded() + + assertEquals( + mapOf(key to 4), + keptCache(AppCacheData(sparkExitNextFundingIndexes = mapOf(key to 3))).sparkExitNextFundingIndexes, + "the next exit funds from this exit's address", + ) + // A scan that kept index 9 between the quote and the start. + assertEquals( + mapOf(key to 9), + keptCache(AppCacheData(sparkExitNextFundingIndexes = mapOf(key to 9))).sparkExitNextFundingIndexes, + "the next exit funds from an address the scan found used", + ) + } + @Test fun `a funding scan the chain fails fails the quote and keeps no index`() = test { val sut = scannedSut(scanChain(used = emptySet(), reads = mutableListOf(), isDown = true)) From f742ad0e55557db7448e61531e4b60fed0f34aa2 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 17:13:02 +0100 Subject: [PATCH 2/3] fix: redo hold keeps the rebuild pace after funding and an empty prepare --- .../to/bitkit/repositories/SparkExitDriver.kt | 8 ++- .../repositories/SparkExitDriverTest.kt | 50 +++++++++++++++++++ 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 0ec03679b8..db0fb470fb 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -293,7 +293,9 @@ class SparkExitDriver( } if (prepared.leaves.isEmpty()) { // A leaf that may still move, such as one the chain could not be read for, is waited for, about a week at - // most; finished leaves are not listed. + // most; finished leaves are not listed. A Redo hold keeps its own pace and bound: the waiting leaf's retry + // clock would stretch it. + holdingRedo(record, waitingLeafIds(record, prepared.skipped, stopped))?.let { return it } if (isWaiting(record, prepared.skipped, stopped)) { Logger.info("Waiting for Spark exit leaves that may still move", context = TAG) return record.copy(retrySince = record.retrySince ?: tip, retriedAt = tip ?: record.retriedAt) @@ -379,7 +381,9 @@ class SparkExitDriver( val since = record.redoHeldSince ?: height if (height != null && since != null && height >= since && height - since >= REDO_HOLD_BLOCKS) return null Logger.info("Holding the Spark exit's Redo rebuild for waiting leaves '$waiting'", context = TAG) - return record.copy(redoHeldSince = since, lastBuildAt = nowMillis()) + // Funding a top-up already covered runs the hold at the rebuild pace, with no fee ask on screen. + val phase = if (record.fundingShortfallSats == null) SparkExitRecord.Phase.Running else record.phase + return record.copy(redoHeldSince = since, lastBuildAt = nowMillis(), phase = phase) } private suspend fun withExitState(record: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 18cb585043..f7099150a4 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1834,6 +1834,56 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(listOf("a1"), chain.broadcasts.map { it.txid }) } + @Test + fun `a redo hold after a funded top-up runs at the rebuild pace`() = test { + var record = divergedOverTwoLeaves() + sdk.preparedResponse = leaf2Unread + repeat(3) { sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("a1"))) } + record = driver(tip = 1_000u).tick(record) + assertEquals(1_000u, record.redoHeldSince) + + val held = SparkExitRecord.Funding(0u, SparkExitFixtures.FUNDING_ADDRESS, "02ab", "f0", 1u, 20_000uL) + record = record.copy(phase = Phase.NeedsFunding(23_000uL), funding = listOf(held)) + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf( + SparkExitFixtures.utxo("f0", 1u, 20_000uL), + SparkExitFixtures.utxo("topup", value = 3_000uL), + ) + now += interval + record = driver(tip = 1_001u).tick(record) + + assertEquals(listOf("f0", "topup"), record.funding.map { it.txid }) + assertEquals(1, record.generation, "a rebuild left out leaf-2's steps the diverged generation recovers") + assertEquals(Phase.Running, record.phase, "a funded hold still asks for fees") + assertEquals(1_000u, record.redoHeldSince) + val requests = sdk.recoverRequests.size + + record = driver(tip = 1_001u).tick(record) + assertEquals(requests, sdk.recoverRequests.size, "built again before the rebuild interval") + } + + @Test + fun `an empty prepare during a redo hold leaves the retry clock alone`() = test { + var record = divergedOverTwoLeaves() + sdk.preparedResponse = leaf2Unread + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("a1"))) + record = driver(tip = 1_000u).tick(record) + + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null, leaves = emptyList()) + .copy(skipped = leaf2Unread.skipped) + now += interval + record = driver(tip = 1_001u).tick(record) + + assertNull(record.retrySince, "the hold started the waiting leaf's retry clock") + assertEquals(1_000u, record.redoHeldSince) + assertEquals(1, record.generation) + assertTrue(record.isRebuilding) + + now += interval + val end = 1_000u + SparkExitDriver.REDO_HOLD_BLOCKS + record = driver(tip = end).tick(record) + assertEquals(end, record.retrySince, "the waiting leaf's retry clock starts once the hold ends") + } + @Test fun `a rebuild from the chain keeps its note until one of its steps confirms`() = test { val built = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) From 6e1c7a2f7535c6647f5099742ac140bc5bdc331c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 17:22:23 +0100 Subject: [PATCH 3/3] test: cover the redo hold without a tip and over a failed-only build --- .../repositories/SparkExitDriverTest.kt | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index f7099150a4..e0955829f7 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1834,6 +1834,47 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(listOf("a1"), chain.broadcasts.map { it.txid }) } + @Test + fun `a redo hold goes on uncounted while the tip cannot be read`() = test { + var record = divergedOverTwoLeaves() + sdk.preparedResponse = leaf2Unread + repeat(4) { sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("a1"))) } + + record = driver(tip = null).tick(record) + assertEquals(1, record.generation, "adopted on a tick whose tip could not be read") + assertNull(record.redoHeldSince) + + now += interval + record = driver(tip = 1_000u).tick(record) + assertEquals(1, record.generation) + assertEquals(1_000u, record.redoHeldSince) + + now += interval + record = driver(tip = null).tick(record) + assertEquals(1, record.generation, "adopted on a tick whose tip could not be read") + assertEquals(1_000u, record.redoHeldSince) + assertTrue(chain.broadcasts.isEmpty()) + } + + @Test + fun `a redo rebuild of only failed cooperative leaves beside a waiting leaf holds too`() = test { + var record = divergedOverTwoLeaves() + sdk.preparedResponse = leaf2Unread + val failed = CooperativeRecoveryFailure( + "leaf-1", + "o", + 0u, + CooperativeRecoveryError.OperatorsUnavailable("down"), + ) + sdk.builds += SparkExitFixtures.recovery(emptyList(), failed = listOf(failed)) + + record = driver(tip = 1_000u).tick(record) + + assertEquals(1, record.generation, "a failed-only rebuild left out leaf-2's steps") + assertTrue(record.isRebuilding) + assertEquals(1_000u, record.redoHeldSince) + } + @Test fun `a redo hold after a funded top-up runs at the rebuild pace`() = test { var record = divergedOverTwoLeaves()