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
7 changes: 3 additions & 4 deletions app/src/main/java/to/bitkit/data/CacheStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -375,9 +375,8 @@ data class AppCacheData(
*/
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.
* When a metadata restore brought back [sparkSendHashes], in epoch seconds, until Spark's synced list fills them,
* as the backup can predate a send Spark made. Null on an install that was never restored.
*/
val sparkHistoryUnseededSince: Long? = null,
/**
Expand All @@ -388,7 +387,7 @@ data class AppCacheData(
/**
* 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.
* unless the Spark operators show it unsent.
*/
val sparkRestoredAt: Long? = null,
) {
Expand Down
4 changes: 2 additions & 2 deletions app/src/main/java/to/bitkit/repositories/BackupRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1078,8 +1078,8 @@ 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.
// invoices from before it too: Spark until the node lists its own sends, and both rails off one Spark
// hasn't listed, until the Spark operators show it unsent or it expires.
val restoredAt = currentTimeMillis().milliseconds.inWholeSeconds
cacheStore.update {
it.copy(
Expand Down
84 changes: 46 additions & 38 deletions app/src/main/java/to/bitkit/repositories/SparkRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,7 @@ class SparkRepo @Inject constructor(
* [paymentDeadlineAt]. A failure inside the send is a [PaymentPendingException], as the payment may have been
* dispatched, and its event decides it. An invoice this wallet already sends is not sent again: one in flight or
* pending fails with [PaymentPendingException], and one Spark completed returns its hash. After a restore, a
* still-valid invoice created before it that Spark hasn't listed as pending or paid fails with
* still-valid invoice created before it that the Spark operators can't show unsent fails with
* [SparkError.RestoredInvoiceUnverified], under the same rule as the node's send.
*/
suspend fun payInvoice(
Expand Down Expand Up @@ -529,15 +529,13 @@ class SparkRepo @Inject constructor(
}
is SparkLightningSend.Found if earlier.status == PaymentStatus.PENDING ->
throw PaymentPendingException(paymentHash)
// Before Spark has listed its sends since a restore, an older invoice is refused here; the branch
// below keeps refusing it after the listing, until the invoice expires.
is SparkLightningSend.Unavailable if isUnlistedSinceRestore(method.invoiceDetails.timestamp) -> {
Logger.warn("Refused a Spark send of '$paymentHash' dated before the restore", context = TAG)
throw SparkError.RestoredInvoiceUnverified()
}
// Spark's list, synced or unreadable, can still lack a send it made before the restore, as on the
// node's path.
else -> refuseUnverifiedRestoredInvoice(invoice.timestamp.toEpochSeconds(), expiresAt.toEpochSeconds())
// Spark's list, synced or unreadable, can lack a send it made before the restore, as on the node's
// path, so the operators decide.
else -> refuseUnverifiedRestoredInvoice(
bolt11,
invoice.timestamp.toEpochSeconds(),
expiresAt.toEpochSeconds(),
)
}
// A cancel, block or identity change can land while Spark prepares, so the last check runs right here.
if (!onBeforeSend()) throw PaymentAbortedBeforeSend()
Expand Down Expand Up @@ -1380,12 +1378,11 @@ class SparkRepo @Inject constructor(
/**
* Spark's pending or paid send of [bolt11], matched by the invoice or its [paymentHash], so the node never pays it
* again; a send still inside Spark's send call is pending. Null when Spark's send failed or none is known.
* While Spark can't list its payments, a send it started for [paymentHash] counts as pending, since it may be live,
* and after a restore, until Spark's synced list seeds the kept hashes, [SparkError.SendRefused] is thrown for an
* invoice created before the restore ([invoiceCreatedAt] in epoch seconds, null when unknown), as the restored
* hashes can lack a send Spark made of it. After a restore, an invoice created before it and not yet expired
* ([invoiceExpiresAt], null when unknown) that Spark hasn't listed is refused with
* [SparkError.RestoredInvoiceUnverified] whatever Spark listed, as Spark's list can lack its sends after a sync.
* While Spark can't list its payments, a send it started for [paymentHash] counts as pending, since it may be live.
* After a restore, an invoice created before it ([invoiceCreatedAt] in epoch seconds, null when unknown) and not
* yet expired ([invoiceExpiresAt], null when unknown) that Spark hasn't listed as pending or paid is refused with
* [SparkError.RestoredInvoiceUnverified] unless the Spark operators show it unsent, as Spark's list can lack its
* sends after a restore.
*/
suspend fun earlierLightningSend(
bolt11: String,
Expand Down Expand Up @@ -1419,13 +1416,7 @@ class SparkRepo @Inject constructor(
}
if (payments == null) {
startedSend(paymentHash)?.let { return@withContext EarlierSend.Pending(it) }
// Restored hashes can lack a send Spark made before the restore, never one of a newer invoice.
val unseededSince = cacheStore.data.first().sparkHistoryUnseededSince
if (sparkService.isSupported && unseededSince != null && (invoiceCreatedAt ?: 0L) < unseededSince) {
Logger.warn("Refused a node send until Spark lists its earlier sends once", context = TAG)
throw SparkError.RestoredInvoiceUnverified()
}
refuseUnverifiedRestoredInvoice(invoiceCreatedAt, invoiceExpiresAt)
refuseUnverifiedRestoredInvoice(bolt11, invoiceCreatedAt, invoiceExpiresAt)
return@withContext null
}
seedSendHashes(payments)
Expand All @@ -1437,12 +1428,12 @@ class SparkRepo @Inject constructor(
if (send == null) {
(retried() ?: paymentHash?.lowercase()?.takeIf { it in unlisted })
?.let { return@withContext EarlierSend.Pending(it) }
refuseUnverifiedRestoredInvoice(invoiceCreatedAt, invoiceExpiresAt)
refuseUnverifiedRestoredInvoice(bolt11, invoiceCreatedAt, invoiceExpiresAt)
return@withContext null
}
if (send.status == PaymentStatus.FAILED) {
retried()?.let { return@withContext EarlierSend.Pending(it) }
refuseUnverifiedRestoredInvoice(invoiceCreatedAt, invoiceExpiresAt)
refuseUnverifiedRestoredInvoice(bolt11, invoiceCreatedAt, invoiceExpiresAt)
}
val hash = (send.details as PaymentDetails.Lightning).htlcDetails.paymentHash
when (send.status) {
Expand All @@ -1454,30 +1445,47 @@ class SparkRepo @Inject constructor(

/** Whether a node send needs its invoice's times for the checks after a restore in [earlierLightningSend]. */
suspend fun holdsRestoredInvoices(): Boolean {
val cache = cacheStore.data.first()
return cache.sparkHistoryUnseededSince != null || cache.sparkRestoredAt != null
}

private suspend fun isUnlistedSinceRestore(invoiceCreatedAt: ULong): Boolean {
val unseededSince = cacheStore.data.first().sparkHistoryUnseededSince ?: return false
return invoiceCreatedAt < unseededSince.coerceAtLeast(0L).toULong()
return cacheStore.data.first().sparkRestoredAt != null
}

/**
* The rule both rails apply after a restore, as Spark's list can lack a send it made before it: an invoice created
* before the restore that hasn't expired, or one whose times are unknown, is refused with
* [SparkError.RestoredInvoiceUnverified] until it expires.
* The rule both rails apply after a restore, as Spark's list can lack a send it made before it: [bolt11], when
* created before the restore and not yet expired, or when its times are unknown, is refused with
* [SparkError.RestoredInvoiceUnverified] unless [isUnsentPerOperators].
*/
private suspend fun refuseUnverifiedRestoredInvoice(invoiceCreatedAt: Long?, invoiceExpiresAt: Long?) {
private suspend fun refuseUnverifiedRestoredInvoice(
bolt11: String,
invoiceCreatedAt: Long?,
invoiceExpiresAt: Long?,
) {
val restoredAt = cacheStore.data.first().sparkRestoredAt ?: return
val isHeld = sparkService.isSupported &&
(invoiceCreatedAt ?: 0L) < restoredAt &&
(invoiceExpiresAt == null || clock.now().epochSeconds < invoiceExpiresAt)
if (!isHeld) return
Logger.warn("Refused a send of a pre-restore invoice Spark hasn't listed", context = TAG)
if (!isHeld || isUnsentPerOperators(bolt11)) return
Logger.warn("Refused a send of a pre-restore invoice the Spark operators can't show unsent", context = TAG)
throw SparkError.RestoredInvoiceUnverified()
}

/**
* 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.
*/
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)
Comment thread
ovitrif marked this conversation as resolved.
Resolved
return false
}
Comment thread
ovitrif marked this conversation as resolved.
Resolved
// A send preferring Spark pays an invoice's Spark address as a direct transfer.
if (!sparkService.prefersSpark) return true
return runCatching { !sparkService.carriesSparkAddress(bolt11) }.getOrDefault(false)
}

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

/** The count of sends recorded so far, read before a node send's checks for [hasRecordedSendSince]. */
Expand Down
21 changes: 21 additions & 0 deletions app/src/main/java/to/bitkit/services/SparkService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import breez_sdk_spark.EventListener
import breez_sdk_spark.FeePolicy
import breez_sdk_spark.FetchClaimDepositQuoteRequest
import breez_sdk_spark.FetchClaimDepositQuoteResponse
import breez_sdk_spark.FetchLightningSendStatusRequest
import breez_sdk_spark.GetInfoRequest
import breez_sdk_spark.GetInfoResponse
import breez_sdk_spark.ImportUnilateralExitStateRequest
Expand All @@ -25,6 +26,7 @@ import breez_sdk_spark.MaxOnchainFee
import breez_sdk_spark.OnchainConfirmationSpeed
import breez_sdk_spark.Payment
import breez_sdk_spark.PaymentRequest
import breez_sdk_spark.PaymentStatus
import breez_sdk_spark.PrepareRecoverFundsRequest
import breez_sdk_spark.PrepareRecoverFundsResponse
import breez_sdk_spark.PrepareSendPaymentRequest
Expand All @@ -46,6 +48,7 @@ import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.lightningdevkit.ldknode.Bolt11Invoice
import org.lightningdevkit.ldknode.Network
import to.bitkit.data.keychain.Keychain
import to.bitkit.env.Env
Expand Down Expand Up @@ -127,6 +130,13 @@ class SparkService @Inject constructor(
*/
fun bolt11SendOptions(prefersSpark: Boolean): SendPaymentOptions =
SendPaymentOptions.Bolt11Invoice(preferSpark = prefersSpark, completionTimeoutSecs = null)

/** The route hint short channel id under which an invoice carries its Spark address, as spark-sdk sets it. */
private const val SPARK_ADDRESS_HINT_SCID = 17_592_187_092_992_000_001uL

/** Whether [shortChannelIds], an invoice's route hint hops, carry a Spark address. */
internal fun hasSparkAddressHint(shortChannelIds: List<ULong>): Boolean =
SPARK_ADDRESS_HINT_SCID in shortChannelIds
}

private val mutex = Mutex()
Expand Down Expand Up @@ -295,6 +305,17 @@ class SparkService @Inject constructor(
suspend fun invoiceExpiresAt(bolt11: String): ULong? =
(requireSdk().parse(bolt11) as? InputType.Bolt11Invoice)?.v1?.let { invoiceExpiresAt(it.timestamp, it.expiry) }

/**
* This wallet's Lightning send of [bolt11] as the Spark operators record it, without the local history: null when
* they know none. A direct Spark transfer to the invoice's Spark address is not covered.
*/
suspend fun lightningSendStatus(bolt11: String): PaymentStatus? =
requireSdk().fetchLightningSendStatus(FetchLightningSendStatusRequest(bolt11)).status

/** Whether [bolt11] carries a Spark address, so a send preferring Spark pays it as a direct transfer. */
fun carriesSparkAddress(bolt11: String): Boolean =
hasSparkAddressHint(Bolt11Invoice.fromStr(bolt11).routeHints().flatten().map { it.shortChannelId })

/** Exports what a unilateral exit needs if the Spark operators stop cooperating; it can reach several MB. */
suspend fun exportExitState(): String = requireSdk().exportUnilateralExitState().exitState

Expand Down
Loading
Loading