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
13 changes: 8 additions & 5 deletions app/src/main/java/to/bitkit/repositories/LightningRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1519,8 +1519,9 @@ class LightningRepo @Inject constructor(
if (shouldPayWithSpark(bolt11, sats)) {
runCatching { requireWalletRestoreComplete() }.onFailure { return Result.failure(it) }
val key = ldkSendKey(bolt11, paymentHash)
// Read before the checks, so a node send admitted after them refuses this one at submission.
// Read before the checks, so a send of either rail recorded after them refuses this one at submission.
val ldkRecordsBefore = ldkSendRecords.get()
val sparkRecordsBefore = sparkRepo.sendRecordMark()
runSuspendCatching { earlierNodeSend(bolt11, paymentHash) }
.getOrElse { return Result.failure(it) }
?.let {
Expand All @@ -1535,7 +1536,8 @@ class LightningRepo @Inject constructor(
val isAuthorized = onBeforeSend().also { if (it) requireWalletRestoreComplete() }
if (isAuthorized) {
isAdmitted = admitSend(key, LightningRail.Spark) {
(ldkSendRecordedAt[key] ?: 0L) > ldkRecordsBefore
(ldkSendRecordedAt[key] ?: 0L) > ldkRecordsBefore ||
sparkRepo.hasRecordedSendSince(sparkRecordsBefore, paymentHash)
}
isRefused = !isAdmitted
if (isRefused) throw PaymentPendingException(paymentHash ?: key)
Comment thread
ovitrif marked this conversation as resolved.
Resolved
Expand Down Expand Up @@ -1695,12 +1697,13 @@ class LightningRepo @Inject constructor(

/**
* The last check before a send of [key] leaves on [rail], so of two sends of one invoice only the first admitted
* goes out: refused while the other rail holds one, or [isSentOnOtherRail] says it recorded one since the checks.
* goes out: refused while the other rail holds one, or Spark does, as it doesn't refuse a repeat, or
* [isSentSinceChecks] says a send was recorded since the checks. The node refuses its own repeats.
*/
private fun admitSend(key: String, rail: LightningRail, isSentOnOtherRail: () -> Boolean): Boolean =
private fun admitSend(key: String, rail: LightningRail, isSentSinceChecks: () -> Boolean): Boolean =
synchronized(admittedSends) {
val held = admittedSends[key]
val isFree = (held == null || held.first == rail) && !isSentOnOtherRail()
val isFree = (held == null || held.first == rail && rail == LightningRail.Ldk) && !isSentSinceChecks()
if (isFree) admittedSends[key] = rail to (held?.second ?: 0) + 1
isFree
}
Expand Down
15 changes: 10 additions & 5 deletions app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +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 }
holdingRedo(record, waiting, isBuilt = true)?.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 @@ -363,7 +363,7 @@ class SparkExitDriver(
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 }
holdingRedo(record, waiting, isBuilt = true)?.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 @@ -374,15 +374,20 @@ class SparkExitDriver(
return broadcastReady(adopted)
}

private fun holdingRedo(record: SparkExitRecord, waiting: List<String>): SparkExitRecord? {
private fun holdingRedo(
record: SparkExitRecord,
waiting: List<String>,
isBuilt: Boolean = false,
): 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
// A build the held funding paid for, or funding a top-up already covered, runs the hold at the rebuild pace,
// with no fee ask on screen; a later build that is short asks again.
val phase = if (isBuilt || record.fundingShortfallSats == null) SparkExitRecord.Phase.Running else record.phase
return record.copy(redoHeldSince = since, lastBuildAt = nowMillis(), phase = phase)
}

Expand Down
12 changes: 6 additions & 6 deletions app/src/main/java/to/bitkit/repositories/SparkRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1469,16 +1469,16 @@ class SparkRepo @Inject constructor(

/**
* Whether the Spark operators confirm this wallet never sent [bolt11] over Lightning, and it can't have been paid
* by a direct Spark transfer, which they don't see: false when they show a send, completed, pending or failed, or
* can't be asked.
* by a direct Spark transfer, which they don't see: false when they show a send completed or pending, or can't be
* asked. A failed one counts as unsent, as they show it failed only once every attempt at the hash was returned.
*/
private suspend fun isUnsentPerOperators(bolt11: String): Boolean {
if (!sparkService.isConnected) return false
val status = runSuspendCatching { sparkService.lightningSendStatus(bolt11) }
.onFailure { Logger.warn("Failed to fetch Spark's send status", it, context = TAG) }
.getOrElse { return false }
if (status != null) {
Logger.info("Spark's operators show a '$status' send of the pre-restore invoice", context = TAG)
if (status != null && status != PaymentStatus.FAILED) {
Logger.info("Found a '$status' Spark operator send of the pre-restore invoice", context = TAG)
return false
}
// A send preferring Spark pays an invoice's Spark address as a direct transfer.
Expand Down Expand Up @@ -1567,8 +1567,8 @@ class SparkRepo @Inject constructor(
}

/**
* Seeds the restored send hashes from Spark's list once it has synced. This ends only the wait for Spark's first
* listing: an older invoice Spark hasn't listed stays refused until it expires.
* Seeds the restored send hashes from Spark's list once it has synced. An older invoice Spark hasn't listed is
* still refused until the Spark operators show it unsent or failed, or it expires.
*/
private suspend fun seedRestoredSendHashes() {
if (cacheStore.data.first().sparkHistoryUnseededSince == null || !canListPayments()) return
Expand Down
51 changes: 51 additions & 0 deletions app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ import to.bitkit.data.keychain.Keychain
import to.bitkit.data.keychain.WalletBackupRestorePendingError
import to.bitkit.ext.createChannelDetails
import to.bitkit.ext.of
import to.bitkit.ext.runSuspendCatching
import to.bitkit.models.ActiveOnchainAttemptBackup
import to.bitkit.models.CoinSelectionPreference
import to.bitkit.models.ElectrumServer
Expand Down Expand Up @@ -1622,6 +1623,56 @@ class LightningRepoTest : BaseUnitTest() {
verify(lightningService, never()).send(any(), anyOrNull(), anyOrNull(), anyOrNull())
}

@Test
fun `of two overlapping spark sends of one invoice only one reaches spark`() = test {
startNodeForTesting()
whenever(lightningService.listPayments()).thenReturn(emptyList())
whenever(sparkRepo.canSend(1_000uL)).thenReturn(true)
var sends = 0
var isOverlapped = false
var overlapping: Result<PaymentId>? = null
// A second send of the same invoice passes its checks while the first is being sent.
whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())).doSuspendableAnswer {
val authorizeSend = it.getArgument<suspend () -> Boolean>(4)
runSuspendCatching {
check(authorizeSend())
sends++
if (!isOverlapped) {
isOverlapped = true
overlapping = sut.payInvoice("h", 1_000uL)
}
"h"
}
}

sut.payInvoice("h", 1_000uL).getOrThrow()

assertIs<PaymentPendingException>(overlapping?.exceptionOrNull(), "Spark sent an invoice it is sending")
assertEquals(1, sends)
}

@Test
fun `a spark send of an invoice spark recorded since its checks is refused at submission`() = test {
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.
whenever(sparkRepo.hasRecordedSendSince(any(), anyOrNull())).thenReturn(true)
var isSent = false
whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())).doSuspendableAnswer {
val authorizeSend = it.getArgument<suspend () -> Boolean>(4)
runSuspendCatching {
isSent = authorizeSend()
"h"
}
}

val result = sut.payInvoice("h", 1_000uL)

assertIs<PaymentPendingException>(result.exceptionOrNull(), "Spark sent an invoice it sent meanwhile")
assertFalse(isSent)
}

@Test
fun `a spark send of an invoice the node already paid settles as paid`() = test {
startNodeForTesting()
Expand Down
22 changes: 22 additions & 0 deletions app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1902,6 +1902,28 @@ class SparkExitDriverTest : BaseUnitTest() {
assertEquals(requests, sdk.recoverRequests.size, "built again before the rebuild interval")
}

@Test
fun `a redo hold built from the held funding drops the fee ask the top-up was for`() = test {
var record = divergedOverTwoLeaves()
sdk.preparedResponse = leaf2Unread
repeat(2) { 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))
val requests = sdk.recoverRequests.size
now += interval
record = driver(tip = 1_001u).tick(record)

assertEquals(requests + 1, sdk.recoverRequests.size, "the held funding did not build the rebuild")
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)
}
Comment thread
ovitrif marked this conversation as resolved.
Resolved

@Test
fun `an empty prepare during a redo hold leaves the retry clock alone`() = test {
var record = divergedOverTwoLeaves()
Expand Down
15 changes: 13 additions & 2 deletions app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -491,8 +491,19 @@ class SparkRepoTest : BaseUnitTest() {
}

@Test
fun `a pre-restore invoice the operators show failed is refused on both rails`() = test {
assertRestoredInvoiceRefusedOnBothRails(status = PaymentStatus.FAILED)
fun `a pre-restore invoice retries on both rails after its spark send failed`() = test {
val sut = restoredSparkForPreRestoreInvoice(status = null, stubStatus = true)
val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED)
whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(failed, sentPayment(fees = 0))
sut.payInvoice("lnbc1280n1send", 128uL)
whenever { sparkService.listPayments() }.thenReturn(listOf(failed))
// The operators show a send failed once every attempt at its hash was returned.
sendStatus = { PaymentStatus.FAILED }
val createdAt = now.epochSeconds - 660

assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash", createdAt, createdAt + 3_600))
sut.payInvoice("lnbc1280n1send", 128uL).getOrThrow()
verify(sparkService, times(2)).send(any(), anyOrNull())
}

@Test
Expand Down
Loading