Skip to content
67 changes: 55 additions & 12 deletions app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,10 @@ class SparkExitDriver(
}
is SparkExitRecord.Phase.AwaitingFunding, is SparkExitRecord.Phase.NeedsFunding -> {
// A higher fee paid from savings: the generation out there keeps going while that payment confirms.
if (record.isDrivingWhileFunding) record = driveWhileFunding(record)
var isChecked = true
if (record.isDrivingWhileFunding) {
record = driveWhileFunding(record) ?: broadcastWithoutSdk(record).also { isChecked = false }
}
record = lookForOwnPayment(record)
val sdk = recovering
val since = record.retrySince
Expand All @@ -154,7 +157,7 @@ class SparkExitDriver(
Logger.warn("Releasing Spark exit leaves '${record.waitingLeafIds}' unfunded", context = TAG)
record = end(record.ended(), record)
} else if (sdk != null && record.phase.requiredFundingSats != null) {
record = buildOnceFunded(record, sdk)
record = buildOnceFunded(record, sdk, stored = start.recovery, isChecked = isChecked)
}
}
SparkExitRecord.Phase.Running if record.isRebuilding -> {
Expand All @@ -178,8 +181,16 @@ class SparkExitDriver(
return record
}

/** Builds once the funding [record] waits for arrived, or from what it holds when that pays for a Redo rebuild. */
private suspend fun buildOnceFunded(record: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord {
/**
* Builds once the funding [record] waits for arrived, or from what it holds when that pays for a Redo rebuild.
* [stored] is the recovery from before this tick's check, and [isChecked] says whether that check ran.
*/
private suspend fun buildOnceFunded(
record: SparkExitRecord,
sdk: SparkExitRecovering,
stored: RecoverFundsResponse?,
isChecked: Boolean,
): SparkExitRecord {
val shortfall = record.fundingShortfallSats
// Nothing to fund when every leaf is recovered cooperatively.
val funded = if (shortfall != null) adoptFunding(record, shortfall) else record
Expand All @@ -201,6 +212,28 @@ class SparkExitDriver(
// Funding an unverified rebuild asked for resumes that rebuild, with its guards, once a block like the
// check's rebuild: the valid generation's retry clock does not pace it.
funded.isUnverifiedAsk && !funded.isRebuilding -> {
// A clean check while the payment came can read the unread step again, and it is then sent: a
// rebuild now would conflict with it at the same fee. The ask ends, and the funding it adopted stays
// for a later rebuild or the leftover sweep.
val unilateral = funded.recovery?.transactions.orEmpty()
.filter { it.kind != RecoveryTxKind.COOPERATIVE }
if (unilateral.any { it.status == ExitTransactionStatus.Ready } ||
unilateral.none { it.status == ExitTransactionStatus.Unverified }
) {
Logger.info("Spark exit steps read again: no funded unverified rebuild", context = TAG)
return funded.copy(phase = SparkExitRecord.Phase.Running, isUnverifiedAsk = false)
}
// A step this check just turned unverified may have been sent on an earlier clean check: the resume
// waits for the next check, as the check's own rebuild does. A tick whose check failed never
// rebuilds, as on the check path.
if (!isChecked) return funded
val unreadBefore = stored?.transactions.orEmpty()
.filter { it.status == ExitTransactionStatus.Unverified }
.map { it.txid }
.toSet()
if (unilateral.any { it.status == ExitTransactionStatus.Unverified && it.txid !in unreadBefore }) {
return funded
}
if (tip != null && funded.unverifiedRebuiltAtHeight == tip) return funded
val resumed = funded.copy(unverifiedRebuiltAtHeight = tip)
build(resumed, sdk, isUnverifiedRebuild = true).let {
Comment thread
ovitrif marked this conversation as resolved.
Resolved
Comment thread
ovitrif marked this conversation as resolved.
Resolved
Expand Down Expand Up @@ -460,13 +493,14 @@ class SparkExitDriver(
return record.withOwnPaymentLooked(height, isKnown)
}

private suspend fun driveWhileFunding(record: SparkExitRecord): SparkExitRecord {
val sdk = recovering ?: return broadcastWithoutSdk(record)
/** Checks and sends the generation out there while its top-up confirms; null when no check ran this tick. */
private suspend fun driveWhileFunding(record: SparkExitRecord): SparkExitRecord? {
val sdk = recovering ?: return null
val stored = requireNotNull(record.recovery)
val checked = runSuspendCatching { sdk.check(withConfirmations(stored)) }
.onFailure { Logger.warn("Failed to check the Spark exit, sending without the SDK", it, context = TAG) }
.getOrNull()
?: return broadcastWithoutSdk(record)
?: return null
val updated = record.copy(recovery = checked.recovery)
return when (checked.verdict) {
RecoveryVerdict.Valid -> {
Expand Down Expand Up @@ -532,8 +566,12 @@ class SparkExitDriver(
if (sent.isFeeBumpPending && tip != null && sent.feeBumpBuiltAtHeight != tip) {
return buildFeeBump(sent, sdk)
}
if (!needsUnverifiedRebuild(sent)) return sent
// A check cannot settle a step the SDK could not read; a fresh build reads the chain again.
// A check marks a step unverified when one chain read fails and clears it on the next clean check, so
// only steps that were all unverified before this check are rebuilt over: one this check just turned
// unverified may be in flight, and holds the rebuild as a ready one does. A step that stays unread is
// rebuilt at the first check, at most once a block, where no other step just turned unverified.
if (!needsUnverifiedRebuild(sent, stored)) return sent
// A step that stays unread past a check is settled by a fresh build, which reads the chain again.
Logger.info("Rebuilding Spark exit over steps the SDK could not read", context = TAG)
val rebuilding = sent.copy(isRebuilding = true, unverifiedRebuiltAtHeight = tip, isRedoRebuild = false)
// Saved as the valid generation: a run killed during the rebuild goes on sending it.
Expand Down Expand Up @@ -794,11 +832,16 @@ class SparkExitDriver(
isRebuilding && phase == SparkExitRecord.Phase.Running && generation == before.generation &&
lostLeaves == before.lostLeaves

private fun needsUnverifiedRebuild(record: SparkExitRecord): Boolean {
private fun needsUnverifiedRebuild(record: SparkExitRecord, stored: RecoverFundsResponse): Boolean {
val height = tip ?: return false
if (record.unverifiedRebuiltAtHeight == height) return false
val unreadBefore = stored.transactions
.filter { it.status == ExitTransactionStatus.Unverified }
.map { it.txid }
.toSet()
val transactions = record.recovery?.transactions.orEmpty().filter { it.kind != RecoveryTxKind.COOPERATIVE }
return transactions.any { it.status == ExitTransactionStatus.Unverified } &&
val unread = transactions.filter { it.status == ExitTransactionStatus.Unverified }
return unread.isNotEmpty() && unread.all { it.txid in unreadBefore } &&
transactions.none { it.status == ExitTransactionStatus.Ready }
Comment thread
ovitrif marked this conversation as resolved.
Resolved
}

Expand Down Expand Up @@ -1174,7 +1217,7 @@ class SparkExitDriver(
var current = record
val recovery = current.recovery ?: return current
// A cooperative step the SDK could not read goes out too: nodes refuse it if its funds already moved. A
// unilateral one waits for a rebuild.
// unilateral one waits for the next clean check, or a rebuild once it stays unread.
recovery.transactions
.filter { it.status == ExitTransactionStatus.Ready || it.isCooperativeUnverified }
.filter { isDue(it.txid, current) }
Expand Down
155 changes: 155 additions & 0 deletions app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,76 @@ class SparkExitDriverTest : BaseUnitTest() {
assertEquals(1, sdk.recoverRequests.size)
}

@Test
fun `a step one failed read turns unverified waits for the next check instead of rebuilding`() = test {
val ready = SparkExitFixtures.recovery(
listOf(
SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)),
SparkExitFixtures.tx("n2", cpfp = "03c2", dependsOn = listOf("n1")),
),
)
val unverified = SparkExitFixtures.recovery(
listOf(
SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)),
SparkExitFixtures.tx(
"n2",
cpfp = "03c2",
dependsOn = listOf("n1"),
status = ExitTransactionStatus.Unverified,
),
),
)
repeat(2) { sdk.checks += check(unverified, RecoveryVerdict.Valid) }
sdk.builds += SparkExitFixtures.recovery(
listOf(
SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)),
SparkExitFixtures.tx("n2b", cpfp = "03c3", dependsOn = listOf("n1")),
),
)

var record = driver(tip = 1_000u).tick(running(ready))

assertTrue(sdk.recoverRequests.isEmpty(), "rebuilt over a step one failed read turned unverified")
assertNull(record.unverifiedRebuiltAtHeight)
assertFalse(record.isUnverifiedAsk)
assertEquals(1, record.generation)
assertTrue(chain.broadcasts.none { it.txid == "n2" })

// Still unread at the next check: now it rebuilds.
record = driver(tip = 1_000u).tick(record)

assertEquals(1, sdk.recoverRequests.size)
assertEquals(1_000u, record.unverifiedRebuiltAtHeight)
assertEquals(2, record.generation)
}

@Test
fun `a step one failed read turns unverified holds the rebuild over another leaf's unread step`() = test {
val stored = SparkExitFixtures.recovery(
listOf(
SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)),
SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified),
SparkExitFixtures.tx("m1", status = ExitTransactionStatus.Confirmed(900u)),
SparkExitFixtures.tx("m2", dependsOn = listOf("m1")),
),
)
val checked = SparkExitFixtures.recovery(
listOf(
SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)),
SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified),
SparkExitFixtures.tx("m1", status = ExitTransactionStatus.Confirmed(900u)),
SparkExitFixtures.tx("m2", dependsOn = listOf("m1"), status = ExitTransactionStatus.Unverified),
),
)
sdk.checks += check(checked, RecoveryVerdict.Valid)

val record = driver(tip = 1_000u).tick(running(stored))

assertTrue(sdk.recoverRequests.isEmpty(), "rebuilt over m2, which one failed read turned unverified")
assertNull(record.unverifiedRebuiltAtHeight)
assertEquals(1, record.generation)
}

@Test
fun `an unverified rebuild that adopts nothing keeps checking and sending the valid generation`() = test {
val unverified = SparkExitFixtures.recovery(
Expand Down Expand Up @@ -493,6 +563,91 @@ class SparkExitDriverTest : BaseUnitTest() {
assertEquals(unverified.transactions.map { it.txid }, record.recovery?.transactions?.map { it.txid })
}

@Test
fun `a funded unverified ask whose step reads again ends without a rebuild`() = test {
val unread = SparkExitFixtures.recovery(
listOf(
SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)),
SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified),
),
)
val ready = SparkExitFixtures.recovery(
listOf(
SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)),
SparkExitFixtures.tx("n2", dependsOn = listOf("n1")),
),
)
repeat(2) { sdk.checks += check(unread, RecoveryVerdict.Valid) }
sdk.checks += check(ready, RecoveryVerdict.Valid)
sdk.recoverErrors += SdkException.InsufficientCpfpFunds(30_000uL, "")
sdk.preparedResponses += SparkExitFixtures.prepared()

var record = driver(tip = 1_000u).tick(running(unread))
record = driver(tip = 1_000u).tick(record)
assertIs<Phase.NeedsFunding>(record.phase)
assertTrue(record.isUnverifiedAsk)
val builds = sdk.recoverRequests.size

// A savings payment keeps the ask open; it confirms on the tick whose check reads n2 again.
chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] =
listOf(SparkExitFixtures.utxo("paid", value = 100_000uL))
record = driver(tip = 1_001u).tick(record.copy(fundingPaymentTxid = "paid"))

