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
19 changes: 14 additions & 5 deletions app/src/main/java/to/bitkit/data/CacheStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -275,12 +275,19 @@ class CacheStore internal constructor(
/**
* Drops the node's sends a listing showed as [failed] only, or as [paid] with an expired invoice, ones it didn't
* show ([listed] is every hash it shows) whose invoice expired past [UNLISTED_SEND_SETTLE_SECS], and past the cap
* the oldest paid or unlisted ones with no known expiry. A send that may be pending ([live]) always stays.
* the oldest paid or unlisted ones with no known expiry. A send that may be pending ([live], or [isLive] inside
* the write, as for one recorded since the listing) always stays.
*/
suspend fun trimLdkSendHashes(paid: Set<String>, failed: Set<String>, listed: Set<String>, live: Set<String>) {
suspend fun trimLdkSendHashes(
paid: Set<String>,
failed: Set<String>,
listed: Set<String>,
live: Set<String>,
isLive: (String) -> Boolean = { false },
) {
store.updateData {
val (hashes, expiries) =
withoutSettled(it.ldkSendHashes, it.ldkSendExpiries, SendListing(paid, failed, listed, live))
val listing = SendListing(paid, failed, listed, live + it.ldkSendHashes.filter(isLive))
val (hashes, expiries) = withoutSettled(it.ldkSendHashes, it.ldkSendExpiries, listing)
it.copy(ldkSendHashes = hashes, ldkSendExpiries = expiries)
}
}
Expand Down Expand Up @@ -325,10 +332,12 @@ class CacheStore internal constructor(
return kept to expiries.filterKeys { it in kept }
}

suspend fun removeLdkSendHash(paymentHash: String) {
/** Drops the node's send of [paymentHash] unless [isKept] holds inside the write, as for a send recorded since. */
suspend fun removeLdkSendHash(paymentHash: String, isKept: () -> Boolean = { false }) {
val hash = paymentHash.lowercase()
if (hash !in store.data.first().ldkSendHashes) return
store.updateData {
if (isKept()) return@updateData it
it.copy(ldkSendHashes = it.ldkSendHashes - hash, ldkSendExpiries = it.ldkSendExpiries - hash)
}
}
Expand Down
4 changes: 3 additions & 1 deletion app/src/main/java/to/bitkit/repositories/BackupRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1336,10 +1336,12 @@ class BackupRepo @Inject constructor(
}
runCatching { restoreSparkExitEarlierAddresses(parsed.sparkExitEarlierAddresses) }
.onFailure { Logger.warn("Failed to restore the earlier Spark exit addresses", it, context = TAG) }
// Payment history stays out of the log, as support requests attach it.
// Payment history and Spark attempt ids stay out of the log, as support requests attach it.
val logged = parsed.cache.copy(
cachedRates = emptyList(),
moveToSparkHashes = emptyList(),
sparkSendAttemptIds = emptyMap(),
sparkUnsavedOwnFailures = emptySet(),
)
Logger.debug("Restored caches: ${jsonLogOf(logged)}", TAG)
onCacheRestored()
Expand Down
21 changes: 15 additions & 6 deletions app/src/main/java/to/bitkit/repositories/LightningRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1661,11 +1661,15 @@ class LightningRepo @Inject constructor(
(kind.bolt11.equals(bolt11, ignoreCase = true) || kind.hash.equals(paymentHash, ignoreCase = true))
}
// A retry in flight, also one that ended while the listing was read, or recorded meanwhile, holds the invoice.
val isRetried = ldkSendsInFlight.containsKey(key) || key in inFlightBefore ||
(ldkSendRecordedAt[key] ?: 0L) > recordsBefore
val isRetried = {
ldkSendsInFlight.containsKey(key) || key in inFlightBefore ||
(ldkSendRecordedAt[key] ?: 0L) > recordsBefore
}
if (send == null || send.status == PaymentStatus.FAILED) {
if (isRetried) return EarlierSend.Pending(key)
cacheStore.removeLdkSendHash(key)
if (isRetried()) return EarlierSend.Pending(key)
// Checked again inside the release and after it, so a node send recorded meanwhile keeps its hash.
cacheStore.removeLdkSendHash(key, isKept = isRetried)
if (isRetried()) return EarlierSend.Pending(key)
}
if (send == null) return null
val hash = (send.kind as PaymentKind.Bolt11).hash
Expand Down Expand Up @@ -1832,8 +1836,13 @@ class LightningRepo @Inject constructor(
val paid = hashes(PaymentStatus.SUCCEEDED)
val failed = hashes(PaymentStatus.FAILED) - paid - live
val listed = outbound.mapNotNullTo(mutableSetOf()) { (it.kind as? PaymentKind.Bolt11)?.hash?.lowercase() }
cacheStore.trimLdkSendHashes(paid = paid - live, failed = failed, listed = listed, live = live)
failed.forEach { ldkSendRecordedAt.remove(it) }
// A send recorded while the listing was read or trimmed keeps its hash and its record.
cacheStore.trimLdkSendHashes(paid = paid - live, failed = failed, listed = listed, live = live) {
ldkSendsInFlight.containsKey(it) || (ldkSendRecordedAt[it] ?: 0L) > recordsBefore
}
failed.forEach { hash ->
ldkSendRecordedAt.computeIfPresent(hash) { _, at -> at.takeIf { at > recordsBefore } }
}
}

/** When [bolt11] expires, in epoch seconds, or null when it can't be parsed. */
Expand Down
32 changes: 23 additions & 9 deletions app/src/main/java/to/bitkit/repositories/SparkRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -567,9 +567,9 @@ class SparkRepo @Inject constructor(
// A caller asking for the invoice again waits for its outcome, also for a send settled while closed. The
// restore lock orders it against a settle taking the hold, which reads the marker under the same lock.
holdRestoreMutex.withLock { restoredAtStart.remove(paymentHash.lowercase()) }
// Read once, as Spark's first sync can land during the checks below.
val canList = canListPayments()
val earlier = lightningSend(paymentHash)
// Read after the listing, so a first sync that lands during it counts, as the listing saw it synced.
val canList = canListPayments()
when (earlier) {
is SparkLightningSend.Found if earlier.status == PaymentStatus.COMPLETED -> {
Logger.info("Skipped Spark send of '$paymentHash', already paid", context = TAG)
Expand All @@ -588,9 +588,9 @@ class SparkRepo @Inject constructor(
)
}
// A list that can't be read may hide a payment of the invoice, which Spark would pay again under a new
// key. Before Spark's first sync its local list is read here, as the synced one was above.
// key. It is read again here: the local one before Spark's first sync, else the synced one.
if (earlier == SparkLightningSend.Unavailable) {
val local = (if (canList) null else runSuspendCatching { listPayments() }.getOrNull())
val local = runSuspendCatching { listPayments() }.getOrNull()
?: throw SparkError.SendRefused("Spark could not list its payments to check the invoice")
when (local.latestSend(paymentHash)?.status) {
PaymentStatus.COMPLETED -> {
Expand Down Expand Up @@ -1500,7 +1500,7 @@ class SparkRepo @Inject constructor(
// kept, as its event can come before the list shows it.
val decidingIds = deciding.mapTo(mutableSetOf()) { it.id }
payments.filter { it.id in unsavedOwnFailures && it.id !in decidingIds }
.forEach { cacheStore.removeSparkUnsavedOwnFailure(it.id) }
.forEach { markUnsavedOwnFailure(it.id, isUnsaved = false) }
deciding
.filter {
it.id in unsavedPayments || it.id in unsavedOwnFailures ||
Expand Down Expand Up @@ -2169,7 +2169,7 @@ class SparkRepo @Inject constructor(
// A failed read would drop the stored note, contact and seen time, so the write waits for the next refresh.
val stored = activityRepo.get().getActivity(id).getOrElse {
unsavedPayments.add(payment.id)
if (isOwn) cacheStore.addSparkUnsavedOwnFailure(payment.id)
if (isOwn) markUnsavedOwnFailure(payment.id, isUnsaved = true)
return false
}
val existing = (stored as? Activity.Lightning)?.v1
Expand All @@ -2180,7 +2180,7 @@ class SparkRepo @Inject constructor(
}
// Another attempt of the same invoice, on either rail, already paid it.
if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) {
cacheStore.removeSparkUnsavedOwnFailure(payment.id)
markUnsavedOwnFailure(payment.id, isUnsaved = false)
return true
}
// A failure, possibly an earlier attempt's, only fails the send's row, which keeps its own details.
Expand Down Expand Up @@ -2213,11 +2213,11 @@ class SparkRepo @Inject constructor(
.let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError }
if (!saved) {
unsavedPayments.add(payment.id)
if (isOwn) cacheStore.addSparkUnsavedOwnFailure(payment.id)
if (isOwn) markUnsavedOwnFailure(payment.id, isUnsaved = true)
return false
}
unsavedPayments.remove(payment.id)
cacheStore.removeSparkUnsavedOwnFailure(payment.id)
markUnsavedOwnFailure(payment.id, isUnsaved = false)
if (payment.paymentType == SparkPaymentType.SEND && payment.fees.toLong() == 0L) {
sendsRecordedWithoutFee.add(payment.id)
} else {
Expand All @@ -2226,6 +2226,20 @@ class SparkRepo @Inject constructor(
return true
}

/**
* Keeps [paymentId] as an own failure whose row is still to save, or drops it. A failed cache write only loses
* that detail, so it never stops the settlement, hold release or report around it.
*/
private suspend fun markUnsavedOwnFailure(paymentId: String, isUnsaved: Boolean) {
runSuspendCatching {
if (isUnsaved) {
cacheStore.addSparkUnsavedOwnFailure(paymentId)
} else {
cacheStore.removeSparkUnsavedOwnFailure(paymentId)
}
}.onFailure { Logger.warn("Failed to update Spark own failure '$paymentId'", it, context = TAG) }
}

private suspend fun settleMoveToSpark(payment: Payment, send: LightningActivity): Boolean {
if (payment.status != PaymentStatus.COMPLETED || send.status == PaymentState.SUCCEEDED) return true
val settled = Activity.Lightning(send.copy(status = PaymentState.SUCCEEDED))
Expand Down
11 changes: 11 additions & 0 deletions app/src/test/java/to/bitkit/data/CacheStoreTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,17 @@ class CacheStoreTest : BaseUnitTest() {
assertFalse(paid.first() in kept, "The oldest paid send was kept over the cap")
}

@Test
fun `a node send listed failed stays kept when it is recorded again before the trim writes`() = test {
sut.addLdkSendHash("h")

sut.trimLdkSendHashes(paid = emptySet(), failed = setOf("h"), listed = setOf("h"), live = emptySet()) {
it == "h"
}

assertEquals(listOf("h"), sut.data.first().ldkSendHashes)
}

@Test
fun `a node send still pending behind the cap of later sends stays kept`() = test {
sut.addLdkSendHash("pending")
Expand Down
59 changes: 55 additions & 4 deletions app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancel
Expand All @@ -36,6 +37,7 @@ import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runCurrent
import org.junit.Before
import org.junit.Test
Expand Down Expand Up @@ -1932,6 +1934,54 @@ class LightningRepoTest : BaseUnitTest() {
verify(sparkRepo).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())
}

@Test
fun `a node send recorded while a spark check releases the invoice keeps its hash`() = test {
assertNodeSendRecordedDuringReleaseKeepsHash(listed = emptyList())
}

@Test
fun `a node send recorded while the listing trims its failed attempt keeps its hash`() = test {
assertNodeSendRecordedDuringReleaseKeepsHash(listed = listOf(nodeSend("h", PaymentStatus.FAILED)))
}

/** The node sends the invoice again once a Spark send's check decided to release the node's [listed] attempt. */
private suspend fun TestScope.assertNodeSendRecordedDuringReleaseKeepsHash(listed: List<PaymentDetails>) {
val inner = InMemoryDataStore(AppCacheData(ldkSendHashesSeeded = true, ldkSendHashes = listOf("h")))
val entered = CompletableDeferred<Unit>()
val queued = CompletableDeferred<String>()
var isArmed = true
var node: Job? = null
val store = CacheStore(
object : DataStore<AppCacheData> by inner {
override suspend fun updateData(transform: suspend (t: AppCacheData) -> AppCacheData): AppCacheData {
val current = inner.data.first()
if (isArmed && "h" in current.ldkSendHashes && "h" !in transform(current).ldkSendHashes) {
isArmed = false
node = launch { sut.payInvoiceWithNode("h") }
entered.await()
}
return inner.updateData(transform)
}
}
)
sut = repoWith(store)
startNodeForTesting()
whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true)))
whenever(lightningService.listPayments()).thenReturn(listed)
whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).doSuspendableAnswer {
entered.complete(Unit)
queued.await()
}
whenever(sparkRepo.canSend(1_000uL)).thenReturn(true)

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

assertIs<PaymentPendingException>(result.exceptionOrNull())
assertEquals(listOf("h"), store.data.first().ldkSendHashes, "a Spark check released a node send's hold")
queued.complete("h")
node?.join()
}

private fun failingOnceOnLdkHash(hash: String): DataStore<AppCacheData> = object : DataStore<AppCacheData> {
private val inner = InMemoryDataStore(AppCacheData(ldkSendHashesSeeded = true))
private var isArmed = true
Expand Down Expand Up @@ -2009,10 +2059,11 @@ class LightningRepoTest : BaseUnitTest() {

verifyBlocking(cacheStore) {
trimLdkSendHashes(
paid = setOf("paid"),
failed = setOf("failed"),
listed = setOf("pending", "paid", "failed"),
live = setOf("pending"),
paid = eq(setOf("paid")),
failed = eq(setOf("failed")),
listed = eq(setOf("pending", "paid", "failed")),
live = eq(setOf("pending")),
isLive = any(),
)
}
}
Expand Down
Loading