Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
de447dc
fix: hold pre-restore invoices until spark lists its sends
ovitrif Nov 11, 2026
1fd0411
fix: refuse a spark send once its deadline passed
ovitrif Nov 11, 2026
2b240a5
fix: let spark pay while the node is down
ovitrif Nov 11, 2026
1481337
fix: drop the spending balance after a full spark withdrawal
ovitrif Nov 11, 2026
39a9317
fix: hold pre-restore invoices until the node lists its sends
ovitrif Nov 11, 2026
4541381
chore: name the changelog fragment after this pr
ovitrif Nov 11, 2026
d8433ef
fix: let confirm and quick pay proceed when spark can pay
ovitrif Nov 11, 2026
36ef97e
fix: hold pre-restore invoices on a restore without metadata
ovitrif Nov 11, 2026
da1ddcd
fix: keep restored spark sends held while their invoices are valid
ovitrif Nov 11, 2026
f681689
fix: keep a full withdrawal's zero balance until a later sync shows f…
ovitrif Nov 11, 2026
b4bbcc7
perf: decode a node send's invoice only during a restore hold
ovitrif Nov 11, 2026
f4836b9
chore: drop the changelog entry for an unreleased spark bug
ovitrif Nov 11, 2026
18953ca
Merge remote-tracking branch 'origin/master' into fix/spark-retry-bef…
ovitrif Nov 11, 2026
694e3b8
fix: give a kept spark send its invoice expiry when restored sends ar…
ovitrif Nov 11, 2026
cf2c10d
fix: saturate a spark invoice's expiry instead of wrapping
ovitrif Nov 11, 2026
a0e995a
fix: refuse a node send of a valid pre-restore invoice spark hasn't l…
ovitrif Nov 11, 2026
cb9a7af
fix: refuse a spark send of a pre-restore invoice until spark lists i…
ovitrif Nov 11, 2026
9d5e267
fix: refuse a spark send of a pre-restore invoice its list lacks
ovitrif Nov 11, 2026
3214ec8
fix: hold a pre-restore invoice until it expires
ovitrif Nov 11, 2026
f7ebbb8
fix: refuse a pre-restore spark send when its list can't be read
ovitrif Nov 11, 2026
2738531
docs: describe the restore hold as lasting until expiry
ovitrif Nov 11, 2026
7a80258
docs: say seeding ends only the wait for spark's first listing
ovitrif Nov 11, 2026
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
46 changes: 46 additions & 0 deletions app/src/main/java/to/bitkit/data/CacheStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,35 @@ class CacheStore internal constructor(
}
}

/**
* After a restore, keeps [paymentHashes], Spark's pending and paid sends from its synced list, once, with their
* invoices' [expiries] in epoch seconds where known, so a still-valid one stays held and outlasts the cap.
*/
suspend fun seedSparkSendHashes(paymentHashes: List<String>, expiries: Map<String, Long> = emptyMap()) {
if (store.data.first().sparkHistoryUnseededSince == null) return
store.updateData { data ->
if (data.sparkHistoryUnseededSince == null) return@updateData data
val seeded = paymentHashes.map { it.lowercase() }.distinct() - data.sparkSendHashes.toSet()
// A kept hash without an expiry gets its invoice's, so the cap can't drop it while valid; a set one stays.
val listedExpiries = expiries.mapKeys { it.key.lowercase() }
data.copy(
sparkSendHashes = seeded + data.sparkSendHashes,
sparkSendExpiries = listedExpiries + data.sparkSendExpiries,
sparkHistoryUnseededSince = null,
)
Comment thread
ovitrif marked this conversation as resolved.
Resolved
}
}

/** After a restore, keeps [paymentHashes], the node's pending and paid sends from its own list, once. */
suspend fun seedRestoredLdkSendHashes(paymentHashes: List<String>) {
if (store.data.first().ldkHistoryUnseededSince == null) return
store.updateData { data ->
if (data.ldkHistoryUnseededSince == null) return@updateData data
val seeded = paymentHashes.map { it.lowercase() }.distinct() - data.ldkSendHashes.toSet()
data.copy(ldkSendHashes = seeded + data.ldkSendHashes, ldkHistoryUnseededSince = null)
}
}

