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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 49 additions & 6 deletions app/src/main/java/to/bitkit/repositories/LightningRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
Expand All @@ -36,6 +37,7 @@ import kotlinx.coroutines.flow.update
import kotlinx.coroutines.flow.updateAndGet
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.selects.select
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
Expand Down Expand Up @@ -196,6 +198,9 @@ class LightningRepo @Inject constructor(
private val syncPending = AtomicBoolean(false)
private val syncRetryJob = AtomicReference<Job?>(null)
private val ordinaryFollowupRetryJob = AtomicReference<Job?>(null)

// The prepared send held while its higher mining fee is reviewed, released before its node stops.
private val reviewedPreparedSend = AtomicReference<PreparedOnchainSend?>(null)
private val pendingStopJob = AtomicReference<Job?>(null)
private val pendingStopLock = Any()
private val lifecycleMutex = Mutex()
Expand Down Expand Up @@ -332,6 +337,8 @@ class LightningRepo @Inject constructor(
if (it is CancellationException) throw it
if (it is PaymentAbortedBeforeSend) {
Logger.debug("Aborted '$operationName' before dispatch", context = TAG)
} else if (it.cause is OnchainSendReviewEndedError) {
Logger.info("Ended '$operationName' unsent at its fee review", context = TAG)
} else {
Logger.error("Error executing '$operationName'", it, context = TAG)
}
Expand Down Expand Up @@ -765,6 +772,9 @@ class LightningRepo @Inject constructor(

return runCatching {
withContext(NonCancellable) {
// Its native handle cancels the unsent transaction through the wallet of the node about to stop,
// so it is dropped before the state change that ends its review.
reviewedPreparedSend.getAndSet(null)?.release()
_lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Stopping) }
lightningService.stop()
clearProbeOutcomes()
Expand Down Expand Up @@ -1925,6 +1935,7 @@ class LightningRepo @Inject constructor(
paymentDeadlineAt: Instant? = null,
contactPublicKey: String? = null,
approvedMiningFeeSats: ULong? = null,
reviewHigherFee: (suspend (OnchainPreparedReceipt) -> Unit)? = null,
): Result<OnchainSendOutcome> = executeWhenNodeRunning("sendOnChain") {
requireWalletRestoreComplete()
require(address.isNotEmpty()) { "Send address cannot be empty" }
Expand Down Expand Up @@ -2002,12 +2013,7 @@ class LightningRepo @Inject constructor(
.also { prepared ->
checkPreparedSpend(prepared.receipt, sats, isDrain, isTransfer, utxosForSend)
if (approvedMiningFeeSats != null) {
val miningFee = prepared.receipt.miningFeeSats
if (prepared.receipt.amountSats != sats || miningFee == null ||
miningFee > approvedMiningFeeSats
) {
throw OnchainSendChangedError(miningFee)
}
checkApprovedSpend(prepared, sats, satsPerVByte, approvedMiningFeeSats, reviewHigherFee)
}
onchainSendAttemptStore.retainPreparedReceipt(
attempt.attemptId,
Expand Down Expand Up @@ -2124,6 +2130,43 @@ class LightningRepo @Inject constructor(
spendableSats.safe() - fee.safe()
}.getOrNull()

private suspend fun checkApprovedSpend(
prepared: PreparedOnchainSend,
sats: ULong,
satsPerVByte: ULong,
approvedMiningFeeSats: ULong,
reviewHigherFee: (suspend (OnchainPreparedReceipt) -> Unit)?,
) {
val receipt = prepared.receipt.copy(feeRateSatsPerVByte = satsPerVByte)
val miningFee = receipt.miningFeeSats
if (receipt.amountSats != sats || miningFee == null) throw OnchainSendChangedError(miningFee)
if (miningFee <= approvedMiningFeeSats) return
reviewHigherFee ?: throw OnchainSendChangedError(miningFee)
reviewedPreparedSend.set(prepared)
var isKept = false
try {
// Returns once this exact prepared send is approved again, throws to send nothing. A node that stops
// meanwhile can no longer submit it, so the review ends there.
val isApproved = coroutineScope {
val review = async { reviewHigherFee(receipt) }
val stop = async { _lightningState.first { !it.nodeLifecycleState.isRunning() } }
select {
review.onAwait { true }
stop.onAwait { false }
}.also {
review.cancel()
stop.cancel()
}
}
// Nothing of a send its node cannot submit is persisted.
if (!isApproved || !prepared.isUsable) throw OnchainSendReviewInterruptedError()
isKept = true
} finally {
Comment thread
jvsena42 marked this conversation as resolved.
Resolved
// An unapproved send frees its inputs and change now, not when its handle is collected.
if (reviewedPreparedSend.compareAndSet(prepared, null) && !isKept) prepared.release()
}
}

private fun checkPreparedSpend(
receipt: OnchainPreparedReceipt,
sats: ULong,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,13 @@ class OnchainSendNotDispatchedError(cause: Throwable) : AppError("On-chain send
class OnchainSendChangedError(val preparedFeeSats: ULong? = null) :
AppError("On-chain send changed after it was approved")

/** A prepared send that ended unsent at the review of its higher mining fee, which is an expected outcome. */
open class OnchainSendReviewEndedError(message: String) : AppError(message)

/** A prepared send whose node stopped or changed while its higher mining fee waited for approval. */
class OnchainSendReviewInterruptedError :
OnchainSendReviewEndedError("The node stopped before the on-chain send was approved")

class OnchainSendPendingError(cause: Throwable, val txid: String? = null) :
AppError("On-chain send outcome is unknown; do not send again", cause)

Expand Down
15 changes: 15 additions & 0 deletions app/src/main/java/to/bitkit/repositories/OnchainSendCoordinator.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,28 @@ internal class PreparedOnchainSendRefused(cause: Throwable) : AppError(cause)
/** One native prepared transaction; its direct submission is cached even if it fails. */
class PreparedOnchainSend(
val receipt: OnchainPreparedReceipt,
private val isCurrent: () -> Boolean = { true },
private val discard: () -> Unit = {},
private val submit: suspend (beforeDispatch: suspend () -> Unit) -> OnchainSendOutcome,
) {
private val mutex = Mutex()
private var result: Result<OnchainSendOutcome>? = null

@Volatile
private var isReleased = false

/** Whether the node and wallet that signed this transaction can still submit it. */
val isUsable: Boolean get() = !isReleased && isCurrent()

/** Drops the native transaction of a send that was never submitted, while its node can still cancel it. */
fun release() {
isReleased = true
discard()
}

suspend fun broadcast(beforeDispatch: suspend () -> Unit = {}): OnchainSendOutcome = withContext(NonCancellable) {
mutex.withLock {
if (isReleased) throw PreparedOnchainSendRefused(OnchainSendReviewInterruptedError())
val cached = result ?: runSuspendCatching { submit(beforeDispatch) }.also { result = it }
cached.getOrThrow()
}
Expand Down
6 changes: 5 additions & 1 deletion app/src/main/java/to/bitkit/services/LightningService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1035,7 +1035,11 @@ class LightningService internal constructor(
prepared.recipientAmountSats(),
miningFeeSats = prepared.miningFeeSats(),
)
PreparedOnchainSend(receipt) { beforeDispatch ->
PreparedOnchainSend(
receipt,
isCurrent = { currentWalletIndex == walletIndex && node === originalNode },
discard = prepared::destroy,
) { beforeDispatch ->
callOnchainSend {
// Dispatch only through the handle that signed the original receipt.
if (currentWalletIndex != walletIndex || node !== originalNode) throw ServiceError.NodeNotSetup()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,11 @@ fun SendConfirmScreen(
if (uiState.initialSubscriptionPaymentNeedsConfirmation) isLoading = false
}

// The prepared send costs more than the fee approved, so the swipe is offered again on its actual fee
LaunchedEffect(uiState.isPreparedFeeReview) {
if (uiState.isPreparedFeeReview) isLoading = false
}

SendConfirmContent(
uiState = uiState,
isNodeRunning = isNodeRunning,
Expand Down
21 changes: 16 additions & 5 deletions app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,11 @@ fun SendSheet(
if (!reviewing) return@LaunchedEffect
lifecycle.withPaymentReview(appViewModel::beginPaymentReview)
}
// The entry is null until navigation settles, also after the activity is recreated
val hasEntry = entry != null
LaunchedEffect(hasEntry, reviewing, appViewModel) {
if (hasEntry) appViewModel.onSendReviewVisible(reviewing)
}
fun showHardwareSuccess(txId: String, amountSats: ULong, walletId: String, isShopPayment: Boolean) {
appViewModel.onSendSuccess(
details = NewTransactionSheetDetails(
Expand Down Expand Up @@ -529,6 +534,8 @@ fun SendSheet(
initialSubscriptionId?.let(appViewModel::subscription)
}

// Leaving the review of a prepared fee cancels that send instead of editing it
BackHandler(enabled = uiState.isPreparedFeeReview) { appViewModel.hideSheet() }
SendConfirmScreen(
savedStateHandle = it.savedStateHandle,
uiState = uiState,
Expand All @@ -541,13 +548,17 @@ fun SendSheet(
syncNodeVariant = syncNodeVariant,
canGoBack = navController.previousBackStackEntry != null,
onBack = {
val didPopToAmount = navController.popBackStack(SendRoute.Amount, inclusive = false)
if (!didPopToAmount && !navController.popBackStack()) {
appViewModel.hideSheet()
}
val didPop = !uiState.isPreparedFeeReview && (
navController.popBackStack(SendRoute.Amount, inclusive = false) ||
navController.popBackStack()
)
if (!didPop) appViewModel.hideSheet()
},
onEvent = { e -> appViewModel.setSendEvent(e) },
onClickAddTag = { navController.navigateTo(SendRoute.AddTag) },
onClickAddTag = {
// The prepared send under review already saved its tags
if (!uiState.isPreparedFeeReview) navController.navigateTo(SendRoute.AddTag)
},
onClickTag = { tag -> appViewModel.removeTag(tag) },
onNavigateToPin = { navController.navigateTo(SendRoute.PinCheck) },
autoPayContent = initialSubscription?.let { subscription ->
Expand Down
Loading
Loading