assertEquals(builds, sdk.recoverRequests.size, "rebuilt over n2, which the clean check made ready and sent")
assertEquals(listOf("n2"), chain.broadcasts.map { it.txid })
assertEquals(Phase.Running, record.phase)
assertFalse(record.isUnverifiedAsk)
assertEquals(1, record.generation)
}

@Test
fun `a funded unverified ask holds its rebuild over a step sent on an earlier clean check`() = test {
Comment thread
ovitrif marked this conversation as resolved.
Resolved
val unread = SparkExitFixtures.recovery(
listOf(
SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)),
SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified),
),
)
val ready = SparkExitFixtures.recovery(
listOf(
SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)),
SparkExitFixtures.tx("n2", dependsOn = listOf("n1")),
),
)
repeat(2) { sdk.checks += check(unread, RecoveryVerdict.Valid) }
sdk.checks += check(ready, RecoveryVerdict.Valid)
sdk.checks += check(unread, RecoveryVerdict.Valid)
sdk.recoverErrors += SdkException.InsufficientCpfpFunds(30_000uL, "")
sdk.preparedResponses += SparkExitFixtures.prepared()

var record = driver(tip = 1_000u).tick(running(unread))
record = driver(tip = 1_000u).tick(record)
val builds = sdk.recoverRequests.size

