diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 136c9413d1..849446f9e5 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -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, expiries: Map = 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, + ) + } + } + + /** After a restore, keeps [paymentHashes], the node's pending and paid sends from its own list, once. */ + suspend fun seedRestoredLdkSendHashes(paymentHashes: List) { + 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 @@ -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. + */ + val sparkRestoredAt: Long? = null, ) { fun isContactDetached(activityId: String, walletId: String): Boolean = scopedActivityId(walletId, activityId) in detachedActivityContacts diff --git a/app/src/main/java/to/bitkit/ext/PaymentFailureReasonExt.kt b/app/src/main/java/to/bitkit/ext/PaymentFailureReasonExt.kt index 6ac4dc62ae..fa3790a8aa 100644 --- a/app/src/main/java/to/bitkit/ext/PaymentFailureReasonExt.kt +++ b/app/src/main/java/to/bitkit/ext/PaymentFailureReasonExt.kt @@ -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() diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 4945114a10..2faa96a4e2 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -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 @@ -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 @@ -1201,7 +1213,16 @@ class BackupRepo @Inject constructor( ) val parsed = decodeBackup(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, + sparkRestoredAt = restoredAt, + ) + } Logger.debug("Restored caches: ${jsonLogOf(parsed.cache.copy(cachedRates = emptyList()))}", TAG) onCacheRestored() val persisted = preActivityMetadataRepo.upsertPreActivityMetadata(parsed.tagMetadata) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 63b44b991b..a3231b62d6 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -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) @@ -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 { @@ -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) @@ -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() } @@ -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() @@ -2740,8 +2766,15 @@ class LightningRepo @Inject constructor( } } - suspend fun estimateRoutingFees(bolt11: String): Result = executeWhenNodeRunning("estimateRoutingFees") { - if (shouldPayWithSpark(bolt11, null)) return@executeWhenNodeRunning sparkRepo.estimateFeeSats(bolt11, null) + suspend fun estimateRoutingFees(bolt11: String): Result { + // 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 = executeWhenNodeRunning( + "estimateRoutingFees" + ) { Logger.info("Estimating routing fees for bolt11: $bolt11", context = TAG) lightningService.estimateRoutingFees(bolt11).onSuccess { Logger.info("Routing fees estimated: '$it'", context = TAG) @@ -2750,11 +2783,13 @@ class LightningRepo @Inject constructor( } } - suspend fun estimateRoutingFeesForAmount(bolt11: String, amountSats: ULong): Result = + suspend fun estimateRoutingFeesForAmount(bolt11: String, amountSats: ULong): Result { + if (shouldPayWithSpark(bolt11, amountSats)) return sparkRepo.estimateFeeSats(bolt11, amountSats) + return estimateNodeRoutingFeesForAmount(bolt11, amountSats) + } + + private suspend fun estimateNodeRoutingFeesForAmount(bolt11: String, amountSats: ULong): Result = 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) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index f3a06f67f0..e0130e120c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -121,6 +121,13 @@ class SparkRepo @Inject constructor( @Volatile private var withdrawalFailedAtSecs: ULong? = null + /** + * When a withdrawal moved the whole balance, in epoch seconds, so a read of 0 is real until a sync after it reads + * a balance again. A refresh that read its balance before the withdrawal can't clear it. + */ + @Volatile + private var withdrewAllAtSecs: ULong? = null + /** Deposits this app broadcast that Spark hasn't listed yet, by txid, so they show as pending at once. */ private val broadcastDeposits = ConcurrentHashMap() @@ -212,6 +219,7 @@ class SparkRepo @Inject constructor( preparedWithdrawal = null withdrawalTxids.clear() withdrawalFailedAtSecs = null + withdrewAllAtSecs = null broadcastDeposits.clear() sendsRecordedWithoutFee.clear() unsavedPayments.clear() @@ -226,7 +234,7 @@ class SparkRepo @Inject constructor( fun canReceive(): Boolean = _state.value.isReady - fun canSend(amountSats: ULong): Boolean = _state.value.isReady && _state.value.sendableSats >= amountSats + fun canSend(amountSats: ULong): Boolean = _state.value.canSend(amountSats) suspend fun createInvoice(amountSats: ULong?, description: String, expirySecs: UInt): Result = withContext(bgDispatcher) { @@ -266,7 +274,9 @@ class SparkRepo @Inject constructor( * when Spark refuses an expired invoice at prepare or send; and with [ServiceError.PaymentDeadlineExpired] past * [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. + * 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 + * [SparkError.RestoredInvoiceUnverified], under the same rule as the node's send. */ suspend fun payInvoice( bolt11: String, @@ -290,6 +300,8 @@ class SparkRepo @Inject constructor( } ensurePaymentDeadline(paymentDeadlineAt) val paymentHash = method.invoiceDetails.paymentHash + val invoice = method.invoiceDetails + val expiresAt = invoice.timestamp.safe() + invoice.expiry.safe() when (val earlier = lightningSend(paymentHash)) { is SparkLightningSend.Found if earlier.status == PaymentStatus.COMPLETED -> { Logger.info("Skipped Spark send of '$paymentHash', already paid", context = TAG) @@ -297,25 +309,32 @@ class SparkRepo @Inject constructor( } is SparkLightningSend.Found if earlier.status == PaymentStatus.PENDING -> throw PaymentPendingException(paymentHash) - else -> Unit + // 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()) } // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. if (!onBeforeSend()) throw PaymentAbortedBeforeSend() if (sendsInFlight.putIfAbsent(paymentHash.lowercase(), bolt11) != null) { throw PaymentPendingException(paymentHash) } - val invoice = method.invoiceDetails - val expiresAt = invoice.timestamp.safe() + invoice.expiry.safe() val sent = try { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() - cacheStore.addSparkSendHash(paymentHash, expiresAt.coerceAtMost(Long.MAX_VALUE.toULong()).toLong()) - // The checks above and saving the hash suspend, so the deadline is checked last, before the send. + cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) + // Kept until the call returns, so a send cut off by process death or cancellation stays held. + cacheStore.addSparkUncertainSend(paymentHash, clock.now().epochSeconds) + // The checks above and both writes suspend, so the deadline is checked last, before the send. runCatching { ensurePaymentDeadline(paymentDeadlineAt) }.onFailure { + cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) throw it } - // Kept until the call returns, so a send cut off by process death or cancellation stays held. - cacheStore.addSparkUncertainSend(paymentHash, clock.now().epochSeconds) runSuspendCatching { sparkService.send(prepared) } } finally { sendsInFlight.remove(paymentHash.lowercase()) @@ -569,6 +588,7 @@ class SparkRepo @Inject constructor( Unit }.onSuccess { withdrawalFailedAtSecs = null + withdrewAllAtSecs = clock.now().epochSeconds.toULong() runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after its withdrawal", it, context = TAG) } }.onFailure { @@ -729,13 +749,17 @@ class SparkRepo @Inject constructor( val failedAt = withdrawalFailedAtSecs val hasSyncedSince = failedAt != null && info.lastSyncError == null && (info.lastSyncedAt ?: 0uL) > failedAt if (info.balanceSats > 0uL || hasSyncedSince) withdrawalFailedAtSecs = null + val withdrewAllAt = withdrewAllAtSecs + if (withdrewAllAt != null && info.balanceSats > 0uL && (info.lastSyncedAt ?: 0uL) > withdrewAllAt) { + withdrewAllAtSecs = null + } val isStale = withdrawalFailedAtSecs != null || info.lastSyncError != null _state.update { it.copy( isReady = true, balanceSats = info.balanceSats, keptBalanceSats = it.shownBalanceSats.takeIf { kept -> - info.balanceSats == 0uL && isStale && kept > 0uL + info.balanceSats == 0uL && isStale && withdrewAllAtSecs == null && kept > 0uL }, pendingDepositSats = pending.sumOf { deposit -> deposit.amountSats }, deposits = (pending + claimed).toImmutableList(), @@ -876,9 +900,19 @@ 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. + * 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. */ - suspend fun earlierLightningSend(bolt11: String, paymentHash: String?): EarlierSend? = + suspend fun earlierLightningSend( + bolt11: String, + paymentHash: String?, + invoiceCreatedAt: Long? = null, + invoiceExpiresAt: Long? = null, + ): EarlierSend? = withContext(bgDispatcher) { val recordsBefore = sendRecords.get() val keptUncertain = cacheStore.data.first().sparkUncertainSends.keys @@ -903,15 +937,33 @@ class SparkRepo @Inject constructor( } else { null } - if (payments == null) return@withContext startedSend(paymentHash)?.let { EarlierSend.Pending(it) } + 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) + return@withContext null + } + seedSendHashes(payments) val send = payments .latestSend { it.invoice.equals(bolt11, ignoreCase = true) || it.htlcDetails.paymentHash.equals(paymentHash, ignoreCase = true) } - ?: return@withContext (retried() ?: paymentHash?.lowercase()?.takeIf { it in unlisted }) - ?.let { EarlierSend.Pending(it) } - if (send.status == PaymentStatus.FAILED) retried()?.let { return@withContext EarlierSend.Pending(it) } + if (send == null) { + (retried() ?: paymentHash?.lowercase()?.takeIf { it in unlisted }) + ?.let { return@withContext EarlierSend.Pending(it) } + refuseUnverifiedRestoredInvoice(invoiceCreatedAt, invoiceExpiresAt) + return@withContext null + } + if (send.status == PaymentStatus.FAILED) { + retried()?.let { return@withContext EarlierSend.Pending(it) } + refuseUnverifiedRestoredInvoice(invoiceCreatedAt, invoiceExpiresAt) + } val hash = (send.details as PaymentDetails.Lightning).htlcDetails.paymentHash when (send.status) { PaymentStatus.PENDING -> EarlierSend.Pending(hash) @@ -920,6 +972,34 @@ 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() + } + + /** + * 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. + */ + private suspend fun refuseUnverifiedRestoredInvoice(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) + throw SparkError.RestoredInvoiceUnverified() + } + + 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]. */ fun sendRecordMark(): Long = sendRecords.get() @@ -998,12 +1078,41 @@ class SparkRepo @Inject constructor( ?.toSet() } + /** + * 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. + */ + private suspend fun seedRestoredSendHashes() { + if (cacheStore.data.first().sparkHistoryUnseededSince == null || !canListPayments()) return + runSuspendCatching { sparkService.listPayments() } + .onSuccess { seedSendHashes(it) } + .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } + } + + /** Keeps Spark's pending and paid sends once, from a list read after it synced, so a restart holds the node off. */ + private suspend fun seedSendHashes(payments: List) { + if (cacheStore.data.first().sparkHistoryUnseededSince == null) return + val sends = payments + .filter { it.status != PaymentStatus.FAILED && it.sendHash() != null } + .sortedBy { it.timestamp } + // A seeded send keeps its invoice's expiry, so Spark holds it while valid and the cap never drops it early. + val expiries = sends.mapNotNull { send -> + val invoice = (send.details as PaymentDetails.Lightning).invoice + val expiresAt = runSuspendCatching { sparkService.invoiceExpiresAt(invoice) }.getOrNull() + expiresAt?.let { requireNotNull(send.sendHash()) to it.coerceAtMost(Long.MAX_VALUE.toULong()).toLong() } + }.toMap() + cacheStore.seedSparkSendHashes(sends.mapNotNull { it.sendHash() }, expiries) + } + /** Records every Spark payment, returning whether all were saved, so a failed write leaves the sync to redo. */ private suspend fun syncActivities(): Boolean { // Read after the records, as a send counts as in flight before it is recorded, so one of the two shows it. val recordsBefore = sendRecords.get() val inFlightBefore = sendsInFlight.keys.toSet() + // Read before the list, as one read before Spark's first sync can lack its restored sends. + val isSynced = canListPayments() val payments = sparkService.listPayments() + if (isSynced) seedSendHashes(payments) val isSaved = payments.map { recordActivity(it) }.all { it } val sendHashes = { status: PaymentStatus -> payments.mapNotNullTo(mutableSetOf()) { it.sendHash(status)?.lowercase() } @@ -1051,6 +1160,7 @@ class SparkRepo @Inject constructor( is SdkEvent.Synced -> { // Spark also reports Synced for a partial or skipped sync, while its wallet sync still fails. if (hasSyncedSince(null)) _state.update { it.copy(hasSynced = true) } + seedRestoredSendHashes() refresh() // A send whose outcome stayed unknown past its polling settles on a later sync. uncertainSends.keys.toList().forEach { trySettleUncertainSend(it) } @@ -1203,7 +1313,8 @@ data class SparkState( val balanceSats: ULong = 0uL, /** * The balance shown while Spark reads 0 after a failed withdrawal or a failed sync, with the funds likely still - * there; null once Spark reads a balance again or syncs after the failure. Never offered to a send. + * there; null once Spark reads a balance again or syncs after the failure, and after a full withdrawal, whose 0 is + * real. Never offered to a send. */ val keptBalanceSats: ULong? = null, /** Deposits seen on-chain that Spark claims into [balanceSats] after 3 confirmations. */ @@ -1214,6 +1325,9 @@ data class SparkState( /** The most Spark can send once its service fee is paid, so a payment near the full balance isn't offered. */ val sendableSats: ULong get() = SparkFees.sendableSats(balanceSats) + /** Whether Spark is ready and can send [amountSats] once its service fee is paid. */ + fun canSend(amountSats: ULong): Boolean = isReady && sendableSats >= amountSats + /** The balance shown in Spending and on the Spark connection, which [keptBalanceSats] stands in for. */ val shownBalanceSats: ULong get() = keptBalanceSats ?: balanceSats } diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index d1f1e5b8ba..f7488d1ac3 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -14,6 +14,7 @@ import breez_sdk_spark.GetInfoRequest import breez_sdk_spark.GetInfoResponse import breez_sdk_spark.ImportUnilateralExitStateRequest import breez_sdk_spark.ImportUnilateralExitStateResponse +import breez_sdk_spark.InputType import breez_sdk_spark.ListPaymentsRequest import breez_sdk_spark.ListUnclaimedDepositsRequest import breez_sdk_spark.MaxFee @@ -61,6 +62,9 @@ class SparkService @Inject constructor( private val keychain: Keychain, ) { companion object { + /** When an invoice made at [timestamp] with [expiry] seconds to live expires, in epoch seconds. */ + internal fun invoiceExpiresAt(timestamp: ULong, expiry: ULong): ULong = timestamp.safe() + expiry.safe() + private const val TAG = "SparkService" /** @@ -272,6 +276,10 @@ class SparkService @Inject constructor( suspend fun listPayments(): List = requireSdk().listPayments(ListPaymentsRequest()).payments + /** When [bolt11] expires, in epoch seconds, read by the SDK's own parser; null when it isn't a BOLT11 invoice. */ + suspend fun invoiceExpiresAt(bolt11: String): ULong? = + (requireSdk().parse(bolt11) as? InputType.Bolt11Invoice)?.v1?.let { invoiceExpiresAt(it.timestamp, it.expiry) } + /** Exports what a unilateral exit needs if the Spark operators stop cooperating; it can reach several MB. */ suspend fun exportExitState(): String = requireSdk().exportUnilateralExitState().exitState @@ -305,10 +313,14 @@ sealed class SparkError(message: String, cause: Throwable? = null) : AppError(me /** * Spark refused a Lightning payment before anything left the wallet: it was not connected, could not prepare the - * payment, or its fee was over the caller's limit. A Paykit request or allowance attempt can then end as failed. + * payment, or its fee was over the caller's limit; or the node refused one because Spark hadn't listed its earlier + * sends yet. A Paykit request or allowance attempt can then end as failed. */ open class SendRefused(message: String, cause: Throwable? = null) : SparkError(message, cause) /** Spark refused to pay an expired Lightning invoice, before anything left the wallet. */ class InvoiceExpired(cause: Throwable? = null) : SendRefused("The Lightning invoice has expired", cause) + + /** Refused a still-valid invoice created before the restore, as Spark can't show it didn't pay it then. */ + class RestoredInvoiceUnverified : SendRefused("Spark can't show it didn't pay this invoice before the restore") } diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendQuickPayScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendQuickPayScreen.kt index c83ca98375..9e0c0c5cb5 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendQuickPayScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendQuickPayScreen.kt @@ -30,6 +30,7 @@ import to.bitkit.ui.scaffold.SheetTopBar import to.bitkit.ui.screens.transfer.components.TransferAnimationView import to.bitkit.ui.shared.modifiers.sheetHeight import to.bitkit.ui.shared.util.gradientBackground +import to.bitkit.ui.sheets.canSendWithoutWaiting import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors import to.bitkit.ui.utils.withAccent @@ -41,6 +42,7 @@ import to.bitkit.viewmodels.QuickPayViewModel fun SendQuickPayScreen( quickPayData: QuickPayData, isRequestActive: Boolean, + canPayWithoutNode: Boolean, onPaymentComplete: (String, Long) -> Unit, onPaymentPending: (String, Long, String) -> Unit, onFallBackToConfirm: () -> Unit, @@ -56,8 +58,14 @@ fun SendQuickPayScreen( onDispose { viewModel.detach(session) } } - LaunchedEffect(quickPayData, lightningState.nodeLifecycleState, isRequestActive) { - if (isRequestActive && lightningState.nodeLifecycleState is NodeLifecycleState.Running) { + // Spark pays a Quick Pay invoice it can cover without the node, so only an otherwise unpayable one waits. + val canPay = canSendWithoutWaiting( + isNodeRunning = lightningState.nodeLifecycleState is NodeLifecycleState.Running, + isHardwareWallet = false, + sparkCanPay = canPayWithoutNode, + ) + LaunchedEffect(quickPayData, canPay, isRequestActive) { + if (isRequestActive && canPay) { viewModel.pay(session, quickPayData) } } @@ -84,7 +92,7 @@ fun SendQuickPayScreen( Content( amount = quickPayData.sats, - nodeLifecycleState = lightningState.nodeLifecycleState, + nodeLifecycleState = if (canPay) NodeLifecycleState.Running else lightningState.nodeLifecycleState, ) } diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index 7906998ac3..fd2c3a9df8 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -56,6 +56,7 @@ import to.bitkit.models.WalletScope import to.bitkit.repositories.ConnectivityState import to.bitkit.repositories.PaykitPaymentRequest import to.bitkit.repositories.PaykitSubscriptionId +import to.bitkit.repositories.SparkState import to.bitkit.ui.components.ConnectionIssuesView import to.bitkit.ui.components.SyncNodeVariant import to.bitkit.ui.components.SyncNodeView @@ -98,6 +99,7 @@ import to.bitkit.ui.utils.composableWithDefaultTransitions import to.bitkit.ui.utils.navigationWithDefaultTransitions import to.bitkit.viewmodels.AppViewModel import to.bitkit.viewmodels.LnurlParams +import to.bitkit.viewmodels.QuickPayData import to.bitkit.viewmodels.SendEffect import to.bitkit.viewmodels.SendEvent import to.bitkit.viewmodels.SendMethod @@ -110,6 +112,34 @@ private const val HARDWARE_SEND_FALLBACK_SATS_PER_VBYTE = 3uL /** A peer reconnecting makes a channel usable again without any node event, so the overlay polls. */ private val CHANNELS_REFRESH_INTERVAL = 1.seconds +/** Whether Spark can pay the scanned Lightning invoice's own amount, so an amountless one still waits for the node. */ +internal fun sparkCanPayInvoice(payMethod: SendMethod, invoiceSats: ULong?, sparkState: SparkState): Boolean = + payMethod == SendMethod.LIGHTNING && invoiceSats != null && invoiceSats > 0uL && sparkState.canSend(invoiceSats) + +/** Whether Spark can pay a Quick Pay invoice; an LNURL one still waits for the node. */ +internal fun sparkCanPayQuickPay(data: QuickPayData, sparkState: SparkState): Boolean = + data is QuickPayData.Bolt11 && sparkCanPayInvoice(SendMethod.LIGHTNING, data.sats, sparkState) + +/** Whether a send can go ahead now: the node runs, a hardware wallet signs it, or Spark pays it without the node. */ +internal fun canSendWithoutWaiting(isNodeRunning: Boolean, isHardwareWallet: Boolean, sparkCanPay: Boolean): Boolean = + isNodeRunning || isHardwareWallet || sparkCanPay + +/** + * A Lightning payment Spark can pay goes ahead without the node. Otherwise the node must run, and with channels a + * payment waits for a usable one. With no channels at all there is nothing to sync into, so validation reports the + * missing capacity instead. + */ +internal fun waitsForNode( + isNodeRunning: Boolean, + hasAnyChannels: Boolean, + hasUsableChannels: Boolean, + sparkCanPay: Boolean, +): Boolean { + if (sparkCanPay) return false + if (!isNodeRunning) return true + return hasAnyChannels && !hasUsableChannels +} + internal fun NavDestination.isPaymentReview(): Boolean = hasRoute() || hasRoute() || hasRoute() || hasRoute() @@ -153,11 +183,17 @@ fun SendSheet( val hasAnyChannels = lightningState.channels.isNotEmpty() val syncNodeVariant = if (hasAnyChannels) SyncNodeVariant.LIGHTNING else SyncNodeVariant.BITCOIN + val sparkState by walletViewModel.sparkState.collectAsStateWithLifecycle() + val sparkCanPay = sparkCanPayInvoice(sendUiState.payMethod, sendUiState.decodedInvoice?.amountSatoshis, sparkState) val shouldShowSyncOverlay = run { if (preparingRequest != null || sendUiState.paykitUsesUsdt) return@run false if (sendUiState.hardwareWalletId != null) return@run false - if (!lightningState.nodeLifecycleState.isRunning()) return@run true - hasAnyChannels && lightningState.channels.none { it.isUsable } + waitsForNode( + isNodeRunning = lightningState.nodeLifecycleState.isRunning(), + hasAnyChannels = hasAnyChannels, + hasUsableChannels = lightningState.channels.any { it.isUsable }, + sparkCanPay = sparkCanPay, + ) } val lifecycle = LocalLifecycleOwner.current.lifecycle @@ -494,8 +530,11 @@ fun SendSheet( SendConfirmScreen( savedStateHandle = it.savedStateHandle, uiState = uiState, - isNodeRunning = uiState.hardwareWalletId != null || - lightningState.nodeLifecycleState.isRunning(), + isNodeRunning = canSendWithoutWaiting( + isNodeRunning = lightningState.nodeLifecycleState.isRunning(), + isHardwareWallet = uiState.hardwareWalletId != null, + sparkCanPay = sparkCanPay, + ), canAutoStart = !isOffline && !shouldShowSyncOverlay, syncNodeVariant = syncNodeVariant, canGoBack = navController.previousBackStackEntry != null, @@ -673,6 +712,7 @@ fun SendSheet( SendQuickPayScreen( quickPayData = request.data, isRequestActive = quickPayRequest?.id == request.id, + canPayWithoutNode = sparkCanPayQuickPay(request.data, sparkState), onPaymentComplete = { paymentHash, amountWithFee -> appViewModel.onSendSuccess( NewTransactionSheetDetails( diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ec41b4b33e..f6192342ca 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1499,6 +1499,7 @@ Received Bitcoin The Lightning payment was stopped before it completed. This Lightning payment expired. Please request a new invoice. + Bitkit can\'t confirm this invoice wasn\'t paid before you restored your wallet. Please request a new invoice. Your instant payment failed. Please try again. This Lightning invoice request expired. Please request a new invoice. The recipient rejected this Lightning invoice request. diff --git a/app/src/test/java/to/bitkit/ext/PaymentFailureReasonExtTest.kt b/app/src/test/java/to/bitkit/ext/PaymentFailureReasonExtTest.kt index 1ac125eb12..b7c2f92e9e 100644 --- a/app/src/test/java/to/bitkit/ext/PaymentFailureReasonExtTest.kt +++ b/app/src/test/java/to/bitkit/ext/PaymentFailureReasonExtTest.kt @@ -49,6 +49,17 @@ class PaymentFailureReasonExtTest { ) } + @Test + fun `a refused pre-restore invoice asks for a new invoice`() { + val message = "Please request a new invoice." + whenever(context.getString(R.string.wallet__payment_failed_description)).thenReturn("Generic payment failed") + whenever(context.getString(R.string.wallet__payment_restored_invoice)).thenReturn(message) + + assertEquals(message, SparkError.RestoredInvoiceUnverified().toSendFailureMessage(context)) + val wrapped = IllegalStateException(SparkError.RestoredInvoiceUnverified()) + assertEquals(message, wrapped.toSendFailureMessage(context)) + } + @Test fun `spark failures show the existing payment failure copy`() { val message = "Generic payment failed" diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index a21e8842bd..70901da134 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -105,6 +105,7 @@ import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNotEquals +import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock @@ -1829,6 +1830,60 @@ class BackupRepoTest : BaseUnitTest() { verify(vssBackupClient, never()).putObject(any(), any()) } + @Test + fun `a metadata restore keeps spark's backed-up send hashes but holds older invoices until spark lists them`() = + test { + val publicAddress = "bcrt1qpublic" + stubPublicAddressRestore(publicAddress) + stubMetadataRestore( + envelope = metadataEnvelope( + metadata = listOf(preActivityMetadata()), + cache = AppCacheData(onchainAddress = publicAddress, sparkSendHashes = listOf("hash")), + ), + ) + + sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertEquals(listOf("hash"), cacheData.value.sparkSendHashes) + assertNotNull(cacheData.value.sparkHistoryUnseededSince) + assertNotNull(cacheData.value.sparkRestoredAt) + } + + @Test + fun `a restore without a metadata backup still holds older invoices on both rails`() = test { + whenever { cacheStore.update(any()) }.thenAnswer { + cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) + } + + sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertNotNull(cacheData.value.sparkHistoryUnseededSince) + assertNotNull(cacheData.value.ldkHistoryUnseededSince) + assertNotNull(cacheData.value.sparkRestoredAt) + } + + @Test + fun `a metadata restore holds older invoices until the node lists its own sends`() = test { + val publicAddress = "bcrt1qpublic" + stubPublicAddressRestore(publicAddress) + stubMetadataRestore( + envelope = metadataEnvelope( + metadata = listOf(preActivityMetadata()), + cache = AppCacheData( + onchainAddress = publicAddress, + ldkSendHashes = listOf("hash"), + ldkSendHashesSeeded = true, + ), + ), + ) + + sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertEquals(listOf("hash"), cacheData.value.ldkSendHashes) + assertTrue(cacheData.value.ldkSendHashesSeeded) + assertNotNull(cacheData.value.ldkHistoryUnseededSince) + } + @Test fun `metadata cache failure remains optional after public address quarantine succeeds`() = test { val publicAddress = "bcrt1qpublic" @@ -1837,7 +1892,9 @@ class BackupRepoTest : BaseUnitTest() { doAnswer { val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) val updated = transform(cacheData.value) - if (failCacheWrite && updated.backupStatuses == cacheData.value.backupStatuses) { + // The metadata cache write follows the restore's own write of its holds. + val isMetadataWrite = cacheData.value.sparkHistoryUnseededSince != null + if (failCacheWrite && isMetadataWrite && updated.backupStatuses == cacheData.value.backupStatuses) { failCacheWrite = false throw BackupRepoTestError("cache store unavailable") } @@ -1853,6 +1910,7 @@ class BackupRepoTest : BaseUnitTest() { verify(privatePaykitRepo).restoreBackup(null) assertTrue(createReservationRepo(reservationStore).isUnavailableForReusableReceive(publicAddress)) verify(vssBackupClient, never()).putObject(eq(BackupCategory.METADATA.name), any()) + assertFalse(failCacheWrite, "the metadata cache write never failed") } @Test diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 888909b361..4bdee90058 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -157,6 +157,7 @@ class LightningRepoTest : BaseUnitTest() { private val probePaymentB = "probe-payment-b" private val probeHashA = "probe-hash-a" private val probeHashB = "probe-hash-b" + private val restoredAt = 1_800_000_000L private val probeNodeId = "02abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdef12" @Before @@ -1347,6 +1348,66 @@ class LightningRepoTest : BaseUnitTest() { assertEquals("hash", sut.payInvoice("bolt11", 1_000uL).getOrThrow()) } + @Test + fun `spark refuses an invoice from before the restore while the node hasn't listed since it`() = test { + startNodeForTesting() + restoredCacheWithInvoiceAt(restoredAt - 60) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + + assertIs(sut.payInvoice("bolt11", 1_000uL).exceptionOrNull()) + whenever(coreService.decode("bolt11")).thenThrow(IllegalStateException("undecodable")) + assertIs(sut.payInvoice("bolt11", 1_000uL).exceptionOrNull()) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `spark pays an invoice from after the restore while the node is down`() = test { + startNodeForTesting() + restoredCacheWithInvoiceAt(restoredAt + 60) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + + assertEquals("hash", sut.payInvoice("bolt11", 1_000uL).getOrThrow()) + } + + @Test + fun `spark is never held on an install that was never restored`() = test { + startNodeForTesting() + whenever(coreService.decode("bolt11")) + .thenReturn(Scanner.Lightning(lightningInvoice("bolt11").copy(timestampSeconds = 1uL))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + + assertEquals("hash", sut.payInvoice("bolt11", 1_000uL).getOrThrow()) + } + + @Test + fun `the node's listing after a restore seeds its hashes and ends the hold`() = test { + val cache = AppCacheData(ldkSendHashesSeeded = true, ldkHistoryUnseededSince = restoredAt) + val store = CacheStore(InMemoryDataStore(cache)) + sut = repoWith(store) + whenever(lightningService.listPayments()).thenReturn(listOf(nodeSend("paid", PaymentStatus.SUCCEEDED))) + + startNodeForTesting() + + assertNull(store.data.first().ldkHistoryUnseededSince) + assertEquals(listOf("paid"), store.data.first().ldkSendHashes) + } + + private suspend fun restoredCacheWithInvoiceAt(createdAt: Long) { + val cache = AppCacheData(ldkSendHashesSeeded = true, ldkHistoryUnseededSince = restoredAt) + whenever(cacheStore.data).thenReturn(flowOf(cache)) + whenever(coreService.decode("bolt11")) + .thenReturn(Scanner.Lightning(lightningInvoice("bolt11").copy(timestampSeconds = createdAt.toULong()))) + } + @Test fun `spark waits for the node's first listing when its earlier sends were never kept`() = test { startNodeForTesting() @@ -2008,6 +2069,15 @@ class LightningRepoTest : BaseUnitTest() { assertEquals(testPaymentId, result.getOrNull()) } + @Test + fun `a node send outside a restore hold leaves the invoice undecoded`() = test { + startNodeForTesting() + whenever(lightningService.send("bolt11", 1000uL)).thenReturn("payment-id") + + assertEquals("payment-id", sut.payInvoice("bolt11", 1000uL).getOrThrow()) + verify(coreService, never()).decode(any()) + } + @Test fun `payInvoice forwards the payment deadline after final authorization`() = test { startNodeForTesting() @@ -4239,6 +4309,15 @@ class LightningRepoTest : BaseUnitTest() { assertTrue(result.isFailure) } + @Test + fun `a fee estimate spark pays needs no running node`() = test { + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.estimateFeeSats("bolt11", 1_000uL)).thenReturn(Result.success(3uL)) + + assertEquals(3uL, sut.estimateRoutingFeesForAmount("bolt11", 1_000uL).getOrThrow()) + verify(lightningService, never()).estimateRoutingFeesForAmount(any(), any()) + } + @Test fun `estimateRoutingFees should succeed when node is running`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index c3d2fa1273..e43cec702a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -76,6 +76,7 @@ import to.bitkit.utils.ServiceError import java.io.File import java.math.BigInteger import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNull @@ -205,6 +206,257 @@ class SparkRepoTest : BaseUnitTest() { assertNull(createSut().earlierLightningSend("lnbc1280n1send", "hash")) } + @Test + fun `a restored wallet's unsynced history refuses the node's send of an invoice from before the restore`() = + test { + cacheData.value = AppCacheData(sparkHistoryUnseededSince = now.epochSeconds) + whenever(sparkService.isConnected).thenReturn(true) + val sut = createSut() + + assertFailsWith { + sut.earlierLightningSend("lnbc1280n1send", "hash", invoiceCreatedAt = now.epochSeconds - 60) + } + assertFailsWith { sut.earlierLightningSend("lnbc1280n1send", "hash") } + } + + @Test + fun `a pre-restore invoice spark's synced list lacks is refused over the node until it expires`() = test { + val restoredAt = now.epochSeconds - 60 + val cache = AppCacheData(sparkHistoryUnseededSince = restoredAt, sparkRestoredAt = restoredAt) + val store = CacheStore(InMemoryDataStore(cache), clock) + whenever(sparkService.isConnected).thenReturn(true) + // Spark reports Synced while its payment-history sync failed, so its list lacks the pre-restore send. + whenever { sparkService.listPayments() }.thenReturn(emptyList()) + val sut = createSut(store) + sut.start(0).getOrThrow() + val createdAt = restoredAt - 600 + + assertFailsWith { + sut.earlierLightningSend("lnbc1280n1send", "hash", createdAt, invoiceExpiresAt = now.epochSeconds + 600) + } + assertNull(store.data.first().sparkHistoryUnseededSince, "spark's own list still seeds the kept hashes") + assertFailsWith { + sut.earlierLightningSend("lnbc1280n1send", "hash", createdAt, invoiceExpiresAt = now.epochSeconds + 600) + } + assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash", createdAt, invoiceExpiresAt = now.epochSeconds)) + assertNull(sut.earlierLightningSend("lnbc1280n1new", "new", now.epochSeconds, now.epochSeconds + 600)) + } + + @Test + fun `a pre-restore invoice that outlasts a week is still refused on both rails on day 8`() = test { + val restoredAt = now.epochSeconds - 8 * 24 * 60 * 60L + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkRestoredAt = restoredAt)), clock) + whenever(sparkService.isConnected).thenReturn(true) + val createdAt = restoredAt - 600 + val expirySecs = 30 * 24 * 60 * 60L + val prepared = prepared(feeSats = 0uL, createdAt = createdAt.toULong(), expirySecs = expirySecs.toULong()) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + val sut = createSut(store) + sut.start(0).getOrThrow() + + assertTrue(sut.holdsRestoredInvoices()) + assertFailsWith { + sut.earlierLightningSend("lnbc1280n1send", "hash", createdAt, createdAt + expirySecs) + } + assertIs(sut.payInvoice("lnbc1280n1send", 128uL).exceptionOrNull()) + verify(sparkService, never()).send(any()) + } + + @Test + fun `an invoice created after the restore pays over the node while spark is unsynced`() = test { + cacheData.value = AppCacheData(sparkHistoryUnseededSince = now.epochSeconds) + whenever(sparkService.isConnected).thenReturn(false) + + assertNull(createSut().earlierLightningSend("lnbc1280n1send", "hash", invoiceCreatedAt = now.epochSeconds + 60)) + } + + @Test + fun `an updated install that was never restored is never held while spark is unsynced`() = test { + whenever(sparkService.isConnected).thenReturn(false) + val sut = createSut() + + assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash", invoiceCreatedAt = 1L)) + assertNull(sut.earlierLightningSend("lnbc1280n1send", "hash")) + } + + @Test + fun `spark's synced list seeds the restored hashes and a later unsynced start still refuses older invoices`() = + test { + val restoredAt = now.epochSeconds + val restored = AppCacheData(sparkHistoryUnseededSince = restoredAt, sparkRestoredAt = restoredAt) + val store = CacheStore(InMemoryDataStore(restored), clock) + whenever(sparkService.isConnected).thenReturn(true) + val failed = sentPayment(fees = 0).copy(id = "failed", status = PaymentStatus.FAILED).withHash("failed") + whenever { sparkService.listPayments() }.thenReturn(listOf(sentPayment(fees = 2), failed)) + createSut(store).start(0).getOrThrow() + + assertEquals(listOf("hash"), store.data.first().sparkSendHashes) + assertNull(store.data.first().sparkHistoryUnseededSince) + + whenever(sparkService.isConnected).thenReturn(false) + val restarted = createSut(store) + assertEquals(EarlierSend.Pending("hash"), restarted.earlierLightningSend("lnbc1280n1send", "hash")) + assertFailsWith { + restarted.earlierLightningSend("lnbc1280n1other", "other", invoiceCreatedAt = 1L) + } + assertNull(restarted.earlierLightningSend("lnbc1280n1other", "other", invoiceCreatedAt = now.epochSeconds)) + } + + @Test + fun `a send spark's list seeded after a restore is not sent again by spark after an unsynced restart`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkHistoryUnseededSince = now.epochSeconds)), clock) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.listPayments() }.thenReturn(listOf(sentPayment(fees = 2))) + whenever { sparkService.invoiceExpiresAt("lnbc1280n1send") }.thenReturn(now.epochSeconds.toULong() + 3_600uL) + createSut(store).start(0).getOrThrow() + assertEquals(listOf("hash"), store.data.first().sparkSendHashes) + + whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = null)) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + val restarted = createSut(store) + restarted.start(0).getOrThrow() + + restarted.payInvoice("lnbc1280n1send", 128uL) + + verify(sparkService, never()).send(any()) + } + + @Test + fun `a ready spark that hasn't synced since the restore refuses an invoice from before it`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkHistoryUnseededSince = now.epochSeconds)), clock) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL).copy(lastSyncedAt = null)) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + val sut = createSut(store) + sut.start(0).getOrThrow() + + val result = sut.payInvoice("lnbc1280n1send", 128uL) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any()) + } + + @Test + fun `a synced spark whose list lacks a pre-restore invoice refuses to send it`() = test { + val restoredAt = now.epochSeconds - 60 + val cache = AppCacheData(sparkHistoryUnseededSince = restoredAt, sparkRestoredAt = restoredAt) + val store = CacheStore(InMemoryDataStore(cache), clock) + whenever(sparkService.isConnected).thenReturn(true) + // Spark reports Synced while its payment-history sync failed, so its list lacks the pre-restore send. + val prepared = prepared(feeSats = 0uL, createdAt = (restoredAt - 600).toULong(), expirySecs = 3_600uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + val sut = createSut(store) + sut.start(0).getOrThrow() + assertNull(store.data.first().sparkHistoryUnseededSince) + + val result = sut.payInvoice("lnbc1280n1send", 128uL) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any()) + } + + @Test + fun `a synced spark whose list can't be read refuses a pre-restore invoice`() = test { + val restoredAt = now.epochSeconds - 60 + val cache = AppCacheData(sparkHistoryUnseededSince = restoredAt, sparkRestoredAt = restoredAt) + val store = CacheStore(InMemoryDataStore(cache), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL, createdAt = (restoredAt - 600).toULong(), expirySecs = 3_600uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + val sut = createSut(store) + sut.start(0).getOrThrow() + assertNull(store.data.first().sparkHistoryUnseededSince) + whenever { sparkService.listPayments() }.thenThrow(RuntimeException("list failed")) + + val result = sut.payInvoice("lnbc1280n1send", 128uL) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any()) + } + + @Test + fun `a synced spark sends an invoice created after the restore`() = test { + val restoredAt = now.epochSeconds - 60 + val cache = AppCacheData(sparkHistoryUnseededSince = restoredAt, sparkRestoredAt = restoredAt) + val store = CacheStore(InMemoryDataStore(cache), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL, createdAt = now.epochSeconds.toULong(), expirySecs = 3_600uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + val sut = createSut(store) + sut.start(0).getOrThrow() + + sut.payInvoice("lnbc1280n1send", 128uL).getOrThrow() + + verify(sparkService).send(any()) + } + + @Test + fun `restored spark sends with valid invoices survive the hash cap`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkHistoryUnseededSince = now.epochSeconds)), clock) + whenever(sparkService.isConnected).thenReturn(true) + val sends = (0..MAX_SPARK_SEND_HASHES).map { + sentPayment(fees = 2).copy(id = "send$it", timestamp = it.toULong()).withHash("paid$it") + } + whenever { sparkService.listPayments() }.thenReturn(sends) + whenever { sparkService.invoiceExpiresAt(any()) }.thenReturn(now.epochSeconds.toULong() + 3_600uL) + + createSut(store).start(0).getOrThrow() + + assertTrue("paid0" in store.data.first().sparkSendHashes, "the cap dropped a still-valid paid invoice") + } + + @Test + fun `a kept spark send without an expiry gets its invoice's expiry when seeded`() = test { + val cache = AppCacheData(sparkHistoryUnseededSince = now.epochSeconds, sparkSendHashes = listOf("paid0")) + val store = CacheStore(InMemoryDataStore(cache), clock) + whenever(sparkService.isConnected).thenReturn(true) + val sends = (0 until MAX_SPARK_SEND_HASHES + 1).map { + sentPayment(fees = 2).copy(id = "send$it", timestamp = it.toULong()).withHash("paid$it") + } + whenever { sparkService.listPayments() }.thenReturn(sends) + whenever { sparkService.invoiceExpiresAt(any()) }.thenReturn(now.epochSeconds.toULong() + 3_600uL) + + createSut(store).start(0).getOrThrow() + + assertTrue("paid0" in store.data.first().sparkSendHashes, "the cap dropped a kept still-valid paid invoice") + } + + @Test + fun `a list read before spark's first sync seeds no hashes`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkHistoryUnseededSince = now.epochSeconds)), clock) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = null)) + createSut(store).start(0).getOrThrow() + + assertEquals(now.epochSeconds, store.data.first().sparkHistoryUnseededSince) + } + + @Test + fun `spark's synced event seeds the restored hashes and ends the hold`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkHistoryUnseededSince = now.epochSeconds)), clock) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = null)) + val sut = createSut(store) + sut.start(0).getOrThrow() + assertEquals(now.epochSeconds, store.data.first().sparkHistoryUnseededSince) + + whenever { sparkService.getInfo() }.thenReturn(info(0uL)) + whenever { sparkService.listPayments() }.thenReturn(listOf(sentPayment(fees = 2))) + sparkEvents.emit(SdkEvent.Synced) + runCurrent() + + assertNull(store.data.first().sparkHistoryUnseededSince) + assertEquals(listOf("hash"), store.data.first().sparkSendHashes) + } + @Test fun `a spark retry recorded while an older list is read holds the node off the invoice`() = test { whenever(sparkService.isConnected).thenReturn(true) @@ -1025,6 +1277,65 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(0uL, sut.state.value.sendableSats, "a send was offered from the kept balance") } + @Test + fun `a zero read after a full withdrawal clears the balance even while spark's sync fails`() = test { + val staleZero = info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + var read = info(10_000uL) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenAnswer { read } + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } + .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) + whenever { sparkService.send(any()) }.thenAnswer { + read = staleZero + sentPayment(fees = 500) + } + val sut = createSut() + sut.refreshState().getOrThrow() + + sut.withdrawAll(ADDRESS, confirmedFeeSats = 500uL).getOrThrow() + sut.refreshState().getOrThrow() + + assertEquals(0uL, sut.state.value.shownBalanceSats, "the withdrawn balance stayed shown") + + // New funds show on a sync after the withdrawal. + read = info(2_000uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) + sut.refreshState().getOrThrow() + read = staleZero + sut.refreshState().getOrThrow() + assertEquals(2_000uL, sut.state.value.shownBalanceSats, "a stale zero after new funds hid them") + } + + @Test + fun `a refresh that read the balance before a full withdrawal never brings it back`() = test { + val staleZero = info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + var read = info(10_000uL) + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenAnswer { read } + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } + .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) + whenever { sparkService.send(any()) }.thenAnswer { + read = staleZero + sentPayment(fees = 500) + } + val sut = createSut() + sut.refreshState().getOrThrow() + // A refresh reads the old balance, then waits on the network while the withdrawal goes out. + val deposits = CompletableDeferred>() + var depositReads = 0 + whenever { sparkService.listUnclaimedDeposits() }.doSuspendableAnswer { + if (depositReads++ == 0) deposits.await() else emptyList() + } + val olderRefresh = async { sut.refreshState() } + runCurrent() + val withdrawal = async { sut.withdrawAll(ADDRESS, confirmedFeeSats = 500uL) } + runCurrent() + deposits.complete(emptyList()) + olderRefresh.await().getOrThrow() + withdrawal.await().getOrThrow() + + assertEquals(0uL, sut.state.value.shownBalanceSats, "the withdrawn balance came back") + } + @Test fun `a synced read after a failed withdrawal clears the kept balance even when it reads zero`() = test { whenever(sparkService.isConnected).thenReturn(true) @@ -1650,6 +1961,27 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any()) } + @Test + fun `a spark send whose deadline passes while its uncertainty is written never leaves`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + val deadline = now + 1.seconds + whenever { cacheStore.addSparkUncertainSend(any(), any()) }.thenAnswer { + now = deadline + 1.seconds + Unit + } + val sut = createSut() + + val result = sut.payInvoice("lnbc1", 100uL, deadline, null) { true } + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any()) + verifyBlocking(cacheStore) { removeSparkUncertainSend("hash") } + verifyBlocking(cacheStore) { removeSparkSendHash("hash") } + } + @Test fun `an older failed row never ends an uncertain spark send while spark can't resync`() = test { whenever(sparkService.isSupported).thenReturn(true) @@ -1893,8 +2225,16 @@ class SparkRepoTest : BaseUnitTest() { lastSyncedAt = 1uL, ) - private fun prepared(feeSats: ULong): PrepareSendPaymentResponse { - val details = mock { on { paymentHash } doReturn "hash" } + private fun prepared( + feeSats: ULong, + createdAt: ULong = 0uL, + expirySecs: ULong = 0uL, + ): PrepareSendPaymentResponse { + val details = mock { + on { paymentHash } doReturn "hash" + on { timestamp } doReturn createdAt + on { expiry } doReturn expirySecs + } return PrepareSendPaymentResponse( paymentMethod = SendPaymentMethod.Bolt11Invoice(details, null, feeSats), amount = BigInteger.valueOf(100), diff --git a/app/src/test/java/to/bitkit/services/SparkServiceTest.kt b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt index 04c5685ed4..e5e88d9be5 100644 --- a/app/src/test/java/to/bitkit/services/SparkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt @@ -56,6 +56,13 @@ class SparkServiceTest { assertEquals(true, options.preferSpark) } + @Test + fun `an invoice expiry past the largest time stays at the largest time`() { + val farOff = SparkService.invoiceExpiresAt(timestamp = ULong.MAX_VALUE - 1uL, expiry = 3_600uL) + assertEquals(ULong.MAX_VALUE, farOff) + assertEquals(1_800_003_600uL, SparkService.invoiceExpiresAt(timestamp = 1_800_000_000uL, expiry = 3_600uL)) + } + @Test fun `claim fee estimate covers the claims seen on mainnet`() { // Mainnet claims so far took 198 and 297 sats; the cap at 1 sat/vB stays above both. diff --git a/app/src/test/java/to/bitkit/test/IdleSparkRepo.kt b/app/src/test/java/to/bitkit/test/IdleSparkRepo.kt index 05f0b04e0b..40a1bcf4b2 100644 --- a/app/src/test/java/to/bitkit/test/IdleSparkRepo.kt +++ b/app/src/test/java/to/bitkit/test/IdleSparkRepo.kt @@ -13,4 +13,5 @@ fun idleSparkRepo(): SparkRepo = mock { on { state } doReturn MutableStateFlow(SparkState()) on { nodeEvents } doReturn MutableSharedFlow() on { wipe(any()) } doReturn Result.success(Unit) + onBlocking { holdsRestoredInvoices() } doReturn false } diff --git a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt new file mode 100644 index 0000000000..8c6a44719e --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt @@ -0,0 +1,48 @@ +package to.bitkit.ui.sheets + +import org.junit.Test +import to.bitkit.repositories.SparkState +import to.bitkit.viewmodels.QuickPayData +import to.bitkit.viewmodels.SendMethod +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class SendSheetSyncOverlayTest { + private val funded = SparkState(isSupported = true, isReady = true, balanceSats = 100_000uL) + + @Test + fun `a scanned invoice a ready funded spark can pay skips the wait for a stopped node`() { + val sparkCanPay = sparkCanPayInvoice(SendMethod.LIGHTNING, 1_000uL, funded) + + assertTrue(sparkCanPay) + assertFalse(waitsForNode(false, hasAnyChannels = true, hasUsableChannels = false, sparkCanPay = sparkCanPay)) + assertFalse(waitsForNode(true, hasAnyChannels = true, hasUsableChannels = false, sparkCanPay = sparkCanPay)) + } + + @Test + fun `confirm and quick pay go ahead without the node when spark can pay`() { + assertTrue(canSendWithoutWaiting(isNodeRunning = false, isHardwareWallet = false, sparkCanPay = true)) + assertFalse(canSendWithoutWaiting(isNodeRunning = false, isHardwareWallet = false, sparkCanPay = false)) + assertTrue(sparkCanPayQuickPay(QuickPayData.Bolt11(1_000uL, "lnbc1"), funded)) + assertFalse(sparkCanPayQuickPay(QuickPayData.Bolt11(1_000uL, "lnbc1"), funded.copy(isReady = false))) + } + + @Test + fun `on-chain, amountless and payments spark can't cover still wait for a stopped node`() { + val cases = listOf( + sparkCanPayInvoice(SendMethod.ONCHAIN, 1_000uL, funded), + sparkCanPayInvoice(SendMethod.LIGHTNING, 0uL, funded), + sparkCanPayInvoice(SendMethod.LIGHTNING, null, funded), + sparkCanPayInvoice(SendMethod.LIGHTNING, 1_000uL, funded.copy(isReady = false)), + sparkCanPayInvoice(SendMethod.LIGHTNING, 1_000uL, funded.copy(balanceSats = 1_000uL)), + ) + + cases.forEach { sparkCanPay -> + assertFalse(sparkCanPay) + assertTrue(waitsForNode(false, hasAnyChannels = false, hasUsableChannels = false, sparkCanPay)) + } + assertFalse(waitsForNode(true, hasAnyChannels = false, hasUsableChannels = false, sparkCanPay = false)) + assertTrue(waitsForNode(true, hasAnyChannels = true, hasUsableChannels = false, sparkCanPay = false)) + assertFalse(waitsForNode(true, hasAnyChannels = true, hasUsableChannels = true, sparkCanPay = false)) + } +}