diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 1166d35165..351f0ac8b0 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -104,6 +104,7 @@ import to.bitkit.services.LnurlService import to.bitkit.services.LnurlWithdrawResponse import to.bitkit.services.NetworkGraphInfo import to.bitkit.services.NodeEventHandler +import to.bitkit.services.SparkError import to.bitkit.utils.AppError import to.bitkit.utils.Logger import to.bitkit.utils.ServiceError @@ -122,6 +123,7 @@ import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.ExperimentalTime import kotlin.time.Instant +import breez_sdk_spark.PaymentStatus as SparkPaymentStatus @Singleton class LightningRepo @Inject constructor( @@ -1563,6 +1565,12 @@ class LightningRepo @Inject constructor( railBefore?.let { rail -> recordSendRail(key, rail) } ?: sendRails.remove(key) } } + .let { + // Refused for a Spark send recorded since the checks, whose completion its caller may miss. + val isOverlapped = isRefused && sparkRepo.hasRecordedSendSince(sparkRecordsBefore, paymentHash) + if (!isOverlapped) return@let it + settledSparkSendOutcome(paymentHash ?: key, key, ldkRecordsBefore) ?: it + } } finally { if (isAdmitted) releaseSend(key) } @@ -1627,6 +1635,30 @@ class LightningRepo @Inject constructor( } } + private suspend fun settledSparkSendOutcome( + paymentHash: String, + key: String, + ldkRecordsBefore: Long, + ): Result? { + // Read before the row too, so a send that ends while it is read still counts as live. + val wasLive = isSendLive(paymentHash, key, ldkRecordsBefore) + val sparkRecordsBefore = sparkRepo.sendRecordMark() + val send = sparkRepo.lightningSend(paymentHash) as? SparkLightningSend.Found ?: return null + val isLive = wasLive || isSendLive(paymentHash, key, ldkRecordsBefore) || + sparkRepo.hasRecordedSendSince(sparkRecordsBefore, paymentHash) + return when (send.status) { + SparkPaymentStatus.COMPLETED -> Result.success(paymentHash) + // A failed row can be an earlier attempt's while a retry of the invoice on either rail can still pay it. + SparkPaymentStatus.FAILED if isLive -> null + SparkPaymentStatus.FAILED -> Result.failure(SparkError.SendRefused("Spark's earlier send of it failed")) + SparkPaymentStatus.PENDING -> null + }?.also { Logger.info("Settled the refused Spark send '$paymentHash' as '${send.status}'", context = TAG) } + } + + private fun isSendLive(paymentHash: String, key: String, ldkRecordsBefore: Long): Boolean = + sparkRepo.isSendInFlight(paymentHash) || synchronized(admittedSends) { admittedSends[key] != null } || + (ldkSendRecordedAt[key] ?: 0L) > ldkRecordsBefore + private fun EarlierSend.toResult(): Result = when (this) { is EarlierSend.Pending -> Result.failure(PaymentPendingException(paymentHash)) is EarlierSend.Paid -> Result.success(paymentHash) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 94f65563d1..debd65d5a6 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -135,7 +135,12 @@ class SparkExitDriver( } suspend fun tick(start: SparkExitRecord): SparkExitRecord { - var record = start + // A Redo's fee ask ended on an earlier tick, so its withdrawal was already seen. + var record = if (start.isRedoAsk && start.phase !is SparkExitRecord.Phase.NeedsFunding) { + start.copy(isRedoAsk = false) + } else { + start + } when (record.phase) { SparkExitRecord.Phase.Done, is SparkExitRecord.Phase.Failed -> { if (!record.isLeftoverSweepPending && !record.isEndedPaymentPending) return record @@ -548,7 +553,7 @@ class SparkExitDriver( // for. is RecoveryVerdict.Redo -> { Logger.warn("Spark exit diverged on-chain while a top-up is awaited", context = TAG) - updated.copy(isRebuilding = true, isRedoRebuild = true, isUnverifiedAsk = false) + updated.copy(isRebuilding = true, isRedoRebuild = true, isUnverifiedAsk = false, isRedoAsk = true) } } } @@ -754,7 +759,11 @@ class SparkExitDriver( if (held == null && record.fundedSats > 0uL) return record val inputFee = SparkExitMath.inputFeeSats(record.feeRateSatPerVbyte) val needed = SparkExitMath.neededFunding(error.requiredSats, record.fundedSats, held, inputFee) - return record.copy(phase = SparkExitRecord.Phase.NeedsFunding(needed)) + // A Redo rebuild's ask ends once the funding it holds pays for a later build. + return record.copy( + phase = SparkExitRecord.Phase.NeedsFunding(needed), + isRedoAsk = record.isRedoAsk || record.isRedoRebuild, + ) } /** diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index eef2309ff3..ce396a8bc3 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -124,6 +124,11 @@ data class SparkExitRecord( 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, + /** + * A Redo verdict came while the exit asked for fee funding: the Redo rebuild may run on the funding it holds, and + * the ask then ends. Kept until a tick starts past that ask. + */ + val isRedoAsk: Boolean = false, /** * A higher fee rate the steps out there are not built at yet: a fee bump whose build kept the valid generation over * a leaf it would leave waiting. Built at that rate again until a build at it is adopted. @@ -955,6 +960,11 @@ object SparkExitJson { r.feeBumpBuiltAtHeight?.let { put("feeBumpBuiltAtHeight", it.toLong()) } } + private fun JsonObjectBuilder.putAskState(r: SparkExitRecord) { + if (r.isUnverifiedAsk) put("isUnverifiedAsk", true) + if (r.isRedoAsk) put("isRedoAsk", true) + } + /** What the exit keeps to pace and bound its rebuilds and waits, each left out at its default. */ private fun JsonObjectBuilder.putRebuildState(r: SparkExitRecord) { if (r.stallRebuilds > 0) put("stallRebuilds", r.stallRebuilds) @@ -975,7 +985,7 @@ object SparkExitJson { 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) + putAskState(r) putFeeBumpState(r) r.fundingStrategy?.let { put("fundingStrategy", it) } if (r.failedLeaves.isNotEmpty()) { @@ -1118,6 +1128,7 @@ object SparkExitJson { isRedoRebuild = o.booleanOrNull("isRedoRebuild") ?: false, redoHeldSince = o.ulongOrNull("redoHeldSince")?.toUInt(), isUnverifiedAsk = o.booleanOrNull("isUnverifiedAsk") ?: false, + isRedoAsk = o.booleanOrNull("isRedoAsk") ?: false, isFeeBumpPending = o.booleanOrNull("isFeeBumpPending") ?: false, feeBumpBuiltAtHeight = o.ulongOrNull("feeBumpBuiltAtHeight")?.toUInt(), fundingStrategy = o.stringOrNull("fundingStrategy"), diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt index 7afb717d83..c1c18c6bde 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt @@ -393,10 +393,17 @@ object SparkExitAlerts { previous.isAwaitingOwnPayment && !record.isAwaitingOwnPayment && record.fundingShortfallSats != null && record.fundingPaymentTxid == null - /** An unverified rebuild's fee ask the tick from [previous] withdrew: the valid generation needs nothing more. */ - fun isFundingAskWithdrawn(record: SparkExitRecord, previous: SparkExitRecord): Boolean = - previous.isUnverifiedAsk && previous.phase is SparkExitRecord.Phase.NeedsFunding && + /** + * A fee ask the tick from [previous] withdrew: an unverified rebuild's, as the valid generation needs nothing more, + * or one of a Redo rebuild, asked before or during it, that runs with no new funding, on the Redo's tick or a later + * one, as the held funding pays for it. + */ + fun isFundingAskWithdrawn(record: SparkExitRecord, previous: SparkExitRecord): Boolean { + val isRedoAsk = (previous.isRedoAsk || record.isRedoAsk || previous.isRedoRebuild) && + record.funding == previous.funding + return (previous.isUnverifiedAsk || isRedoAsk) && previous.phase is SparkExitRecord.Phase.NeedsFunding && record.phase == SparkExitRecord.Phase.Running + } /** A started exit nothing was paid into: no adopted funding, no payment from savings. */ fun isAwaitingFirstFunding(record: SparkExitRecord): Boolean = diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 5c1bfc06cf..46b0f18962 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1488,6 +1488,9 @@ class SparkRepo @Inject constructor( private fun ULong.toEpochSeconds(): Long = coerceAtMost(Long.MAX_VALUE.toULong()).toLong() + /** Whether a Spark send of [paymentHash] is inside its send call, before or after its records are written. */ + fun isSendInFlight(paymentHash: String): Boolean = sendsInFlight.containsKey(paymentHash.lowercase()) + /** The count of sends recorded so far, read before a node send's checks for [hasRecordedSendSince]. */ fun sendRecordMark(): Long = sendRecords.get() diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 242e68ef88..39038dcdd1 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -99,6 +99,7 @@ import to.bitkit.services.LightningService import to.bitkit.services.LnurlService import to.bitkit.services.NetworkGraphInfo import to.bitkit.services.NodeEventHandler +import to.bitkit.services.SparkError import to.bitkit.services.SparkService import to.bitkit.test.BaseUnitTest import to.bitkit.test.InMemoryDataStore @@ -121,6 +122,7 @@ import kotlin.time.Clock import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant +import breez_sdk_spark.PaymentStatus as SparkPaymentStatus @OptIn(kotlin.time.ExperimentalTime::class, ExperimentalCoroutinesApi::class) class LightningRepoTest : BaseUnitTest() { @@ -1656,8 +1658,9 @@ class LightningRepoTest : BaseUnitTest() { startNodeForTesting() whenever(lightningService.listPayments()).thenReturn(emptyList()) whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) - // An earlier Spark send of the invoice was recorded and ended after this send's checks passed. + // An earlier Spark send of the invoice was recorded after this send's checks passed, and is still pending. whenever(sparkRepo.hasRecordedSendSince(any(), anyOrNull())).thenReturn(true) + whenever(sparkRepo.lightningSend("h")).thenReturn(SparkLightningSend.Found(SparkPaymentStatus.PENDING, null)) var isSent = false whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())).doSuspendableAnswer { val authorizeSend = it.getArgument Boolean>(4) @@ -1673,6 +1676,112 @@ class LightningRepoTest : BaseUnitTest() { assertFalse(isSent) } + private var sparkRecords = 0L + private var sparkSendRecordedAt = 0L + + /** Spark's send records, where [recordSparkSend] records a send of the invoice after the marks read so far. */ + private fun stubSparkSendRecords() { + whenever(sparkRepo.sendRecordMark()).thenAnswer { sparkRecords } + whenever(sparkRepo.hasRecordedSendSince(any(), anyOrNull())).thenAnswer { + sparkSendRecordedAt > it.getArgument(0) + } + } + + private fun recordSparkSend() { + sparkSendRecordedAt = ++sparkRecords + } + + /** Spark's send, refused at admission as an earlier Spark send of the invoice was recorded since its checks. */ + private suspend fun stubSparkSendRefusedForARecordedOne() { + stubSparkSendRecords() + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())).doSuspendableAnswer { + val authorizeSend = it.getArgument Boolean>(4) + recordSparkSend() + runSuspendCatching { + authorizeSend() + "h" + } + } + } + + @Test + fun `a spark send refused for an earlier spark send that settled first returns its outcome`() = test { + startNodeForTesting() + whenever(lightningService.listPayments()).thenReturn(emptyList()) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + // The earlier Spark send of the invoice was recorded after this send's checks passed, and completed first. + stubSparkSendRefusedForARecordedOne() + whenever(sparkRepo.lightningSend("h")).thenReturn(SparkLightningSend.Found(SparkPaymentStatus.COMPLETED, "p")) + + assertEquals("h", sut.payInvoice("h", 1_000uL).getOrThrow(), "a paid send left its caller pending") + + whenever(sparkRepo.lightningSend("h")).thenReturn(SparkLightningSend.Found(SparkPaymentStatus.FAILED, null)) + + assertIs(sut.payInvoice("h", 1_000uL).exceptionOrNull()) + } + + @Test + fun `a spark send refused over a failed spark row stays pending while a spark retry is in flight`() = test { + startNodeForTesting() + whenever(lightningService.listPayments()).thenReturn(emptyList()) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + stubSparkSendRefusedForARecordedOne() + // A retry recorded since the checks is still inside its send call, over an earlier attempt's failed row. + whenever(sparkRepo.lightningSend("h")).thenReturn(SparkLightningSend.Found(SparkPaymentStatus.FAILED, null)) + whenever(sparkRepo.isSendInFlight("h")).thenReturn(true) + + assertIs(sut.payInvoice("h", 1_000uL).exceptionOrNull()) + } + + @Test + fun `a spark send refused over a failed spark row stays pending when a send ends or starts during its read`() = + test { + startNodeForTesting() + whenever(lightningService.listPayments()).thenReturn(emptyList()) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + stubSparkSendRefusedForARecordedOne() + var isInFlight = true + whenever(sparkRepo.isSendInFlight("h")).thenAnswer { isInFlight } + // The competing retry completes and is released while the older attempt's failed row is read. + whenever(sparkRepo.lightningSend("h")).doSuspendableAnswer { + isInFlight = false + SparkLightningSend.Found(SparkPaymentStatus.FAILED, null) + } + + assertIs(sut.payInvoice("h", 1_000uL).exceptionOrNull(), "a send that ended") + + // Another retry starts and ends while the row is read. + whenever(sparkRepo.lightningSend("h")).doSuspendableAnswer { + recordSparkSend() + SparkLightningSend.Found(SparkPaymentStatus.FAILED, null) + } + + assertIs(sut.payInvoice("h", 1_000uL).exceptionOrNull(), "a send that started") + } + + @Test + fun `a spark send refused over a failed spark row stays pending once the node sent the invoice`() = test { + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn("h") + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + stubSparkSendRecords() + // Refused for a failed Spark send recorded since the checks, while the node's retry of the invoice is sent. + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())).doSuspendableAnswer { + val authorizeSend = it.getArgument Boolean>(4) + recordSparkSend() + runSuspendCatching { + authorizeSend() + "h" + }.also { sut.payInvoiceWithNode("h").getOrThrow() } + } + whenever(sparkRepo.lightningSend("h")).thenReturn(SparkLightningSend.Found(SparkPaymentStatus.FAILED, null)) + + assertIs(sut.payInvoice("h", 1_000uL).exceptionOrNull()) + verify(lightningService).send(any(), anyOrNull(), anyOrNull(), anyOrNull()) + } + @Test fun `a spark send of an invoice the node already paid settles as paid`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt index 765ab54987..2edfc0e554 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt @@ -82,6 +82,21 @@ class SparkExitAlertsTest { assertFalse(SparkExitAlerts.isFundingAskWithdrawn(asked, asked)) } + @Test + fun `a fee ask a redo came during is withdrawn once it runs on the held funding`() { + val held = SparkExitRecord.Funding(0u, SparkExitFixtures.FUNDING_ADDRESS, "02ab", "f0", 1u, 20_000uL) + val asked = SparkExitFixtures.record(Phase.NeedsFunding(5_000uL)).copy(funding = listOf(held)) + val redo = asked.copy(isRedoAsk = true) + val running = asked.copy(phase = Phase.Running, isRedoAsk = true) + val topUp = running.copy(funding = listOf(held, held.copy(txid = "topup", valueSats = 5_000uL))) + + // On the Redo's own tick only the record after it carries the flag; on a later tick both do. + assertTrue(SparkExitAlerts.isFundingAskWithdrawn(running, asked)) + assertTrue(SparkExitAlerts.isFundingAskWithdrawn(running, redo)) + assertFalse(SparkExitAlerts.isFundingAskWithdrawn(topUp, redo), "a top-up answered the ask") + assertFalse(SparkExitAlerts.isFundingAskWithdrawn(running.copy(isRedoAsk = false), asked)) + } + @Test fun `posts each lost leaf event, and a failure unless every leaf was lost`() { val lost = running.copy(lostLeaves = listOf(SparkExitRecord.LostLeaf("leaf-1", 16_384uL))) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index dd3eec2471..c9b6a95d4b 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1911,17 +1911,129 @@ class SparkExitDriverTest : BaseUnitTest() { 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)) + val asked = record.copy(phase = Phase.NeedsFunding(23_000uL), funding = listOf(held)) chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("f0", 1u, 20_000uL)) + // The rebuild needs fee funding, which the held input pays. + sdk.preparedResponse = leaf2Unread.copy(funding = SparkExitFixtures.prepared().funding) val requests = sdk.recoverRequests.size now += interval - record = driver(tip = 1_001u).tick(record) + record = driver(tip = 1_001u).tick(asked) assertEquals(requests + 1, sdk.recoverRequests.size, "the held funding did not build the rebuild") + assertEquals( + listOf(CpfpInput.P2wpkh("f0", 1u, 20_000uL, "02ab")), + sdk.recoverRequests.last().fundingInputs, + ) assertEquals(1, record.generation, "a rebuild left out leaf-2's steps the diverged generation recovers") assertEquals(Phase.Running, record.phase, "a hold the held funding paid for still asks for fees") assertNull(record.fundingShortfallSats) assertEquals(1_000u, record.redoHeldSince) + assertTrue(SparkExitAlerts.isFundingAskWithdrawn(record, asked), "the fee ask's notification stayed") + + // A later build of the hold that comes up short asks again. + sdk.recoverErrors += SdkException.InsufficientCpfpFunds(30_000uL, "") + now += interval + record = driver(tip = 1_002u).tick(record) + + assertIs(record.phase) + assertEquals(1, record.generation) + } + + /** A generation asking for fee funding while it keeps going, holding 20,000 sats, whose next check returns Redo. */ + private fun askingWhenRedoCame(builtAt: Long): SparkExitRecord { + val old = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))) + sdk.checks += check(old, redo) + val held = SparkExitRecord.Funding(0u, SparkExitFixtures.FUNDING_ADDRESS, "02ab", "f0", 1u, 20_000uL) + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("f0", 1u, 20_000uL)) + val asked = running(old, builtAt).copy(phase = Phase.NeedsFunding(23_000uL), funding = listOf(held)) + assertTrue(asked.isDrivingWhileFunding) + return asked + } + + @Test + fun `a redo on a fee ask built from the held funding that tick withdraws the ask`() = test { + val asked = askingWhenRedoCame(builtAt = now - interval) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("a1"))) + + val record = driver(tip = 1_000u).tick(asked) + + assertEquals(2, record.generation, "the held funding did not build the Redo rebuild") + assertEquals(Phase.Running, record.phase) + assertTrue(SparkExitAlerts.isFundingAskWithdrawn(record, asked), "the fee ask's notification stayed") + } + + @Test + fun `a redo on a fee ask built from the held funding a later tick withdraws the ask`() = test { + val asked = askingWhenRedoCame(builtAt = now) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("a1"))) + + val redone = driver(tip = 1_000u).tick(asked) + assertIs(redone.phase, "built before the rebuild interval") + assertFalse(SparkExitAlerts.isFundingAskWithdrawn(redone, asked)) + + now += interval + val record = driver(tip = 1_001u).tick(redone) + + assertEquals(2, record.generation) + assertEquals(Phase.Running, record.phase) + assertTrue(SparkExitAlerts.isFundingAskWithdrawn(record, redone), "the fee ask's notification stayed") + sdk.checks += check(requireNotNull(record.recovery), RecoveryVerdict.Valid) + assertFalse(driver(tip = 1_001u).tick(record).isRedoAsk, "the ended ask stayed marked") + } + + @Test + fun `a redo hold's own short build asks, and a later build on the held funding withdraws the ask`() = test { + var record = divergedOverTwoLeaves() + sdk.preparedResponse = leaf2Unread + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("a1"))) + record = driver(tip = 1_000u).tick(record) + assertEquals(Phase.Running, record.phase) + assertEquals(1_000u, record.redoHeldSince) + + val held = SparkExitRecord.Funding(0u, SparkExitFixtures.FUNDING_ADDRESS, "02ab", "f0", 1u, 20_000uL) + record = record.copy(funding = listOf(held)) + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("f0", 1u, 20_000uL)) + sdk.recoverErrors += SdkException.InsufficientCpfpFunds(30_000uL, "") + now += interval + val asked = driver(tip = 1_001u).tick(record) + assertIs(asked.phase, "the hold's short build did not ask") + + // The next build needs less, which the held funding pays. + sdk.preparedResponse = leaf2Unread.copy(funding = SparkExitFixtures.prepared().funding) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("a1"))) + now += interval + record = driver(tip = 1_002u).tick(asked) + + assertEquals(Phase.Running, record.phase) + assertEquals(1, record.generation) + assertEquals(asked.funding, record.funding) + assertTrue(SparkExitAlerts.isFundingAskWithdrawn(record, asked), "the fee ask's notification stayed") + } + + @Test + fun `a redo hold of only failed cooperative leaves drops the fee ask the held funding pays`() = test { + var record = divergedOverTwoLeaves() + sdk.preparedResponse = leaf2Unread + 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) + val asked = record.copy(phase = Phase.NeedsFunding(23_000uL), funding = listOf(held)) + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("f0", 1u, 20_000uL)) + val failed = CooperativeRecoveryFailure( + "leaf-1", + "o", + 0u, + CooperativeRecoveryError.OperatorsUnavailable("down"), + ) + sdk.builds += SparkExitFixtures.recovery(emptyList(), failed = listOf(failed)) + now += interval + record = driver(tip = 1_001u).tick(asked) + + assertEquals(1, record.generation, "a failed-only rebuild left out leaf-2's steps") + assertEquals(Phase.Running, record.phase, "a failed-only hold the held funding paid for still asks for fees") + assertEquals(1_000u, record.redoHeldSince) } @Test diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index b5b19d1d12..9e23e0fc55 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -648,6 +648,32 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) } + @Test + fun `a spark retry paused before its journal writes reads as in flight over an older failed row`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.listPayments() } + .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) + val journaling = CompletableDeferred() + whenever { cacheStore.addSparkSendHash(any(), anyOrNull()) }.doSuspendableAnswer { journaling.await() } + val sut = createSut() + sut.start(0).getOrThrow() + val mark = sut.sendRecordMark() + + val retry = async { sut.payInvoice("lnbc1280n1send", 128uL) } + runCurrent() + + // Recorded, but its journal is not written yet, so Spark's list still reads the older attempt's failure. + assertTrue(sut.hasRecordedSendSince(mark, "hash")) + assertEquals(PaymentStatus.FAILED, assertIs(sut.lightningSend("hash")).status) + assertTrue(sut.isSendInFlight("hash"), "a paused retry read as settled") + journaling.complete(Unit) + assertEquals("hash", retry.await().getOrThrow()) + assertFalse(sut.isSendInFlight("hash")) + } + @Test fun `a readable history without a live attempt lets the node pay a recorded invoice`() = test { cacheData.value = AppCacheData(sparkSendHashes = listOf("hash"))