diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 1f3fa591d9..1d3acb5bdf 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -27,6 +27,7 @@ import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.first @@ -213,6 +214,12 @@ class LightningRepo @Inject constructor( private val pendingStopLock = Any() private val lifecycleMutex = Mutex() + /** Starts called and not returned yet, also while one waits for a stop to finish or between its retries. */ + private val pendingStartCount = MutableStateFlow(0) + + /** Counts [wipeStorage] calls, so a send that waited for the node can tell the wallet was wiped meanwhile. */ + private val wipeCount = AtomicLong(0) + /** * Serializes a whole server-change transaction (stop, start, persist) against the background * recovery a failed change launches. [lifecycleMutex] is taken separately by `stop()` and @@ -300,7 +307,7 @@ class LightningRepo @Inject constructor( */ suspend fun executeWhenNodeRunning( operationName: String, - waitTimeout: Duration = 1.minutes, + waitTimeout: Duration = NODE_RUN_WAIT_TIMEOUT, operation: suspend () -> Result, ): Result = withContext(bgDispatcher) { Logger.verbose("Operation called: '$operationName'", context = TAG) @@ -380,17 +387,28 @@ class LightningRepo @Inject constructor( eventHandler: NodeEventHandler? = null, channelMigration: ChannelDataMigration? = null, shouldValidateGraph: Boolean = true, - ): Result = startNode( - walletIndex = walletIndex, - timeout = timeout, - shouldRetry = shouldRetry, - customServerUrl = customServerUrl, - customRgsServerUrl = customRgsServerUrl, - eventHandler = eventHandler, - channelMigration = channelMigration, - shouldValidateGraph = shouldValidateGraph, - shouldRetryYieldToStop = false, - ) + ): Result = whileStartPending { + startNode( + walletIndex = walletIndex, + timeout = timeout, + shouldRetry = shouldRetry, + customServerUrl = customServerUrl, + customRgsServerUrl = customRgsServerUrl, + eventHandler = eventHandler, + channelMigration = channelMigration, + shouldValidateGraph = shouldValidateGraph, + shouldRetryYieldToStop = false, + ) + } + + private inline fun whileStartPending(start: () -> T): T { + pendingStartCount.update { it + 1 } + try { + return start() + } finally { + pendingStartCount.update { it - 1 } + } + } private suspend fun startNode( walletIndex: Int = 0, @@ -1023,6 +1041,7 @@ class LightningRepo @Inject constructor( suspend fun wipeStorage(walletIndex: Int): Result = withContext(bgDispatcher) { Logger.debug("wipeStorage called, stopping node first", context = TAG) + wipeCount.incrementAndGet() lifecycleMutex.withLock { stopLocked().mapCatching { Logger.debug("node stopped, calling wipeStorage", context = TAG) @@ -1057,16 +1076,18 @@ class LightningRepo @Inject constructor( var stopRequests: Long? = null recoverOnCancellation(stopRequestsSeen = { stopRequests }) { - stop().onFailure { - Logger.error("Failed to stop node during electrum server change", it, context = TAG) - return@withContext Result.failure(it) - } - // A stop requested from here on, during the change's first build included, wins over every start. - stopRequests = stopRequestCount.get() + whileStartPending { + stop().onFailure { + Logger.error("Failed to stop node during electrum server change", it, context = TAG) + return@withContext Result.failure(it) + } + // A stop requested from here on, during the change's first build included, wins over every start. + stopRequests = stopRequestCount.get() - Logger.debug("Starting node with new electrum server: '$newServerUrl'", context = TAG) + Logger.debug("Starting node with new electrum server: '$newServerUrl'", context = TAG) - startConfigChange(stopRequests = stopRequests, customServerUrl = newServerUrl) + startConfigChange(stopRequests = stopRequests, customServerUrl = newServerUrl) + } }.onFailure { // Recover in the background: a wedged node's release can gate the rebuild for tens of // seconds, and the caller must surface this failure now rather than block on recovery. @@ -1097,16 +1118,18 @@ class LightningRepo @Inject constructor( var stopRequests: Long? = null recoverOnCancellation(stopRequestsSeen = { stopRequests }) { - stop().onFailure { - Logger.error("Failed to stop node during RGS server change", it, context = TAG) - return@withContext Result.failure(it) - } - // A stop requested from here on, during the change's first build included, wins over every start. - stopRequests = stopRequestCount.get() + whileStartPending { + stop().onFailure { + Logger.error("Failed to stop node during RGS server change", it, context = TAG) + return@withContext Result.failure(it) + } + // A stop requested from here on, during the change's first build included, wins over every start. + stopRequests = stopRequestCount.get() - Logger.debug("Starting node with new RGS server: '$newRgsUrl'", context = TAG) + Logger.debug("Starting node with new RGS server: '$newRgsUrl'", context = TAG) - startConfigChange(stopRequests = stopRequests, customRgsServerUrl = newRgsUrl) + startConfigChange(stopRequests = stopRequests, customRgsServerUrl = newRgsUrl) + } }.onFailure { // Recover in the background: a wedged node's release can gate the rebuild for tens of // seconds, and the caller must surface this failure now rather than block on recovery. @@ -1387,38 +1410,40 @@ class LightningRepo @Inject constructor( } Logger.debug("Stopping node for recovery attempt", context = TAG) - stop().onFailure { e -> - Logger.error("Failed to stop node during recovery", e, context = TAG) - return@withContext Result.failure(e) - } - - Logger.debug("Starting node with previous config for recovery", context = TAG) - val stopRequests = stopRequestCount.get() - - var result: Result - var attempt = 0 - // The stopped node's VSS writes can keep retrying for minutes, past one build's wait for them. - do { - // A stop requested since the app went to the background wins over recovery. - if (pendingStopJob.get() != null) { - Logger.info("Skipped recovery start because a stop was requested", context = TAG) - return@withContext Result.failure(NodeStartYieldedToStopError(null)) + whileStartPending { + stop().onFailure { e -> + Logger.error("Failed to stop node during recovery", e, context = TAG) + return@withContext Result.failure(e) } - attempt++ - if (attempt > 1) { - Logger.warn("Retrying recovery start '$attempt/$BUSY_STORE_START_ATTEMPTS'", context = TAG) + + Logger.debug("Starting node with previous config for recovery", context = TAG) + val stopRequests = stopRequestCount.get() + + var result: Result + var attempt = 0 + // The stopped node's VSS writes can keep retrying for minutes, past one build's wait for them. + do { + // A stop requested since the app went to the background wins over recovery. + if (pendingStopJob.get() != null) { + Logger.info("Skipped recovery start because a stop was requested", context = TAG) + return@withContext Result.failure(NodeStartYieldedToStopError(null)) + } + attempt++ + if (attempt > 1) { + Logger.warn("Retrying recovery start '$attempt/$BUSY_STORE_START_ATTEMPTS'", context = TAG) + } + // A direct stop since recovery's own stop wins over every attempt. + result = startNode( + shouldRetry = false, + shouldCancelPendingStop = false, + stopRequestsSeen = stopRequests, + ) + } while (result.exceptionOrNull().isKvStoreSetupFailure() && attempt < BUSY_STORE_START_ATTEMPTS) + result.onSuccess { + Logger.debug("Successfully started node with previous config", context = TAG) + }.onFailure { + Logger.error("Failed starting node with previous config", it, context = TAG) } - // A direct stop since recovery's own stop wins over every attempt. - result = startNode( - shouldRetry = false, - shouldCancelPendingStop = false, - stopRequestsSeen = stopRequests, - ) - } while (result.exceptionOrNull().isKvStoreSetupFailure() && attempt < BUSY_STORE_START_ATTEMPTS) - result.onSuccess { - Logger.debug("Successfully started node with previous config", context = TAG) - }.onFailure { - Logger.error("Failed starting node with previous config", it, context = TAG) } } } @@ -1712,6 +1737,7 @@ class LightningRepo @Inject constructor( maxTotalRoutingFeeMsat: ULong?, isAuthorizedAtSubmission: (() -> Boolean)?, rechecksBeforeSend: Boolean = false, + isRetryAfterNodeStart: Boolean = false, onBeforeSend: suspend () -> Boolean, ): Result { // The rail is picked again on every attempt, so each one checks the other holds no live send of the invoice. @@ -1719,11 +1745,27 @@ class LightningRepo @Inject constructor( if (shouldPayWithSpark(bolt11, sats)) { runCatching { requireWalletRestoreComplete() }.onFailure { return Result.failure(it) } val key = ldkSendKey(bolt11, paymentHash) + val wipesBefore = wipeCount.get() // Read before the checks, so a send of either rail recorded after them refuses this one at submission. val ldkRecordsBefore = ldkSendRecords.get() val sparkRecordsBefore = sparkRepo.sendRecordMark() runSuspendCatching { earlierNodeSend(bolt11, paymentHash) } - .getOrElse { return Result.failure(it) } + .getOrElse { + // Nothing is authorized or admitted yet, so the payment starts over once the node can list its + // sends: the rail is picked again, and an earlier node send of the invoice is found. + val canRetry = it is ServiceError.NodeNotStarted && !isRetryAfterNodeStart + if (!canRetry || !awaitNodeListing(wipesBefore)) return Result.failure(it) + return payInvoiceChecked( + bolt11 = bolt11, + sats = sats, + paymentDeadlineAt = paymentDeadlineAt, + maxTotalRoutingFeeMsat = maxTotalRoutingFeeMsat, + isAuthorizedAtSubmission = isAuthorizedAtSubmission, + rechecksBeforeSend = rechecksBeforeSend, + isRetryAfterNodeStart = true, + onBeforeSend = onBeforeSend, + ) + } ?.let { // The node paid it, so its caller settles from the node's payment, as its event already fired. if (it is EarlierSend.Paid) recordSendRail(it.paymentHash, LightningRail.Ldk) @@ -1794,6 +1836,41 @@ class LightningRepo @Inject constructor( ) } + /** + * Waits, up to [NODE_RUN_WAIT_TIMEOUT], until the node runs and lists its payments. A node stopping, or stopped + * with a start called, is waited for, also across a start's retry or its restart for a stale graph. The wait + * ends without it when the node cannot run and no start is left pending, as after a failed start, or when the + * wallet was wiped since [wipesBefore], as the node that runs next can be another wallet's. + */ + private suspend fun awaitNodeListing(wipesBefore: Long): Boolean { + val isWiped = { isWiping || wipeCount.get() != wipesBefore } + // The two flows only wake the wait. What it decides on is read then, the count before the state: read as a + // pair they can show a failed start beside a count another start has left since, which never was the case. + val changes = combine(_lightningState, pendingStartCount) { _, _ -> } + var isListing = false + withTimeoutOrNull(NODE_RUN_WAIT_TIMEOUT) { + while (!isListing) { + var wasRunning = false + changes.first { + val starts = pendingStartCount.value + val lifecycle = _lightningState.value.nodeLifecycleState + val canStillRun = lifecycle.canRun() || lifecycle is NodeLifecycleState.Stopping || starts > 0 + wasRunning = lifecycle.isRunning() + wasRunning || isWiped() || !canStillRun + } + // Decided on what woke the wait: a node that stopped again since is asked for its listing and waited. + if (!wasRunning || isWiped()) return@withTimeoutOrNull + // A listing that fails is asked again, so the wait ends with the hold's own error, never a throw. + isListing = runSuspendCatching { listPaymentsKeepingSendHashes() }.getOrNull() != null + if (!isListing) delay(NODE_LISTING_POLL_DELAY) + } + } + if (!isListing || isWiped()) return false + // The node is marked running before its channels are published, and the rail is picked from them. + refreshChannelsAndPeers() + return !isWiped() + } + /** Pays [bolt11] from the node's channels only, for a send quoted on them that must never fall back to Spark. */ suspend fun payInvoiceWithNode(bolt11: String): Result { val paymentHash = runCatching { Bolt11Invoice.fromStr(bolt11).paymentHash() }.getOrNull() @@ -3081,21 +3158,46 @@ class LightningRepo @Inject constructor( /** * The completion event of a send that settled before its caller started watching for it, read from the rail it - * last went out on: a node send only when it succeeded, as one the node paid earlier gets no new event. + * last went out on: a node send once it succeeded, or with [includeNodeFailure] once it failed with no attempt of + * it live. The node lists no failure reason, so a caller that can still get the node's failure event leaves it out. */ - suspend fun settledSparkSendEvent(paymentHash: String): Event? = - if (isLdkSend(paymentHash)) paidNodeSendEvent(paymentHash) else sparkRepo.settledSendEvent(paymentHash) + suspend fun settledSparkSendEvent(paymentHash: String, includeNodeFailure: Boolean = true): Event? = + if (isLdkSend(paymentHash)) { + settledNodeSendEvent(paymentHash, includeNodeFailure) + } else { + sparkRepo.settledSendEvent(paymentHash) + } - private suspend fun paidNodeSendEvent(paymentHash: String): Event? { + private suspend fun settledNodeSendEvent(paymentHash: String, includeFailure: Boolean): Event? { + val key = paymentHash.lowercase() + // Read before the row too, so a retry that ends while it is read still counts as live. The marks come first, + // so a send they count as recorded is already admitted or in flight when liveness is read. + val ldkRecordsBefore = ldkSendRecordedAt[key] ?: 0L + val sparkRecordsBefore = sparkRepo.sendRecordMark() + val wasLive = isSendLive(paymentHash, key, ldkRecordsBefore) val payments = runSuspendCatching { lightningService.listPayments() } .onFailure { Logger.warn("Failed to list node payments", it, context = TAG) } .getOrNull() val payment = payments?.firstOrNull { - it.direction == PaymentDirection.OUTBOUND && it.status == PaymentStatus.SUCCEEDED && + it.direction == PaymentDirection.OUTBOUND && (it.kind as? PaymentKind.Bolt11)?.hash.equals(paymentHash, ignoreCase = true) } ?: return null val kind = payment.kind as PaymentKind.Bolt11 - return Event.PaymentSuccessful(payment.id, kind.hash, kind.preimage, payment.feePaidMsat) + return when (payment.status) { + PaymentStatus.SUCCEEDED -> Event.PaymentSuccessful( + payment.id, + kind.hash, + kind.preimage, + payment.feePaidMsat, + ) + PaymentStatus.FAILED -> { + // A failed row can be an earlier attempt's while a retry of it on either rail can still pay it. + val isLive = wasLive || isSendLive(paymentHash, key, ldkRecordsBefore) || + sparkRepo.hasRecordedSendSince(sparkRecordsBefore, paymentHash) + Event.PaymentFailed(payment.id, kind.hash, null).takeIf { includeFailure && !isLive } + } + PaymentStatus.PENDING -> null + } } /** Spark's record of the Lightning send with [paymentHash], for recovery after its completion event was missed. */ @@ -3496,24 +3598,26 @@ class LightningRepo @Inject constructor( channelMigration: ChannelDataMigration? = null, walletIndex: Int = 0, ): Result = withContext(bgDispatcher) { - Logger.info("Restarting node", context = TAG) - stop().onFailure { - Logger.error("Failed to stop node during restart", it, context = TAG) - return@withContext Result.failure(it) - } - startNode( - walletIndex = walletIndex, - channelMigration = channelMigration, - shouldRetryYieldToStop = true - ).onFailure { - if (it is NodeStartYieldedToStopError) { - Logger.info("Deferred node restart to a requested stop", context = TAG) - } else { - Logger.error("Failed to start node during restart", it, context = TAG) + whileStartPending { + Logger.info("Restarting node", context = TAG) + stop().onFailure { + Logger.error("Failed to stop node during restart", it, context = TAG) + return@withContext Result.failure(it) + } + startNode( + walletIndex = walletIndex, + channelMigration = channelMigration, + shouldRetryYieldToStop = true + ).onFailure { + if (it is NodeStartYieldedToStopError) { + Logger.info("Deferred node restart to a requested stop", context = TAG) + } else { + Logger.error("Failed to start node during restart", it, context = TAG) + } + return@withContext Result.failure(it) + }.onSuccess { + Logger.info("Node restarted successfully", context = TAG) } - return@withContext Result.failure(it) - }.onSuccess { - Logger.info("Node restarted successfully", context = TAG) } } @@ -3546,6 +3650,10 @@ class LightningRepo @Inject constructor( private val ABANDON_SYNC_TIMEOUT = 30.seconds private val NO_USABLE_CHANNELS_FEEDBACK_DELAY = 2_500.milliseconds + /** Max time an operation waits for a starting node to run. */ + private val NODE_RUN_WAIT_TIMEOUT = 1.minutes + private val NODE_LISTING_POLL_DELAY = 500.milliseconds + /** Max time to wait for a starting node before its id is treated as unavailable. */ private val NODE_ID_WAIT_TIMEOUT = 15.seconds diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index e6ff629b86..0363f244d7 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -25,6 +25,7 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull +import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.NodeException import org.lightningdevkit.ldknode.PaymentDetails import org.lightningdevkit.ldknode.PaymentDirection @@ -283,8 +284,10 @@ class QuickPayRepo @Inject constructor( PreparePayResult.REJECTED -> return PreparePayResult.RECOVERED -> settleRecovered(invoiceHash) PreparePayResult.FRESH -> { - dispatchBolt11(invoice, invoiceHash, canDispatch) - awaitCompletionOrPending(invoiceHash) + val job = currentCoroutineContext()[Job] + val op = mutex.withLock { opsByKey[invoiceHash]?.takeIf { it.job === job } } ?: return + dispatchBolt11(invoice, op, canDispatch) + awaitCompletionOrPending(op) } } } @@ -432,27 +435,29 @@ class QuickPayRepo @Inject constructor( } } - private suspend fun dispatchBolt11(invoice: ResolvedInvoice, invoiceHash: String, canDispatch: () -> Boolean) { + private suspend fun dispatchBolt11(invoice: ResolvedInvoice, op: InFlightOp, canDispatch: () -> Boolean) { var isAuthorizationLapsed = false lightningRepo.payInvoiceAuthorizedAtSubmission(invoice.bolt11, sats = null, canDispatch) { isAuthorizationLapsed = !canDispatch() - !isAuthorizationLapsed && tryMarkDispatched(invoiceHash) + !isAuthorizationLapsed && tryMarkDispatched(op) }.fold( - onSuccess = { onInvoiceAccepted(invoiceHash, it) }, + onSuccess = { onInvoiceAccepted(op, invoice.bolt11, it) }, onFailure = { when { - isAuthorizationLapsed -> fallBackBeforeDispatch(invoiceHash) + isAuthorizationLapsed -> fallBackBeforeDispatch(op) // Stopped on the node's queue, after it was marked dispatched but before anything was submitted. - it.isStoppedAtSubmission() -> fallBackBeforeDispatch(invoiceHash, isMarkedDispatched = true) - else -> onInvoiceRejected(invoiceHash, invoice.bolt11, it) + it.isStoppedAtSubmission() -> fallBackBeforeDispatch(op, isMarkedDispatched = true) + else -> onInvoiceRejected(op, invoice.bolt11, it) } }, ) } /** Releases a payment that was never submitted and sends its session to the swipe review. */ - private suspend fun fallBackBeforeDispatch(invoiceHash: String, isMarkedDispatched: Boolean = false) { + private suspend fun fallBackBeforeDispatch(op: InFlightOp, isMarkedDispatched: Boolean = false) { + val invoiceHash = op.invoiceHash mutex.withLock { + if (isSupersededLocked(op)) return@withLock val current = opsByKey[invoiceHash] if (current == null || current.dispatched != isMarkedDispatched) return@withLock spend.release(invoiceHash) @@ -461,10 +466,10 @@ class QuickPayRepo @Inject constructor( } } - private suspend fun tryMarkDispatched(invoiceHash: String): Boolean { + private suspend fun tryMarkDispatched(op: InFlightOp): Boolean { val settings = readSettings() return mutex.withLock { - val current = opsByKey[invoiceHash] ?: return@withLock false + val current = opsByKey[op.invoiceHash]?.takeIf { it === op } ?: return@withLock false if (current.rejection != null) return@withLock false val rejection = sendRejectionLocked(current, settings) if (rejection != null) { @@ -487,8 +492,18 @@ class QuickPayRepo @Inject constructor( return null } - private suspend fun onInvoiceAccepted(invoiceHash: String, paymentId: String) { + private suspend fun onInvoiceAccepted(op: InFlightOp, paymentRequest: String, paymentId: String) { + val invoiceHash = op.invoiceHash mutex.withLock { + if (isSupersededLocked(op)) return@withLock + val undispatched = opsByKey[invoiceHash]?.takeIf { !it.dispatched } + if (undispatched != null) { + // Accepted without a dispatch, so an earlier send of the invoice paid it and nothing new went out. + spend.release(invoiceHash) + emitErrorLocked(undispatched, QuickPayAlreadyPaidError(), paymentRequest) + removeOpLocked(undispatched) + return@withLock + } spend.markSubmitted(invoiceHash, paymentId) val current = opsByKey[invoiceHash] ?: return@withLock current.paymentId = paymentId @@ -499,30 +514,31 @@ class QuickPayRepo @Inject constructor( } private suspend fun onInvoiceRejected( - invoiceHash: String, + op: InFlightOp, paymentRequest: String, error: Throwable, ) { if (error is PaymentAbortedBeforeSend) { - releaseIfNotDispatched(invoiceHash) + releaseIfNotDispatched(op) return } - handleDispatchError(invoiceHash, paymentRequest, error) + handleDispatchError(op, paymentRequest, error) } - private suspend fun awaitCompletionOrPending(invoiceHash: String) { - val current = mutex.withLock { opsByKey[invoiceHash] } ?: return + private suspend fun awaitCompletionOrPending(op: InFlightOp) { + if (mutex.withLock { opsByKey[op.invoiceHash] !== op }) return withTimeoutOrNull(LightningRepo.SEND_LN_TIMEOUT) { - current.settled.await() + op.settled.await() } mutex.withLock { - val live = opsByKey[invoiceHash] ?: return@withLock - emitPendingLocked(live) + if (opsByKey[op.invoiceHash] === op) emitPendingLocked(op) } } - private suspend fun releaseIfNotDispatched(invoiceHash: String) { + private suspend fun releaseIfNotDispatched(op: InFlightOp) { + val invoiceHash = op.invoiceHash mutex.withLock { + if (isSupersededLocked(op)) return@withLock val current = opsByKey[invoiceHash] if (current == null || current.dispatched) return@withLock spend.release(invoiceHash) @@ -562,13 +578,15 @@ class QuickPayRepo @Inject constructor( } private suspend fun handleDispatchError( - invoiceHash: String, + op: InFlightOp, paymentRequest: String, error: Throwable, ) { + val invoiceHash = op.invoiceHash when (val kind = classifyDispatchError(error)) { QuickPayDispatchClass.PRE_DISPATCH_REJECTION -> { mutex.withLock { + if (isSupersededLocked(op)) return@withLock signalCompletionLocked( paymentId = null, paymentHash = invoiceHash, @@ -581,7 +599,8 @@ class QuickPayRepo @Inject constructor( QuickPayDispatchClass.AMBIGUOUS, -> { val rows = loadPaymentRows() - mutex.withLock { + val isEarlierSendTracked = mutex.withLock { + if (isSupersededLocked(op)) return@withLock false settleAmbiguousLocked( invoiceHash = invoiceHash, paymentRequest = paymentRequest, @@ -590,23 +609,35 @@ class QuickPayRepo @Inject constructor( duplicate = kind == QuickPayDispatchClass.DUPLICATE_PAYMENT, ) } + if (isEarlierSendTracked) resolveSettledEarlierSend(invoiceHash) } } } + /** Settles a dispatch error, true when it tracked an earlier send of the invoice that QuickPay didn't make. */ private suspend fun settleAmbiguousLocked( invoiceHash: String, paymentRequest: String, error: Throwable, rows: List?, duplicate: Boolean, - ) { + ): Boolean { val op = opsByKey[invoiceHash] if (!duplicate && op != null && !op.dispatched) { spend.release(invoiceHash) - emitErrorLocked(op, error, paymentRequest) removeOpLocked(op) - return + if (error !is PaymentPendingException) { + emitErrorLocked(op, error, paymentRequest) + return false + } + // Refused for an earlier send of the invoice, which may have been paid since. A failed row proves nothing, + // as the refusal can be for a retry of it still in flight, so anything else is tracked as pending. + if (rows != null && isEarlierSendPaid(invoiceHash, rows)) { + emitErrorLocked(op, QuickPayAlreadyPaidError(), paymentRequest) + return false + } + emitPendingLocked(op) + return true } val record = spend.matching(invoiceHash) val applied = if (record != null && rows != null) { @@ -618,9 +649,9 @@ class QuickPayRepo @Inject constructor( if (remaining != null) { op?.dispatched = true op?.let { emitPendingLocked(it) } - return + return false } - if (op == null) return + if (op == null) return false when (applied) { AmbiguousApply.SUCCEEDED -> emitSuccessLocked(op, feePaidMsat = null) AmbiguousApply.ALREADY_PAID -> emitErrorLocked(op, QuickPayAlreadyPaidError(), paymentRequest) @@ -629,6 +660,29 @@ class QuickPayRepo @Inject constructor( -> emitErrorLocked(op, error, paymentRequest) } removeOpLocked(op) + return false + } + + /** + * Resolves the tracked earlier send of [invoiceHash] when its rail shows it settled, as its event may have been + * handled before it was tracked, which no later event resolves. + */ + private suspend fun resolveSettledEarlierSend(invoiceHash: String) { + // Settled only when confirmed: once it succeeded, or once it failed with no attempt of it live on either rail. + val event = runSuspendCatching { lightningRepo.settledSparkSendEvent(invoiceHash) }.getOrNull() + val resolution = when (event) { + is Event.PaymentSuccessful if event.paymentHash == invoiceHash -> + PendingPaymentResolution.Success(invoiceHash) + is Event.PaymentFailed if event.paymentHash == invoiceHash -> + PendingPaymentResolution.Failure(invoiceHash, event.reason) + else -> return + } + if (pendingPaymentRepo.isPending(invoiceHash)) pendingPaymentRepo.resolve(resolution) + } + + private fun isEarlierSendPaid(invoiceHash: String, rows: List): Boolean = rows.any { + it.isOutboundBolt11 && it.status == QuickPayReconcileRow.Status.SUCCEEDED && + it.invoicePaymentHash.equals(invoiceHash, ignoreCase = true) } private suspend fun detachSession(sessionId: String) { @@ -668,6 +722,13 @@ class QuickPayRepo @Inject constructor( if (!success && !isAttributedFailure(record, op, paymentId, paymentHash)) { return QuickPayCompletionOutcome.None } + if (success && op != null && !op.dispatched) { + // QuickPay sent nothing yet, so the success is an earlier send's: the invoice is paid, and not by QuickPay. + spend.release(record.invoicePaymentHash) + emitErrorLocked(op, QuickPayAlreadyPaidError(), op.paymentRequest) + removeOpLocked(op) + return QuickPayCompletionOutcome.None + } spend.settle(keys, success) @@ -806,6 +867,9 @@ class QuickPayRepo @Inject constructor( op.paymentId?.takeIf { it.isNotBlank() && it != op.invoiceHash }?.let { opsByKey[it] = op } } + /** True when a later pay registered its own op for this op's invoice, which this op's dispatch must not touch. */ + private fun isSupersededLocked(op: InFlightOp): Boolean = opsByKey[op.invoiceHash].let { it != null && it !== op } + private fun removeOpLocked(op: InFlightOp) { opsByKey.entries.removeAll { it.value === op } } diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index a19961687c..fc06b3200d 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -6648,7 +6648,7 @@ class AppViewModel @Inject constructor( ) if (quickPayHandled) return - waitForUsableChannels(walletGeneration, amount) + waitForUsableChannels(walletGeneration, amount.coerceAtLeast(1u)) if (!canSendLightning(amount)) { val maxSendLightning = walletRepo.balanceState.value.maxSendLightningSats val shortfall = amount.safe() - maxSendLightning.safe() @@ -6932,8 +6932,12 @@ class AppViewModel @Inject constructor( val open = invoiceHash != null && quickPayRepo.hasOpen(invoiceHash) // QuickPay has no confirm screen to show the update fee, so a payment that needs the update is reviewed. While // the node starts or its channels reconnect their balance is unknown, so that is decided once they are usable. + // An amount Spark covers alone never needs the update, so it does not wait for the node. An amountless + // invoice has no amount to cover yet, so it keeps the wait. val isQuickPayOn = settingsStore.data.first().isQuickPayEnabled - if (!open && isQuickPayOn && channelsAreSettling()) waitForUsableChannels(walletGeneration) + if (!open && isQuickPayOn && channelsAreSettling()) { + waitForUsableChannels(walletGeneration, amountSats.takeIf { it > 0uL }) + } if (!open && moveToSparkRepo.needsUpdateToSend(amountSats)) return false val canApply = open || canApplyQuickPay(amountSats) requireCurrentPaymentPreparation(walletGeneration) @@ -8983,7 +8987,11 @@ class AppViewModel @Inject constructor( outcome(it)?.let { result -> WatchResult.Complete(result) } ?: WatchResult.Continue() } } - lightningRepo.settledSparkSendEvent(hash)?.let(::outcome)?.also { watch.cancel() } ?: watch.await() + // A node failure comes with its reason in the watched event, which the payment list does not carry. + lightningRepo.settledSparkSendEvent(hash, includeNodeFailure = false) + ?.let(::outcome) + ?.also { watch.cancel() } + ?: watch.await() } return result ?: Result.failure(PaymentPendingException(hash)) } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index b50a9e7f18..e5d00c5ddd 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -39,6 +39,7 @@ import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.runCurrent import org.junit.Before import org.junit.Test @@ -128,6 +129,7 @@ import kotlin.test.assertNull import kotlin.test.assertTrue 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.Instant import breez_sdk_spark.PaymentStatus as SparkPaymentStatus @@ -1525,6 +1527,410 @@ class LightningRepoTest : BaseUnitTest() { assertIs(retry.exceptionOrNull()) } + @Test + fun `a spark send held for the node's listing is retried once the starting node runs`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + var authorizations = 0 + + val payment = async { sut.payInvoice("bolt11", 1_000uL, onBeforeSend = { authorizations++ == 0 }) } + runCurrent() + assertFalse(payment.isCompleted, "The send failed instead of waiting for the starting node") + assertEquals(0, authorizations, "The send was authorized before the node listed its sends") + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + startNodeForTesting() + + assertEquals("hash", payment.await().getOrThrow()) + verify(sparkRepo, times(1)).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + verify(lightningService, never()).send(any(), anyOrNull(), anyOrNull(), anyOrNull()) + } + + @Test + fun `a spark send held for the node's listing fails with the hold once the node start times out`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + var isAuthorizationAsked = false + + val payment = async { + sut.payInvoice("bolt11", 1_000uL, onBeforeSend = { + isAuthorizationAsked = true + true + }) + } + advanceTimeBy(59.seconds) + assertFalse(payment.isCompleted) + advanceTimeBy(2.seconds) + + assertIs(payment.await().exceptionOrNull()) + assertFalse(isAuthorizationAsked) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `a spark send held for the node's listing fails at once when the node cannot run`() = test { + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + runCurrent() + + assertTrue(payment.isCompleted) + assertIs(payment.await().exceptionOrNull()) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + // Reachable only while a running node is being reset: the stale-graph restart and the recovery screen's reset. + @Test + fun `a held spark send fails with the hold after the bound when a running node never lists`() = test { + startNodeForTesting() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + advanceTimeBy(59.seconds) + assertFalse(payment.isCompleted, "The send gave up while the node could still list its sends in time") + advanceTimeBy(2.seconds) + + assertIs(payment.await().exceptionOrNull()) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `a listing that fails during the hold returns the hold's failure instead of throwing`() = test { + startNodeForTesting() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + var listings = 0 + whenever(lightningService.listPayments()).doSuspendableAnswer { + if (listings++ == 0) null else throw AppError("listing failed") + } + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + + val payment = runCatching { sut.payInvoice("bolt11", 1_000uL) } + + assertTrue(payment.isSuccess, "The send threw instead of returning its failure") + assertIs(payment.getOrThrow().exceptionOrNull()) + assertTrue(listings > 1) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `a held spark send keeps waiting through a failed start when another start is queued`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + whenever(lightningService.node).thenReturn(mock()) + whenever(lightningService.sync()).thenReturn(Unit) + val blocktank = mock() + whenever(coreService.blocktank).thenReturn(blocktank) + whenever(blocktank.info(any())).thenReturn(null) + val failed = CompletableDeferred() + var starts = 0 + whenever { lightningService.start(anyOrNull(), any()) }.doSuspendableAnswer { + if (starts++ == 0) { + failed.await() + throw AppError("start failed") + } + } + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + runCurrent() + val failingStart = async { sut.start(shouldRetry = false) } + runCurrent() + val queuedStart = async { sut.start(shouldRetry = false) } + runCurrent() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + failed.complete(Unit) + + assertTrue(failingStart.await().isFailure) + assertTrue(queuedStart.await().isSuccess) + assertEquals("hash", payment.await().getOrThrow()) + } + + @Test + fun `a held spark send ends when a wipe begins, before any storage is wiped`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + runCurrent() + sut.setWiping(true) + assertTrue(sut.start().isFailure) + runCurrent() + + assertTrue(payment.isCompleted, "The send kept waiting through a wipe") + assertIs(payment.await().exceptionOrNull()) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `a spark send held while a restart stops the node is retried once the restart runs it`() = test { + startNodeForTesting() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + withHeldStop { stopped -> + val restart = async { sut.restartNode() } + runCurrent() + whenever(lightningService.listPayments()).thenReturn(null) + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + runCurrent() + assertFalse(payment.isCompleted) + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + stopped.complete(Unit) + + assertTrue(restart.await().isSuccess) + assertEquals("hash", payment.await().getOrThrow()) + } + } + + @Test + fun `a held spark send waits for the listing when the node runs before it can list`() = test { + startNodeForTesting() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + advanceTimeBy(5.seconds) + assertFalse(payment.isCompleted, "The send used its retry before the node could list") + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + + assertEquals("hash", payment.await().getOrThrow()) + verify(sparkRepo, times(1)).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `a held spark send sends nothing when its caller is cancelled during the wait`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + var isAuthorizationAsked = false + + val payment = async { + sut.payInvoice("bolt11", 1_000uL, onBeforeSend = { + isAuthorizationAsked = true + true + }) + } + runCurrent() + assertFalse(payment.isCompleted) + payment.cancel() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + startNodeForTesting() + advanceTimeBy(2.minutes) + + assertTrue(payment.isCancelled) + assertFalse(isAuthorizationAsked) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + verify(lightningService, never()).send(any(), anyOrNull(), anyOrNull(), anyOrNull()) + } + + @Test + fun `a held spark send fails promptly when the node start fails`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(lightningService.node).thenReturn(mock()) + whenever { lightningService.start(anyOrNull(), any()) }.doSuspendableAnswer { throw AppError("start failed") } + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + runCurrent() + assertFalse(payment.isCompleted) + assertTrue(sut.start(shouldRetry = false).isFailure) + runCurrent() + + assertTrue(payment.isCompleted, "The send kept waiting for a node whose start failed") + assertIs(payment.await().exceptionOrNull()) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `a held spark send sends nothing when the wallet is wiped during the wait`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + whenever(sparkRepo.wipe(0)).thenReturn(Result.success(Unit)) + whenever(lightningService.node).thenReturn(mock()) + withHeldStop { stopped -> + var isAuthorizationAsked = false + + val payment = async { + sut.payInvoice("bolt11", 1_000uL, onBeforeSend = { + isAuthorizationAsked = true + true + }) + } + runCurrent() + val wipe = launch { sut.wipeStorage(0) } + runCurrent() + // The next wallet's node starts behind the wipe, so the wait sees a start coming all along. + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + val start = launch { startNodeForTesting() } + runCurrent() + stopped.complete(Unit) + wipe.join() + start.join() + + assertIs(payment.await().exceptionOrNull()) + assertFalse(isAuthorizationAsked) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + } + + @Test + fun `a spark send held while the node stops is retried once the queued start runs`() = test { + startNodeForTesting() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("hash")) + withHeldStop { stopped -> + val stop = launch { sut.stop() } + runCurrent() + assertEquals(NodeLifecycleState.Stopping, sut.lightningState.value.nodeLifecycleState) + whenever(lightningService.listPayments()).thenReturn(null) + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + runCurrent() + assertFalse(payment.isCompleted, "The send failed while the node was stopping") + val start = launch { sut.start() } + runCurrent() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + stopped.complete(Unit) + stop.join() + start.join() + + assertEquals("hash", payment.await().getOrThrow()) + verify(sparkRepo, times(1)).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + } + + @Test + fun `a spark send held while the node stops fails once it is stopped with no start coming`() = test { + startNodeForTesting() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + withHeldStop { stopped -> + val stop = launch { sut.stop() } + runCurrent() + whenever(lightningService.listPayments()).thenReturn(null) + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + runCurrent() + assertFalse(payment.isCompleted) + stopped.complete(Unit) + stop.join() + runCurrent() + + assertTrue(payment.isCompleted, "The send kept waiting for a node nothing starts") + assertIs(payment.await().exceptionOrNull()) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + } + + @Test + fun `the retry after the node starts returns the node's payment when it lists the invoice as paid`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + var isAuthorizationAsked = false + + val payment = async { + sut.payInvoice("bolt11", 1_000uL, onBeforeSend = { + isAuthorizationAsked = true + true + }) + } + runCurrent() + whenever(lightningService.listPayments()).thenReturn(listOf(nodeSend("bolt11", PaymentStatus.SUCCEEDED))) + startNodeForTesting() + + assertEquals("bolt11", payment.await().getOrThrow()) + assertFalse(isAuthorizationAsked) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + verify(lightningService, never()).send(any(), anyOrNull(), anyOrNull(), anyOrNull()) + } + + @Test + fun `the retry after the node starts pays over the node when its channels cover the amount`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success("spark-hash")) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn("node-hash") + + val payment = async { sut.payInvoice("bolt11", 1_000uL) } + runCurrent() + assertFalse(payment.isCompleted) + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + whenever(lightningService.channels).thenReturn( + listOf(createChannelDetails().copy(isUsable = true, nextOutboundHtlcLimitMsat = 2_000_000uL)), + ) + startNodeForTesting() + + assertEquals("node-hash", payment.await().getOrThrow()) + verify(lightningService, times(1)).send(eq("bolt11"), eq(1_000uL), anyOrNull(), anyOrNull()) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `the retry after the node starts sends nothing when the node lists its earlier send`() = test { + sut.setInitNodeLifecycleState() + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashes = listOf("bolt11")))) + whenever(lightningService.listPayments()).thenReturn(null) + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + var isAuthorizationAsked = false + + val payment = async { + sut.payInvoice("bolt11", 1_000uL, onBeforeSend = { + isAuthorizationAsked = true + true + }) + } + runCurrent() + assertFalse(payment.isCompleted) + whenever(lightningService.listPayments()).thenReturn(listOf(nodeSend("bolt11", PaymentStatus.PENDING))) + startNodeForTesting() + + assertIs(payment.await().exceptionOrNull()) + assertFalse(isAuthorizationAsked) + verify(sparkRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + verify(lightningService, never()).send(any(), anyOrNull(), anyOrNull(), anyOrNull()) + } + @Test fun `spark still pays while the node can't list when the node never tried the invoice`() = test { startNodeForTesting() @@ -1589,6 +1995,17 @@ class LightningRepoTest : BaseUnitTest() { assertEquals(listOf("paid"), store.data.first().ldkSendHashes) } + /** Holds the node's stop until [block] releases it or ends, as a stop left held would hang a failed test. */ + private suspend fun withHeldStop(block: suspend (CompletableDeferred) -> Unit) { + val stopped = CompletableDeferred() + whenever(lightningService.stop()).doSuspendableAnswer { stopped.await() } + try { + block(stopped) + } finally { + stopped.complete(Unit) + } + } + private suspend fun restoredCacheWithInvoiceAt(createdAt: Long) { val cache = AppCacheData(ldkSendHashesSeeded = true, ldkHistoryUnseededSince = restoredAt) whenever(cacheStore.data).thenReturn(flowOf(cache)) @@ -1999,6 +2416,77 @@ class LightningRepoTest : BaseUnitTest() { verify(lightningService).send(any(), anyOrNull(), anyOrNull(), anyOrNull()) } + @Test + fun `a failed node send with no attempt live settles as failed`() = test { + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn("h") + assertEquals("h", sut.payInvoice("h", 1_000uL).getOrThrow()) + + // Its failure event was handled before the caller watched for it, so the caller reads the settled payment. + whenever(lightningService.listPayments()).thenReturn(listOf(nodeSend("h", PaymentStatus.FAILED))) + + assertEquals("h", assertIs(sut.settledSparkSendEvent("h")).paymentHash) + } + + @Test + fun `a failed node send settles nothing while a retry of it is sent`() = test { + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn("h") + assertEquals("h", sut.payInvoice("h", 1_000uL).getOrThrow()) + whenever(lightningService.listPayments()).thenReturn(listOf(nodeSend("h", PaymentStatus.FAILED))) + val proceed = CompletableDeferred() + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).doSuspendableAnswer { + proceed.await() + "h" + } + val retry = backgroundScope.launch { sut.payInvoice("h", 1_000uL) } + runCurrent() + + assertNull(sut.settledSparkSendEvent("h")) + proceed.complete(Unit) + retry.join() + } + + @Test + fun `a failed node send settles nothing when a retry of it ends while the payments are listed`() = test { + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn("h") + assertEquals("h", sut.payInvoice("h", 1_000uL).getOrThrow()) + val proceed = CompletableDeferred() + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).doSuspendableAnswer { + proceed.await() + "h" + } + val retry = backgroundScope.launch { sut.payInvoice("h", 1_000uL) } + runCurrent() + // The listing reads the earlier attempt's failed row, and the retry is sent and released before it returns. + whenever(lightningService.listPayments()).doSuspendableAnswer { + proceed.complete(Unit) + retry.join() + listOf(nodeSend("h", PaymentStatus.FAILED)) + } + + assertNull(sut.settledSparkSendEvent("h")) + } + + @Test + fun `a failed node send is left to its event when the caller can still get it`() = test { + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.listPayments()).thenReturn(emptyList()) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn("h") + assertEquals("h", sut.payInvoice("h", 1_000uL).getOrThrow()) + whenever(lightningService.listPayments()).thenReturn(listOf(nodeSend("h", PaymentStatus.FAILED))) + + assertNull(sut.settledSparkSendEvent("h", includeNodeFailure = false)) + } + @Test fun `a spark send of an invoice the node already paid settles as paid`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index 24210d0f49..00c04b46b0 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -750,6 +750,39 @@ class MoveToSparkRepoTest : BaseUnitTest() { assertTrue(!MoveToSparkMath.needsUpdateToSend(149_126uL, channels, spark)) } + @Test + fun `a payment Spark can send alone never needs the update, whatever the channels hold`() { + val channelSets = listOf( + null, + emptyList(), + listOf(channel("c1", 10_000uL)), + listOf(channel("c1", 100_000uL)), + listOf(channel("c1", 100_000uL), channel("c2", 400_000uL)), + ) + val sparkStates = listOf(0uL, 1uL, 999uL, 50_000uL, 1_000_000uL).flatMap { balance -> + listOf( + SparkState(isReady = true, balanceSats = balance), + SparkState(isReady = false, balanceSats = balance), + SparkState(isReady = true, isExiting = true, balanceSats = balance), + SparkState(isReady = false, isExiting = true, balanceSats = balance), + ) + } + for (spark in sparkStates) { + val amounts = listOf(0uL, 1uL, 500uL, 10_000uL, 100_000uL, 149_125uL, 2_000_000uL) + + listOf(spark.sendableSats, spark.sendableSats + 1uL, spark.balanceSats) + for (channels in channelSets) { + for (amount in amounts.filter { spark.canSend(it) }) { + assertTrue( + !MoveToSparkMath.needsUpdateToSend(amount, channels, spark), + "'$amount' sats need the update though Spark sends them alone: $spark, $channels", + ) + } + } + if (!spark.isReady) assertTrue(amounts.none { spark.canSend(it) }) + if (spark.isExiting) assertTrue(amounts.none { it > 0uL && spark.canSend(it) }) + } + } + @Test fun `max send counts the combined balance`() { val channels = listOf(channel("c1", 100_000uL)) diff --git a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt index af3c71bde8..75cf7deafa 100644 --- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt @@ -8,6 +8,7 @@ import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow @@ -20,6 +21,7 @@ import kotlinx.coroutines.yield import org.junit.Before import org.junit.Test import org.junit.runner.RunWith +import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.NodeException import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull @@ -876,6 +878,207 @@ class QuickPayRepoTest : BaseUnitTest() { assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) } + @Test + fun `already paid return without a dispatch refunds a fresh reserve and emits already paid`() = test { + val (bolt11, hash) = testInvoice() + // An earlier send of the invoice paid it: success without authorizing, dispatching or a new payment event. + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { Result.success(hash) } + val session = QuickPaySession() + + sut.attach(session).test { + sut.payNow(session, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u)) + val error = assertIs(awaitItem()) + assertIs(error.error) + assertEquals(bolt11, error.paymentRequest) + } + assertEquals(0L, spentCents()) + assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) + verify(pendingPaymentRepo, never()).track(any()) + } + + @Test + fun `pending return without a dispatch refunds a fresh reserve and emits pending`() = test { + val (bolt11, hash) = testInvoice() + // An earlier send of the invoice is still in flight: refused without authorizing or dispatching. + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { Result.failure(PaymentPendingException(hash)) } + val session = QuickPaySession() + + sut.attach(session).test { + sut.payNow(session, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u)) + val pending = assertIs(awaitItem()) + assertEquals(hash, pending.paymentHash) + assertEquals(bolt11, pending.paymentRequest) + } + assertEquals(0L, spentCents()) + assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) + verify(pendingPaymentRepo).track(hash) + assertFalse(sut.hasOpen(hash)) + } + + @Test + fun `pending return with a failed row and a live retry tracks pending`() = test { + val (bolt11, hash) = testInvoice() + // Refused for a retry of the invoice in flight, whose earlier attempt is listed failed. + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { Result.failure(PaymentPendingException(hash)) } + whenever { lightningRepo.settledSparkSendEvent(hash) }.thenReturn(null) + paymentRows = listOf(failedRow(hash)) + val session = QuickPaySession() + + sut.attach(session).test { + sut.payNow(session, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u)) + assertIs(awaitItem()) + } + assertEquals(0L, spentCents()) + assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) + verify(pendingPaymentRepo).track(hash) + verify(pendingPaymentRepo, never()).resolve(any()) + assertFalse(sut.hasOpen(hash)) + } + + @Test + fun `pending return for an earlier send resolved before it was tracked resolves it again`() = test { + val (bolt11, hash) = testInvoice() + val pendingPayments = PendingPaymentRepo() + // The earlier send's screen tracked it, and its success resolved it before QuickPay tracked it. + pendingPayments.track(hash) + pendingPayments.resolve(PendingPaymentResolution.Success(hash)) + // Read at the refusal, before the row showed the success. + sut = repo(pendingPaymentRepo = pendingPayments, paymentLookup = { listOf(pendingRow(hash)) }) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { Result.failure(PaymentPendingException(hash)) } + whenever { lightningRepo.settledSparkSendEvent(hash) } + .thenReturn(Event.PaymentSuccessful("pid", hash, null, null)) + val session = QuickPaySession() + + sut.attach(session).test { + sut.payNow(session, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u)) + assertIs(awaitItem()) + } + assertFalse(pendingPayments.isPending(hash)) + assertIs(pendingPayments.consumeResolution(hash)) + assertEquals(0L, spentCents()) + } + + @Test + fun `earlier send success during the lookup refunds an undispatched reserve`() = test { + val (bolt11, hash) = testInvoice() + var isDelivered = false + sut = repo( + paymentLookup = { + // The earlier manual send's success arrives while the refusal's rows are read. + if (!isDelivered) { + isDelivered = true + sut.signalCompletion(paymentId = hash, paymentHash = hash, success = true) + } + listOf(succeededRow(hash)) + }, + ) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { Result.failure(PaymentPendingException(hash)) } + val session = QuickPaySession() + + sut.attach(session).test { + sut.payNow(session, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u)) + val error = assertIs(awaitItem()) + assertIs(error.error) + expectNoEvents() + } + assertTrue(isDelivered) + assertEquals(0L, spentCents()) + assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) + verify(pendingPaymentRepo, never()).track(any()) + } + + @Test + fun `success event before dispatch refunds the reserve and stops the send`() = test { + val (bolt11, hash) = testInvoice() + val started = CompletableDeferred() + val proceed = CompletableDeferred() + var isAuthorized: Boolean? = null + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val onBeforeSend = invocation.getArgument Boolean>(3) + started.complete(Unit) + proceed.await() + isAuthorized = onBeforeSend() + if (isAuthorized == true) Result.success("pid") else Result.failure(PaymentAbortedBeforeSend()) + } + val session = QuickPaySession() + + sut.attach(session).test { + val pay = backgroundScope.launch { + sut.payNow(session, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u)) + } + started.await() + assertEquals(250L, spentCents()) + + val outcome = sut.signalCompletion(paymentId = hash, paymentHash = hash, success = true) + + assertEquals(QuickPayCompletionKind.NONE, outcome.kind) + assertIs(assertIs(awaitItem()).error) + proceed.complete(Unit) + pay.join() + expectNoEvents() + } + assertEquals(false, isAuthorized) + assertEquals(0L, spentCents()) + assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) + } + + @Test + fun `stale dispatch after an early success leaves a later pay of the invoice alone`() = test { + val (bolt11, hash) = testInvoice() + val started = CompletableDeferred() + val proceed = CompletableDeferred() + var calls = 0 + var isStaleAuthorized: Boolean? = null + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + if (++calls > 1) awaitCancellation() + // The first send is still waiting before dispatch, for example on the node, when the invoice is paid. + started.complete(Unit) + proceed.await() + isStaleAuthorized = invocation.getArgument Boolean>(3)() + Result.failure(PaymentAbortedBeforeSend()) + } + val first = QuickPaySession() + val second = QuickPaySession() + val request = QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u) + + sut.attach(first).test { + val stale = backgroundScope.launch { sut.payNow(first, request) } + started.await() + sut.signalCompletion(paymentId = hash, paymentHash = hash, success = true) + assertIs(assertIs(awaitItem()).error) + + sut.attach(second).test { + val later = backgroundScope.launch { sut.payNow(second, request) } + runCurrent() + assertEquals(2, calls) + assertEquals(250L, spentCents()) + + proceed.complete(Unit) + stale.join() + + assertEquals(false, isStaleAuthorized) + assertTrue(sut.hasOpen(hash)) + assertEquals(250L, spentCents()) + expectNoEvents() + later.cancel() + } + } + } + @Test fun `re-pay of a settled hash does not double-count`() = test { val (bolt11, hash) = testInvoice() @@ -1731,7 +1934,12 @@ class QuickPayRepoTest : BaseUnitTest() { quickPayDailyLimitMultiplier = 5, ) - private fun repo(): QuickPayRepo { + private fun repo( + pendingPaymentRepo: PendingPaymentRepo = this.pendingPaymentRepo, + paymentLookup: QuickPayPaymentLookup = QuickPayPaymentLookup { + paymentRows ?: lightningRepo.listPaymentsOrNull()?.map { QuickPayReconcileRow(it) } + }, + ): QuickPayRepo { return QuickPayRepo( cacheStore = cacheStore, settingsStore = settingsStore, @@ -1741,9 +1949,7 @@ class QuickPayRepoTest : BaseUnitTest() { invoiceParser = QuickPayInvoiceParser { bolt11 -> bolt11.takeIf { it == TEST_BOLT11 }?.let { TEST_HASH } }, - paymentLookup = QuickPayPaymentLookup { - paymentRows ?: lightningRepo.listPaymentsOrNull()?.map { QuickPayReconcileRow(it) } - }, + paymentLookup = paymentLookup, ioDispatcher = testDispatcher, clock = clock, ) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index b0f0c8bab3..3ab37e2a1e 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -12399,7 +12399,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val invoice = lightningInvoice(bolt11, 1_000u) val paymentHash = invoice.paymentHash.toHex() whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -12436,7 +12436,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val paymentHash = invoice.paymentHash.toHex() whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = 1_000u)).thenReturn(Result.success(paymentHash)) whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = 2_000u)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -12469,7 +12469,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val paymentHash = invoice.paymentHash.toHex() whenever(context.getString(R.string.wallet__send_quickpay__already_paid)).thenReturn("Already paid") whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -12506,7 +12506,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val invoice = lightningInvoice(bolt11, 0u) val paymentHash = invoice.paymentHash.toHex() whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = 2_000u)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -12534,7 +12534,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val invoice = lightningInvoice(bolt11, 1_000u) val paymentHash = invoice.paymentHash.toHex() whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -12560,7 +12560,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val invoice = lightningInvoice(bolt11, 1_000u) val paymentHash = invoice.paymentHash.toHex() whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -12608,7 +12608,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val paymentHash = invoice.paymentHash.toHex() whenever(moveToSparkRepo.needsUpdateToSend(1_000uL)).thenReturn(true) whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -12636,7 +12636,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val invoice = lightningInvoice(bolt11, 1_000u) val paymentHash = invoice.paymentHash.toHex() whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -12841,7 +12841,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.onSendSuccess(details) Result.success(paymentHash) } - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = "payment_id", paymentHash = paymentHash, @@ -20830,7 +20830,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val paymentHash = "spark_hash" balanceState.value = BalanceState(maxSendLightningSats = 100_000u) whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.success(paymentHash)) - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = paymentHash, paymentHash = paymentHash, @@ -20862,7 +20862,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)) .thenReturn(Result.failure(PaymentPendingException(paymentHash))) // Spark's success was handled after the send returned pending, before the send screen tracked it. - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenReturn( + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenReturn( Event.PaymentSuccessful( paymentId = paymentHash, paymentHash = paymentHash, @@ -20896,7 +20896,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)) .thenReturn(Result.failure(PaymentPendingException(paymentHash))) // The send screen moved on to a payment to a contact before the pending send's success was read. - whenever(lightningRepo.settledSparkSendEvent(paymentHash)).thenAnswer { + whenever(lightningRepo.settledSparkSendEvent(eq(paymentHash), any())).thenAnswer { setActiveContactPaymentContext(nextContactKey) Event.PaymentSuccessful( paymentId = paymentHash, @@ -24617,6 +24617,144 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertNull(sut.quickPayData.value, "QuickPay paid a payment that needs the update") } + @Test + fun `a scan while the node starts uses QuickPay without the channel wait when Spark covers the amount`() = test { + val bolt11 = "lnbcrt1quickpaysparkstarting" + enableQuickPay() + stubLightningScan(bolt11 = bolt11, amountSats = 500u) + whenever(lightningRepo.canSendWithSpark(500u)).thenReturn(true) + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Starting))) + + sut.onScanResult(bolt11) + advanceUntilIdle() + + verify(lightningRepo, never()).waitForUsableChannels(any()) + assertEquals(QuickPayData.Bolt11(sats = 500u, bolt11 = bolt11), sut.quickPayData.value?.data) + assertEquals(Sheet.Send(SendRoute.QuickPay), sut.currentSheet.value) + } + + @Test + fun `a scan while the node starts waits for the channels when Spark covers less than the amount`() = test { + val bolt11 = "lnbcrt1quickpaysparkshort" + enableQuickPay() + stubLightningScan(bolt11 = bolt11, amountSats = 500u) + whenever(lightningRepo.canSendWithSpark(any())).thenAnswer { (it.arguments[0] as Long) <= 499L } + val nodeState = MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Starting)) + whenever(lightningRepo.lightningState).thenReturn(nodeState) + var isQuickPaySetBeforeWait = false + whenever(lightningRepo.waitForUsableChannels()).thenAnswer { + isQuickPaySetBeforeWait = sut.quickPayData.value != null + nodeState.value = LightningState(nodeLifecycleState = NodeLifecycleState.Running) + Unit + } + + sut.onScanResult(bolt11) + advanceUntilIdle() + + verify(lightningRepo).waitForUsableChannels() + assertFalse(isQuickPaySetBeforeWait) + assertEquals(QuickPayData.Bolt11(sats = 500u, bolt11 = bolt11), sut.quickPayData.value?.data) + } + + @Test + fun `an amountless scan while the node starts keeps the channel wait when Spark is ready with no balance`() = test { + val bolt11 = "lnbcrt1quickpayamountless" + // QuickPay never takes a zero amount. + enableQuickPay(canApply = false) + stubLightningScan(bolt11 = bolt11, amountSats = 0u) + whenever(lightningRepo.canSendWithSpark(0u)).thenReturn(true) + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Starting))) + + sut.onScanResult(bolt11) + advanceUntilIdle() + + // Once before the QuickPay decision and once before the send path reads what Lightning can send. + verify(lightningRepo, times(2)).waitForUsableChannels() + verify(lightningRepo, never()).waitForUsableChannels(awaitUsable = false) + assertNull(sut.quickPayData.value) + } + + @Test + fun `a scan with unusable channels uses QuickPay without waiting for them when Spark covers the amount`() = test { + val bolt11 = "lnbcrt1quickpaysparkpeeroffline" + enableQuickPay() + stubLightningScan(bolt11 = bolt11, amountSats = 500u) + whenever(lightningRepo.canSendWithSpark(500u)).thenReturn(true) + val offlinePeerChannel = mock { on { isUsable } doReturn false } + whenever(lightningRepo.lightningState).thenReturn( + MutableStateFlow( + LightningState( + nodeLifecycleState = NodeLifecycleState.Running, + channels = persistentListOf(offlinePeerChannel), + ) + ) + ) + + sut.onScanResult(bolt11) + advanceUntilIdle() + + verify(lightningRepo, never()).waitForUsableChannels() + verify(lightningRepo).waitForUsableChannels(awaitUsable = false) + assertEquals(QuickPayData.Bolt11(sats = 500u, bolt11 = bolt11), sut.quickPayData.value?.data) + } + + @Test + fun `a fixed lnurl scan while the node starts uses QuickPay without the channel wait when Spark covers`() = test { + val input = "lnurl1quickpaysparkstarting" + val data = + LnurlPayData(input, "https://example.com/callback", 1_000_000uL, 1_000_000uL, "[]", null, false, null) + enableQuickPay() + whenever(coreService.decode(input)).thenReturn(Scanner.LnurlPay(data)) + whenever(lightningRepo.canSend(1_000u)).thenReturn(true) + whenever(lightningRepo.canSendWithSpark(1_000u)).thenReturn(true) + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Starting))) + + sut.onScanResult(input) + advanceUntilIdle() + + verify(lightningRepo, never()).waitForUsableChannels(any()) + assertEquals(QuickPayData.LnurlPay(sats = 1_000u, data = data), sut.quickPayData.value?.data) + } + + @Test + fun `a unified scan while the node starts uses QuickPay without the channel wait when Spark covers`() = test { + val bolt11 = "lnbcrt1quickpaysparkunified" + val uri = "bitcoin:$REGTEST_ADDRESS?amount=0.0002&lightning=$bolt11" + enableQuickPay() + stubUnifiedScan(uri = uri, bolt11 = bolt11, amountSats = 20_000u, payeeNodeId = FOREIGN_NODE_ID.fromHex()) + whenever(lightningRepo.canSendWithSpark(20_000u)).thenReturn(true) + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Starting))) + + sut.onScanResult(uri) + advanceUntilIdle() + + verify(lightningRepo, never()).waitForUsableChannels(any()) + assertEquals(QuickPayData.Bolt11(sats = 20_000u, bolt11 = bolt11), sut.quickPayData.value?.data) + } + + @Test + fun `a payment that needs the update is never sent by QuickPay when the channel wait is skipped`() = test { + val bolt11 = "lnbcrt1quickpaysparkupdate" + enableQuickPay() + stubLightningScan(bolt11 = bolt11, amountSats = 500u) + whenever(lightningRepo.canSendWithSpark(500u)).thenReturn(true) + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Starting))) + whenever(moveToSparkRepo.needsUpdateToSend(500uL)).thenReturn(true) + whenever(moveToSparkRepo.quote()).thenReturn(Result.success(MoveToSparkQuote("lnbcrt1spark", 500uL, 1uL))) + whenever(moveToSparkRepo.estimateFeeAfterUpdate(bolt11, 500uL)).thenReturn(2uL) + + sut.onScanResult(bolt11) + advanceUntilIdle() + + assertNull(sut.quickPayData.value, "QuickPay paid a payment that needs the update") + verify(quickPayRepo, never()).canApply(any()) + } + @Test fun `a fixed-amount scan with QuickPay off does not wait for channels whose peer is offline`() = test { val bolt11 = "lnbcrt1quickpayoffpeeroffline" diff --git a/changelog.d/next/2036.fixed.md b/changelog.d/next/2036.fixed.md new file mode 100644 index 0000000000..36755808e2 --- /dev/null +++ b/changelog.d/next/2036.fixed.md @@ -0,0 +1 @@ +Fixed QuickPay waiting about 10 seconds for the Lightning node when Bitkit is opened by a payment request and the Spark balance covers the amount.