/**
* 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
Expand Down Expand Up @@ -323,6 +352,23 @@ data class AppCacheData(
* there. Until then an unlistable node holds every Spark send.
*/
val ldkSendHashesSeeded: Boolean = false,
/**
* When a metadata restore brought back [sparkSendHashes], in epoch seconds, until Spark's synced list fills them:
* the backup can predate a send Spark made, so meanwhile a Spark that can't list its payments holds the node off
* invoices created before it. Null on an install that was never restored, whose kept hashes are complete.
*/
val sparkHistoryUnseededSince: Long? = null,
/**
* When a metadata restore brought back [ldkSendHashes], in epoch seconds, until the node's own list fills them:
* while the node can't list its payments, Spark holds off invoices created before it. Null when never restored.
*/
val ldkHistoryUnseededSince: Long? = null,
/**
* When the wallet was restored, in epoch seconds. Spark's list can lack a send it made before then even after a
* sync, so both rails refuse a still-valid invoice created before it that Spark hasn't listed as pending or paid,
* until that invoice expires.
*/
Comment thread
ovitrif marked this conversation as resolved.
Resolved
val sparkRestoredAt: Long? = null,
) {
fun isContactDetached(activityId: String, walletId: String): Boolean =
scopedActivityId(walletId, activityId) in detachedActivityContacts
Expand Down
4 changes: 4 additions & 0 deletions app/src/main/java/to/bitkit/ext/PaymentFailureReasonExt.kt
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ fun Throwable.toSendFailureMessage(context: Context): String {
val fallbackMessage = context.getString(R.string.wallet__payment_failed_description)
val rawMessage = message?.trim().orEmpty()

if (generateSequence(this) { it.cause }.any { it is SparkError.RestoredInvoiceUnverified }) {
return context.getString(R.string.wallet__payment_restored_invoice)
}

// Spark and its SDK speak in English developer messages; they go to the log, the user gets the existing copy.
if (this is LdkError || this is SparkError || this is SdkException || rawMessage.isBlank() ||
rawMessage.looksInternalPaymentError()
Expand Down
23 changes: 22 additions & 1 deletion app/src/main/java/to/bitkit/repositories/BackupRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
import kotlin.time.Clock
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlin.time.ExperimentalTime
Expand Down Expand Up @@ -1047,6 +1048,17 @@ class BackupRepo @Inject constructor(
}
connectionSession.replay()
prepareUsdtRecoveryRestore()
// Armed before any category, so a restore whose metadata is missing or unreadable holds each rail off
// invoices from before it too: until that rail lists its own sends, and, for one Spark hasn't listed,
// until the invoice expires.
val restoredAt = currentTimeMillis().milliseconds.inWholeSeconds
cacheStore.update {
it.copy(
sparkHistoryUnseededSince = restoredAt,
ldkHistoryUnseededSince = restoredAt,
sparkRestoredAt = restoredAt,
)
}
var metadataReceived = false
val metadataResult = performRestore(BackupCategory.METADATA, failedCategories) { dataBytes ->
metadataReceived = true
Expand Down Expand Up @@ -1201,7 +1213,16 @@ class BackupRepo @Inject constructor(
)
val parsed = decodeBackup<MetadataBackupV1>(migration.json)
val cleanCache = parsed.cache.resetBip21() // Force address rotation
cacheStore.update { cleanCache.copy(backupStatuses = it.backupStatuses) }
// The backed-up send hashes can predate either rail's latest sends, so each rail's own list seeds them again.
val restoredAt = currentTimeMillis().milliseconds.inWholeSeconds
cacheStore.update {
cleanCache.copy(
backupStatuses = it.backupStatuses,
sparkHistoryUnseededSince = restoredAt,
ldkHistoryUnseededSince = restoredAt,
Comment thread
ovitrif marked this conversation as resolved.
Resolved
sparkRestoredAt = restoredAt,
)
}
Comment thread
ovitrif marked this conversation as resolved.
Resolved
Logger.debug("Restored caches: ${jsonLogOf(parsed.cache.copy(cachedRates = emptyList()))}", TAG)
onCacheRestored()
val persisted = preActivityMetadataRepo.upsertPreActivityMetadata(parsed.tagMetadata)
Expand Down
53 changes: 44 additions & 9 deletions app/src/main/java/to/bitkit/repositories/LightningRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1575,7 +1575,8 @@ class LightningRepo @Inject constructor(
* The node's pending or paid send of [bolt11]. While the node can't list its payments (stopped or not started yet),
* a send it started for the invoice may be live or paid, and its event may never come, so the node not started yet
* is thrown rather than a Pending nothing resolves. Before the node first listed its payments, the sends it made
* earlier are unknown, so the same is thrown.
* earlier are unknown, so the same is thrown, as it is after a restore, until the node lists them, for an invoice
* created before the restore.
*/
private suspend fun earlierNodeSend(bolt11: String, paymentHash: String?): EarlierSend? {
val key = ldkSendKey(bolt11, paymentHash)
Expand All @@ -1592,6 +1593,12 @@ class LightningRepo @Inject constructor(
Logger.warn("Refused a Spark send until the node lists its earlier payments once", context = TAG)
throw ServiceError.NodeNotStarted()
}
// Restored hashes can lack a send the node made before the restore, never one of a newer invoice.
val unseededSince = cache.ldkHistoryUnseededSince
if (unseededSince != null && (invoiceCreatedAt(bolt11) ?: 0L) < unseededSince) {
Logger.warn("Refused a Spark send until the node lists its payments since the restore", context = TAG)
throw ServiceError.NodeNotStarted()
}
return null
}
val send = payments.firstOrNull {
Expand Down Expand Up @@ -1654,7 +1661,15 @@ class LightningRepo @Inject constructor(
requireWalletRestoreComplete()
// Read before the checks, so a Spark send admitted after them refuses this one at submission.
val sparkRecordsBefore = sparkRepo.sendRecordMark()
sparkRepo.earlierLightningSend(bolt11, paymentHash)?.let { return@executeWhenNodeRunning it.toResult() }
// Only a restore hold needs the invoice's times.
val invoice = if (sparkRepo.holdsRestoredInvoices()) decodedInvoice(bolt11) else null
sparkRepo.earlierLightningSend(
bolt11,
paymentHash,
invoice?.timestampSeconds?.toEpochSeconds(),
invoice?.let { (it.timestampSeconds.safe() + it.expirySeconds.safe()).toEpochSeconds() },
)
?.let { return@executeWhenNodeRunning it.toResult() }
if (!onBeforeSend()) return@executeWhenNodeRunning Result.failure(PaymentAbortedBeforeSend())
requireWalletRestoreComplete()
val key = ldkSendKey(bolt11, paymentHash)
Expand Down Expand Up @@ -1717,7 +1732,9 @@ class LightningRepo @Inject constructor(
) {
val outbound = payments.filter { it.direction == PaymentDirection.OUTBOUND }
val sends = outbound.filter { it.status != PaymentStatus.FAILED }.sortedBy { it.latestUpdateTimestamp }
cacheStore.seedLdkSendHashes(sends.mapNotNull { (it.kind as? PaymentKind.Bolt11)?.hash })
val sendHashes = sends.mapNotNull { (it.kind as? PaymentKind.Bolt11)?.hash }
cacheStore.seedLdkSendHashes(sendHashes)
cacheStore.seedRestoredLdkSendHashes(sendHashes)
val hashes = { status: PaymentStatus ->
outbound.filter { it.status == status }
.mapNotNullTo(mutableSetOf()) { (it.kind as? PaymentKind.Bolt11)?.hash?.lowercase() }
Expand All @@ -1738,6 +1755,15 @@ class LightningRepo @Inject constructor(
.coerceAtMost(Long.MAX_VALUE.toULong()).toLong()
}.getOrNull()

/** When [bolt11] was created, in epoch seconds, or null when it can't be decoded. */
private suspend fun invoiceCreatedAt(bolt11: String): Long? =
decodedInvoice(bolt11)?.timestampSeconds?.toEpochSeconds()

private suspend fun decodedInvoice(bolt11: String) =
runSuspendCatching { (coreService.decode(bolt11) as? Scanner.Lightning)?.invoice }.getOrNull()

private fun ULong.toEpochSeconds(): Long = coerceAtMost(Long.MAX_VALUE.toULong()).toLong()

/** The payment hash a node send is kept under, or the invoice itself when it can't be parsed. */
private fun ldkSendKey(bolt11: String, paymentHash: String?): String = (paymentHash ?: bolt11).lowercase()

Expand Down Expand Up @@ -2740,8 +2766,15 @@ class LightningRepo @Inject constructor(
}
}

suspend fun estimateRoutingFees(bolt11: String): Result<ULong> = executeWhenNodeRunning("estimateRoutingFees") {
if (shouldPayWithSpark(bolt11, null)) return@executeWhenNodeRunning sparkRepo.estimateFeeSats(bolt11, null)
suspend fun estimateRoutingFees(bolt11: String): Result<ULong> {
// Spark quotes without the node, so a payment it makes never waits for the node to run.
if (shouldPayWithSpark(bolt11, null)) return sparkRepo.estimateFeeSats(bolt11, null)
return estimateNodeRoutingFees(bolt11)
}

private suspend fun estimateNodeRoutingFees(bolt11: String): Result<ULong> = executeWhenNodeRunning(
"estimateRoutingFees"
) {
Logger.info("Estimating routing fees for bolt11: $bolt11", context = TAG)
lightningService.estimateRoutingFees(bolt11).onSuccess {
Logger.info("Routing fees estimated: '$it'", context = TAG)
Expand All @@ -2750,11 +2783,13 @@ class LightningRepo @Inject constructor(
}
}

suspend fun estimateRoutingFeesForAmount(bolt11: String, amountSats: ULong): Result<ULong> =
suspend fun estimateRoutingFeesForAmount(bolt11: String, amountSats: ULong): Result<ULong> {
if (shouldPayWithSpark(bolt11, amountSats)) return sparkRepo.estimateFeeSats(bolt11, amountSats)
return estimateNodeRoutingFeesForAmount(bolt11, amountSats)
}

private suspend fun estimateNodeRoutingFeesForAmount(bolt11: String, amountSats: ULong): Result<ULong> =
executeWhenNodeRunning("estimateRoutingFeesForAmount") {
if (shouldPayWithSpark(bolt11, amountSats)) {
return@executeWhenNodeRunning sparkRepo.estimateFeeSats(bolt11, amountSats)
}
Logger.info("Estimating routing fees for amount: '$amountSats'", context = TAG)
lightningService.estimateRoutingFeesForAmount(bolt11, amountSats).onSuccess {
Logger.info("Routing fees estimated: '$it'", context = TAG)
Expand Down
Loading
Loading