Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions app/src/main/java/to/bitkit/repositories/LightningRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3133,6 +3133,24 @@ 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)

/** The most Spark can send now, its own fee kept, which the cached Spending limit trails until the node runs. */
fun sparkSendableSats(): ULong = sparkRepo.state.value.sendableSats

/**
* 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)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ fun SendAmountScreen(
amountInputViewModel = amountInputViewModel,
syncNodeVariant = syncNodeVariant,
currencies = currencies,
balances = balances,
onBack = {
onEvent(SendEvent.AmountReset)
onBack()
Expand Down
81 changes: 74 additions & 7 deletions app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -116,6 +118,25 @@ 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

/** 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)
Expand All @@ -140,6 +161,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<SendRoute.Recipient>() || hasRoute<SendRoute.Address>() ||
Comment thread
ovitrif marked this conversation as resolved.
Resolved
hasRoute<SendRoute.ContactSelect>() || hasRoute<SendRoute.QrScanner>() || hasRoute<SendRoute.ComingSoon>()

/** Whether [this] comes after a payment was submitted, where waiting for the node no longer applies. */
internal fun NavDestination.isPastReview(): Boolean =
hasRoute<SendRoute.Pending>() || hasRoute<SendRoute.Success>() || hasRoute<SendRoute.Error>() ||
hasRoute<SendRoute.WithdrawError>() || hasRoute<SendRoute.QuickPay>()

internal fun NavDestination.isPaymentReview(): Boolean =
hasRoute<SendRoute.Confirm>() || hasRoute<SendRoute.PinCheck>() ||
hasRoute<SendRoute.RecoveryPinCheck>() || hasRoute<SendRoute.HardwareSign>()
Expand Down Expand Up @@ -187,21 +226,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<SendRoute.Amount>() ?: (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,
)
}

Expand Down Expand Up @@ -239,8 +297,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
Expand Down Expand Up @@ -410,6 +466,7 @@ fun SendSheet(
}
composableWithDefaultTransitions<SendRoute.Address> {
val uiState by appViewModel.sendUiState.collectAsStateWithLifecycle()
DisposableEffect(Unit) { onDispose { appViewModel.cancelAddressValidation() } }
SendAddressScreen(
uiState = uiState,
onBack = { navController.popBackStack() },
Expand Down Expand Up @@ -465,13 +522,22 @@ 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
Comment thread
ovitrif marked this conversation as resolved.
Resolved
} else {
lightningState.nodeLifecycleState
},
canGoBack = startDestination != SendRoute.Amount || uiState.isPaymentRequest,
syncNodeVariant = syncNodeVariant,
// The cached limit is not refreshed while the node is down; only Spark can pay then
balances = LocalBalances.current.let { balances ->
if (sparkTakesAmount && !lightningState.nodeLifecycleState.isRunning()) {
balances.copy(maxSendLightningSats = sparkState.sendableSats)
Comment thread
ovitrif marked this conversation as resolved.
Resolved
} else {
balances
}
},
Comment thread
ovitrif marked this conversation as resolved.
Resolved
onBack = {
if (!navController.popBackStack()) {
appViewModel.hideSheet()
Expand Down Expand Up @@ -957,7 +1023,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(),
) {
Expand Down
51 changes: 47 additions & 4 deletions app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<Boolean> = _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 <T> 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
Expand All @@ -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)
Expand Down Expand Up @@ -3575,6 +3595,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 ->
Expand Down Expand Up @@ -3672,6 +3697,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)
Comment thread
ovitrif marked this conversation as resolved.
Resolved
}
lightningRepo.syncState()
if (!lightningRepo.canSend(invoice.amountSatoshis)) {
val maxSendLightning = walletRepo.balanceState.value.maxSendLightningSats
Expand Down Expand Up @@ -3847,7 +3880,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
Expand Down Expand Up @@ -5549,8 +5585,12 @@ class AppViewModel @Inject constructor(
SendMethod.LIGHTNING -> {
sparkWithdrawalValidity(amount)?.let { return it }
val maxSendable = maxSendableLightningSats()
// Spark keeps the routing reserve that Available leaves out
val sparkDebit = amount.safe() + _sendUiState.value.estimatedRoutingFee.safe()
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)) &&

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] Revalidate the entered amount when the Spark fee arrives

With the node down and a zero cache, tap Available while the Spark Max quote is still in flight. The amount passes validation with a zero reserve. A later quote can lower Available below the entered amount, but the fee update leaves the validity flag true and Continue uses that flag. The user could advance to review with an amount the updated limit rejects. Revalidate the entered amount when the quote arrives and enforce the updated limit on Continue. A focused Kotlin probe confirmed that fresh validation rejects the amount while the stored validity remains true.

lightningRepo.canSend(amount)
is LnurlParams.LnurlWithdraw -> amount <= lnurl.data.maxWithdrawableSat()
is LnurlParams.LnurlPay -> {
val maxSat = lnurl.data.maxSendableSat()
Expand Down Expand Up @@ -9194,7 +9234,9 @@ class AppViewModel @Inject constructor(
val decodedInvoice = currentState.decodedInvoice ?: return
val bolt11 = decodedInvoice.bolt11

val maxSendLightning = walletRepo.balanceState.value.maxSendLightningSats
// The cached limit is re-derived only once the node runs, so Spark's live amount is quoted while it trails
val cachedMax = walletRepo.balanceState.value.maxSendLightningSats
val maxSendLightning = maxOf(cachedMax, lightningRepo.sparkSendableSats())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MEDIUM] Quote the Spark limit when only Spark can pay

With the node stopped, open an amountless invoice when the cached Spending limit exceeds Spark’s live sendable balance. The keypad uses the Spark limit, but the Max quote takes the larger cached limit. That amount cannot route through Spark, so the estimate falls through to the stopped node and leaves a zero reserve. Available would then offer an amount the wallet cannot fund whenever the route fee exceeds the remaining fee headroom. Use the same live limit for the quote and the keypad while Spark is the only available rail. The route selection and a focused Kotlin probe confirmed the quote and validation behavior.

if (maxSendLightning == 0uL) {
_sendUiState.update { it.copy(estimatedRoutingFee = 0uL) }
return
Expand Down Expand Up @@ -9538,6 +9580,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.
Expand Down
29 changes: 29 additions & 0 deletions app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading