diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index aa4408f4f9..ad51a99c0c 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -3133,6 +3133,21 @@ class LightningRepo @Inject constructor( /** Whether Spark alone can pay [amountSats], which it does whenever the node cannot. */ fun canSendWithSpark(amountSats: ULong): Boolean = sparkRepo.canSend(amountSats) + /** + * Waits, up to [NODE_RUN_WAIT_TIMEOUT], while the node is stopping or a start is queued, so a caller that then + * checks channels sees the restarted node rather than the stop. Returns at once when no start is coming. + */ + suspend fun awaitPendingNodeStart() { + val changes = combine(_lightningState, pendingStartCount) { _, _ -> } + withTimeoutOrNull(NODE_RUN_WAIT_TIMEOUT) { + changes.first { + val lifecycle = _lightningState.value.nodeLifecycleState + val isComing = lifecycle is NodeLifecycleState.Stopping || pendingStartCount.value > 0 + lifecycle.canRun() || !isComing + } + } + } + /** Whether Spark's whole balance covers a withdrawal debiting [debitSats], its fees included. */ fun canWithdrawWithSpark(debitSats: ULong): Boolean = sparkRepo.canWithdraw(debitSats) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendAmountScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendAmountScreen.kt index 265f54f871..a4c339543b 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendAmountScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendAmountScreen.kt @@ -182,9 +182,10 @@ fun SendAmountScreen( } } - LaunchedEffect(uiState.decodedInvoice, uiState.payMethod) { + LaunchedEffect(uiState.decodedInvoice, uiState.payMethod, balances.maxSendLightningSats) { if (uiState.payMethod == SendMethod.LIGHTNING && uiState.decodedInvoice != null) { - currentOnEvent(SendEvent.EstimateMaxRoutingFee) + val quote = SendEvent.EstimateMaxRoutingFee(uiState.decodedInvoice.bolt11, balances.maxSendLightningSats) + currentOnEvent(quote) } } @@ -194,6 +195,7 @@ fun SendAmountScreen( amountInputViewModel = amountInputViewModel, syncNodeVariant = syncNodeVariant, currencies = currencies, + balances = balances, onBack = { onEvent(SendEvent.AmountReset) onBack() @@ -463,7 +465,7 @@ private fun SendAmountNodeRunning( PrimaryButton( text = stringResource(R.string.common__continue), - enabled = uiState.isAmountInputValid && !uiState.isFundingSourceLoading, + enabled = uiState.isAmountInputValid && !uiState.isFundingSourceLoading && !uiState.awaitsSparkMaxFee, isLoading = uiState.isLoading, onClick = onContinue, textStyle = if (uiState.paykitUsesUsdt) AppTextStyles.BodySSB.copy(letterSpacing = 0.sp) else null, 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 4d2b495d8e..570c5df809 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue @@ -57,6 +58,7 @@ import to.bitkit.repositories.ConnectivityState import to.bitkit.repositories.PaykitPaymentRequest import to.bitkit.repositories.PaykitSubscriptionId import to.bitkit.repositories.SparkState +import to.bitkit.ui.LocalBalances import to.bitkit.ui.components.ConnectionIssuesView import to.bitkit.ui.components.SyncNodeVariant import to.bitkit.ui.components.SyncNodeView @@ -116,6 +118,31 @@ private val CHANNELS_REFRESH_INTERVAL = 1.seconds internal fun sparkCanPayInvoice(payMethod: SendMethod, invoiceSats: ULong?, sparkState: SparkState): Boolean = payMethod == SendMethod.LIGHTNING && invoiceSats != null && invoiceSats > 0uL && sparkState.canSend(invoiceSats) +/** + * The amount Spark would pay for the scanned invoice: its own amount, or for an amountless one the amount entered, so + * the review of an amountless invoice Spark can pay goes ahead without the node too. + */ +internal fun sendInvoiceSats(invoiceSats: ULong?, enteredSats: ULong): ULong? = + invoiceSats?.takeIf { it > 0uL } ?: enteredSats.takeIf { invoiceSats != null && it > 0uL } + +/** + * Whether the amount of an amountless Lightning invoice can be entered without the node: Spark can send, so an amount + * within its balance pays without channels. An LNURL payment still waits for the node. + */ +internal fun sparkCanTakeAmount( + payMethod: SendMethod, + invoiceSats: ULong?, + isLnurl: Boolean, + sparkState: SparkState, +): Boolean = payMethod == SendMethod.LIGHTNING && invoiceSats == 0uL && !isLnurl && + sparkState.isUsable && sparkState.sendableSats > 0uL + +internal fun lightningAmountLimit(cachedMax: ULong, sparkMax: ULong?, isNodeRunning: Boolean): ULong = when { + sparkMax == null -> cachedMax + isNodeRunning -> maxOf(cachedMax, sparkMax) + else -> sparkMax +} + /** 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) @@ -140,6 +167,24 @@ internal fun waitsForNode( return hasAnyChannels && !hasUsableChannels } +/** + * Whether [route] comes before a payment is decoded: choosing, scanning or typing a recipient. Nothing there needs the + * node, and a Lightning invoice Spark can pay must reach it, so the sync overlay waits for the next step. + */ +internal fun isRecipientStep(route: SendRoute): Boolean = when (route) { + SendRoute.Recipient, SendRoute.Address, SendRoute.ContactSelect, SendRoute.QrScanner, SendRoute.ComingSoon -> true + else -> false +} + +internal fun NavDestination.isRecipientStep(): Boolean = + hasRoute() || hasRoute() || + hasRoute() || hasRoute() || hasRoute() + +/** Whether [this] comes after a payment was submitted, where waiting for the node no longer applies. */ +internal fun NavDestination.isPastReview(): Boolean = + hasRoute() || hasRoute() || hasRoute() || + hasRoute() || hasRoute() + internal fun NavDestination.isPaymentReview(): Boolean = hasRoute() || hasRoute() || hasRoute() || hasRoute() @@ -187,21 +232,40 @@ fun SendSheet( val isOffline by remember { derivedStateOf { connectivityState != ConnectivityState.CONNECTED } } val lightningState by walletViewModel.lightningState.collectAsStateWithLifecycle() val sendUiState by appViewModel.sendUiState.collectAsStateWithLifecycle() + val isWaitingForNode by appViewModel.isSendWaitingForNode.collectAsStateWithLifecycle() val contacts by appViewModel.pubkyContacts.collectAsStateWithLifecycle() var routingCacheResetAttempted by rememberSaveable(startDestination) { mutableStateOf(false) } 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 invoiceSats = sendUiState.decodedInvoice?.amountSatoshis + val sparkCanPay = sparkCanPayInvoice( + sendUiState.payMethod, + sendInvoiceSats(invoiceSats, sendUiState.amount), + sparkState, + ) + val sparkTakesAmount = sparkCanTakeAmount( + payMethod = sendUiState.payMethod, + invoiceSats = invoiceSats, + isLnurl = sendUiState.lnurl != null, + sparkState = sparkState, + ) + val navController = rememberNavController() + val entry by navController.currentBackStackEntryAsState() + // Until navigation settles the entry is null, and the sheet shows its start destination + val isRecipientStep = entry?.destination?.isRecipientStep() ?: isRecipientStep(startDestination) + val isAmountStep = entry?.destination?.hasRoute() ?: (startDestination == SendRoute.Amount) + // A Spark payment can be submitted before the node runs, and its balance then no longer covers it + val isPastReview = entry?.destination?.isPastReview() == true val shouldShowSyncOverlay = run { if (preparingRequest != null || sendUiState.paykitUsesUsdt) return@run false - if (sendUiState.hardwareWalletId != null) return@run false + if (sendUiState.hardwareWalletId != null || isPastReview) return@run false waitsForNode( isNodeRunning = lightningState.nodeLifecycleState.isRunning(), hasAnyChannels = hasAnyChannels, hasUsableChannels = lightningState.channels.any { it.isUsable }, - sparkCanPay = sparkCanPay, + sparkCanPay = sparkCanPay || isAmountStep && sparkTakesAmount, ) } @@ -239,8 +303,6 @@ fun SendSheet( .imePadding() .testTag("SendSheet"), ) { - val navController = rememberNavController() - val entry by navController.currentBackStackEntryAsState() val reviewing = entry?.destination?.isPaymentReview() == true LaunchedEffect(reviewing, lifecycle, appViewModel) { if (!reviewing) return@LaunchedEffect @@ -410,6 +472,7 @@ fun SendSheet( } composableWithDefaultTransitions { val uiState by appViewModel.sendUiState.collectAsStateWithLifecycle() + DisposableEffect(Unit) { onDispose { appViewModel.cancelAddressValidation() } } SendAddressScreen( uiState = uiState, onBack = { navController.popBackStack() }, @@ -465,13 +528,23 @@ fun SendSheet( val lightningState by walletViewModel.lightningState.collectAsStateWithLifecycle() SendAmountScreen( uiState = uiState, - nodeLifecycleState = if (uiState.hardwareWalletId != null) { + // Spark takes an amountless invoice's amount without the node, as a hardware wallet does + nodeLifecycleState = if (uiState.hardwareWalletId != null || sparkTakesAmount) { NodeLifecycleState.Running } else { lightningState.nodeLifecycleState }, canGoBack = startDestination != SendRoute.Amount || uiState.isPaymentRequest, syncNodeVariant = syncNodeVariant, + balances = LocalBalances.current.let { balances -> + balances.copy( + maxSendLightningSats = lightningAmountLimit( + cachedMax = balances.maxSendLightningSats, + sparkMax = sparkState.sendableSats.takeIf { sparkTakesAmount }, + isNodeRunning = lightningState.nodeLifecycleState.isRunning(), + ), + ) + }, onBack = { if (!navController.popBackStack()) { appViewModel.hideSheet() @@ -957,7 +1030,8 @@ fun SendSheet( } AnimatedVisibility( - visible = shouldShowSyncOverlay && !isOffline, + // A recipient step shows it only while a scanned payment waits for the node + visible = (if (isRecipientStep) isWaitingForNode else shouldShowSyncOverlay) && !isOffline, enter = fadeIn(), exit = fadeOut(), ) { diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index bb6370fd50..089d27e327 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -429,6 +429,22 @@ class AppViewModel @Inject constructor( if (canPresent()) _mainScreenEffect.emit(effect) } + /** Scanned payments that wait for the node or a usable channel before they can be reviewed. */ + private val _isSendWaitingForNode = MutableStateFlow(0) + val isSendWaitingForNode: StateFlow = _isSendWaitingForNode + .map { it > 0 } + .stateIn(viewModelScope, SharingStarted.Eagerly, false) + + /** Runs [wait] counted in [isSendWaitingForNode], since the recipient steps have no overlay of their own. */ + private suspend fun showingNodeWait(wait: suspend () -> T): T { + _isSendWaitingForNode.update { it + 1 } + return try { + wait() + } finally { + _isSendWaitingForNode.update { it - 1 } + } + } + /** * Waits for the node's channels before a Lightning send. When Spark covers [amountSats] there is no wait for a * usable channel: a running node only publishes its current channels, which the send limit reads, and a node not @@ -441,7 +457,11 @@ class AppViewModel @Inject constructor( requireCurrentPaymentPreparation(walletGeneration) val isNodeRunning = lightningRepo.lightningState.value.nodeLifecycleState.isRunning() val sparkCovers = amountSats != null && lightningRepo.canSendWithSpark(amountSats) - if (isNodeRunning || !sparkCovers) lightningRepo.waitForUsableChannels(awaitUsable = !sparkCovers) + when { + // A wait for a usable channel is shown; with Spark covering, only the channels are published + !sparkCovers -> showingNodeWait { lightningRepo.waitForUsableChannels(awaitUsable = true) } + isNodeRunning -> lightningRepo.waitForUsableChannels(awaitUsable = false) + } requireCurrentPaymentPreparation(walletGeneration) walletRepo.refreshMaxSendLightning() requireCurrentPaymentPreparation(walletGeneration) @@ -456,6 +476,7 @@ class AppViewModel @Inject constructor( /** Bumped only when a new send starts, unlike [sendStateGeneration], which edits within one send also bump. */ @Volatile private var sendSession = 0L + private var maxRoutingFeeJob: Job? = null /** Swipes and payments still running from the confirm screen, by [sendSession]; see [isSendSwipeRunning]. */ private val sendSwipeRuns = mutableMapOf() @@ -3617,9 +3638,7 @@ class AppViewModel @Inject constructor( SendEvent.CancelInitialSubscriptionPayment -> onCancelInitialSubscriptionPayment() is SendEvent.ConfirmAmountWarning -> onConfirmAmountWarning(it.warning) SendEvent.DismissAmountWarning -> onDismissAmountWarning() - SendEvent.EstimateMaxRoutingFee -> viewModelScope.launch { - estimateMaxAmountRoutingFee() - } + is SendEvent.EstimateMaxRoutingFee -> estimateMaxAmountRoutingFee(it) SendEvent.PayConfirmed -> onConfirmPay() SendEvent.ClearPayConfirmation -> _sendUiState.update { s -> s.copy(shouldConfirmPay = false) } @@ -3668,6 +3687,11 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToAddress) } + /** A typed address can wait for the node, so leaving it must stop that wait and its late result. */ + fun cancelAddressValidation() { + addressValidationJob?.cancel() + } + private fun resetAddressInput() { addressValidationJob?.cancel() _sendUiState.update { state -> @@ -3765,6 +3789,14 @@ class AppViewModel @Inject constructor( } if (invoice.amountSatoshis > 0uL) { + // Manual entry opens before the node runs, so wait for its channels unless Spark covers the amount + if (!lightningRepo.lightningState.value.nodeLifecycleState.isRunning()) { + // A foreground start can queue behind a background stop, which reads as unable to run + if (!lightningRepo.canSendWithSpark(invoice.amountSatoshis)) { + showingNodeWait { lightningRepo.awaitPendingNodeStart() } + } + waitForUsableChannels(amountSats = invoice.amountSatoshis) + } lightningRepo.syncState() if (!lightningRepo.canSend(invoice.amountSatoshis)) { val maxSendLightning = walletRepo.balanceState.value.maxSendLightningSats @@ -3940,7 +3972,10 @@ class AppViewModel @Inject constructor( return@takeIf canSend } - private suspend fun LightningInvoice.isOwnInvoice(): Boolean = isPayee(lightningRepo.awaitNodeId()) + /** On a cold start the node id is known only once the node runs, so that wait is shown. */ + private suspend fun LightningInvoice.isOwnInvoice(): Boolean = isPayee( + lightningRepo.getLastKnownNodeId() ?: showingNodeWait { lightningRepo.awaitNodeId() } + ) private fun LightningInvoice.isPayee(nodeId: String?): Boolean { val payee = payeeNodeId?.toHex() ?: return false @@ -5186,6 +5221,7 @@ class AppViewModel @Inject constructor( private suspend fun onAmountContinue() { if (_sendUiState.value.isLoading || !reviewPaykitAmount()) return + if (!isAmountlessInvoiceWithinLimit()) return _sendUiState.update { it.copy( selectedUtxos = null, @@ -5223,7 +5259,12 @@ class AppViewModel @Inject constructor( } updateCanSwitchWallet() - setSendEffect(SendEffect.NavigateToConfirm) + setSendEffect(SendEffect.NavigateToConfirm) { isAmountlessInvoiceWithinLimit() } + } + + private suspend fun isAmountlessInvoiceWithinLimit(): Boolean { + val state = _sendUiState.value + return !state.isAmountlessLightningInvoice || (!state.awaitsSparkMaxFee && validateAmount(state.amount)) } /** @@ -5635,15 +5676,23 @@ class AppViewModel @Inject constructor( private suspend fun validateAmount( amount: ULong, payMethod: SendMethod = _sendUiState.value.payMethod, + routingFee: ULong = _sendUiState.value.estimatedRoutingFee, ): Boolean { if (amount == 0uL) return false return when (payMethod) { SendMethod.LIGHTNING -> { sparkWithdrawalValidity(amount)?.let { return it } - val maxSendable = maxSendableLightningSats() + val maxSendable = maxSendableLightningSats(routingFee) + // Spark keeps the routing reserve that Available leaves out + val sparkDebit = amount.safe() + routingFee.safe() + if (onlySparkTakesInvoiceAmount(_sendUiState.value)) { + return lightningRepo.canSendWithSpark(sparkDebit) + } when (val lnurl = _sendUiState.value.lnurl) { - null -> amount <= maxSendable && lightningRepo.canSend(amount) + // The cached limit is re-derived only once the node runs, so it can trail Spark's balance + null -> (amount <= maxSendable || lightningRepo.canSendWithSpark(sparkDebit)) && + lightningRepo.canSend(amount) is LnurlParams.LnurlWithdraw -> amount <= lnurl.data.maxWithdrawableSat() is LnurlParams.LnurlPay -> { val maxSat = lnurl.data.maxSendableSat() @@ -5705,9 +5754,8 @@ class AppViewModel @Inject constructor( return true.takeIf { lightningRepo.canWithdrawWithSpark(amount) } } - private fun maxSendableLightningSats(): ULong { + private fun maxSendableLightningSats(fee: ULong = _sendUiState.value.estimatedRoutingFee): ULong { val max = walletRepo.balanceState.value.maxSendLightningSats - val fee = _sendUiState.value.estimatedRoutingFee return max.safe() - fee.safe() } @@ -9280,24 +9328,40 @@ class AppViewModel @Inject constructor( } } - private suspend fun estimateMaxAmountRoutingFee() { - val currentState = _sendUiState.value - if (currentState.payMethod != SendMethod.LIGHTNING) return - - val decodedInvoice = currentState.decodedInvoice ?: return - val bolt11 = decodedInvoice.bolt11 - - val maxSendLightning = walletRepo.balanceState.value.maxSendLightningSats - if (maxSendLightning == 0uL) { - _sendUiState.update { it.copy(estimatedRoutingFee = 0uL) } - return - } + private fun onlySparkTakesInvoiceAmount(state: SendUiState) = + state.isAmountlessLightningInvoice && !lightningRepo.lightningState.value.nodeLifecycleState.isRunning() && + lightningRepo.canSendWithSpark(1u) - lightningRepo.estimateMaxSendFee(bolt11, maxSendLightning).onSuccess { fee -> - _sendUiState.update { it.copy(estimatedRoutingFee = fee) } - }.onFailure { e -> - Logger.error("Failed to estimate routing fee for max amount", e, context = TAG) - _sendUiState.update { it.copy(estimatedRoutingFee = 0uL) } + private fun estimateMaxAmountRoutingFee(quote: SendEvent.EstimateMaxRoutingFee) { + val session = sendSession + val current = _sendUiState.value + if (current.payMethod != SendMethod.LIGHTNING || current.decodedInvoice?.bolt11 != quote.bolt11) return + maxRoutingFeeJob?.cancel() + val pendingInvoice = quote.bolt11.takeIf { onlySparkTakesInvoiceAmount(current) } + _sendUiState.update { it.copy(pendingSparkMaxInvoice = pendingInvoice) } + maxRoutingFeeJob = viewModelScope.launch { + val fee = if (quote.maxSendSats == 0uL) { + 0uL + } else { + lightningRepo.estimateMaxSendFee(quote.bolt11, quote.maxSendSats).getOrElse { error -> + Logger.warn("Failed to estimate routing fee for max amount", error, context = TAG) + 0uL + } + } + ensureActive() + _sendUiState.update { state -> + if (session != sendSession || state.payMethod != SendMethod.LIGHTNING || + state.decodedInvoice?.bolt11 != quote.bolt11 + ) { + return@update state + } + val valid = if (state.isAmountlessLightningInvoice) { + validateAmount(state.amount, routingFee = fee) + } else { + state.isAmountInputValid + } + state.copy(estimatedRoutingFee = fee, isAmountInputValid = valid, pendingSparkMaxInvoice = null) + } } } @@ -9642,6 +9706,7 @@ class AppViewModel @Inject constructor( // A read still preparing belongs to this Send visit: it must not reopen a sheet or reach QuickPay. // A scan that closes Send itself keeps running, and no later visit may cancel it. if (isRunningScan.get() != true) cancelSendVisitScan() else sendVisitScanJob = null + cancelAddressValidation() hasLeftSendRecipient = true sendStateGeneration++ // A closed send is over: a swap failing for it later gives no contact back to whatever comes next. @@ -11106,6 +11171,7 @@ data class SendUiState( val onchainFeeUi: OnchainFeeUi = OnchainFeeUi(), val lightningFeeSats: Long? = null, val estimatedRoutingFee: ULong = 0uL, + val pendingSparkMaxInvoice: String? = null, val lastLightningFee: Long = 0L, val contactPaymentProfile: PubkyProfile? = null, val isPaymentRequest: Boolean = false, @@ -11160,6 +11226,14 @@ data class SendUiState( val routedPaykitRoute: PaykitRouteUi? get() = paykitRoute?.takeIf { payMethod == SendMethod.LIGHTNING } + val awaitsSparkMaxFee: Boolean + get() = isAmountlessLightningInvoice && pendingSparkMaxInvoice != null && + pendingSparkMaxInvoice == decodedInvoice?.bolt11 + + val isAmountlessLightningInvoice: Boolean + get() = payMethod == SendMethod.LIGHTNING && decodedInvoice?.amountSatoshis == 0uL && + lnurl == null && paykitRoute == null && !isPaymentRequest && !paykitUsesUsdt + /** Whether bitkit-core's router picks how this contact payment is paid; USDT and hardware wallets pay as picked. */ val routesPaykitPayment: Boolean get() = !paykitUsesUsdt && hardwareWalletId == null && lnurl !is LnurlParams.LnurlWithdraw @@ -11450,7 +11524,7 @@ sealed interface SendEvent { data object PaymentMethodSwitch : SendEvent data class PaymentMethodSelect(val source: SendFundingSource) : SendEvent data class ConfirmAmountWarning(val warning: SanityWarning) : SendEvent - data object EstimateMaxRoutingFee : SendEvent + data class EstimateMaxRoutingFee(val bolt11: String, val maxSendSats: ULong) : SendEvent data object DismissAmountWarning : SendEvent data object PayConfirmed : SendEvent data object ClearPayConfirmation : SendEvent diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index a0aa9ec43e..de67f24a9f 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1967,6 +1967,35 @@ class LightningRepoTest : BaseUnitTest() { } } + @Test + fun `a pending node start is awaited through a stop it queued behind`() = test { + startNodeForTesting() + withHeldStop { stopped -> + val stop = launch { sut.stop() } + runCurrent() + val wait = async { sut.awaitPendingNodeStart() } + val start = launch { sut.start() } + runCurrent() + assertFalse(wait.isCompleted, "The wait ended while the node was stopping") + stopped.complete(Unit) + stop.join() + start.join() + wait.await() + + assertTrue(sut.lightningState.value.nodeLifecycleState.isRunning()) + } + } + + @Test + fun `a pending node start returns at once when the node is stopped with no start coming`() = test { + startNodeForTesting() + sut.stop() + + sut.awaitPendingNodeStart() + + assertEquals(NodeLifecycleState.Stopped, sut.lightningState.value.nodeLifecycleState) + } + @Test fun `a spark send held while the node stops fails once it is stopped with no start coming`() = test { startNodeForTesting() diff --git a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt index 8c6a44719e..d758f03dbc 100644 --- a/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt +++ b/app/src/test/java/to/bitkit/ui/sheets/SendSheetSyncOverlayTest.kt @@ -4,7 +4,9 @@ import org.junit.Test import to.bitkit.repositories.SparkState import to.bitkit.viewmodels.QuickPayData import to.bitkit.viewmodels.SendMethod +import kotlin.test.assertEquals import kotlin.test.assertFalse +import kotlin.test.assertNull import kotlin.test.assertTrue class SendSheetSyncOverlayTest { @@ -45,4 +47,51 @@ class SendSheetSyncOverlayTest { assertTrue(waitsForNode(true, hasAnyChannels = true, hasUsableChannels = false, sparkCanPay = false)) assertFalse(waitsForNode(true, hasAnyChannels = true, hasUsableChannels = true, sparkCanPay = false)) } + + @Test + fun `recipient steps never wait for the node`() { + // Coming Soon is Contact's fallback while Paykit is off, so it shows at once too + listOf( + SendRoute.Recipient, + SendRoute.Address, + SendRoute.ContactSelect, + SendRoute.QrScanner, + SendRoute.ComingSoon, + ).forEach { + assertTrue(isRecipientStep(it)) + } + listOf(SendRoute.Amount, SendRoute.Confirm, SendRoute.QuickPay).forEach { + assertFalse(isRecipientStep(it)) + } + } + + @Test + fun `an amountless invoice spark pays uses the entered amount`() { + assertEquals(1_000uL, sendInvoiceSats(invoiceSats = 1_000uL, enteredSats = 5uL)) + assertEquals(5uL, sendInvoiceSats(invoiceSats = 0uL, enteredSats = 5uL)) + assertNull(sendInvoiceSats(invoiceSats = 0uL, enteredSats = 0uL)) + assertNull(sendInvoiceSats(invoiceSats = null, enteredSats = 5uL)) + assertTrue(sparkCanPayInvoice(SendMethod.LIGHTNING, sendInvoiceSats(0uL, 1_000uL), funded)) + } + + @Test + fun `amount entry and its Max quote use the capacity of the available rails`() { + assertEquals(40_000uL, lightningAmountLimit(100_000u, 40_000u, isNodeRunning = false)) + assertEquals(40_000uL, lightningAmountLimit(0u, 40_000u, isNodeRunning = false)) + assertEquals(40_000uL, lightningAmountLimit(0u, 40_000u, isNodeRunning = true)) + assertEquals(100_000uL, lightningAmountLimit(100_000u, 40_000u, isNodeRunning = true)) + assertEquals(100_000uL, lightningAmountLimit(100_000u, null, isNodeRunning = true)) + } + + @Test + fun `spark takes the amount of an amountless invoice only`() { + assertTrue(sparkCanTakeAmount(SendMethod.LIGHTNING, 0uL, isLnurl = false, funded)) + assertFalse(sparkCanTakeAmount(SendMethod.LIGHTNING, 1_000uL, isLnurl = false, funded)) + assertFalse(sparkCanTakeAmount(SendMethod.LIGHTNING, null, isLnurl = false, funded)) + assertFalse(sparkCanTakeAmount(SendMethod.LIGHTNING, 0uL, isLnurl = true, funded)) + assertFalse(sparkCanTakeAmount(SendMethod.ONCHAIN, 0uL, isLnurl = false, funded)) + assertFalse(sparkCanTakeAmount(SendMethod.LIGHTNING, 0uL, isLnurl = false, funded.copy(isReady = false))) + assertFalse(sparkCanTakeAmount(SendMethod.LIGHTNING, 0uL, isLnurl = false, funded.copy(balanceSats = 0uL))) + assertFalse(sparkCanTakeAmount(SendMethod.LIGHTNING, 0uL, isLnurl = false, funded.copy(isExiting = true))) + } } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 672cf8b27a..536a1b526f 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -4409,6 +4409,20 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(hwWalletRepo).cancelPairingCode() } + @Test + fun `amount Spark can pay is valid above a stale spending limit`() = test { + // The cached limit is only re-derived once the node runs, so it can trail Spark's balance + balanceState.value = BalanceState(maxSendLightningSats = 1_000u) + whenever(lightningRepo.canSendWithSpark(5_000u)).thenReturn(true) + whenever(lightningRepo.canSend(5_000u)).thenReturn(true) + setSendState(SendUiState(payMethod = SendMethod.LIGHTNING)) + + sut.setSendEvent(SendEvent.AmountChange(5_000u)) + advanceUntilIdle() + + assertTrue(sut.sendUiState.value.isAmountInputValid) + } + @Test fun `canSwitchWallet is false when not unified`() = test { sut.setSendEvent(SendEvent.AmountChange(1000u)) @@ -5549,6 +5563,158 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(coreService, never()).decode(any()) } + @Test + fun `manual invoice Spark cannot cover waits for the node before checking capacity`() = test { + val bolt11 = "lnbcrt1manualwait" + stubLightningScan(bolt11 = bolt11, amountSats = 50_000u) + whenever(lightningRepo.canSendWithSpark(50_000u)).thenReturn(false) + whenever(lightningRepo.getLastKnownNodeId()).thenReturn(OWN_NODE_ID) + sut.showSheet(Sheet.Send()) + + sut.setSendEvent(SendEvent.AddressChange(bolt11)) + advanceUntilIdle() + + inOrder(lightningRepo) { + verify(lightningRepo).awaitPendingNodeStart() + verify(lightningRepo).waitForUsableChannels(awaitUsable = true) + verify(lightningRepo).canSend(50_000u) + } + assertTrue(sut.sendUiState.value.isAddressInputValid) + } + + @Test + fun `manual invoice Spark covers skips the queued node start`() = test { + val bolt11 = "lnbcrt1manualspark" + stubLightningScan(bolt11 = bolt11, amountSats = 5_000u) + whenever(lightningRepo.canSendWithSpark(5_000u)).thenReturn(true) + whenever(lightningRepo.getLastKnownNodeId()).thenReturn(OWN_NODE_ID) + sut.showSheet(Sheet.Send()) + + sut.setSendEvent(SendEvent.AddressChange(bolt11)) + advanceUntilIdle() + + verify(lightningRepo, never()).awaitPendingNodeStart() + verify(lightningRepo, never()).waitForUsableChannels(awaitUsable = true) + } + + @Test + fun `manual invoice with the node running checks capacity without waiting`() = test { + val bolt11 = "lnbcrt1manualrunning" + stubLightningScan(bolt11 = bolt11, amountSats = 50_000u) + whenever(lightningRepo.canSendWithSpark(50_000u)).thenReturn(false) + whenever(lightningRepo.getLastKnownNodeId()).thenReturn(OWN_NODE_ID) + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Running))) + sut.showSheet(Sheet.Send()) + + sut.setSendEvent(SendEvent.AddressChange(bolt11)) + advanceUntilIdle() + + verify(lightningRepo, never()).waitForUsableChannels(any()) + verify(lightningRepo).canSend(50_000u) + } + + @Test + fun `closing Send cancels a typed invoice's node wait`() = test { + val bolt11 = "lnbcrt1manualclosed" + stubLightningScan(bolt11 = bolt11, amountSats = 50_000u) + whenever(lightningRepo.canSendWithSpark(50_000u)).thenReturn(false) + whenever(lightningRepo.getLastKnownNodeId()).thenReturn(OWN_NODE_ID) + val nodeReady = CompletableDeferred() + whenever(lightningRepo.waitForUsableChannels(any())).doSuspendableAnswer { nodeReady.await() } + sut.showSheet(Sheet.Send()) + sut.setSendEvent(SendEvent.AddressChange(bolt11)) + advanceTimeBy(5_000) + runCurrent() + assertTrue(sut.isSendWaitingForNode.value) + + sut.hideSheet() + runCurrent() + nodeReady.complete(Unit) + advanceUntilIdle() + + assertFalse(sut.isSendWaitingForNode.value) + assertFalse(sut.sendUiState.value.isAddressInputValid) + } + + @Test + fun `amount Spark can pay keeps the routing fee reserve`() = test { + balanceState.value = BalanceState(maxSendLightningSats = 10_000u) + whenever(lightningRepo.canSendWithSpark(9_950u)).thenReturn(true) + whenever(lightningRepo.canSendWithSpark(10_000u)).thenReturn(true) + whenever(lightningRepo.canSendWithSpark(10_050u)).thenReturn(false) + whenever(lightningRepo.canSend(any())).thenReturn(true) + setSendState(SendUiState(payMethod = SendMethod.LIGHTNING, estimatedRoutingFee = 100u)) + + sut.setSendEvent(SendEvent.AmountChange(9_950u)) + advanceUntilIdle() + assertFalse(sut.sendUiState.value.isAmountInputValid) + + sut.setSendEvent(SendEvent.AmountChange(9_900u)) + advanceUntilIdle() + assertTrue(sut.sendUiState.value.isAmountInputValid) + } + + @Test + fun `max quote uses the displayed Spark limit and revalidates the entered amount`() = test { + val bolt11 = "lnbcrt1maxspark" + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + whenever(lightningRepo.canSendWithSpark(1u)).thenReturn(true) + whenever(lightningRepo.canSendWithSpark(40_000u)).thenReturn(true) + val quote = CompletableDeferred>() + whenever(lightningRepo.estimateMaxSendFee(bolt11, 40_000u)).doSuspendableAnswer { quote.await() } + setSendState(SendUiState(payMethod = SendMethod.LIGHTNING, decodedInvoice = lightningInvoice(bolt11, 0u))) + + sut.setSendEvent(SendEvent.AmountMax(40_000u)) + advanceUntilIdle() + assertTrue(sut.sendUiState.value.isAmountInputValid) + + sut.setSendEvent(SendEvent.EstimateMaxRoutingFee(bolt11, 40_000u)) + runCurrent() + assertTrue(sut.sendUiState.value.awaitsSparkMaxFee) + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + expectNoEvents() + } + quote.complete(Result.success(120u)) + advanceUntilIdle() + assertFalse(sut.sendUiState.value.awaitsSparkMaxFee) + + assertEquals(120uL, sut.sendUiState.value.estimatedRoutingFee) + assertFalse(sut.sendUiState.value.isAmountInputValid) + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + expectNoEvents() + } + } + + @Test + fun `a delayed Max quote cannot update another invoice or a reopened Send`() = test { + val bolt11 = "lnbcrt1maxfirst" + val first = SendUiState(payMethod = SendMethod.LIGHTNING, decodedInvoice = lightningInvoice(bolt11, 0u)) + for (reopen in listOf(false, true)) { + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + setSendState(first) + val quote = CompletableDeferred>() + whenever(lightningRepo.estimateMaxSendFee(bolt11, 1000u)).doSuspendableAnswer { quote.await() } + sut.setSendEvent(SendEvent.EstimateMaxRoutingFee(bolt11, 1000u)) + runCurrent() + if (reopen) { + sut.hideSheet() + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + } + val nextInvoice = if (reopen) bolt11 else "lnbcrt1maxsecond" + setSendState(first.copy(decodedInvoice = lightningInvoice(nextInvoice, 0u), estimatedRoutingFee = 10u)) + quote.complete(if (reopen) Result.failure(IllegalStateException("old quote")) else Result.success(76u)) + advanceUntilIdle() + assertEquals(10uL, sut.sendUiState.value.estimatedRoutingFee) + } + } + @Test fun `manual own USDT address explains why sending is blocked`() = test { if (!Env.isUsdtEnabled) return@test diff --git a/changelog.d/next/2244.fixed.md b/changelog.d/next/2244.fixed.md new file mode 100644 index 0000000000..03f98cebe5 --- /dev/null +++ b/changelog.d/next/2244.fixed.md @@ -0,0 +1 @@ +Fixed the Send sheet waiting for the Lightning node before you can pick a recipient, and before you can enter the amount of an invoice your spending balance can pay. diff --git a/journeys/send/onchain-connecting-view.xml b/journeys/send/onchain-connecting-view.xml index 3b28bbdf9f..93ab406334 100644 --- a/journeys/send/onchain-connecting-view.xml +++ b/journeys/send/onchain-connecting-view.xml @@ -6,19 +6,18 @@ "Please wait for Bitkit to connect to the bitcoin network (±10 seconds)." A wallet whose channels have loaded keeps the purple Spending variant. - The view shows only until the node runs. A cold launch shows home only once the node runs, so - restart the node from the LDK debug screen and open Send at once; the view then shows for about - 2 seconds. Take a screenshot or record as soon as Send opens. iOS reaches the view by another - route; see its journey and journeys/README.md. - - Precondition: onboarded dev wallet with no Lightning channels. Start on the wallet home screen. + Precondition: onboarded regtest wallet with confirmed Savings and no channels. Copy another + regtest wallet's on-chain address without an amount. Restart the node from the LDK debug screen with node startup + held long enough to paste the address, then release startup at the step below. Tap the header menu (testTag "HeaderMenu") and then Settings (testTag "DrawerSettings") Tap the Advanced tab (testTag "Tab-advanced"), then Dev Settings (testTag "DevSettings"), then LDK Tap Restart, go back to the wallet home screen at once and tap Send (testTag "Send") + Verify Recipient shows Scan, Paste and Enter Manually and the connecting overlay is absent + Tap Paste to open Amount for the copied on-chain address Verify the Send sheet shows the "Send Bitcoin" header, "Connecting to network" with "Connecting" in orange, the bitcoin coin inside orange rings, the text "Please wait for Bitkit to connect to the bitcoin network (±10 seconds)." and a spinner - Verify the view gives way to the Send recipient screen once the node runs + Release node startup and verify the overlay clears to Amount with Savings available and the number pad enabled Close the Send sheet