diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 06aa0c4587..31f441cac9 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -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 @@ -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 @@ -196,6 +198,9 @@ class LightningRepo @Inject constructor( private val syncPending = AtomicBoolean(false) private val syncRetryJob = AtomicReference(null) private val ordinaryFollowupRetryJob = AtomicReference(null) + + // The prepared send held while its higher mining fee is reviewed, released before its node stops. + private val reviewedPreparedSend = AtomicReference(null) private val pendingStopJob = AtomicReference(null) private val pendingStopLock = Any() private val lifecycleMutex = Mutex() @@ -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) } @@ -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() @@ -1925,6 +1935,7 @@ class LightningRepo @Inject constructor( paymentDeadlineAt: Instant? = null, contactPublicKey: String? = null, approvedMiningFeeSats: ULong? = null, + reviewHigherFee: (suspend (OnchainPreparedReceipt) -> Unit)? = null, ): Result = executeWhenNodeRunning("sendOnChain") { requireWalletRestoreComplete() require(address.isNotEmpty()) { "Send address cannot be empty" } @@ -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, @@ -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 { + // 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, diff --git a/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt b/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt index 8f1c55b0ac..d802159c8c 100644 --- a/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt +++ b/app/src/main/java/to/bitkit/repositories/OnchainSendAttemptStore.kt @@ -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) diff --git a/app/src/main/java/to/bitkit/repositories/OnchainSendCoordinator.kt b/app/src/main/java/to/bitkit/repositories/OnchainSendCoordinator.kt index f8a34de714..2d082b3474 100644 --- a/app/src/main/java/to/bitkit/repositories/OnchainSendCoordinator.kt +++ b/app/src/main/java/to/bitkit/repositories/OnchainSendCoordinator.kt @@ -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? = 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() } diff --git a/app/src/main/java/to/bitkit/services/LightningService.kt b/app/src/main/java/to/bitkit/services/LightningService.kt index 2021ad314a..c867c42243 100644 --- a/app/src/main/java/to/bitkit/services/LightningService.kt +++ b/app/src/main/java/to/bitkit/services/LightningService.kt @@ -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() diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt index a3d45a4bf9..185ca32729 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt @@ -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, 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 3dddda875e..a89ae3e49f 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -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( @@ -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, @@ -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 -> diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index a646786060..4ef6952265 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -46,10 +46,12 @@ import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.persistentMapOf import kotlinx.collections.immutable.toImmutableList import kotlinx.collections.immutable.toImmutableMap +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable @@ -137,6 +139,7 @@ import to.bitkit.ext.totalValue import to.bitkit.ext.walletId import to.bitkit.ext.watchUntil import to.bitkit.flags.PaykitFeatureFlags +import to.bitkit.models.BITCOIN_SYMBOL import to.bitkit.models.FeeRate import to.bitkit.models.HwFundingSignedTx import to.bitkit.models.HwWallet @@ -193,6 +196,8 @@ import to.bitkit.repositories.OnchainSendBlockedError import to.bitkit.repositories.OnchainSendNotDispatchedError import to.bitkit.repositories.OnchainSendOutcome import to.bitkit.repositories.OnchainSendPendingError +import to.bitkit.repositories.OnchainSendReviewEndedError +import to.bitkit.repositories.OnchainSendReviewInterruptedError import to.bitkit.repositories.PaykitAllowanceEntry import to.bitkit.repositories.PaykitAllowanceError import to.bitkit.repositories.PaykitAllowanceEvent @@ -432,6 +437,7 @@ class AppViewModel @Inject constructor( fun setSendEvent(event: SendEvent) { if ((currentSheet.value as? Sheet.Send)?.preparingRequest != null) return + if (preparedFeeReview != null && event.changesReviewedSend()) return when (event) { SendEvent.AmountContinue -> { if (amountContinuePending) return @@ -609,6 +615,13 @@ class AppViewModel @Inject constructor( // The confirmed send that holds the submission guard; dismissing that send releases the guard for the next one. private var confirmedPaymentSubmission: Any? = null + + // The prepared send whose mining fee is above the reviewed one, held until it is approved again or cancelled. + @Volatile + private var preparedFeeReview: PreparedFeeReview? = null + + @Volatile + private var isSendReviewVisible = true private val activePaymentSubmissions = mutableSetOf() private var paykitPaymentRequestPollingJob: Job? = null private var paykitSessionRestoreRetryJob: Job? = null @@ -672,6 +685,8 @@ class AppViewModel @Inject constructor( .stateIn(viewModelScope, SharingStarted.Lazily, Env.PIN_ATTEMPTS) fun addTagToSelected(newTag: String) { + // A prepared send saved its tags with its attempt, before the fee review. + if (preparedFeeReview != null) return _sendUiState.update { it.copy( selectedTags = (it.selectedTags + newTag).distinct().toImmutableList() @@ -683,6 +698,7 @@ class AppViewModel @Inject constructor( } fun removeTag(tag: String) { + if (preparedFeeReview != null) return _sendUiState.update { it.copy( selectedTags = it.selectedTags.filterNot { tagItem -> tagItem == tag }.toImmutableList() @@ -6673,12 +6689,15 @@ class AppViewModel @Inject constructor( Logger.debug("Swipe to pay event, checking send confirmation conditions", context = TAG) if (!_sendUiState.value.isAmountInputValid || !_sendUiState.value.isHardwareFeeReady) return viewModelScope.launch { - if (!prepareCoinSelection()) return@launch + val review = preparedFeeReview + if (review == null && !prepareCoinSelection()) return@launch val amount = _sendUiState.value.amount - handleSanityChecks(amount) + handleSanityChecks(amount, preparedFeeSats = review?.feeSats) if (_sendUiState.value.showSanityWarningDialog != null) return@launch // await for dialog UI interaction + if (preparedFeeReview !== review) return@launch + review?.isSwiped = true _sendUiState.update { it.copy(shouldConfirmPay = true) } } } @@ -6721,7 +6740,7 @@ class AppViewModel @Inject constructor( handlePaymentPreparationFailure(PaykitPaymentRequestError.RequestUnavailable, contactPaymentContext) } - private suspend fun handleSanityChecks(amountSats: ULong) { + private suspend fun handleSanityChecks(amountSats: ULong, preparedFeeSats: ULong? = null) { if (_sendUiState.value.showSanityWarningDialog != null) return val settings = settingsStore.data.first() @@ -6763,17 +6782,21 @@ class AppViewModel @Inject constructor( if (_sendUiState.value.payMethod != SendMethod.ONCHAIN && leg == null) return - val totalFee = if (leg != null) { + val totalFee = if (preparedFeeSats != null) { + preparedFeeSats + } else if (leg != null) { leg.debitSat.safe() - leg.deliveredSat.safe() } else if (_sendUiState.value.hardwareWalletId != null) { _sendUiState.value.onchainFeeUi.sats?.toULong() ?: return } else { - lightningRepo.calculateTotalFee( - amountSats = amountSats, - address = _sendUiState.value.address, - speed = _sendUiState.value.speed, - utxosToSpend = _sendUiState.value.selectedUtxos, - ).getOrNull() ?: return + // A max send shows its drain's fee, which is the one it is approved at. + _sendUiState.value.onchainFeeUi.sats?.toULong()?.takeIf { _sendUiState.value.isMaxAmount } + ?: lightningRepo.calculateTotalFee( + amountSats = amountSats, + address = _sendUiState.value.address, + speed = _sendUiState.value.speed, + utxosToSpend = _sendUiState.value.selectedUtxos, + ).getOrNull() ?: return } if ( @@ -6805,6 +6828,8 @@ class AppViewModel @Inject constructor( } private suspend fun proceedWithPayment(contactPaymentContext: ContactPaymentContext?) { + val reviewedOnchainFeeSats = _sendUiState.value.onchainFeeUi.sats?.toULong() ?: 0uL + val session = sendSession delay(SCREEN_TRANSITION_DELAY) // wait for screen transitions when applicable if (showCommittedSwap()) return @@ -6941,6 +6966,8 @@ class AppViewModel @Inject constructor( contactPaymentContext, amount, allowanceAttemptId, + reviewedOnchainFeeSats, + session, ) SendMethod.LIGHTNING -> proceedWithLightningPayment( @@ -6986,6 +7013,8 @@ class AppViewModel @Inject constructor( contactPaymentContext: ContactPaymentContext?, amount: ULong, allowanceAttemptId: String?, + reviewedFeeSats: ULong, + session: Long, ) { val originalPayer = preparedPaymentProofRequest?.let { paykitPaymentProofRepo.captureOriginalOnchainPayer(it).getOrElse { error -> @@ -7026,6 +7055,18 @@ class AppViewModel @Inject constructor( incomingPaymentRequest?.let { paykitPaymentRequestRepo.ensurePaymentAllowed(it).getOrThrow() } sendAttempted = true }, + approvedMiningFeeSats = reviewedFeeSats, + reviewHigherFee = { receipt -> + reviewPreparedFee(receipt, session) + // The request and its payer are checked again, since the renewed approval can come much later. + if (preparedPaymentProofRequest != null) { + paykitPaymentProofRepo.verifyOriginalOnchainPayer( + preparedPaymentProofRequest, + requireNotNull(originalPayer), + ).getOrThrow() + } + incomingPaymentRequest?.let { paykitPaymentRequestRepo.ensurePaymentAllowed(it).getOrThrow() } + }, ).onSuccess { outcome -> proofRequest = null when (outcome) { @@ -7086,6 +7127,7 @@ class AppViewModel @Inject constructor( preparedPaymentProofRequest = proofRequest, contactPaymentContext = contactPaymentContext, allowanceAttemptId = allowanceAttemptId, + session = session, ) } } @@ -7103,6 +7145,7 @@ class AppViewModel @Inject constructor( incomingPaymentRequest: PaykitPaymentRequest?, preparedPaymentProofRequest: PaykitPaymentRequest?, contactPaymentContext: ContactPaymentContext?, + session: Long, allowanceAttemptId: String? = null, ) { val amount = _sendUiState.value.amount @@ -7195,6 +7238,25 @@ class AppViewModel @Inject constructor( releasePrivatePaymentListIfNeeded(contactPaymentContext) cancelPaymentProofPreparation(preparedPaymentProofRequest) if (error is OnchainSendNotDispatchedError) paykitPaymentProofRepo.reconcile() + showOnchainPaymentFailure(error, contactPaymentContext, session) + } + + private fun showOnchainPaymentFailure( + error: Throwable, + contactPaymentContext: ContactPaymentContext?, + session: Long, + ) { + val cancelled = error.cause as? PreparedFeeReviewCancelledError + val isInterrupted = error.cause is OnchainSendReviewInterruptedError + if (cancelled != null || isInterrupted) { + Logger.info("Cancelled on-chain send at its prepared fee review", context = TAG) + if (cancelled?.isNotified == false) return + toastFeeChangedNotSent() + // The cleanup before this can outlast the send, so only the sheet of that same send is closed. + val isSameSend = session == sendSession && currentSheet.value is Sheet.Send + if (isSameSend && (cancelled?.closesSend == true || isInterrupted)) hideSheet() + return + } Logger.error("Error sending onchain payment", error, context = TAG) if (contactPaymentContext?.isInitialSubscriptionPayment == true) { setSendEffect(SendEffect.NavigateToError(error.toSendFailureDetails(context, _sendUiState.value.address))) @@ -7208,6 +7270,98 @@ class AppViewModel @Inject constructor( } } + /** + * Shows the prepared send on the confirmation and returns once it is approved again, by the swipe and the PIN or + * biometrics the first approval used. Throws when the send is cancelled, no longer the one on screen, or not + * approved within [PREPARED_FEE_REVIEW_TIMEOUT]. The held transaction keeps the fee rate it was prepared at. + */ + private suspend fun reviewPreparedFee(receipt: OnchainPreparedReceipt, session: Long) = + withContext(Dispatchers.Main.immediate) { + val feeSats = requireNotNull(receipt.miningFeeSats) + check(feeSats <= Long.MAX_VALUE.toULong()) + val reviewedFeeSats = _sendUiState.value.onchainFeeUi.sats?.toULong() ?: 0uL + val increase = formatMoneyValue(feeSats.safe() - reviewedFeeSats.safe()) + // The send was authorized, so leaving its confirmation before the review must not drop it silently. + if (session != sendSession || currentSheet.value !is Sheet.Send || !isSendReviewVisible || + receipt.address != _sendUiState.value.address + ) { + throw PreparedFeeReviewCancelledError(isNotified = true) + } + val review = PreparedFeeReview(feeSats) + preparedFeeReview = review + Logger.info("Asking to approve prepared fee '$feeSats' above reviewed '$reviewedFeeSats'", context = TAG) + _sendUiState.update { + it.copy( + amount = receipt.amountSats, + onchainFeeUi = it.onchainFeeUi.copy(sats = feeSats.toLong(), isLoading = false), + confirmedWarnings = it.confirmedWarnings + .filterNot { warning -> + warning == SanityWarning.FEE_OVER_HALF_VALUE || warning == SanityWarning.FEE_OVER_10_USD + } + .toImmutableList(), + showSanityWarningDialog = null, + shouldConfirmPay = false, + isPreparedFeeReview = true, + ) + } + toast( + type = Toast.ToastType.INFO, + title = context.getString(R.string.lightning__spending_confirm__fees_changed_title), + description = context.getString(R.string.lightning__spending_confirm__fees_changed_network) + .replace("{amount}", "$BITCOIN_SYMBOL $increase"), + ) + try { + val isApproved = withTimeoutOrNull(PREPARED_FEE_REVIEW_TIMEOUT) { + val dismissal = launch { + currentSheet.first { it !is Sheet.Send } + review.answer.complete(false) + } + review.answer.await().also { dismissal.cancel() } + } + val current = _sendUiState.value + val isSameSend = session == sendSession && current.amount == receipt.amountSats && + current.address == receipt.address && current.onchainFeeUi.sats == feeSats.toLong() + when { + isApproved == false -> throw PreparedFeeReviewCancelledError(isNotified = review.isRouteLost) + isApproved == null || !isSameSend -> { + throw PreparedFeeReviewCancelledError(isNotified = true, closesSend = session == sendSession) + } + } + } finally { + if (preparedFeeReview === review) { + preparedFeeReview = null + _sendUiState.update { it.copy(isPreparedFeeReview = false) } + } + } + } + + /** Whether the send sheet shows the confirmation or its PIN check, the only screens a fee review can use. */ + fun onSendReviewVisible(isVisible: Boolean) { + isSendReviewVisible = isVisible + if (isVisible) return + preparedFeeReview?.isRouteLost = true + cancelPreparedFeeReview() + } + + private fun toastFeeChangedNotSent() { + viewModelScope.launch(start = CoroutineStart.UNDISPATCHED) { + // A review can end while the app is in the background, where its toast would expire unseen. + if (isPaymentRequestPollingStopped.value) { + isPaymentRequestPollingStopped.first { !it } + _isAuthenticated.first { it } + } + toast( + type = Toast.ToastType.WARNING, + title = context.getString(R.string.lightning__spending_confirm__fees_changed_title), + description = context.getString(R.string.wallet__send_fee_changed_not_sent), + ) + } + } + + private fun cancelPreparedFeeReview() { + preparedFeeReview?.answer?.complete(false) + } + suspend fun retryOriginalOnchainSend( original: OnchainSendAttempt, feeRateSatsPerVByte: ULong, @@ -8197,6 +8351,8 @@ class AppViewModel @Inject constructor( paymentDeadlineAt: Instant? = null, beforeSendAttempt: suspend () -> Unit = {}, onBroadcast: suspend (Txid) -> Unit = {}, + approvedMiningFeeSats: ULong? = null, + reviewHigherFee: (suspend (OnchainPreparedReceipt) -> Unit)? = null, ): Result = lightningRepo.sendOnChain( address = address, sats = amount, @@ -8212,6 +8368,8 @@ class AppViewModel @Inject constructor( paymentDeadlineAt = paymentDeadlineAt, beforeSendAttempt = beforeSendAttempt, onBroadcast = onBroadcast, + approvedMiningFeeSats = approvedMiningFeeSats, + reviewHigherFee = reviewHigherFee, ) private suspend fun sendLightning( @@ -8524,7 +8682,11 @@ class AppViewModel @Inject constructor( private fun updateOnchainFeeUi(transform: (OnchainFeeUi) -> OnchainFeeUi) { _sendUiState.update { - if (it.isRetainedHardwarePayment) it else it.copy(onchainFeeUi = transform(it.onchainFeeUi)) + if (it.isRetainedHardwarePayment || it.isPreparedFeeReview) { + it + } else { + it.copy(onchainFeeUi = transform(it.onchainFeeUi)) + } } } @@ -8596,6 +8758,15 @@ class AppViewModel @Inject constructor( satsPerVByte = satsPerVByte.toULong(), ).also { requireCurrentPaymentPreparation(walletGeneration) }.getOrNull()?.toLong() ?: 0 } + // A max send is prepared as a drain, whose fee can be above the one of a fixed send of the same amount. + val drainFee = if (currentState.isMaxAmount && currentState.payMethod == SendMethod.ONCHAIN) { + lightningRepo.estimateSendAllFee(currentState.address, speed ?: currentState.speed, currentState.feeRates) + .also { requireCurrentPaymentPreparation(walletGeneration) } + .getOrNull() + } else { + null + } + if (drainFee != null) return drainFee.toLong() return lightningRepo.calculateTotalFee( amountSats = currentState.amount, address = currentState.address, @@ -8627,6 +8798,7 @@ class AppViewModel @Inject constructor( if (!canPrepareSend(walletGeneration)) return false sendStateGeneration++ sendSession++ + cancelPreparedFeeReview() addressValidationJob?.cancel() paykitReviewedAmount = null paykitAmountConversion = PaykitAmountConversion() @@ -8899,6 +9071,7 @@ class AppViewModel @Inject constructor( sendStateGeneration++ // A closed send is over: a swap failing for it later gives no contact back to whatever comes next. sendSession++ + cancelPreparedFeeReview() // A payment still running for the dismissed send, like a slow swap commit, must not block the next. if (confirmedPaymentSubmission != null) releaseConfirmedPaymentSubmission() cancelHardwarePaymentRequestIfNeeded() @@ -9111,6 +9284,12 @@ class AppViewModel @Inject constructor( private fun onConfirmPay() { Logger.debug("Payment checks confirmed, proceeding…", context = TAG) + preparedFeeReview?.let { review -> + _sendUiState.update { it.copy(shouldConfirmPay = false) } + // Only the confirmation of a swipe made on the prepared fee approves it. + if (review.isSwiped) review.answer.complete(true) + return + } if (isSubmittingPaymentRequest || isSoftwarePaymentSubmissionActive) { _sendUiState.update { it.copy(shouldConfirmPay = false) } return @@ -10226,6 +10405,8 @@ data class SendUiState( val showSanityWarningDialog: SanityWarning? = null, val confirmedWarnings: ImmutableList = persistentListOf(), val shouldConfirmPay: Boolean = false, + /** The confirmation shows a prepared send's actual mining fee, above the one first reviewed, for approval. */ + val isPreparedFeeReview: Boolean = false, val selectedUtxos: ImmutableList? = null, val lnurl: LnurlParams? = null, val isLoading: Boolean = false, @@ -10494,6 +10675,37 @@ sealed interface SendEvent { data object Contacts : SendEvent } +private fun SendEvent.changesReviewedSend(): Boolean = when (this) { + SendEvent.SpeedAndFee, SendEvent.BackToAmount, SendEvent.NavToAddress, SendEvent.PaymentMethodSwitch, + is SendEvent.PaymentMethodSelect -> true + + else -> false +} + +private class PreparedFeeReview(val feeSats: ULong) { + val answer = CompletableDeferred() + + @Volatile + var isSwiped = false + + @Volatile + var isRouteLost = false +} + +/** + * [isNotified] when the user did not cancel the review themselves, so they are told the payment was not sent. + * [closesSend] when that send is still the one on screen. + */ +private class PreparedFeeReviewCancelledError(val isNotified: Boolean = false, val closesSend: Boolean = false) : + OnchainSendReviewEndedError("On-chain send was cancelled at its prepared fee review") + +/** + * How long a prepared send waits for its higher fee to be approved. Its attempt blocks other on-chain sends, wallet + * backup and Paykit sync meanwhile, and it keeps the fee rate it was prepared at, so the wait is kept to what + * reading the fee, answering a warning and entering a PIN take. + */ +private val PREPARED_FEE_REVIEW_TIMEOUT = 2.minutes + private data class SwapRoutedPayment( val payment: PubkySwapRoutePayment, val holdPaymentHash: String, diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index b15701949a..4f4961f82c 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1103,6 +1103,7 @@ الدعم فشلت المعاملة السرعة والرسوم + رسوم الشبكة أعلى من الرسوم التي أكدتها، لذلك لم يتم إرسال الدفعة. يرجى المحاولة مرة أخرى. تعيين رسوم مخصصة الرسوم غير صالحة تعذر زيادة الرسوم أكثر. وإلا ستتجاوز نصف رصيد الإدخال الحالي. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index b55b5e2ea4..036689fdc6 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1134,6 +1134,7 @@ Contactar a soporte Transacción ha fallado Velocidad y tarifa + La comisión de red es más alta que la que confirmó, por lo que el pago no se envió. Por favor, inténtelo de nuevo. Fijar tarifa personalizada Tarifa inválida No es posible aumentar más la comisión. De lo contrario, superaría la mitad del saldo de entrada actual. diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 0d2f1094f2..1969719f21 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1128,6 +1128,7 @@ Contacta amb el suport Transacció fallida Velocitat i comissió + La comissió de xarxa és més alta que la que has confirmat, així que el pagament no s\'ha enviat. Si us plau, torna-ho a provar. Estableix una tarifa personalitzada Comissió no vàlida No es pot augmentar més la tarifa. Altrament, superarà la meitat del saldo d\'entrada actual. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index ccbb0d48d0..2d9d49e79d 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1132,6 +1132,7 @@ Kontaktovat podporu Transakce selhala Rychlost a poplatek + Síťový poplatek je vyšší než ten, který jste potvrdili, takže platba nebyla odeslána. Zkuste to prosím znovu. Nastavit vlastní poplatek Neplatný poplatek Poplatek nelze dále zvýšit. Jinak by přesáhl polovinu aktuálního vstupního zůstatku. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index c20520eb71..769d103e1e 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1029,6 +1029,7 @@ Gebühr unterschreitet das Mindestlimit Erhöhe die benutzerdefinierte Gebühr und versuche es erneut. Gebühr kann nicht weiter reduziert werden. + Die Netzwerkgebühr ist höher als die von dir bestätigte, daher wurde die Zahlung nicht gesendet. Bitte versuche es erneut. Benutzerdefinierte Gebühr festlegen ₿ {feeSats} für diese Transaktion ₿ {feeSats} für diese Transaktion ({fiatSymbol}{fiatFormatted}) diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 38ce4f74cb..280d225d59 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1108,6 +1108,7 @@ Επικοινωνία με Υποστήριξη Αποτυχία συναλλαγής Ταχύτητα και τέλος + Το τέλος δικτύου είναι υψηλότερο από αυτό που επιβεβαίωσες, οπότε η πληρωμή δεν στάλθηκε. Δοκίμασε ξανά. Ορισμός προσαρμοσμένου τέλους Μη έγκυρο τέλος Δεν είναι δυνατή η περαιτέρω αύξηση του τέλους. Διαφορετικά θα υπερβεί το μισό του τρέχοντος υπολοίπου εισόδου. diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index d12d501a56..9906dff08c 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1129,6 +1129,7 @@ Contactar con el servicio de asistencia Transacción ha fallado Velocidad y tarifa + La comisión de red es más alta que la que confirmaste, por lo que el pago no se envió. Por favor, inténtalo de nuevo. Fijar tarifa personalizada Comisión inválida No se puede aumentar más la comisión. De lo contrario, excederá la mitad del saldo de entrada actual. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 7bf2841ec3..a10b8fb1e0 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1021,6 +1021,7 @@ Aumenta la comisión personalizada e inténtalo de nuevo. La Comisión Excede el Límite Máximo Reduce la comisión personalizada e inténtalo de nuevo. + La comisión de red es más alta que la que confirmó, por lo que el pago no se envió. Por favor, inténtelo de nuevo. Fijar tarifa personalizada ₿ {feeSats} para esta transacción ₿ {feeSats} para esta transacción ({fiatSymbol}{fiatFormatted}) diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 8e2a6b947f..ff086f8d6e 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1026,6 +1026,7 @@ Augmentez les frais et réessayez. Impossible de réduire davantage le montant des frais de réseaux Impossible d\'augmenter davantage les frais. Sinon, cela dépasserait la moitié du solde d\'entrée actuel. + Les frais de réseau sont plus élevés que ceux que vous avez confirmés, le paiement n\'a donc pas été envoyé. Veuillez réessayer. Fixer des frais personnalisés ₿ {feeSats} pour cette transaction ₿ {feeSats} pour cette transaction ({fiatSymbol}{fiatFormatted} ) diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 0702497a37..92b86015f2 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1130,6 +1130,7 @@ Contatta l\'Assistenza Transazione Fallita Velocità e commissioni + La commissione di rete è più alta di quella che hai confermato, quindi il pagamento non è stato inviato. Per favore riprova. Imposta commissione personalizzata Commissione non valida Impossibile aumentare ulteriormente la commissione. Altrimenti supererebbe meta\' del saldo corrente. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 61cbdea222..e58f279205 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1125,6 +1125,7 @@ Contact Opnemen Transactie mislukt Snelheid en vergoeding + De netwerkvergoeding is hoger dan de vergoeding die je hebt bevestigd, dus de betaling is niet verzonden. Probeer het opnieuw. Aangepaste vergoeding instellen Vergoeding ongeldig Kan de vergoeding niet verder verhogen. Anders overschrijdt het de helft van het huidige invoersaldo. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index db4c3150cc..a15183132d 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1028,6 +1028,7 @@ Zwiększ opłatę niestandardową i spróbuj ponownie. Nie ma możliwości dalszego obniżenia opłaty transakcyjnej. Nie można dalej zwiększyć opłaty. W przeciwnym razie przekroczy połowę obecnego salda wejściowego. + Opłata sieciowa jest wyższa niż potwierdzona, dlatego płatność nie została wysłana. Spróbuj ponownie. Ustaw opłatę niestandardową ₿ {feeSats} dla tej transakcji ₿ {feeSats} dla tej transakcji ({fiatSymbol}{fiatFormatted} ) diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 8ec81691da..2d9c7afe25 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1134,6 +1134,7 @@ Suporte Falha na Transação Taxa e velocidade + A taxa de rede é maior do que a que você confirmou, então o pagamento não foi enviado. Por favor, tente novamente. Definir Taxa Personalizada Taxa Inválida Não é possível aumentar mais a taxa. Caso contrário, excederá metade do saldo de entrada atual. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index fb66951439..e8701c7b86 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -888,6 +888,7 @@ Taxa abaixo do limite mínimo Aumente a taxa personalizada e tente novamente. Não é possível reduzir ainda mais a taxa. + A taxa de rede é superior à que confirmou, pelo que o pagamento não foi enviado. Por favor, tente novamente. Definir Taxa Personalizada ₿ {feeSats} para esta transação ₿ {feeSats} para esta transação ({fiatSymbol}{fiatFormatted} ) diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index e061c8cc57..7965ffb807 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1149,6 +1149,7 @@ Связаться с Поддержкой Транзакция не удалась Скорость и комиссия + Комиссия сети выше подтверждённой вами, поэтому платёж не был отправлен. Пожалуйста, попробуйте снова. Установить Пользовательскую Комиссию Неверная комиссия Невозможно увеличить комиссию дальше. Иначе она превысит половину текущего входного баланса. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 53a9e11f1f..1cf91009b3 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1729,6 +1729,7 @@ Contact Support Transaction Failed Speed and fee + The network fee is higher than the one you confirmed, so the payment was not sent. Please try again. Set Custom Fee Fee Invalid Unable to increase the fee any further. Otherwise, it will exceed half the current input balance. diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 50ba7be684..c2f7adca99 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -3359,6 +3359,363 @@ class LightningRepoTest : BaseUnitTest() { } } + @Test + fun `a prepared fee above the approved one is not broadcast before it is approved again`() = test { + val txid = "ab".repeat(32) + val (repo, store) = feeReviewRepo() + var broadcasts = 0 + stubFeeReviewPreparation(txid, feeSats = 212uL) { broadcasts++ } + val approval = CompletableDeferred() + val reviewed = mutableListOf() + + val send = async { + repo.sendOnChain( + "address", + 1_000uL, + approvedMiningFeeSats = 203uL, + reviewHigherFee = { + reviewed += it + approval.await() + }, + ) + } + + assertEquals(0, broadcasts) + assertFalse(send.isCompleted) + assertEquals(listOf(212uL), reviewed.map { it.miningFeeSats }) + assertEquals(1_000uL, reviewed.single().amountSats) + // The attempt owner is held without a candidate, so no other send starts and nothing can be recovered. + val held = assertNotNull(store.current()) + assertTrue(held.candidateTxids.isEmpty() && !held.initialDispatchAttempted) + + approval.complete(Unit) + + assertEquals(OnchainSendOutcome.Accepted(txid), send.await().getOrThrow()) + assertEquals(1, broadcasts) + val sent = assertNotNull(store.current()) + assertEquals(listOf(txid), sent.candidateTxids) + assertEquals(mapOf(txid to 212uL), sent.candidateMiningFees) + assertEquals(OnchainSendEvidence.Accepted, sent.evidence) + verify(lightningService, times(1)) + .prepareOnchainSend(any(), any(), any(), anyOrNull(), any(), any(), anyOrNull()) + } + + @Test + fun `cancelling the review of a higher prepared fee sends nothing and releases the attempt`() = test { + val (repo, store) = feeReviewRepo() + var broadcasts = 0 + stubFeeReviewPreparation("ab".repeat(32), feeSats = 212uL) { broadcasts++ } + val cancelled = AppError("cancelled") + + val result = repo.sendOnChain( + "address", + 1_000uL, + approvedMiningFeeSats = 203uL, + reviewHigherFee = { throw cancelled }, + ) + + val error = assertIs(result.exceptionOrNull()) + assertEquals(cancelled, error.cause) + assertEquals(0, broadcasts) + assertNull(store.current()) + + // The released owner blocks no later send. + stubFeeReviewPreparation("cd".repeat(32), feeSats = 203uL) { broadcasts++ } + assertTrue(repo.sendOnChain("address", 1_000uL, approvedMiningFeeSats = 203uL).isSuccess) + assertEquals(1, broadcasts) + } + + @Test + fun `a request's higher prepared fee keeps its guard until the cancelled review's proof is removed`() = test { + val (repo, store) = feeReviewRepo() + val requestId = PaykitPaymentRequestId("request", "payer") + var broadcasts = 0 + stubFeeReviewPreparation("ab".repeat(32), feeSats = 212uL) { broadcasts++ } + val reviewed = mutableListOf() + + val result = repo.sendOnChain( + "address", + 1_000uL, + requestId = requestId, + payerIdentity = "payer-identity", + approvedMiningFeeSats = 203uL, + reviewHigherFee = { + reviewed += store.current() + throw AppError("cancelled") + }, + ) + + assertIs(result.exceptionOrNull()) + assertEquals(0, broadcasts) + assertTrue(reviewed.single()?.preparationPending == true) + // The request's guard outlives the cancelled review, so the same request is not admitted twice. + val guard = assertNotNull(store.current()) + assertEquals(requestId, guard.requestId) + assertTrue(guard.preparationPending && guard.candidateTxids.isEmpty() && !guard.initialDispatchAttempted) + assertIs( + repo.sendOnChain("address", 1_000uL, requestId = requestId, payerIdentity = "payer-identity") + .exceptionOrNull(), + ) + + // Removing its started proof, as the payment's failure cleanup does, releases the guard. + assertTrue(repo.releaseInterruptedShopPreparation { it.attemptId == guard.attemptId }) + assertNull(store.current()) + } + + @Test + fun `a request's higher prepared fee is sent once after renewed approval`() = test { + val txid = "ab".repeat(32) + val (repo, store) = feeReviewRepo() + val requestId = PaykitPaymentRequestId("request", "payer") + var broadcasts = 0 + stubFeeReviewPreparation(txid, feeSats = 212uL) { broadcasts++ } + + val result = repo.sendOnChain( + "address", + 1_000uL, + requestId = requestId, + payerIdentity = "payer-identity", + approvedMiningFeeSats = 203uL, + reviewHigherFee = { assertEquals(0, broadcasts) }, + ) + + assertEquals(OnchainSendOutcome.Accepted(txid), result.getOrThrow()) + assertEquals(1, broadcasts) + val sent = assertNotNull(store.current()) + assertEquals(requestId, sent.requestId) + assertEquals(mapOf(txid to 212uL), sent.candidateMiningFees) + assertFalse(sent.preparationPending) + } + + @Test + fun `a node stopping during the review of a higher prepared fee releases the send unsent`() = test { + val (repo, store) = feeReviewRepo() + var broadcasts = 0 + var releases = 0 + var reviewEnded = false + val prepared = feeReviewPrepared(discard = { releases++ }) { broadcasts++ } + whenever(lightningService.prepareOnchainSend(any(), any(), any(), anyOrNull(), any(), any(), anyOrNull())) + .thenReturn(prepared) + + val send = async { + repo.sendOnChain( + "address", + 1_000uL, + approvedMiningFeeSats = 203uL, + reviewHigherFee = { + try { + awaitCancellation() + } finally { + reviewEnded = true + } + }, + ) + } + assertFalse(send.isCompleted) + repo.stop() + + val error = assertIs(send.await().exceptionOrNull()) + assertIs(error.cause) + assertTrue(reviewEnded) + assertEquals(1, releases) + assertFalse(prepared.isUsable) + assertEquals(0, broadcasts) + assertNull(store.current()) + inOrder(lightningService) { + verify(lightningService).prepareOnchainSend(any(), any(), any(), anyOrNull(), any(), any(), anyOrNull()) + verify(lightningService).stop() + } + } + + @Test + fun `a review that ends without approval releases the prepared send at once`() = test { + val (repo, store) = feeReviewRepo() + var broadcasts = 0 + var releases = 0 + whenever(lightningService.prepareOnchainSend(any(), any(), any(), anyOrNull(), any(), any(), anyOrNull())) + .thenReturn(feeReviewPrepared(discard = { releases++ }) { broadcasts++ }) + + val result = repo.sendOnChain( + "address", + 1_000uL, + approvedMiningFeeSats = 203uL, + reviewHigherFee = { throw AppError("cancelled") }, + ) + + assertIs(result.exceptionOrNull()) + assertEquals(1, releases) + assertEquals(0, broadcasts) + assertNull(store.current()) + // The node stopping later finds nothing left to release. + repo.stop() + assertEquals(1, releases) + } + + @Test + fun `an approved review keeps the prepared send for its broadcast`() = test { + val (repo, _) = feeReviewRepo() + var releases = 0 + var releasesAtBroadcast = -1 + whenever(lightningService.prepareOnchainSend(any(), any(), any(), anyOrNull(), any(), any(), anyOrNull())) + .thenReturn(feeReviewPrepared(discard = { releases++ }) { releasesAtBroadcast = releases }) + + val result = repo.sendOnChain("address", 1_000uL, approvedMiningFeeSats = 203uL, reviewHigherFee = {}) + + assertTrue(result.isSuccess) + assertEquals(0, releasesAtBroadcast) + assertEquals(0, releases) + } + + @Test + fun `a request approved on a replaced node is refused before its candidate is saved`() = test { + val (repo, store) = feeReviewRepo() + val requestId = PaykitPaymentRequestId("request", "payer") + var broadcasts = 0 + var isCurrent = true + val prepared = feeReviewPrepared(isCurrent = { isCurrent }) { broadcasts++ } + whenever(lightningService.prepareOnchainSend(any(), any(), any(), anyOrNull(), any(), any(), anyOrNull())) + .thenReturn(prepared) + + val result = repo.sendOnChain( + "address", + 1_000uL, + requestId = requestId, + payerIdentity = "payer-identity", + approvedMiningFeeSats = 203uL, + reviewHigherFee = { isCurrent = false }, + ) + + // Never dispatched and never saved, so it is not reported as a pending payment. + val error = assertIs(result.exceptionOrNull()) + assertIs(error.cause) + assertEquals(0, broadcasts) + val guard = assertNotNull(store.current()) + assertTrue(guard.preparationPending && guard.candidateTxids.isEmpty() && guard.txid == null) + assertTrue(repo.releaseInterruptedShopPreparation { it.attemptId == guard.attemptId }) + assertNull(store.current()) + } + + private fun feeReviewPrepared( + isCurrent: () -> Boolean = { true }, + discard: () -> Unit = {}, + onBroadcast: () -> Unit, + ): PreparedOnchainSend { + val txid = "ab".repeat(32) + return PreparedOnchainSend( + OnchainPreparedReceipt( + txid = txid, + inputs = listOf(OnchainSendInput("11".repeat(32), 0u)), + address = "address", + amountSats = 1_000uL, + miningFeeSats = 212uL, + ), + isCurrent = isCurrent, + discard = discard, + ) { beforeDispatch -> + beforeDispatch() + onBroadcast() + OnchainSendOutcome.Accepted(txid) + } + } + + @Test + fun `a review that outlives the payment deadline sends nothing and releases the attempt`() = test { + val (repo, store) = feeReviewRepo() + val prepared = PreparedOnchainSend( + OnchainPreparedReceipt( + txid = "ab".repeat(32), + inputs = listOf(OnchainSendInput("11".repeat(32), 0u)), + address = "address", + amountSats = 1_000uL, + miningFeeSats = 212uL, + ), + ) { throw to.bitkit.utils.ServiceError.PaymentDeadlineExpired() } + whenever(lightningService.prepareOnchainSend(any(), any(), any(), anyOrNull(), any(), any(), anyOrNull())) + .thenReturn(prepared) + + val result = repo.sendOnChain("address", 1_000uL, approvedMiningFeeSats = 203uL, reviewHigherFee = {}) + + assertIs(result.exceptionOrNull()) + assertNull(store.current()) + } + + @Test + fun `an equal or lower prepared fee sends without another review`() = test { + for (feeSats in listOf(203uL, 190uL)) { + val txid = "ab".repeat(32) + val (repo, _) = feeReviewRepo() + var broadcasts = 0 + var reviews = 0 + stubFeeReviewPreparation(txid, feeSats) { broadcasts++ } + + val result = repo.sendOnChain( + "address", + 1_000uL, + approvedMiningFeeSats = 203uL, + reviewHigherFee = { reviews++ }, + ) + + assertEquals(OnchainSendOutcome.Accepted(txid), result.getOrThrow()) + assertEquals(1, broadcasts, "Fee $feeSats") + assertEquals(0, reviews, "Fee $feeSats") + } + } + + private suspend fun stubFeeReviewPreparation(txid: String, feeSats: ULong, onBroadcast: () -> Unit) { + val prepared = PreparedOnchainSend( + OnchainPreparedReceipt( + txid = txid, + inputs = listOf(OnchainSendInput("11".repeat(32), 0u)), + address = "address", + amountSats = 1_000uL, + miningFeeSats = feeSats, + ), + ) { beforeDispatch -> + beforeDispatch() + onBroadcast() + OnchainSendOutcome.Accepted(txid) + } + whenever(lightningService.prepareOnchainSend(any(), any(), any(), anyOrNull(), any(), any(), anyOrNull())) + .thenReturn(prepared) + } + + /** The repository over a real attempt store, so admission, retention, dispatch and release are the app's own. */ + private suspend fun feeReviewRepo(): Pair { + val key = Keychain.Key.ONCHAIN_SEND_ATTEMPT.name + var saved: String? = null + whenever(keychain.loadString(key, 0)).thenAnswer { saved } + whenever(keychain.upsertString(eq(key), any(), eq(0))).doSuspendableAnswer { saved = it.getArgument(1) } + whenever(keychain.delete(key, 0)).doSuspendableAnswer { + saved = null + Unit + } + val store = OnchainSendAttemptStore(testDispatcher, keychain, lightningService, kotlin.time.Clock.System) + sut = LightningRepo( + bgDispatcher = testDispatcher, + lightningService = lightningService, + settingsStore = settingsStore, + coreService = coreService, + keychain = keychain, + lnurlService = lnurlService, + cacheStore = cacheStore, + preActivityMetadataRepo = preActivityMetadataRepo, + onchainSendAttemptStore = store, + connectivityRepo = connectivityRepo, + vssBackupClientLdk = vssBackupClientLdk, + urlValidator = urlValidator, + electrumProbeService = electrumProbeService, + sparkRepo = sparkRepo, + ) + whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) + val activityService = mock() + whenever(coreService.activity).thenReturn(activityService) + whenever(preActivityMetadataRepo.addPreActivityMetadata(any())).thenReturn(Result.success(Unit)) + whenever(activityService.getOnchainActivityByTxId(any(), any())).thenReturn(mock()) + startNodeForTesting() + val repo = spy(sut).also { doReturn(Result.success(1uL)).whenever(it).getFeeRateForSpeed(any(), anyOrNull()) } + return repo to store + } + private fun preparedOutcome(outcome: OnchainSendOutcome, amountSats: ULong = 1_000uL) = PreparedOnchainSend( OnchainPreparedReceipt(outcome.txid, listOf(OnchainSendInput("11".repeat(32), 0u)), "address", amountSats), ) { diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 1966b6962a..eb8e3ae6dc 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -1383,6 +1383,7 @@ class SparkExitRepoTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) verify(sparkRepo, never()).setExiting(true, true) } @@ -1524,6 +1525,7 @@ class SparkExitRepoTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) } @@ -1551,6 +1553,7 @@ class SparkExitRepoTest : BaseUnitTest() { contactPublicKey = anyOrNull(), // Savings never pays more fee than the one confirmed. approvedMiningFeeSats = eq(300uL), + reviewHigherFee = anyOrNull(), ) } @@ -1574,6 +1577,7 @@ class SparkExitRepoTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = eq(600uL), + reviewHigherFee = anyOrNull(), ) } @@ -1596,6 +1600,7 @@ class SparkExitRepoTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) } @@ -1740,6 +1745,7 @@ class SparkExitRepoTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) assertEquals("again", assertNotNull(store.load()).fundingPaymentTxid) assertFalse(sut.state.value.isSavingsPaymentRefused) @@ -1826,6 +1832,7 @@ class SparkExitRepoTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) }.doSuspendableAnswer { answer() } whenever(lightning.completeAcceptedOrdinaryFollowup(any())).thenReturn(Unit) @@ -1999,6 +2006,7 @@ class SparkExitRepoTest : BaseUnitTest() { contactPublicKey = anyOrNull(), // The total shown less the extra funding. approvedMiningFeeSats = eq(400uL), + reviewHigherFee = anyOrNull(), ) } diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt index 8018f7367f..d0f3c6eb8d 100644 --- a/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt @@ -195,6 +195,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) } @@ -209,6 +210,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) }.thenReturn(Result.failure(OnchainSendNotDispatchedError(OnchainSendChangedError(preparedFeeSats = 700uL)))) val sut = createSut() @@ -225,6 +227,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = eq(500uL), + reviewHigherFee = anyOrNull(), ) assertEquals("Changed", toasts.single().title) assertTrue(toasts.single().description.orEmpty().startsWith("rose "), "${toasts.single().description}") @@ -240,6 +243,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = eq(700uL), + reviewHigherFee = anyOrNull(), ) } @@ -301,6 +305,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) }.thenReturn(Result.success(OnchainSendOutcome.Accepted("txid", 50_000uL))) whenever(sparkRepo.depositClaims).thenReturn(MutableStateFlow(mapOf("txid" to SparkDepositClaim.Later))) @@ -321,6 +326,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) verify(sparkRepo).onDepositBroadcast("txid", 50_000uL) verify(sparkRepo).followDepositClaim("txid", SparkClaimSpeed.Later, 1_350uL) @@ -374,6 +380,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) }.thenReturn(Result.success(OnchainSendOutcome.Accepted("TXID", 50_000uL))) val sut = createSut() @@ -418,6 +425,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) }.thenReturn(Result.success(OnchainSendOutcome.Unknown("txid"))) val retained = OnchainSendAttempt( @@ -451,6 +459,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) }.thenReturn(Result.success(OnchainSendOutcome.Unknown("txid"))) val retained = OnchainSendAttempt( @@ -498,6 +507,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) }.thenReturn(Result.failure(OnchainSendBlockedError(older))) whenever { lightningRepo.currentOnchainSendAttempt() }.thenReturn(older) @@ -526,6 +536,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) }.thenReturn(Result.success(OnchainSendOutcome.Unknown("txid"))) val retained = OnchainSendAttempt( @@ -566,6 +577,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) }.thenReturn(Result.failure(OnchainSendPendingError(IllegalStateException("timeout"), "txid"))) val retained = OnchainSendAttempt( @@ -598,6 +610,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) }.thenReturn(Result.success(OnchainSendOutcome.Unknown("txid"))) val retained = OnchainSendAttempt( @@ -633,6 +646,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) } @@ -645,6 +659,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) }.thenReturn(Result.success(OnchainSendOutcome.Unknown("txid"))) val retained = OnchainSendAttempt( @@ -678,6 +693,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) assertEquals(SideEffect.Sent, effects.lastOrNull()) } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 3b45e96c05..6fa328c438 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -174,12 +174,15 @@ import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LightningState import to.bitkit.repositories.MethodId import to.bitkit.repositories.NodeEventUpdate +import to.bitkit.repositories.OnchainPreparedReceipt import to.bitkit.repositories.OnchainSendAttempt import to.bitkit.repositories.OnchainSendAttemptUnreadableError import to.bitkit.repositories.OnchainSendBlockedError import to.bitkit.repositories.OnchainSendEvidence +import to.bitkit.repositories.OnchainSendInput import to.bitkit.repositories.OnchainSendNotDispatchedError import to.bitkit.repositories.OnchainSendOutcome +import to.bitkit.repositories.OnchainSendReviewInterruptedError import to.bitkit.repositories.PaykitAllowanceEvent import to.bitkit.repositories.PaykitAllowanceRepo import to.bitkit.repositories.PaykitBillingPeriod @@ -7882,7 +7885,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(lightningRepo, never()).sendOnChain( any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), any(), any(), any(), any(), anyOrNull(), - anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), ) verify(lightningRepo, never()).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull()) } @@ -12097,6 +12100,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ), ).doSuspendableAnswer { entered.complete(Unit) @@ -12218,6 +12222,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) verify( paykitPaymentProofRepo @@ -12295,6 +12300,387 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(privatePaykitRepo).consumePrivatePaymentList(contactKey, privateContext) } + @Test + fun `a higher prepared fee is not sent under the first approval`() = test { + var broadcasts = 0 + stubPreparedOnchainSend(preparedFeeSats = 212uL) { broadcasts++ } + openOnchainConfirm(reviewedFeeSats = 203) + + confirmPreparedPayment() + + assertEquals(0, broadcasts) + val review = sut.sendUiState.value + assertTrue(review.isPreparedFeeReview) + assertEquals(212L, review.onchainFeeUi.sats) + assertEquals(1_000uL, review.amount) + assertFalse(review.shouldConfirmPay) + verify(toastManager).enqueue( + check { + assertEquals(Toast.ToastType.INFO, it.type) + assertEquals("Fees changed", it.title) + assertEquals("Fees are ₿ 9 higher", it.description) + }, + ) + verify(formatMoneyValue).invoke(9uL) + + // A confirmation that no swipe on the actual fee asked for approves nothing. + sut.setSendEvent(SendEvent.PayConfirmed) + settlePreparedPayment() + assertEquals(0, broadcasts) + assertTrue(sut.sendUiState.value.isPreparedFeeReview) + } + + @Test + fun `renewed approval sends the prepared candidate once`() = test { + var broadcasts = 0 + stubPreparedOnchainSend(preparedFeeSats = 212uL) { broadcasts++ } + openOnchainConfirm(reviewedFeeSats = 203) + confirmPreparedPayment() + + sut.setSendEvent(SendEvent.SwipeToPay) + settlePreparedPayment() + assertEquals(0, broadcasts) + assertTrue(sut.sendUiState.value.shouldConfirmPay) + sut.setSendEvent(SendEvent.PayConfirmed) + settlePreparedPayment() + + assertEquals(1, broadcasts) + assertFalse(sut.sendUiState.value.isPreparedFeeReview) + assertEquals("txid", sut.successSendUiState.value.paymentHashOrTxId) + verifyOnchainSendCount(1) + } + + @Test + fun `the review of a prepared fee cannot be edited into another send`() = test { + var broadcasts = 0 + stubPreparedOnchainSend(preparedFeeSats = 212uL) { broadcasts++ } + openOnchainConfirm(reviewedFeeSats = 203) + confirmPreparedPayment() + val review = sut.sendUiState.value + + for (event in listOf(SendEvent.SpeedAndFee, SendEvent.BackToAmount, SendEvent.PaymentMethodSwitch)) { + sut.setSendEvent(event) + settlePreparedPayment() + } + + sut.addTagToSelected("late") + + assertEquals(review, sut.sendUiState.value) + assertEquals(0, broadcasts) + } + + @Test + fun `dismissing the review of a higher prepared fee sends nothing and frees the next send`() = test { + var broadcasts = 0 + stubPreparedOnchainSend(preparedFeeSats = 212uL) { broadcasts++ } + openOnchainConfirm(reviewedFeeSats = 203) + confirmPreparedPayment() + clearInvocations(toastManager) + + sut.hideSheet() + settlePreparedPayment() + + assertEquals(0, broadcasts) + assertFalse(sut.sendUiState.value.isPreparedFeeReview) + verify(paykitPaymentProofRepo).reconcile() + verify(toastManager, never()).enqueue(any()) + + stubPreparedOnchainSend(preparedFeeSats = 212uL) { broadcasts++ } + openOnchainConfirm(reviewedFeeSats = 212) + confirmPreparedPayment() + + assertEquals(1, broadcasts) + verifyOnchainSendCount(2) + } + + @Test + fun `cancelling the review of a request's prepared fee fails its started proof without sending`() = test { + val request = paymentRequest() + val privateContext = privatePaymentContext(7uL) + var broadcasts = 0 + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + stubPreparedOnchainSend(preparedFeeSats = 212uL) { broadcasts++ } + openOnchainConfirm(reviewedFeeSats = 203, request = request, privateContext = privateContext) + confirmPreparedPayment() + assertTrue(sut.sendUiState.value.isPreparedFeeReview) + + sut.hideSheet() + settlePreparedPayment() + + assertEquals(0, broadcasts) + verify(paykitPaymentProofRepo).failOnchainPayment(request) + verify(paykitPaymentProofRepo).reconcile() + verify(privatePaykitRepo, times(1)).consumePrivatePaymentList(testPublicKey, privateContext) + verifyOnchainSendCount(1) + } + + @Test + fun `a request that ended during the review of its prepared fee is not paid`() = test { + val request = paymentRequest() + val privateContext = privatePaymentContext(7uL) + var broadcasts = 0 + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + stubPreparedOnchainSend(preparedFeeSats = 212uL) { broadcasts++ } + openOnchainConfirm(reviewedFeeSats = 203, request = request, privateContext = privateContext) + confirmPreparedPayment() + whenever(paykitPaymentRequestRepo.ensurePaymentAllowed(request)) + .thenReturn(Result.failure(PaykitPaymentRequestError.RequestUnavailable)) + + confirmPreparedPayment() + + assertEquals(0, broadcasts) + verify(paykitPaymentProofRepo).failOnchainPayment(request) + verifyOnchainSendCount(1) + } + + @Test + fun `an equal or lower prepared fee sends without a second approval`() = test { + for (preparedFeeSats in listOf(203uL, 190uL)) { + var broadcasts = 0 + stubPreparedOnchainSend(preparedFeeSats) { broadcasts++ } + openOnchainConfirm(reviewedFeeSats = 203) + + confirmPreparedPayment() + + assertEquals(1, broadcasts, "Fee $preparedFeeSats") + assertFalse(sut.sendUiState.value.isPreparedFeeReview) + assertEquals(203L, sut.sendUiState.value.onchainFeeUi.sats) + } + } + + @Test + fun `fee warnings of a renewed approval use the prepared fee`() = test { + var broadcasts = 0 + sut.setIsAuthenticated(true) + stubPreparedOnchainSend(preparedFeeSats = 600uL) { broadcasts++ } + openOnchainConfirm(reviewedFeeSats = 203) + confirmPreparedPayment() + assertNull(sut.sendUiState.value.showSanityWarningDialog) + + sut.setSendEvent(SendEvent.SwipeToPay) + settlePreparedPayment() + + // 600 of fee is over half the 1 000 sent, which the 203 first reviewed was not. + assertEquals(SanityWarning.FEE_OVER_HALF_VALUE, sut.sendUiState.value.showSanityWarningDialog) + assertFalse(sut.sendUiState.value.shouldConfirmPay) + sut.setSendEvent(SendEvent.PayConfirmed) + settlePreparedPayment() + assertEquals(0, broadcasts) + + sut.setSendEvent(SendEvent.ConfirmAmountWarning(SanityWarning.FEE_OVER_HALF_VALUE)) + settlePreparedPayment() + assertTrue(sut.sendUiState.value.shouldConfirmPay) + sut.setSendEvent(SendEvent.PayConfirmed) + settlePreparedPayment() + + assertEquals(1, broadcasts) + } + + @Test + fun `starting another send during the review of a prepared fee sends nothing`() = test { + var broadcasts = 0 + stubPreparedOnchainSend(preparedFeeSats = 212uL) { broadcasts++ } + openOnchainConfirm(reviewedFeeSats = 203) + confirmPreparedPayment() + assertTrue(sut.sendUiState.value.isPreparedFeeReview) + clearInvocations(toastManager) + + assertTrue(sut.resetSendState(hardwareWalletId = null)) + settlePreparedPayment() + + assertEquals(0, broadcasts) + assertFalse(sut.sendUiState.value.isPreparedFeeReview) + assertNull(sut.sendUiState.value.onchainFeeUi.sats) + verify(paykitPaymentProofRepo).reconcile() + verify(toastManager, never()).enqueue(any()) + } + + @Test + fun `a prepared fee left unapproved is cancelled with a notice`() = test { + var broadcasts = 0 + stubPreparedOnchainSend(preparedFeeSats = 212uL) { broadcasts++ } + openOnchainConfirm(reviewedFeeSats = 203) + confirmPreparedPayment() + clearInvocations(toastManager) + + advanceTimeBy(100.seconds) + runCurrent() + assertTrue(sut.sendUiState.value.isPreparedFeeReview) + advanceTimeBy(20.seconds) + runCurrent() + + assertEquals(0, broadcasts) + assertFalse(sut.sendUiState.value.isPreparedFeeReview) + assertNull(sut.currentSheet.value) + verify(paykitPaymentProofRepo).reconcile() + verifyFeeChangedNotSentToast() + } + + @Test + fun `a send dismissed before its prepared fee could be reviewed is reported as not sent`() = test { + for (leave in listOf<() -> Unit>({ sut.hideSheet() }, { sut.onSendReviewVisible(false) })) { + var broadcasts = 0 + stubPreparedOnchainSend(preparedFeeSats = 212uL, beforeReview = leave) { broadcasts++ } + openOnchainConfirm(reviewedFeeSats = 203) + sut.onSendReviewVisible(true) + clearInvocations(toastManager) + + confirmPreparedPayment() + + assertEquals(0, broadcasts) + assertFalse(sut.sendUiState.value.isPreparedFeeReview) + assertEquals(203L, sut.sendUiState.value.onchainFeeUi.sats) + verifyFeeChangedNotSentToast() + } + } + + @Test + fun `approving a review that no longer shows the prepared send reports it as not sent`() = test { + var broadcasts = 0 + stubPreparedOnchainSend(preparedFeeSats = 212uL) { broadcasts++ } + openOnchainConfirm(reviewedFeeSats = 203) + confirmPreparedPayment() + clearInvocations(toastManager) + setSendState(sut.sendUiState.value.copy(amount = 2_000uL)) + + confirmPreparedPayment() + + assertEquals(0, broadcasts) + assertNull(sut.currentSheet.value) + verifyFeeChangedNotSentToast() + } + + @Test + fun `leaving the confirmation during the review of a prepared fee reports the send as not sent`() = test { + var broadcasts = 0 + stubPreparedOnchainSend(preparedFeeSats = 212uL) { broadcasts++ } + openOnchainConfirm(reviewedFeeSats = 203) + sut.onSendReviewVisible(true) + confirmPreparedPayment() + assertTrue(sut.sendUiState.value.isPreparedFeeReview) + clearInvocations(toastManager) + + sut.onSendReviewVisible(false) + settlePreparedPayment() + + assertEquals(0, broadcasts) + assertFalse(sut.sendUiState.value.isPreparedFeeReview) + verifyFeeChangedNotSentToast() + } + + @Test + fun `a review ended by its node stopping reports the send as not sent`() = test { + stubOnchainSend( + PREPARED_FEE_ADDRESS, + 1_000uL, + Result.failure(OnchainSendNotDispatchedError(OnchainSendReviewInterruptedError())), + ) + openOnchainConfirm(reviewedFeeSats = 203) + clearInvocations(toastManager) + + confirmPreparedPayment() + + assertNull(sut.currentSheet.value) + verify(paykitPaymentProofRepo).reconcile() + verifyFeeChangedNotSentToast() + } + + @Test + fun `a review ended by its node stopping does not close a send opened during its cleanup`() = test { + val cleanup = CompletableDeferred() + whenever { paykitPaymentProofRepo.reconcile() }.doSuspendableAnswer { cleanup.await() } + stubOnchainSend( + PREPARED_FEE_ADDRESS, + 1_000uL, + Result.failure(OnchainSendNotDispatchedError(OnchainSendReviewInterruptedError())), + ) + openOnchainConfirm(reviewedFeeSats = 203) + confirmPreparedPayment() + clearInvocations(toastManager) + + sut.hideSheet() + val next = Sheet.Send(SendRoute.Amount) + sut.showSheet(next) + settlePreparedPayment() + assertEquals(next, sut.currentSheet.value) + cleanup.complete(Unit) + settlePreparedPayment() + + assertEquals(next, sut.currentSheet.value) + verifyFeeChangedNotSentToast() + } + + @Test + fun `a review ended in the background reports the send once the app is back and unlocked`() = test { + stubOnchainSend( + PREPARED_FEE_ADDRESS, + 1_000uL, + Result.failure(OnchainSendNotDispatchedError(OnchainSendReviewInterruptedError())), + ) + openOnchainConfirm(reviewedFeeSats = 203) + sut.stopPaykitPaymentRequestPolling() + clearInvocations(toastManager) + + confirmPreparedPayment() + + assertNull(sut.currentSheet.value) + verify(toastManager, never()).enqueue(any()) + + // The app locked when it went to the background. + sut.setIsAuthenticated(false) + sut.startPaykitPaymentRequestPolling() + try { + runCurrent() + verify(toastManager, never()).enqueue(any()) + + sut.setIsAuthenticated(true) + runCurrent() + verifyFeeChangedNotSentToast() + } finally { + sut.stopPaykitPaymentRequestPolling() + } + } + + @Test + fun `fee warnings of a max send use the drain fee it shows`() = test { + sut.setIsAuthenticated(true) + openOnchainConfirm(reviewedFeeSats = 600) + setSendState(sut.sendUiState.value.copy(isMaxAmount = true)) + + sut.setSendEvent(SendEvent.SwipeToPay) + advanceUntilIdle() + + assertEquals(SanityWarning.FEE_OVER_HALF_VALUE, sut.sendUiState.value.showSanityWarningDialog) + verify(lightningRepo, never()) + .calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + } + + @Test + fun `a max send shows the fee of the drain it is prepared as`() = test { + val feeRates = FeeRates(fast = 5u, mid = 2u, slow = 1u) + whenever { + lightningRepo.estimateSendAllFee(PREPARED_FEE_ADDRESS, TransactionSpeed.Medium, feeRates) + }.thenReturn(Result.success(331uL)) + whenever { lightningRepo.estimateSendAllFee(any(), eq(TransactionSpeed.Fast), anyOrNull()) } + .thenReturn(Result.failure(AppError("no drain"))) + whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any()) } + .thenReturn(Result.success(203uL)) + for (isMaxAmount in listOf(true, false)) { + openOnchainConfirm(reviewedFeeSats = 1) + setSendState(sut.sendUiState.value.copy(isMaxAmount = isMaxAmount, feeRates = feeRates)) + + sut.setSendEvent(SendEvent.SpeedAndFee) + advanceUntilIdle() + + val feeUi = sut.sendUiState.value.onchainFeeUi + assertEquals(if (isMaxAmount) 331L else 203L, feeUi.sats, "Max $isMaxAmount") + // A drain that cannot be estimated falls back to the fixed-amount estimate. + assertEquals(203L, feeUi.estimates[FeeRate.FAST], "Max $isMaxAmount") + } + } + @Test fun `spark route pays the contact while spending is the source`() = test { val leg = sparkRouteLeg("bcrt1qroutedcontact") @@ -12647,6 +13033,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) } @@ -13571,6 +13958,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) } @@ -13848,6 +14236,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) } @@ -13899,6 +14288,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) verify(paykitPaymentProofRepo, never()).markOnchainPaymentStarted( any(), @@ -14854,6 +15244,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) } @@ -15000,6 +15391,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) } @@ -15093,6 +15485,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) } @@ -16350,6 +16743,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) } @@ -16397,6 +16791,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) } @@ -16464,6 +16859,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) } @@ -16593,6 +16989,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) } @@ -17332,6 +17729,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) } @@ -19100,6 +19498,139 @@ class AppViewModelSendFlowTest : BaseUnitTest() { advanceUntilIdle() } + private suspend fun TestScope.openOnchainConfirm( + reviewedFeeSats: Long, + request: PaykitPaymentRequest? = null, + privateContext: PrivatePaykitPaymentContext? = null, + ) { + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u) + whenever(formatMoneyValue(any())).thenReturn("9") + whenever(context.getString(R.string.lightning__spending_confirm__fees_changed_title)) + .thenReturn("Fees changed") + whenever(context.getString(R.string.lightning__spending_confirm__fees_changed_network)) + .thenReturn("Fees are {amount} higher") + whenever(context.getString(R.string.wallet__send_fee_changed_not_sent)) + .thenReturn("Fee changed, payment not sent") + sut.showSheet(Sheet.Send(SendRoute.Confirm)) + runCurrent() + if (request != null) { + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + setActiveContactPaymentContext(testPublicKey, privateContext, request) + } + setSendState( + SendUiState( + address = PREPARED_FEE_ADDRESS, + amount = request?.amount?.atomic ?: 1_000uL, + isAmountInputValid = true, + payMethod = SendMethod.ONCHAIN, + speed = TransactionSpeed.Medium, + isPaymentRequest = request != null, + onchainFeeUi = OnchainFeeUi(sats = reviewedFeeSats), + ), + ) + } + + /** + * Stands in for the repository's prepared send: a mining fee above the approved one is handed to the reviewer, + * and only its return lets the same prepared transaction be broadcast. + */ + private fun TestScope.settlePreparedPayment() { + // Short of the review's own timeout, which advanceUntilIdle would run into. + advanceTimeBy(5.seconds) + runCurrent() + } + + private fun TestScope.confirmPreparedPayment() { + sut.setSendEvent(SendEvent.SwipeToPay) + settlePreparedPayment() + sut.setSendEvent(SendEvent.PayConfirmed) + settlePreparedPayment() + } + + private fun verifyFeeChangedNotSentToast() { + verify(toastManager).enqueue( + check { + assertEquals(Toast.ToastType.WARNING, it.type) + assertEquals("Fees changed", it.title) + assertEquals("Fee changed, payment not sent", it.description) + }, + ) + } + + private suspend fun stubPreparedOnchainSend( + preparedFeeSats: ULong, + beforeReview: () -> Unit = {}, + onBroadcast: () -> Unit, + ) { + whenever { + lightningRepo.sendOnChain( + address = any(), + sats = any(), + speed = anyOrNull(), + utxosToSpend = anyOrNull(), + feeRates = anyOrNull(), + isTransfer = any(), + channelId = anyOrNull(), + isMaxAmount = any(), + tags = any(), + beforeSendAttempt = any(), + onBroadcast = any(), + requestId = anyOrNull(), + orderId = anyOrNull(), + transferContext = anyOrNull(), + payerIdentity = anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), + ) + }.doSuspendableAnswer { invocation -> + runSuspendCatching { + invocation.getArgument Unit>(9)() + val approvedFeeSats = requireNotNull(invocation.getArgument(17)) + if (preparedFeeSats > approvedFeeSats) { + val receipt = OnchainPreparedReceipt( + txid = "txid", + inputs = listOf(OnchainSendInput("11".repeat(32), 0u)), + address = invocation.getArgument(0), + amountSats = invocation.getArgument(1).toULong(), + feeRateSatsPerVByte = 1uL, + miningFeeSats = preparedFeeSats, + ) + val review = requireNotNull(invocation.getArgument<(suspend (OnchainPreparedReceipt) -> Unit)?>(18)) + beforeReview() + runSuspendCatching { review(receipt) }.getOrElse { throw OnchainSendNotDispatchedError(it) } + } + onBroadcast() + OnchainSendOutcome.Accepted("txid") + } + } + } + + private suspend fun verifyOnchainSendCount(count: Int) { + verify(lightningRepo, times(count)).sendOnChain( + address = any(), + sats = any(), + speed = anyOrNull(), + utxosToSpend = anyOrNull(), + feeRates = anyOrNull(), + isTransfer = any(), + channelId = anyOrNull(), + isMaxAmount = any(), + tags = any(), + beforeSendAttempt = any(), + onBroadcast = any(), + requestId = anyOrNull(), + orderId = anyOrNull(), + transferContext = anyOrNull(), + payerIdentity = anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), + ) + } + private suspend fun stubSuccessfulOnchainSend(address: String, sats: ULong, txId: String = "txid") { stubOnchainSend(address, sats, Result.success(OnchainSendOutcome.Accepted(txId)), broadcastTxId = txId) } @@ -19130,6 +19661,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) } @@ -19160,6 +19692,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), + reviewHigherFee = anyOrNull(), ) }.doSuspendableAnswer { invocation -> kotlin.check(invocation.getArgument(0) == address) @@ -21834,7 +22367,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(lightningRepo, never()).sendOnChain( any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), any(), any(), any(), any(), anyOrNull(), - anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), ) verify(paykitPaymentRequestRepo, never()).accept(any()) verify(paykitPaymentProofRepo, never()).prepare(any(), any(), any(), any(), anyOrNull(), anyOrNull()) @@ -21986,6 +22519,7 @@ private const val SAMROCK_SETUP_URL = private const val RESTORE_STARTED_AT = 1_700_000_000L private const val HARDWARE_WALLET_ID = "trezor:wallet" private const val REGTEST_ADDRESS = "bcrt1qs04g2ka4pr9s3mv73nu32tvfy7r3cxd27wkyu8" +private const val PREPARED_FEE_ADDRESS = "bcrt1qpreparedfee" private const val SWAP_QUOTE_ID = "swap-quote" private const val SWAP_ID = "swap" private const val SWAP_HOLD_INVOICE = "lnbcrt1swaphold" diff --git a/changelog.d/next/1657.fixed.md b/changelog.d/next/1657.fixed.md new file mode 100644 index 0000000000..772fbc7864 --- /dev/null +++ b/changelog.d/next/1657.fixed.md @@ -0,0 +1 @@ +Fixed Bitcoin payments from Savings being sent with a higher network fee than the one shown on the confirmation: Bitkit now shows the actual fee and asks you to confirm again before sending. diff --git a/journeys/send/README.md b/journeys/send/README.md index fbaf0d4d87..592174ad57 100644 --- a/journeys/send/README.md +++ b/journeys/send/README.md @@ -11,3 +11,5 @@ The native-binding tests also cover labels, proof-of-payment aliases and questio `own-invoice-guard.xml` covers the existing Lightning self-payment guard and is unchanged by this adoption. The shared journey verifies the recipient and amount in the payment UI. Metadata preservation, including `bitcoin:donation`, is asserted by the native-binding and app regression tests. Neither platform’s confirmation displays a standalone BIP21 note. Inspect the full recipient through the `ReviewUri` test tag after opening Show Details. + +`prepared-fee-review.xml` covers the renewed approval of an on-chain send whose prepared transaction costs more mining fee than the confirmation showed. Confirm preselects inputs and the send reuses them, so an ordinary send does not diverge; the journey reproduces it with an amount within about one fee of the whole balance (preselection fails) and a deposit confirmed while Confirm is open, as its description explains. The request, expiry, wallet-change and persistence-failure cases need controlled faults the Capabilities table does not provide and are covered by `LightningRepoTest.kt` and `AppViewModelSendFlowTest.kt`. diff --git a/journeys/send/prepared-fee-review.xml b/journeys/send/prepared-fee-review.xml new file mode 100644 index 0000000000..6d0db75463 --- /dev/null +++ b/journeys/send/prepared-fee-review.xml @@ -0,0 +1,35 @@ + + + Verifies that an on-chain send from Savings whose prepared transaction costs more mining fee than + the confirmation showed is not broadcast under that approval: the confirmation returns with the + actual fee, and the payment goes out only after a second swipe, with PIN or biometrics when they + are enabled for payments. Preconditions: an onboarded regtest wallet with a PIN required for + payments, coin selection set to automatic First-In-First-Out (Settings, Advanced, Coin Selection), + Savings funded with ./lsp deposits, and ./lsp available to deposit and mine while the Confirm + screen stays open. Confirm normally preselects inputs and the send reuses them, so the fees agree. + They diverge when the amount is within about one fee of the whole balance: preselection fails + (the app log shows "Selecting UTXOs" with no "Selected" line), Confirm estimates without fixed + inputs, and a coin confirmed while Confirm is open is added at send time (observed: 180 sats + shown, 277 sats prepared). Find that amount by entering the Savings balance minus the fee of + spending every output without change and lowering it by a few sats until the log shows the + failed preselection. If the "Received Bitcoin" sheet covers Confirm after the deposit, close it + with its button before swiping. The second swipe must follow within two minutes: after that the + review closes with a toast saying the payment was not sent. On the emulator, drive the swipe + with adb shell input draganddrop across the handle; a plain input swipe does not register. ./lsp + has no transaction lookup: confirm a broadcast by mining a block and watching the sent activity + confirm. A refusal logs "Asking to approve prepared fee"; after it there must be no second + "sendOnChain" call and exactly one "Created sent onchain activity". + + + Open Send, enter a second regtest wallet's address, and enter the near-balance amount found as the description says, then continue to the Confirm screen (tag "SendConfirmContent") + Expand Show Details (tag "SendConfirmToggleDetails") if collapsed and record the fee shown under Speed and Fee + With the Confirm screen still open, deposit a new output to this wallet's Savings address with ./lsp and mine one block, then wait until the Savings balance includes it; close the Received Bitcoin sheet if it opens over Confirm + Swipe the send handle (tag "GRAB") fully to the right and enter the PIN + Verify the Confirm screen (tag "SendConfirmContent") is shown again instead of the success screen, the fee under Speed and Fee is higher than the recorded one, the amount (tag "ReviewAmount") is unchanged and the send handle (tag "GRAB") is back at its start; take a screenshot right after the swipe to capture the Fees changed toast + Tap the Speed and Fee value, the amount (tag "ReviewAmount") and Add Tag (tag "TagsAddSend") and verify none opens another screen + Swipe the send handle (tag "GRAB") fully to the right again and enter the PIN + Wait for the Bitcoin Sent success screen (tag "SendSuccess"), tap Details (tag "Details"), and verify the sent activity shows the higher fee, not the first recorded one + Return to the wallet home screen, repeat the first five actions for another send that returns to the Confirm screen with a higher fee, then press system Back + Verify the send sheet closes without a success screen or an error toast, the activity list has no new sent payment, and a new send to the same address reaches the Confirm screen + +