diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 4dad77b605..1166d35165 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -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 { @@ -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) @@ -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 } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index db0fb470fb..94f65563d1 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -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) @@ -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) @@ -374,15 +374,20 @@ class SparkExitDriver( return broadcastReady(adopted) } - private fun holdingRedo(record: SparkExitRecord, waiting: List): SparkExitRecord? { + private fun holdingRedo( + record: SparkExitRecord, + waiting: List, + 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) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 47ceeaa971..5c1bfc06cf 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -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. @@ -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 diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 81b9fc2dc8..242e68ef88 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -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 @@ -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? = 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 Boolean>(4) + runSuspendCatching { + check(authorizeSend()) + sends++ + if (!isOverlapped) { + isOverlapped = true + overlapping = sut.payInvoice("h", 1_000uL) + } + "h" + } + } + + sut.payInvoice("h", 1_000uL).getOrThrow() + + assertIs(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 Boolean>(4) + runSuspendCatching { + isSent = authorizeSend() + "h" + } + } + + val result = sut.payInvoice("h", 1_000uL) + + assertIs(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() diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index e0955829f7..dd3eec2471 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -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) + } + @Test fun `an empty prepare during a redo hold leaves the retry clock alone`() = test { var record = divergedOverTwoLeaves() diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 28837d44e5..b5b19d1d12 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -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