Skip to content
2 changes: 2 additions & 0 deletions app/src/main/java/to/bitkit/data/CacheStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,8 @@ data class AppCacheData(
val pendingSparkWithdrawal: PendingSparkWithdrawal? = null,
/** The latest Spark withdrawals to Paykit contacts that settled as sent, so a restart never reads one as unsent. */
val sentSparkWithdrawals: List<SentSparkWithdrawal> = listOf(),
/** Pubky Swaps routes committed or restored whose claim has not confirmed yet, so each start resumes them. */
val unfinishedPubkySwaps: List<String> = listOf(),
/** Hashes of the latest Lightning sends Spark started, so the node holds off while Spark can't list them. */
val sparkSendHashes: List<String> = listOf(),
/** Invoice expiry in epoch seconds of the [sparkSendHashes] that know it. */
Expand Down
5 changes: 2 additions & 3 deletions app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,8 @@ class PaykitRouteRepo @Inject constructor(
if (legs.isNotEmpty()) {
return@runSuspendCatching paykitRoutePayment(request.copy(serviceLegs = legs), network)
}
if (quotes.any { it.exceptionOrNull() is SparkError.WithdrawalPending }) {
throw SparkError.WithdrawalPending()
}
// The pending withdrawal's address and contact tell the app whether it pays this contact.
quotes.firstNotNullOfOrNull { it.exceptionOrNull() as? SparkError.WithdrawalPending }?.let { throw it }
if (quotes.any { it.exceptionOrNull() is SparkError.WithdrawalOverBalance }) {
throw SparkError.WithdrawalOverBalance()
}
Expand Down
270 changes: 234 additions & 36 deletions app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion app/src/main/java/to/bitkit/repositories/SparkRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -886,7 +886,9 @@ class SparkRepo @Inject constructor(
suspend fun withdrawalRouteLeg(endpoint: PaykitEndpoint, amountSats: ULong): Result<ServiceRouteLeg?> =
withContext(bgDispatcher) {
runSuspendCatching {
if (cacheStore.data.first().pendingSparkWithdrawal != null) throw SparkError.WithdrawalPending()
cacheStore.data.first().pendingSparkWithdrawal?.let {
throw SparkError.WithdrawalPending(address = it.address, contact = it.contact)
}
if (!canWithdraw(amountSats)) return@runSuspendCatching null
val method = sparkService.prepareSend(endpoint.value, amountSats).paymentMethod
val quote = (method as SendPaymentMethod.BitcoinAddress).feeQuote
Expand Down
6 changes: 5 additions & 1 deletion app/src/main/java/to/bitkit/services/SparkService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,11 @@ sealed class SparkError(message: String, cause: Throwable? = null) : AppError(me
/** The withdrawal fee rose above the fee the user confirmed. */
class WithdrawalFeeChanged : SparkError("Spark withdrawal fee changed since it was confirmed")

class WithdrawalPending : SparkError("An earlier Spark withdrawal is still settling")
/** An earlier contact withdrawal, to [address] for [contact] where its journal records them, is still settling. */
class WithdrawalPending(
val address: String? = null,
val contact: String? = null,
) : SparkError("An earlier Spark withdrawal is still settling")

/** Spark could withdraw to the contact, but its balance can't cover the amount plus the withdrawal fee. */
class WithdrawalOverBalance : SparkError("Spark balance can't cover the withdrawal and its fee")
Expand Down
3 changes: 3 additions & 0 deletions app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import to.bitkit.repositories.PaykitUsdtPaymentRepo
import to.bitkit.repositories.PrivatePaykitAddressReservationRepo
import to.bitkit.repositories.PrivatePaykitRepo
import to.bitkit.repositories.PubkyRepo
import to.bitkit.repositories.PubkySwapsRouteRepo
import to.bitkit.repositories.UsdtRepo
import to.bitkit.repositories.WatchOnlyAccountRepo
import to.bitkit.services.CoreService
Expand All @@ -44,6 +45,7 @@ class WipeWalletUseCase @Inject constructor(
private val hwWalletRepo: HwWalletRepo,
private val lightningRepo: LightningRepo,
private val pubkyRepo: PubkyRepo,
private val pubkySwapsRouteRepo: PubkySwapsRouteRepo,
private val privatePaykitRepo: Provider<PrivatePaykitRepo>,
private val privatePaykitAddressReservationRepo: PrivatePaykitAddressReservationRepo,
private val firebaseMessaging: FirebaseMessaging,
Expand Down Expand Up @@ -100,6 +102,7 @@ class WipeWalletUseCase @Inject constructor(

private suspend fun wipeLocal(walletIndex: Int, resetWalletState: () -> Unit): Result<Unit> {
lightningRepo.wipeStorage(walletIndex).onFailure { return Result.failure(it) }
pubkySwapsRouteRepo.resetForWipe()
step("clear post-migration sync flag") { migrationService.setNeedsPostMigrationSync(false) }
step("clear migration data") { migrationService.cleanupAfterMigration() }
step("clear Paykit address reservations") { privatePaykitAddressReservationRepo.clear() }
Expand Down
114 changes: 104 additions & 10 deletions app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,7 @@ import to.bitkit.utils.timedsheets.sheets.NotificationsTimedSheet
import to.bitkit.utils.timedsheets.sheets.QuickPayTimedSheet
import to.bitkit.utils.timedsheets.sheets.UsdtTimedSheet
import java.math.BigDecimal
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong
import javax.inject.Inject
import kotlin.coroutines.cancellation.CancellationException
Expand Down Expand Up @@ -420,6 +421,9 @@ class AppViewModel @Inject constructor(
private var onchainSendRefreshJob: Job? = null
private var sendStateGeneration = 0L

/** Bumped only when a new send starts, unlike [sendStateGeneration], which edits within one send also bump. */
private var sendSession = 0L

fun setSendEvent(event: SendEvent) {
if ((currentSheet.value as? Sheet.Send)?.preparingRequest != null) return
when (event) {
Expand Down Expand Up @@ -580,6 +584,13 @@ class AppViewModel @Inject constructor(
/** The address and amount of the uncertain Spark withdrawal to a contact a pending screen waits on. */
@Volatile
private var uncertainSparkWithdrawal: Pair<String, ULong>? = null

/** The swap whose hold payment went out for a send, which may still pay the contact, so that send pays once. */
@Volatile
private var committedSwap: CommittedSwap? = null

/** The swap behind each hold payment still out, so a hold that fails stops its swap. */
private val swapIdsByHoldHash = ConcurrentHashMap<String, String>()
private var isPresentingPaymentRequest = false
private val isPaymentRequestPollingStopped = MutableStateFlow(false)
private var isPaymentRequestOverlayVisible = false
Expand Down Expand Up @@ -2980,6 +2991,7 @@ class AppViewModel @Inject constructor(
if (isAutomaticAllowancePayment(paymentHash)) return
if (moveToSparkRepo.isWatchedMovePayment(paymentHash)) return
if (pendingPaymentRepo.isPending(paymentHash)) {
releaseFailedSwapHold(paymentHash)
clearPendingContactPaymentContext(paymentHash)
pendingPaymentRepo.resolve(PendingPaymentResolution.Failure(paymentHash, event.reason))
if (shouldNotifyPendingResolution(paymentHash)) {
Expand Down Expand Up @@ -5027,7 +5039,14 @@ class AppViewModel @Inject constructor(
// Spark could reach the contact, but not with the withdrawal fee on top, so no route pays for want of balance.
val isLegOverBalance = result.exceptionOrNull() is SparkError.WithdrawalOverBalance
// Only a Spark leg could pay, and Spark takes one contact withdrawal at a time.
val isLegSettling = result.exceptionOrNull() is SparkError.WithdrawalPending
val settling = result.exceptionOrNull() as? SparkError.WithdrawalPending
val isLegSettling = settling != null
// A swap pays from Spending, so only a withdrawal still settling to this contact, or to an unknown one, keeps
// the payment from a swap that could pay the contact a second time.
val isSettlingHere = settling != null && (
settling.address == null || settling.address in route.endpoints.map { it.value } ||
settling.contact == contact?.publicKey
)
val picked = if (isLegOverBalance || isLegSettling) {
PaykitRoute.None(result.exceptionOrNull()?.message.orEmpty())
} else {
Expand Down Expand Up @@ -5062,7 +5081,7 @@ class AppViewModel @Inject constructor(
_sendUiState.update { it.copy(paykitRoute = route.copy(serviceLeg = null)) }
// A Spark balance too small for the amount and fee, or no route at all, leaves the payment to a swap
// provider when one can carry it: its quote follows, so nothing shows here.
if (hasSwapFallback && !isLegSettling) return PaykitRouteOutcome.SwapFallback
if (hasSwapFallback && !isSettlingHere) return PaykitRouteOutcome.SwapFallback
// The router's reason is English for the log: the app tells a short balance from an unusable contact.
val isAmountShort = state.amount > lightningSpendable.safe() + onchainSpendable.safe()
// The router never saw an LNURL whose limits refuse the amount, so its limit says why.
Expand Down Expand Up @@ -6762,6 +6781,7 @@ class AppViewModel @Inject constructor(
private suspend fun proceedWithPayment(contactPaymentContext: ContactPaymentContext?) {
delay(SCREEN_TRANSITION_DELAY) // wait for screen transitions when applicable

if (showCommittedSwap()) return
if (!validateIncomingPaymentRequest(contactPaymentContext)) return
_sendUiState.value.activePaykitSwapRoute?.let { route ->
if (route.quote?.deliveredSat == _sendUiState.value.amount) return@let
Expand Down Expand Up @@ -7302,6 +7322,7 @@ class AppViewModel @Inject constructor(
allowanceAttemptId: String?,
) {
val sendGeneration = sendStateGeneration
val session = sendSession
// A payment edited from Amount in the same sheet holds a fresh quote or none, so the result is no longer its.
val isSendCurrent = {
sendGeneration == sendStateGeneration &&
Expand All @@ -7320,6 +7341,8 @@ class AppViewModel @Inject constructor(
"Swap hold invoice is not a Lightning invoice"
}.paymentHash.toHex()
}.getOrElse {
// No hold payment goes out, so the provider never funds the swap.
pubkySwapsRouteRepo.dropFailedSwap(payment.swapId)
failSwapRoutedPayment(it, contactPaymentContext, allowanceAttemptId, isSendCurrent())
return
}
Expand All @@ -7341,11 +7364,16 @@ class AppViewModel @Inject constructor(
contactPaymentContext?.let {
synchronized(contactPaymentContextLock) { pendingContactPaymentContexts[holdPaymentHash] = it }
}
committedSwap = CommittedSwap(session, holdPaymentHash, payment.deliveredSat)
swapIdsByHoldHash[holdPaymentHash] = payment.swapId
// The hold invoice settles only after the claim reveals the preimage, so its payment stays pending.
lightningRepo.payInvoice(payment.invoice).onFailure {
// Spark may have sent it, so an unknown outcome waits on the claim like a sent hold payment.
if (it is PaymentPendingException) return@onFailure
holdFailure.cancel()
swapIdsByHoldHash.remove(holdPaymentHash)
pubkySwapsRouteRepo.dropFailedSwap(payment.swapId)
clearCommittedSwap(holdPaymentHash)
clearPendingContactPaymentContext(holdPaymentHash)
if (tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash)
failSwapRoutedPayment(it, contactPaymentContext, allowanceAttemptId, isSendCurrent())
Expand All @@ -7371,7 +7399,14 @@ class AppViewModel @Inject constructor(
// Paykit's background work go on meanwhile.
viewModelScope.launch {
finishSwapRoutedPayment(
SwapRoutedPayment(payment, holdPaymentHash, tagsSaved, contactPaymentContext, allowanceAttemptId),
SwapRoutedPayment(
payment = payment,
holdPaymentHash = holdPaymentHash,
tagsSaved = tagsSaved,
contactPaymentContext = contactPaymentContext,
allowanceAttemptId = allowanceAttemptId,
sendSession = session,
),
holdFailure,
isSendCurrent,
)
Expand All @@ -7392,6 +7427,7 @@ class AppViewModel @Inject constructor(
holdFailure.cancel()
}
claim.onSuccess {
swapIdsByHoldHash.remove(holdPaymentHash)
finishManualAllowancePayment(swap.allowanceAttemptId, succeeded = true)
Logger.info("Claimed Pubky Swaps route '${payment.swapId}' in '$it'", context = TAG)
}.onFailure {
Expand All @@ -7403,18 +7439,30 @@ class AppViewModel @Inject constructor(
// A failed hold payment keeps its hash on the send: its own failure handler may still be on its way to
// the error screen and finds the send by that hash.
clearSwapRouteQuote(isSendCurrent(), keepHoldPaymentHash = it is LightningPaymentFailedError)
clearCommittedSwap(holdPaymentHash)
swapIdsByHoldHash.remove(holdPaymentHash)
finishManualAllowancePayment(swap.allowanceAttemptId, succeeded = false)
clearPendingContactPaymentContext(holdPaymentHash)
releasePrivatePaymentListIfNeeded(swap.contactPaymentContext)
releaseSwapPrivatePaymentList(swap.contactPaymentContext)
if (swap.tagsSaved) preActivityMetadataRepo.deletePreActivityMetadata(holdPaymentHash)
if (it is LightningPaymentFailedError) return
if (it is LightningPaymentFailedError) {
restoreSwapContact(swap)
return
}
// A failed swap never reveals the preimage, so its hold payment cannot settle and a retry is safe.
Logger.error("Failed Pubky Swaps route '${payment.swapId}'", it, context = TAG)
pendingPaymentRepo.resolve(PendingPaymentResolution.Failure(holdPaymentHash))
if (shouldNotifyPendingResolution(holdPaymentHash)) notifyPendingPaymentFailed()
}
}

private fun restoreSwapContact(swap: SwapRoutedPayment) {
if (swap.sendSession != sendSession) return
synchronized(contactPaymentContextLock) {
if (activeContactPaymentContext == null) activeContactPaymentContext = swap.contactPaymentContext
}
}

/** A swap that failed before its hold payment went out moved no funds, so the send retries from the amount. */
private suspend fun failSwapRoutedPayment(
error: Throwable,
Expand All @@ -7423,10 +7471,7 @@ class AppViewModel @Inject constructor(
isCurrent: Boolean,
) {
clearSwapRouteQuote(isCurrent)
// Nothing was paid to the list's address, so a retry may pay from the same list.
contactPaymentContext?.privatePaymentContext?.let {
privatePaykitRepo.releasePrivatePaymentList(contactPaymentContext.publicKey, it)
}
releaseSwapPrivatePaymentList(contactPaymentContext)
finishManualAllowancePayment(allowanceAttemptId, succeeded = false)
if (!isCurrent) {
handlePaymentPreparationFailure(error, contactPaymentContext, isSendCurrent = false)
Expand All @@ -7445,6 +7490,47 @@ class AppViewModel @Inject constructor(
}
}

private fun showCommittedSwap(): Boolean {
val swap = committedSwap?.takeIf { it.sendSession == sendSession } ?: return false
setSendEffect(
SendEffect.NavigateToPending(
paymentHash = swap.holdPaymentHash,
amount = swap.deliveredSat.toLong(),
retryRoute = SendRetryRoute.Amount,
),
)
return true
}

private suspend fun releaseSwapPrivatePaymentList(context: ContactPaymentContext?) {
val privatePaymentContext = context?.privatePaymentContext ?: return
privatePaykitRepo.releasePrivatePaymentList(context.publicKey, privatePaymentContext)
}

private fun clearCommittedSwap(holdPaymentHash: String) {
if (committedSwap?.holdPaymentHash == holdPaymentHash) committedSwap = null
}

private fun releaseFailedSwapHold(paymentHash: String) {
// The provider never funds a swap whose hold payment failed, so it stops advancing, and the contact's list
// paid nothing.
swapIdsByHoldHash.remove(paymentHash)?.let { swapId ->
val context = synchronized(contactPaymentContextLock) { pendingContactPaymentContexts[paymentHash] }
viewModelScope.launch {
pubkySwapsRouteRepo.dropFailedSwap(swapId)
releaseSwapPrivatePaymentList(context)
}
}
val swap = committedSwap?.takeIf { it.holdPaymentHash == paymentHash } ?: return
committedSwap = null
if (swap.sendSession != sendSession) return
synchronized(contactPaymentContextLock) {
if (activeContactPaymentContext == null) {
activeContactPaymentContext = pendingContactPaymentContexts[paymentHash]
Comment thread
ovitrif marked this conversation as resolved.
Resolved
}
}
Comment thread
ovitrif marked this conversation as resolved.
Resolved
}

private fun clearSwapRouteQuote(isSendCurrent: Boolean, keepHoldPaymentHash: Boolean = false) {
if (!isSendCurrent) return
_sendUiState.update {
Expand All @@ -7464,7 +7550,7 @@ class AppViewModel @Inject constructor(
payment: PubkySwapRoutePayment,
holdFailure: Deferred<PaymentFailureReason?>,
): Result<String> = coroutineScope {
val claim = async { pubkySwapsRouteRepo.awaitClaim(payment.swapId) }
val claim = async { pubkySwapsRouteRepo.awaitClaim(payment.swapId, holdFailure = holdFailure) }
select {
claim.onAwait { it }
holdFailure.onAwait {
Expand Down Expand Up @@ -8516,6 +8602,7 @@ class AppViewModel @Inject constructor(
val hardwareAvailableSats = hardwareWalletId?.let { hardwareEstimatedAvailable(it, speed, rates) } ?: 0uL
if (!canPrepareSend(walletGeneration)) return false
sendStateGeneration++
sendSession++
addressValidationJob?.cancel()
paykitReviewedAmount = null
paykitAmountConversion = PaykitAmountConversion()
Expand Down Expand Up @@ -10380,6 +10467,13 @@ private data class SwapRoutedPayment(
val tagsSaved: Boolean,
val contactPaymentContext: ContactPaymentContext?,
val allowanceAttemptId: String?,
val sendSession: Long,
)

private data class CommittedSwap(
val sendSession: Long,
val holdPaymentHash: String,
val deliveredSat: ULong,
)

private class LightningPaymentFailedError(
Expand Down
Loading
Loading