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
23 changes: 22 additions & 1 deletion app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -290,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)
Expand Down Expand Up @@ -340,6 +345,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)
Expand All @@ -355,6 +361,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
Comment thread
ovitrif marked this conversation as resolved.
Resolved
// 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)
Expand All @@ -365,6 +374,18 @@ class SparkExitDriver(
return broadcastReady(adopted)
}

private fun holdingRedo(record: SparkExitRecord, waiting: List<String>): 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)
// 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
Comment thread
ovitrif marked this conversation as resolved.
Resolved
return record.copy(redoHeldSince = since, lastBuildAt = nowMillis(), phase = phase)
}

private suspend fun withExitState(record: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord {
record.exitStateSnapshot?.let { snapshot ->
runSuspendCatching { sdk.importExitState(snapshot) }
Expand Down
9 changes: 9 additions & 0 deletions app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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,
/**
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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) }
Expand Down Expand Up @@ -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(),
Expand Down
210 changes: 210 additions & 0 deletions app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1761,6 +1761,170 @@ 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)
Comment thread
ovitrif marked this conversation as resolved.
Resolved
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 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()
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")))
Expand Down Expand Up @@ -2446,6 +2610,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>(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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -229,6 +230,7 @@ class SparkExitRecordTest {
"exitStateSnapshot",
"isRebuiltFromChain",
"isRedoRebuild",
"redoHeldSince",
"isFeeBumpPending",
"feeBumpBuiltAtHeight",
"earlierReceivedSats",
Expand Down
24 changes: 24 additions & 0 deletions app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
Loading