Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -130,13 +130,21 @@ data class OnchainSendAttempt(
get() = requestId == null && isTransfer && orderId != null

/**
* A Shop payment, or a Blocktank funding, from the node wallet that dispatched but never had its acceptance
* confirmed.
* An ordinary savings send, which may pay a Spark exit's fee funding. It is released only once that exit no longer
* needs it ([SparkExitFundingRelease]).
*/
val mayFundSparkExit: Boolean
get() = requestId == null && !isTransfer && orderId == null

/**
* A Shop payment, a Blocktank funding, or a savings send a Spark exit may no longer need, from the node wallet
* that dispatched but never had its acceptance confirmed.
*/
val canBeAbandoned: Boolean
get() {
val isShopPayment = requestId != null && !isTransfer && !payerIdentity.isNullOrBlank()
return isUnresolved && (isShopPayment || isBlocktankFunding) && walletId == WalletScope.default &&
return isUnresolved && (isShopPayment || isBlocktankFunding || mayFundSparkExit) &&
walletId == WalletScope.default &&
initialDispatchAttempted && txid != null && !originalInputs.isNullOrEmpty() &&
candidateTxids.isNotEmpty()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,9 @@ class PaykitPaymentProofRepo @Inject constructor(
private val HARDWARE_OBSERVATION_TIMEOUT = 15.seconds
}

/** The Spark exit a savings send may fund, read from its stores; null when it cannot be read. */
internal var sparkExit: (OnchainSendAttempt) -> SparkExitFundingRelease.Exit? = SparkExitFundingRelease::storedExit

private val operationMutex = Mutex()
private val persistenceMutex = Mutex()
private val deliveryScope = appScope(ioDispatcher, TAG)
Expand Down Expand Up @@ -623,6 +626,7 @@ class PaykitPaymentProofRepo @Inject constructor(
suspend fun onchainRequestHasEnded(attempt: OnchainSendAttempt): Boolean = withContext(ioDispatcher) {
// Blocktank no longer sells channels, so its order has always ended.
if (attempt.isBlocktankFunding) return@withContext attempt.canBeAbandoned
if (attempt.mayFundSparkExit) return@withContext sparkExitFundingHasEnded(attempt)
val identity = currentIdentity()?.takeIf { PubkyPublicKeyFormat.matches(it, attempt.payerIdentity) }
val record = attempt.takeIf { it.canBeAbandoned && identity != null }?.let { payerRecord(it) }
val periodStartsAt = attempt.requestId?.billingPeriodStartsAt
Expand All @@ -635,6 +639,24 @@ class PaykitPaymentProofRepo @Inject constructor(
}
}

/**
* Whether [attempt] pays a Spark exit's funding address, current or earlier, or the exit cannot be read: Payment
* Pending pays it again only while the exit still asks for it, and offers its release once the exit no longer does.
*/
suspend fun isSparkExitFunding(attempt: OnchainSendAttempt): Boolean = withContext(ioDispatcher) {
if (!attempt.mayFundSparkExit) return@withContext false
// An approved release is finished from here, even once the exit's record is gone.
if (attempt.releaseApproved) return@withContext true
val exit = sparkExit(attempt) ?: return@withContext true
SparkExitFundingRelease.isExitFunding(attempt, exit)
}

private fun sparkExitFundingHasEnded(attempt: OnchainSendAttempt): Boolean {
val exit = sparkExit(attempt)?.takeIf { attempt.canBeAbandoned } ?: return false
if (attempt.releaseApproved) return !SparkExitFundingRelease.isAdopted(attempt, exit)
return SparkExitFundingRelease.exitNoLongerNeeds(attempt, exit)
}

private suspend fun payerRecord(attempt: OnchainSendAttempt): PaymentRequestRecord? {
val requestId = attempt.requestId ?: return null
return paykitSdkService.paymentRequests().firstOrNull {
Expand Down Expand Up @@ -770,7 +792,7 @@ class PaykitPaymentProofRepo @Inject constructor(
// failure leaves the release unfinished, to be finished again later.
attempt.requestId?.let { allowanceExecutor.get().onchainSendReleased(attempt.payerIdentity, it) }
val removeOriginalProof: suspend (OnchainSendAttempt) -> Boolean =
{ if (it.isBlocktankFunding) true else removeOriginalShopProofs(it) }
{ if (it.isBlocktankFunding || it.mayFundSparkExit) true else removeOriginalShopProofs(it) }
if (!lightningRepo.abandonUnbroadcastOnchainSend(attempt, removeOriginalProof)) {
throw OnchainSendBlockedError(attempt)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package to.bitkit.repositories

import to.bitkit.env.Env
import java.io.File

/**
* A savings send to a Spark exit's funding address, told apart by that address alone. Once the exit no longer needs
* it, the send can be released like a Shop payment whose request ended, instead of blocking every new send.
*/
object SparkExitFundingRelease {
/** The exit state the checks read: the wallet's record and its earlier exits' addresses. */
data class Exit(val record: SparkExitRecord?, val earlier: List<SparkExitEarlierAddress>)

private fun OnchainSendAttempt.hasCandidate(txid: String?): Boolean {
if (txid == null) return false
return this.txid.equals(txid, ignoreCase = true) || candidateTxids.any { it.equals(txid, ignoreCase = true) }
}

/** Whether [attempt] pays the funding address of the exit in [exit]'s record or of an earlier exit. */
fun isExitFunding(attempt: OnchainSendAttempt, exit: Exit): Boolean =
attempt.mayFundSparkExit && (
exit.record?.funding?.firstOrNull()?.address == attempt.address ||
exit.earlier.any { it.address == attempt.address }
)

/**
* Whether the exit no longer needs [attempt]: it was cancelled or ended, or it holds all the funding it asked for
* and none of it is [attempt]'s. While the exit still waits for one of [attempt]'s transactions, or asks for
* funding at its address, it needs it; one it adopted means the payment landed, so it is never released.
*/
fun exitNoLongerNeeds(attempt: OnchainSendAttempt, exit: Exit): Boolean {
if (!attempt.mayFundSparkExit) return false
val record = exit.record?.takeIf { it.funding.firstOrNull()?.address == attempt.address }
?: return exit.earlier.any { it.address == attempt.address }
// A payment the exit still waits for; once other funding filled it, the txid stays behind unwatched.
val awaited = record.fundingPaymentTxid?.takeIf { record.isAwaitingOwnPayment || record.isEndedPaymentPending }
val landed = record.funding.mapNotNull { it.txid } + record.leftover.map { it.txid } + listOfNotNull(awaited)
if (landed.any { attempt.hasCandidate(it) }) return false
return !record.isActive || record.fundingShortfallSats == null
}

/** Whether one of [attempt]'s transactions landed at the exit, as funding or leftover: it reached the network. */
fun isAdopted(attempt: OnchainSendAttempt, exit: Exit): Boolean {
val record = exit.record ?: return false
val landed = record.funding.mapNotNull { it.txid } + record.leftover.map { it.txid }
return landed.any { attempt.hasCandidate(it) }
}

/**
* Whether savings may pay [attempt] to the exit again now, over what its funding address holds ([utxos], null
* when it could not be read): while the exit still asks for funding there, waits for this very payment, or holds
* this payment's own coin, and never once its release was approved. A retry re-signs the same inputs, so it never
* pays twice, and what savings pays beyond the ask comes back as leftover. A send to no exit's address is not this
* check's to refuse.
*/
fun mayPayAgain(attempt: OnchainSendAttempt, exit: Exit, utxos: List<EsploraUtxo>?): Boolean {
// A release approved for it is Send Pending's to finish, even once the exit's record is gone.
if (attempt.mayFundSparkExit && attempt.releaseApproved) return false
if (!isExitFunding(attempt, exit)) return true
val record = exit.record?.takeIf { it.isActive && it.funding.firstOrNull()?.address == attempt.address }
if (record == null || utxos == null) return false
// Other wallets' coins alone cover the funding: nothing is left to ask, and its release takes care of it.
val isOwnPaid = attempt.hasCandidate(record.fundingPaymentTxid)
val unpaid = if (isOwnPaid) record.copy(fundingPaymentTxid = null) else record
val others = utxos.filterNot { attempt.hasCandidate(it.txid) }
if (SparkExitMath.fundingState(unpaid, others) == SparkExitFundingState.Seen) return false
return when (SparkExitMath.fundingState(record, utxos)) {
// Partial payments from other wallets still leave an ask.
is SparkExitFundingState.Ask -> true
// Waiting for this very payment.
SparkExitFundingState.Paid -> isOwnPaid
// Covered with this payment's own unconfirmed coin: a retry only bumps it.
SparkExitFundingState.Seen -> SparkExitMath.newFunding(utxos, record).any {
!it.status.confirmed && attempt.hasCandidate(it.txid)
}
else -> false
}
}

/** The stored exit of [attempt]'s wallet; null when it cannot be read, so nothing is released. */
fun storedExit(attempt: OnchainSendAttempt): Exit? = runCatching {
Exit(
record = SparkExitStore(File(Env.sparkExitRecordPath(attempt.walletIndex))).load(),
earlier = runCatching {
SparkExitEarlierAddressStore(File(Env.sparkExitEarlierAddressesPath(attempt.walletIndex))).load()
}.getOrDefault(emptyList()),
)
}.getOrNull()
}
26 changes: 25 additions & 1 deletion app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1140,6 +1140,27 @@ class SparkExitRepo @Inject constructor(
}
}

/**
* Refuses paying [attempt] to a Spark exit again once the stored exit of its wallet no longer asks for it, read
* right before dispatch; an exit that cannot be read refuses a send that may fund one.
*/
suspend fun authorizePayAgain(attempt: OnchainSendAttempt) {
if (!attempt.mayFundSparkExit) return
val exit = withContext(bgDispatcher) { SparkExitFundingRelease.storedExit(attempt) }
checkNotNull(exit) { "The Spark exit could not be read" }
authorizePayAgain(attempt, exit)
}

/** Funding from another wallet may have reached the address while the payment was prepared. */
private suspend fun authorizePayAgain(attempt: OnchainSendAttempt, exit: SparkExitFundingRelease.Exit) {
check(!attempt.releaseApproved) { "Its release was approved" }
if (!SparkExitFundingRelease.isExitFunding(attempt, exit)) return
val utxos = runSuspendCatching { chain?.utxos(attempt.address) }.getOrNull()
check(SparkExitFundingRelease.mayPayAgain(attempt, exit, utxos)) {
"The Spark exit no longer asks for this funding"
}
}

/**
* Pays the exit's fee funding from savings again after a node refused the payment: the same attempt, re-signed at
* the rate the user approved over the inputs it already spends. Every version spends those inputs, so at most one
Expand All @@ -1162,7 +1183,10 @@ class SparkExitRepo @Inject constructor(
attemptId = refused.attemptId,
walletId = refused.walletId,
feeRateSatsPerVByte = refused.feeRateSatsPerVByte,
) { check(it.attemptId == refused.attemptId && it.address == refused.address) }
) {
check(it.attemptId == refused.attemptId && it.address == refused.address)
authorizePayAgain(it, SparkExitFundingRelease.Exit(record, _state.value.earlierAddresses))
}
.getOrElse {
pendingFundingTxid(it, refused.address)?.let { pending -> keepFundingPayment(pending) }
_state.value.record?.let { current -> noteSavingsSend(current) }
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package to.bitkit.ui.screens.wallets.send

import androidx.annotation.StringRes
import androidx.compose.animation.core.EaseInOut
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
Expand Down Expand Up @@ -126,7 +127,7 @@ fun SendPendingScreen(
AbandonExpiredPayment(
abandonError = uiState.abandonErrorMessage(),
isAbandoned = uiState.abandoned,
isTransfer = uiState.abandonableAttempt?.isBlocktankFunding == true,
note = uiState.abandonableAttempt.abandonNote(),
showConfirmation = showAbandonConfirmation,
onConfirm = { requiresPin, useBiometrics ->
showAbandonConfirmation = false
Expand Down Expand Up @@ -159,7 +160,7 @@ fun SendPendingScreen(
refusalReason = refusalReason,
onClose = onClose,
onViewDetails = onViewDetails,
canRetry = uiState.recoveryAttempt != null,
canRetry = uiState.canRetry,
isRecovering = uiState.isRecovering,
recoveryError = uiState.abandonErrorMessage() ?: uiState.recoveryErrorMessage(),
onRetry = onRetry,
Expand All @@ -174,7 +175,7 @@ fun SendPendingScreen(
private fun AbandonExpiredPayment(
abandonError: String?,
isAbandoned: Boolean,
isTransfer: Boolean,
@StringRes note: Int,
showConfirmation: Boolean,
onConfirm: (requiresPin: Boolean, useBiometrics: Boolean) -> Unit,
onDismiss: () -> Unit,
Expand All @@ -199,13 +200,7 @@ private fun AbandonExpiredPayment(
if (showConfirmation) {
AppAlertDialog(
title = stringResource(R.string.wallet__send_pending__abandon),
text = stringResource(
if (isTransfer) {
R.string.wallet__send_pending__abandon_transfer_note
} else {
R.string.wallet__send_pending__abandon_note
}
),
text = stringResource(note),
confirmText = stringResource(R.string.common__continue),
dismissText = stringResource(R.string.common__cancel),
onConfirm = { onConfirm(isPinEnabled && pinForPayments, isBiometricEnabled && isBiometrySupported) },
Expand All @@ -214,6 +209,13 @@ private fun AbandonExpiredPayment(
}
}

@StringRes
private fun OnchainSendAttempt?.abandonNote(): Int = when {
this?.isBlocktankFunding == true -> R.string.wallet__send_pending__abandon_transfer_note
this?.mayFundSparkExit == true -> R.string.wallet__send_pending__abandon_exit_note
else -> R.string.wallet__send_pending__abandon_note
}

@Composable
private fun SendPendingUiState.abandonErrorMessage(): String? = abandonError?.let {
stringResource(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ class SendPendingViewModel @Inject constructor(
val hasOriginalReceipt = !attempt?.originalInputs.isNullOrEmpty() &&
attempt.candidateTxids.any { it.equals(txid, true) }
if (matchesOriginalWallet && hasOriginalReceipt) {
val isExitFunding = paykitPaymentProofRepo.isSparkExitFunding(attempt)
_uiState.update { it.copy(isSparkExitFunding = isExitFunding) }
if (attempt.isUnresolved) _uiState.update { it.copy(recoveryAttempt = attempt) }
observeOriginalCompletion(attempt)
offerAbandonIfRequestEnded(attempt)
Expand Down Expand Up @@ -180,6 +182,8 @@ class SendPendingViewModel @Inject constructor(
// The request can end, or a failed check recover, while Payment Pending stays open.
private fun offerAbandonIfRequestEnded(attempt: OnchainSendAttempt) {
if (!attempt.canBeAbandoned) return
// Only a Spark exit's funding is released among ordinary sends.
if (attempt.mayFundSparkExit && !_uiState.value.isSparkExitFunding) return
viewModelScope.launch {
// Transfers do not come back once unavailable, so one check decides a Blocktank funding.
if (attempt.isBlocktankFunding) {
Expand Down Expand Up @@ -351,7 +355,15 @@ data class SendPendingUiState(
val isAbandoning: Boolean = false,
val abandoned: Boolean = false,
val abandonError: AbandonError? = null,
)
/** The attempt pays a Spark exit's funding: paid again while the exit asks, released once it no longer does. */
val isSparkExitFunding: Boolean = false,
) {
val canRetry: Boolean
get() {
val attempt = recoveryAttempt ?: return false
return !(isSparkExitFunding && (abandonableAttempt != null || attempt.releaseApproved))
Comment thread
ovitrif marked this conversation as resolved.
Resolved
}
}

enum class AbandonError { MayStillConfirm, SyncUnavailable, ReleasePending }

Expand Down
2 changes: 2 additions & 0 deletions app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7779,6 +7779,8 @@ class AppViewModel @Inject constructor(
attempt.attemptId == original.attemptId && attempt.requestId == original.requestId &&
attempt.orderId == original.orderId && attempt.payerIdentity == original.payerIdentity
)
// Read right before dispatch: a Spark exit's funding is paid again only while the exit still asks for it.
sparkExitRepo.authorizePayAgain(attempt)
if (request != null) {
val currentRequest =
(
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-ar/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1188,6 +1188,7 @@
<string name="wallet__send_paykit_no_route__description">ليس لدى جهة الاتصال هذه أي طريقة دفع يمكن لـ Bitkit استخدامها الآن.</string>
<string name="wallet__send_paykit_no_route__title">لا يمكن الدفع لجهة الاتصال هذه</string>
<string name="wallet__send_paykit_withdrawal_settling__description">لا يزال سحب سابق من رصيد الإنفاق قيد التسوية. حاول مرة أخرى بعد اكتماله.</string>
<string name="wallet__send_pending__abandon_exit_note">لم يعد هذا التحويل القسري بحاجة إلى هذه الدفعة. يتحقق Bitkit أولًا من الشبكة، ثم يعيد عملاتها إلى محفظتك حتى لا تتأكد أبدًا. يكلّف ذلك رسوم شبكة.</string>
<string name="wallet__send_pending__abandon_transfer_note">لم تعد التحويلات إلى رصيد الإنفاق متاحة. يتحقق Bitkit أولًا من الشبكة، ثم يعيد عملات هذا التحويل إلى محفظتك حتى لا يتأكد التحويل الأصلي أبدًا. يكلّف ذلك رسوم شبكة.</string>
<string name="wallet__send_quickpay__nav_title">QuickPay</string>
<string name="wallet__send_quickpay__title">جارٍ دفع\n&lt;accent&gt;الفاتورة...&lt;/accent&gt;</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-b+es+419/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1219,6 +1219,7 @@
<string name="wallet__send_paykit_no_route__description">Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora.</string>
<string name="wallet__send_paykit_no_route__title">No se puede pagar a este contacto</string>
<string name="wallet__send_paykit_withdrawal_settling__description">Un retiro anterior de tu saldo para gastos aún se está liquidando. Inténtalo de nuevo cuando termine.</string>
<string name="wallet__send_pending__abandon_exit_note">Esta transferencia forzada ya no necesita este pago. Bitkit primero revisa la red y luego devuelve sus monedas a tu billetera para que nunca se confirme. Esto tiene una comisión de red.</string>
<string name="wallet__send_pending__abandon_transfer_note">Las transferencias al saldo de gasto ya no están disponibles. Bitkit primero revisa la red y luego devuelve las monedas de esta transferencia a tu billetera para que la transferencia original nunca se confirme. Esto tiene una comisión de red.</string>
<string name="wallet__send_pending__description">Este pago está tardando un poco más de lo esperado. Puede seguir utilizando Bitkit.</string>
<string name="wallet__send_pending__nav_title">Pago pendiente</string>
Expand Down
Loading