// The payment is unconfirmed while a clean check sends n2, so the ask stays open.
chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] =
listOf(SparkExitFixtures.utxo("paid", value = 100_000uL, confirmed = false))
record = driver(tip = 1_000u).tick(record.copy(fundingPaymentTxid = "paid"))
assertEquals(listOf("n2"), chain.broadcasts.map { it.txid })
assertTrue(record.isUnverifiedAsk)

// It confirms on the tick whose check fails to read n2.
chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] =
listOf(SparkExitFixtures.utxo("paid", value = 100_000uL))
record = driver(tip = 1_001u).tick(record)

assertTrue(record.funding.any { it.txid == "paid" }, "the payment was not adopted, so the hold never ran")
assertEquals(builds, sdk.recoverRequests.size, "rebuilt over n2, sent on the previous tick")
assertTrue(record.isUnverifiedAsk)
assertEquals(1, record.generation)

// A next tick whose check fails reads nothing, so it does not rebuild either.
sdk.recoverErrors += SdkException.InsufficientCpfpFunds(30_000uL, "")
record = driver(tip = 1_001u).tick(record)
assertEquals(builds, sdk.recoverRequests.size, "rebuilt over n2 with no second check")
assertTrue(record.isUnverifiedAsk)
}

@Test
fun `a funded unverified rebuild that waits for the unread leaf leaves no stale retry clock`() = test {
val unread = SparkExitFixtures.recovery(
Expand Down
Loading