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
32 changes: 32 additions & 0 deletions app/src/main/java/to/bitkit/repositories/LightningRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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(
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -1627,6 +1635,30 @@ class LightningRepo @Inject constructor(
}
}

private suspend fun settledSparkSendOutcome(
paymentHash: String,
key: String,
ldkRecordsBefore: Long,
): Result<PaymentId>? {
// 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()
Comment thread
ovitrif marked this conversation as resolved.
Resolved
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"))
Comment thread
ovitrif marked this conversation as resolved.
Resolved
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
Comment thread
ovitrif marked this conversation as resolved.
Resolved

private fun EarlierSend.toResult(): Result<PaymentId> = when (this) {
is EarlierSend.Pending -> Result.failure(PaymentPendingException(paymentHash))
is EarlierSend.Paid -> Result.success(paymentHash)
Expand Down
15 changes: 12 additions & 3 deletions app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
}
}
Expand Down Expand Up @@ -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,
)
}

/**
Expand Down
13 changes: 12 additions & 1 deletion app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand All @@ -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()) {
Expand Down Expand Up @@ -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"),
Expand Down
13 changes: 10 additions & 3 deletions app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment thread
ovitrif marked this conversation as resolved.
Resolved
}
Comment thread
ovitrif marked this conversation as resolved.
Resolved

/** A started exit nothing was paid into: no adopted funding, no payment from savings. */
fun isAwaitingFirstFunding(record: SparkExitRecord): Boolean =
Expand Down
3 changes: 3 additions & 0 deletions app/src/main/java/to/bitkit/repositories/SparkRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
111 changes: 110 additions & 1 deletion app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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() {
Expand Down Expand Up @@ -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<suspend () -> Boolean>(4)
Expand All @@ -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<Long>(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<suspend () -> 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<SparkError.SendRefused>(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<PaymentPendingException>(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<PaymentPendingException>(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<PaymentPendingException>(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<suspend () -> Boolean>(4)
recordSparkSend()
runSuspendCatching {
authorizeSend()
"h"
}.also { sut.payInvoiceWithNode("h").getOrThrow() }
}
whenever(sparkRepo.lightningSend("h")).thenReturn(SparkLightningSend.Found(SparkPaymentStatus.FAILED, null))

assertIs<PaymentPendingException>(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()
Expand Down
15 changes: 15 additions & 0 deletions app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
Expand Down
Loading
Loading