diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 849446f9e5..bbede61b0d 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -18,6 +18,8 @@ import to.bitkit.models.FxRate import to.bitkit.models.NewTransactionSheetDetails import to.bitkit.models.QuickPayLedger import to.bitkit.models.WalletScope +import to.bitkit.repositories.PendingSparkWithdrawal +import to.bitkit.repositories.SentSparkWithdrawal import to.bitkit.utils.Logger import javax.inject.Inject import javax.inject.Singleton @@ -334,6 +336,10 @@ data class AppCacheData( val quickPayLedger: QuickPayLedger? = null, /** LNURL-pay comments by payment hash, kept until the sent payment's activity stores them. */ val pendingLightningMessages: Map = mapOf(), + /** A Spark withdrawal to a Paykit contact that started, kept until Spark's payment list settles it. */ + 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 = listOf(), /** Hashes of the latest Lightning sends Spark started, so the node holds off while Spark can't list them. */ val sparkSendHashes: List = listOf(), /** Invoice expiry in epoch seconds of the [sparkSendHashes] that know it. */ diff --git a/app/src/main/java/to/bitkit/data/SparkPayoutChain.kt b/app/src/main/java/to/bitkit/data/SparkPayoutChain.kt new file mode 100644 index 0000000000..eb0a2b55c3 --- /dev/null +++ b/app/src/main/java/to/bitkit/data/SparkPayoutChain.kt @@ -0,0 +1,54 @@ +package to.bitkit.data + +import io.ktor.client.HttpClient +import io.ktor.client.request.get +import io.ktor.client.statement.bodyAsText +import io.ktor.http.HttpStatusCode +import io.ktor.http.isSuccess +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.boolean +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.lightningdevkit.ldknode.Network +import to.bitkit.env.Env +import to.bitkit.ext.runSuspendCatching +import to.bitkit.utils.Logger +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Whether a Spark withdrawal's payout transaction is mined, asked of the Esplora chain Spark reads. Unlike the payout + * address's unspent outputs, the transaction's status still answers once the contact has spent the payout. + */ +@Singleton +class SparkPayoutChain @Inject constructor( + private val client: HttpClient, +) { + companion object { + private const val TAG = "SparkPayoutChain" + private const val SPARK_REGTEST_ESPLORA_URL = "https://regtest-mempool.us-west-2.sparkinfra.net/api" + private val json = Json { ignoreUnknownKeys = true } + + /** The Esplora to ask on [network]: the one Spark reads there, or null where the app knows none. */ + fun esploraUrl(network: Network): String? = when (network) { + Network.BITCOIN -> Env.bitkitEsploraUrl + Network.REGTEST -> SPARK_REGTEST_ESPLORA_URL + else -> null + } + } + + /** Whether [txid] is in a block; null when this network has no Esplora to ask or the lookup failed. */ + suspend fun isMined(txid: String): Boolean? { + val baseUrl = esploraUrl(Env.network) ?: return null + return runSuspendCatching { + val response = client.get("$baseUrl/tx/$txid/status") + // Spark can list a payout before it is broadcast, and the chain then knows no such transaction yet. + if (response.status == HttpStatusCode.NotFound) return@runSuspendCatching false + check(response.status.isSuccess()) { "status ${response.status.value}" } + json.parseToJsonElement(response.bodyAsText()).jsonObject.getValue("confirmed").jsonPrimitive.boolean + }.getOrElse { + Logger.warn("Failed to look up Spark payout transaction '$txid'", it, context = TAG) + null + } + } +} diff --git a/app/src/main/java/to/bitkit/models/PaykitPaymentStateBackup.kt b/app/src/main/java/to/bitkit/models/PaykitPaymentStateBackup.kt index 38a9731d0f..bebf545af1 100644 --- a/app/src/main/java/to/bitkit/models/PaykitPaymentStateBackup.kt +++ b/app/src/main/java/to/bitkit/models/PaykitPaymentStateBackup.kt @@ -66,6 +66,7 @@ data class PaykitPaymentStateBackup( val privatePaymentListVersion: ULong? = null, val previousPrivatePaymentListVersion: ULong? = null, val allowanceId: String? = null, + val sparkWithdrawal: Boolean = false, ) { init { require( @@ -98,6 +99,7 @@ data class PaykitPaymentStateBackup( privatePaymentListVersion = proof.privatePaymentListVersion, previousPrivatePaymentListVersion = proof.previousPrivatePaymentListVersion, allowanceId = proof.allowanceId, + sparkWithdrawal = proof.sparkWithdrawal, ) fun restored() = PendingPaykitPaymentProof( @@ -124,6 +126,7 @@ data class PaykitPaymentStateBackup( privatePaymentListVersion = privatePaymentListVersion, previousPrivatePaymentListVersion = previousPrivatePaymentListVersion, allowanceId = allowanceId, + sparkWithdrawal = sparkWithdrawal, ) } } diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index a3231b62d6..576552bb45 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -153,6 +153,9 @@ class LightningRepo @Inject constructor( /** Whether Spark synced its payments since it connected, so its payment list is complete. */ val isSparkSynced: Flow get() = sparkRepo.state.map { it.hasSynced }.distinctUntilChanged() + /** How each journaled Spark contact withdrawal closed. */ + val sparkWithdrawalSettlements: Flow get() = sparkRepo.withdrawalSettlements + private val scope = appScope(bgDispatcher, TAG) private val _eventHandlers = ConcurrentHashMap.newKeySet() @@ -2610,9 +2613,22 @@ class LightningRepo @Inject constructor( } } + /** What became of a Spark withdrawal attempt of exactly [amountSats] to [address], from Spark's payment list. */ + suspend fun sparkWithdrawalOutcome( + address: String, + amountSats: ULong, + earlierTxids: Set, + ): SparkWithdrawalOutcome = sparkRepo.withdrawalOutcome(address, amountSats, earlierTxids) + + /** Txids of the Spark withdrawals to [address] so far, which a new attempt to it never counts as its own. */ + suspend fun sparkWithdrawalTxidsTo(address: String): Set = sparkRepo.withdrawalTxidsTo(address) + /** Whether Spark alone can pay [amountSats], which it does whenever the node cannot. */ fun canSendWithSpark(amountSats: ULong): Boolean = sparkRepo.canSend(amountSats) + /** Whether Spark's whole balance covers a withdrawal debiting [debitSats], its fees included. */ + fun canWithdrawWithSpark(debitSats: ULong): Boolean = sparkRepo.canWithdraw(debitSats) + fun canSend(amountSats: ULong): Boolean { val state = _lightningState.value if (sparkRepo.canSend(amountSats)) return true diff --git a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt index 47d0ec151a..0d18b41ad0 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt @@ -1113,6 +1113,27 @@ class PaykitAllowanceExecutor @Inject constructor( } } + /** + * Records a manual on-chain send of [requestId] that Spark's list later shows sent as succeeded with its + * [transactionId], so an attempt left unknown no longer holds the request. Throws when an outcome could not be + * recorded, so the proof that found it stays for another pass. + */ + suspend fun onchainSendSettled(payerIdentity: String?, requestId: PaykitPaymentRequestId, transactionId: String) { + val identity = activeIdentity?.takeIf { PubkyPublicKeyFormat.matches(it, payerIdentity) } ?: return + withContext(ioDispatcher) { + settleMutex.withLock { + val attempts = localState(identity).journal.filter { + it.requestId == requestId && !it.isAutomatic && it.paymentHash == null && + it.stage in SETTLEABLE_STAGES + } + for (attempt in attempts) { + updateJournalEntry(attempt.attemptId, identity) { it.copy(transactionId = transactionId) } + record(attempt.attemptId, PaymentOutcome.SUCCEEDED, identity) + } + } + } + } + // endregion // region Helpers diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index 0023bb8226..44bedac639 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -110,6 +110,8 @@ data class PendingPaykitPaymentProof( val previousPrivatePaymentListVersion: ULong? = null, /** Set only for an automatic Allowance payment, from its submitted attempt. Manual payments omit it. */ val allowanceId: String? = null, + /** An on-chain payment sent as a Spark withdrawal, settled from Spark's payment list instead of the node's. */ + val sparkWithdrawal: Boolean = false, ) data class PaykitOnchainPaymentProofResolution( @@ -120,6 +122,12 @@ data class PaykitOnchainPaymentProofResolution( val amountSats: ULong? = null, ) +/** A request whose uncertain Spark withdrawal Spark showed never sent, so its pending payment can fail. */ +data class PaykitSparkWithdrawalRelease( + val identity: String, + val requestId: PaykitPaymentRequestId, +) + @Singleton class PaykitPaymentProofRepo @Inject constructor( @IoDispatcher private val ioDispatcher: CoroutineDispatcher, @@ -186,6 +194,8 @@ class PaykitPaymentProofRepo @Inject constructor( } private val _onchainPaymentResolutions = MutableStateFlow>(emptyList()) val onchainPaymentResolutions = _onchainPaymentResolutions.asStateFlow() + private val _sparkWithdrawalReleases = MutableStateFlow>(emptyList()) + val sparkWithdrawalReleases = _sparkWithdrawalReleases.asStateFlow() suspend fun prepare( request: PaykitPaymentRequest, @@ -308,6 +318,48 @@ class PaykitPaymentProofRepo @Inject constructor( privatePaymentListVersion: ULong? = null, signedTx: HwFundingSignedTx? = null, previousPrivatePaymentListVersion: ULong? = null, + ): Result = markOnchainStarted( + request = request, + address = address, + amountSats = amountSats, + walletId = walletId, + privatePaymentListVersion = privatePaymentListVersion, + signedTx = signedTx, + previousPrivatePaymentListVersion = previousPrivatePaymentListVersion, + sparkWithdrawal = false, + ) + + /** Marks the on-chain proof of [request] started for a Spark withdrawal of [amountSats] to [address]. */ + suspend fun markSparkOnchainPaymentStarted( + request: PaykitPaymentRequest, + address: String, + amountSats: ULong, + privatePaymentListVersion: ULong? = null, + previousPrivatePaymentListVersion: ULong? = null, + earlierWithdrawalTxids: Set = emptySet(), + ): Result = markOnchainStarted( + request = request, + address = address, + amountSats = amountSats, + walletId = WalletScope.default, + privatePaymentListVersion = privatePaymentListVersion, + signedTx = null, + previousPrivatePaymentListVersion = previousPrivatePaymentListVersion, + sparkWithdrawal = true, + earlierWithdrawalTxids = earlierWithdrawalTxids, + ) + + @Suppress("LongParameterList") + private suspend fun markOnchainStarted( + request: PaykitPaymentRequest, + address: String, + amountSats: ULong, + walletId: String, + privatePaymentListVersion: ULong?, + signedTx: HwFundingSignedTx?, + previousPrivatePaymentListVersion: ULong?, + sparkWithdrawal: Boolean, + earlierWithdrawalTxids: Set = emptySet(), ): Result = withContext(ioDispatcher) { runSuspendCatching { val identity = currentIdentity() ?: throw PaykitPaymentRequestError.RequestUnavailable @@ -347,12 +399,124 @@ class PaykitPaymentProofRepo @Inject constructor( hardwareFeeRate = signedTx?.feeRate, hardwareTotalSpent = signedTx?.totalSpent, hardwareDispatchAttempted = signedTx?.let { false }, + sparkWithdrawal = sparkWithdrawal, + onchainMatchingTransactionIdsBeforeAttempt = if (sparkWithdrawal) { + earlierWithdrawalTxids + } else { + proofs[index].onchainMatchingTransactionIdsBeforeAttempt + }, ) persist(proofs) } }.onFailure { Logger.warn("Failed to mark a Paykit on-chain payment as started", it, context = TAG) } } + /** Completes the started proof of [request] paid by the Spark withdrawal [txid] and delivers it. */ + suspend fun completeSparkOnchainPayment(request: PaykitPaymentRequest, txid: String): Boolean = + withContext(ioDispatcher) { + if (!txid.isHex(HASH_BYTE_COUNT)) return@withContext false + val identity = currentIdentity() ?: return@withContext false + runSuspendCatching { + operationMutex.withLock { + val proof = loadProofs().lastOrNull { + PubkyPublicKeyFormat.matches(it.identity, identity) && it.requestId == request.id && + it.sparkWithdrawal && it.paymentStarted && it.proofData == null + } ?: return@withLock false + completeSparkOnchainProofLocked(proof, txid) + } + }.onFailure { + Logger.warn("Failed to complete a Paykit proof for a Spark withdrawal", it, context = TAG) + }.getOrDefault(false) + } + + /** + * Releases the started Spark proof of [request] when Spark shows its withdrawal never sent, so the request can be + * paid again; returns whether it did. + */ + suspend fun releaseUnsentSparkOnchainProof(request: PaykitPaymentRequest): Boolean = withContext(ioDispatcher) { + val identity = currentIdentity() ?: return@withContext false + runSuspendCatching { + operationMutex.withLock { + val proof = loadProofs().lastOrNull { + PubkyPublicKeyFormat.matches(it.identity, identity) && it.requestId == request.id && + it.sparkWithdrawal && it.paymentStarted && it.proofData == null + } ?: return@withLock false + reconcileSparkOnchainProof(proof) + loadProofs().none { it == proof } + } + }.onFailure { + Logger.warn("Failed to release an unsent Spark withdrawal proof", it, context = TAG) + }.getOrDefault(false) + } + + /** + * Releases the started Spark proof of [request] for a withdrawal Spark refused before its journal was written, so + * nothing left the wallet and no listing is needed; returns whether it did. + */ + suspend fun releaseRefusedSparkOnchainProof(request: PaykitPaymentRequest): Boolean = withContext(ioDispatcher) { + val identity = currentIdentity() ?: return@withContext false + runSuspendCatching { + operationMutex.withLock { + val proof = loadProofs().lastOrNull { + PubkyPublicKeyFormat.matches(it.identity, identity) && it.requestId == request.id && + it.sparkWithdrawal && it.paymentStarted && it.proofData == null + } ?: return@withLock false + releaseUnsentSparkOnchainProofLocked(proof) + true + } + }.onFailure { + Logger.warn("Failed to release a refused Spark withdrawal proof", it, context = TAG) + }.getOrDefault(false) + } + + /** Settles a started Spark proof from Spark's list: completed by its own withdrawal, removed when it never sent. */ + private suspend fun reconcileSparkOnchainProof(proof: PendingPaykitPaymentProof): Boolean { + if (!proof.paymentStarted || proof.proofData != null) return false + val address = proof.onchainAddress ?: return false + val amount = proof.onchainAmountSats ?: return false + val outcome = lightningRepo.sparkWithdrawalOutcome( + address, + amount, + proof.onchainMatchingTransactionIdsBeforeAttempt, + ) + // The request's allowance attempt is settled first: a failed ledger write keeps the proof for the next pass. + return when (outcome) { + is SparkWithdrawalOutcome.Sent -> { + allowanceExecutor.get().onchainSendSettled(proof.identity, proof.requestId, outcome.txid) + completeSparkOnchainProofLocked(proof, outcome.txid) + } + SparkWithdrawalOutcome.Unsent -> { + releaseUnsentSparkOnchainProofLocked(proof) + false + } + SparkWithdrawalOutcome.Unknown -> false + } + } + + private suspend fun releaseUnsentSparkOnchainProofLocked(proof: PendingPaykitPaymentProof) { + allowanceExecutor.get().onchainSendReleased(proof.identity, proof.requestId) + Logger.info("Released a Paykit proof whose Spark withdrawal never sent", context = TAG) + releaseDeniedPrivateConsumption(proof) + removeProofsLocked { it == proof } + // The pending screen of an uncertain Spark send waits on this to fail it. + val release = PaykitSparkWithdrawalRelease(proof.identity, proof.requestId) + _sparkWithdrawalReleases.update { if (release in it) it else it + release } + } + + private suspend fun completeSparkOnchainProofLocked(proof: PendingPaykitPaymentProof, txid: String): Boolean { + val proofs = loadProofs().toMutableList() + val index = proofs.indexOf(proof) + if (index < 0) return false + val completed = proof.copy( + paymentIdentifier = txid.lowercase(), + proofData = txid.lowercase(), + onchainAcceptanceVerified = true, + ) + proofs[index] = completed + // The pending screen of an uncertain Spark send waits on this resolution. + return persistAndSubmit(listOf(completed), proofs).also { publishOnchainResolution(completed, txid) } + } + suspend fun completeLightningPayment(paymentHash: String, preimage: String?) = withContext(ioDispatcher) { if (preimage == null) return@withContext if (!preimage.matchesPaymentHash(paymentHash)) { @@ -1193,7 +1357,10 @@ class PaykitPaymentProofRepo @Inject constructor( }.getOrElse { return@withContext } if (snapshot.isEmpty()) return@withContext finishDeniedHardwarePreparations(snapshot) - snapshot.filter { it.kind == PaykitPaymentProofKind.Onchain && it.onchainWalletId == WalletScope.default } + snapshot.filter { + it.kind == PaykitPaymentProofKind.Onchain && it.onchainWalletId == WalletScope.default && + !it.sparkWithdrawal + } .forEach { proof -> val txid = proof.proofData ?: attempt?.txid val validCompletedProof = proof.paymentStarted && proof.proofData?.isHex(HASH_BYTE_COUNT) == true && @@ -1261,6 +1428,9 @@ class PaykitPaymentProofRepo @Inject constructor( activityReady: Boolean, ): Boolean { if (proof.hardwareDispatchDenied) return false + if (proof.sparkWithdrawal) { + return if (proof.proofData != null) submitReady(proof) else reconcileSparkOnchainProof(proof) + } if (proof.kind == PaykitPaymentProofKind.Onchain && proof.onchainWalletId == WalletScope.default && !activityReady ) { @@ -1459,6 +1629,10 @@ class PaykitPaymentProofRepo @Inject constructor( } } + fun consumeSparkWithdrawalRelease(release: PaykitSparkWithdrawalRelease) { + _sparkWithdrawalReleases.update { it - release } + } + fun consumeOnchainPaymentResolution(resolution: PaykitOnchainPaymentProofResolution) { _onchainPaymentResolutions.update { it - resolution } } diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentRequestRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentRequestRepo.kt index 877c5a0438..30fd34c5bb 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentRequestRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentRequestRepo.kt @@ -340,6 +340,11 @@ class PaykitPaymentRequestRepo @Inject constructor( /** Maximum number of concurrent public capability lookups per discovery. */ private const val PAYMENT_REQUEST_DISCOVERY_CONCURRENCY = 8 + + private val DECLINED_STATES = setOf( + PaymentRequestLifecycleState.REJECTED, + PaymentRequestLifecycleState.CANCELED, + ) } private val operationMutex = Mutex() @@ -1818,6 +1823,7 @@ class PaykitPaymentRequestRepo @Inject constructor( listOf(updatedRequest) + requests.filterNot { it.id == current.id } } _pendingRequests.update { requests -> requests.filterNot { it.id == current.id } } + if (resultingState in DECLINED_STATES) markPresentedLocked(current.id) discardExpiredRequestsLocked() if (resultingState == PaymentRequestLifecycleState.ACCEPTED) { scheduleAcceptedResponse(current.counterparty) @@ -2045,8 +2051,21 @@ class PaykitPaymentRequestRepo @Inject constructor( .onFailure { Logger.warn("Failed to prune accepted Paykit payment requests", it, context = TAG) } } + private suspend fun markPresentedLocked(id: PaykitPaymentRequestId) { + if (id in presentedRequestIds) return + presentedRequestIds = presentedRequestIds + id + val identity = activeIdentity ?: return + runSuspendCatching { presentationStore.save(identity, presentedRequestIds) } + .onFailure { Logger.warn("Failed to persist surfaced Paykit payment requests", it, context = TAG) } + } + + // A request the user declined stays marked while the SDK still lists it, + // so it never pops up again if a later read reports it as proposed. private suspend fun prunePresentedRequestIds(requests: List) { - val requestIds = requests.mapTo(mutableSetOf()) { it.id } + val declinedIds = _paymentRequestHistory.value + .filter { it.direction == PaykitPaymentRequestDirection.Incoming && it.lifecycleState in DECLINED_STATES } + .map { it.id } + val requestIds = requests.mapTo(mutableSetOf()) { it.id } + declinedIds val prunedIds = presentedRequestIds.intersect(requestIds) if (prunedIds == presentedRequestIds) return presentedRequestIds = prunedIds diff --git a/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt new file mode 100644 index 0000000000..395a6fd446 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt @@ -0,0 +1,113 @@ +package to.bitkit.repositories + +import com.synonym.bitkitcore.PaykitEndpoint +import com.synonym.bitkitcore.PaykitRoute +import com.synonym.bitkitcore.PaykitRouteRequest +import com.synonym.bitkitcore.ServiceRouteLeg +import com.synonym.bitkitcore.paykitRoutePayment +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.withContext +import to.bitkit.di.IoDispatcher +import to.bitkit.env.Env +import to.bitkit.ext.runSuspendCatching +import to.bitkit.models.toCoreNetwork +import to.bitkit.services.SparkError +import to.bitkit.utils.AppError +import to.bitkit.utils.Logger +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.time.Instant + +/** + * Picks how to pay a Paykit contact through bitkit-core's Paykit router: directly from a balance the wallet holds, + * or through a Spark withdrawal to the contact's on-chain endpoint when no balance reaches the contact. The router + * makes no network calls; the app quotes each Spark leg only when no balance pays, and runs the one the router returns. + */ +@Singleton +class PaykitRouteRepo @Inject constructor( + @IoDispatcher private val ioDispatcher: CoroutineDispatcher, + private val sparkRepo: SparkRepo, +) { + companion object { + private const val TAG = "PaykitRouteRepo" + } + + /** Whether Spark holds a balance it can send, so a Spark leg may reach a contact no other balance reaches. */ + val canRouteThroughSpark: Boolean + get() = sparkRepo.state.value.let { it.isReady && it.sendableSats > 0uL } + + /** + * Fails with [SparkError.WithdrawalOverBalance] when no route pays because Spark's balance covers the amount but + * not the withdrawal fee on top, so the app tells a short balance from a contact it can't pay, and with + * [SparkError.WithdrawalPending] when only a Spark leg could pay while an earlier contact withdrawal settles. + */ + suspend fun route( + amountSats: ULong, + endpoints: List, + lightningSpendableSats: ULong, + onchainSpendableSats: ULong, + quoteServiceLegs: Boolean, + ): Result = withContext(ioDispatcher) { + runSuspendCatching { + val request = PaykitRouteRequest( + amountSat = amountSats, + contactEndpoints = endpoints, + lightningSpendableSat = lightningSpendableSats, + onchainSpendableSat = onchainSpendableSats, + serviceLegs = emptyList(), + // Only bitkit-core's Pubky Swaps route reads these, and the app never asks it, so no Swap comes back. + providers = emptyList(), + feeRateSatVb = 0uL, + ) + val network = Env.network.toCoreNetwork() + // The router pays directly before it weighs any leg, so legs are quoted only when no balance pays. + val route = paykitRoutePayment(request, network) + if (!quoteServiceLegs || route !is PaykitRoute.None) return@runSuspendCatching route + val quotes = serviceLegQuotes(endpoints, amountSats) + val legs = quotes.mapNotNull { it.getOrNull() } + if (legs.isNotEmpty()) { + return@runSuspendCatching paykitRoutePayment(request.copy(serviceLegs = legs), network) + } + if (quotes.any { it.exceptionOrNull() is SparkError.WithdrawalPending }) { + throw SparkError.WithdrawalPending() + } + if (quotes.any { it.exceptionOrNull() is SparkError.WithdrawalOverBalance }) { + throw SparkError.WithdrawalOverBalance() + } + route + } + } + + /** Spark withdrawals to the contact's on-chain endpoints, each quoted with its fee. */ + private suspend fun serviceLegQuotes( + endpoints: List, + amountSats: ULong, + ): List> = + endpoints.filter { MethodId.fromRawValue(it.methodId)?.isOnchain == true }.map { endpoint -> + sparkRepo.withdrawalRouteLeg(endpoint, amountSats) + .onFailure { Logger.warn("No Spark route to '${endpoint.methodId}'", it, context = TAG) } + } + + /** + * Runs a service leg the router picked to the [contact] and returns the txid that pays them; [onBeforeSend] runs + * once the leg is prepared, right before it sends; past [paymentDeadlineAt] it sends nothing. + */ + suspend fun payServiceLeg( + leg: ServiceRouteLeg, + contact: String?, + tags: List = emptyList(), + paymentDeadlineAt: Instant? = null, + onBeforeSend: suspend () -> Boolean = { true }, + ): Result = when (leg.service) { + SparkRepo.ROUTE_SERVICE -> sparkRepo.withdraw( + address = leg.endpoint.value, + amountSats = leg.deliveredSat, + contact = contact, + maxDebitSats = leg.debitSat, + tags = tags, + paymentDeadlineAt = paymentDeadlineAt, + onBeforeSend = onBeforeSend, + ) + else -> Result.failure(AppError("Unsupported route service '${leg.service}'")) + } +} diff --git a/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt b/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt index 50ae2dba44..9f995ead97 100644 --- a/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PrivatePaykitRepo.kt @@ -1228,6 +1228,10 @@ class PrivatePaykitRepo @Inject constructor( if (!isCurrentPublication(generation, identity, requireImmediatePublication)) return@withLock if (lightningRefresh?.isStillCurrent?.invoke() == false) return@withLock if (publication.updates.isEmpty()) { + Logger.debug( + "Skipped private payment list publication during '$reason': no list changed", + context = TAG, + ) schedulePendingPrivateMessageDrainRetries(reason, links.linkRetryKeys, identity = identity) if (requireImmediatePublication) publication.firstError?.let { throw it } return@withLock @@ -1238,6 +1242,10 @@ class PrivatePaykitRepo @Inject constructor( clearUnlistedLinkedPeers = false, deferDuringPayment = publicationPriority == Priority.Background, ) + Logger.debug( + "Published private payment lists to '${publication.updates.size}' contacts during '$reason'", + context = TAG, + ) val deliveryError = applyPrivatePaymentListDeliveryReport(report, reason, publicationWindow) val firstError = publication.firstError ?: deliveryError val retryKeys = (links.linkRetryKeys + privatePaymentListDeliveryRetryKeys(report)).distinct() diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index e0130e120c..46469b49cd 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -15,8 +15,11 @@ import breez_sdk_spark.SendOnchainFeeQuote import breez_sdk_spark.SendPaymentMethod import com.synonym.bitkitcore.Activity import com.synonym.bitkitcore.LightningActivity +import com.synonym.bitkitcore.OnchainActivity +import com.synonym.bitkitcore.PaykitEndpoint import com.synonym.bitkitcore.PaymentState import com.synonym.bitkitcore.PaymentType +import com.synonym.bitkitcore.ServiceRouteLeg import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList @@ -36,11 +39,14 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull +import kotlinx.serialization.Serializable import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.PaymentFailureReason import org.lightningdevkit.ldknode.PaymentId import to.bitkit.async.appScope import to.bitkit.data.CacheStore +import to.bitkit.data.SettingsStore +import to.bitkit.data.SparkPayoutChain import to.bitkit.di.BgDispatcher import to.bitkit.env.Defaults import to.bitkit.env.Env @@ -50,11 +56,13 @@ import to.bitkit.ext.runSuspendCatching import to.bitkit.models.SparkExitBackupV1 import to.bitkit.models.WalletScope import to.bitkit.models.safe +import to.bitkit.services.CoreService import to.bitkit.services.SparkError import to.bitkit.services.SparkService import to.bitkit.utils.Logger import to.bitkit.utils.ServiceError import java.io.File +import java.util.UUID import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicLong @@ -62,6 +70,7 @@ import javax.inject.Inject import javax.inject.Provider import javax.inject.Singleton import kotlin.time.Clock +import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant import breez_sdk_spark.PaymentType as SparkPaymentType @@ -81,10 +90,15 @@ class SparkRepo @Inject constructor( private val contactResolver: Provider, private val pendingPaymentRepo: PendingPaymentRepo, private val clock: Clock, + private val coreService: Provider, + private val settingsStore: SettingsStore, + private val payoutChain: SparkPayoutChain, ) { companion object { private const val TAG = "SparkRepo" private const val MSATS_PER_SAT = 1_000uL + const val ROUTE_SERVICE = "spark" + private const val ROUTE_ATOMICITY = "trusted" /** How often to look at a deposit until its Instant claim is decided. */ private val CLAIM_POLL_INTERVAL = 5.seconds @@ -100,6 +114,12 @@ class SparkRepo @Inject constructor( /** Tries to learn the outcome of a send whose result was lost while Spark cannot list its payments. */ private const val SETTLE_ATTEMPTS = 10 + /** How long a journaled withdrawal Spark doesn't list stays open before a sync closes it as never sent. */ + private val UNLISTED_WITHDRAWAL_GRACE = 10.minutes + + /** How many sent contact withdrawals stay recorded for a request proof to complete from. */ + private const val MAX_SENT_WITHDRAWALS = 20 + private val SETTLE_RETRY_INTERVAL = 30.seconds /** Seconds a withdrawal quote must still hold to be reused, so it can't expire mid-send. */ @@ -154,6 +174,19 @@ class SparkRepo @Inject constructor( @Volatile private var hasSyncedActivities = false + /** + * A withdrawal's send call is running or its returned payment is being recorded, so its journal entry must not be + * settled before Spark lists it. + */ + @Volatile + private var isWithdrawing = false + + /** Counts withdrawal sends that ended, so a list read before one ended never settles its journal. */ + private val withdrawalSendsEnded = AtomicLong(0) + + /** A withdrawal to a contact holds the one journal slot, from before it prepares until its send call returns. */ + private val isClaimingWithdrawal = AtomicBoolean(false) + /** The remote exit data backup was merged in, or there was none, so an upload cannot drop what it held. */ @Volatile var hasMergedRemoteExitState = false @@ -177,6 +210,10 @@ class SparkRepo @Inject constructor( val nodeEvents: SharedFlow = _nodeEvents.asSharedFlow() private val _exitStateGeneration = MutableStateFlow(0L) + private val _withdrawalSettlements = MutableSharedFlow(extraBufferCapacity = 8) + + /** How each journaled contact withdrawal closed, which a pending send screen waits on. */ + val withdrawalSettlements: SharedFlow = _withdrawalSettlements.asSharedFlow() /** * Counts Spark's connections and changes to its unilateral exit data, so the exit data backup is redone whenever it @@ -193,13 +230,19 @@ class SparkRepo @Inject constructor( restoreUncertainSends() val connected = sparkService.connect(walletIndex) importRestoredExitState(walletIndex) - // The SDK starts syncing inside build(), before the listener exists, so its first Synced can be missed. - runSuspendCatching { sparkService.syncWallet() } - .onSuccess { if (hasSyncedSince(null)) _state.update { it.copy(hasSynced = true) } } + // The SDK starts syncing inside build(), before the listener exists, so its first Synced can be missed. A + // sync that never reached Spark still returns, so only one that did may drop an unlisted withdrawal. + val synced = runSuspendCatching { sparkService.syncWallet() } .onFailure { Logger.warn("Failed to sync Spark after connecting", it, context = TAG) } + .isSuccess && hasSyncedSince(null) + if (synced) _state.update { it.copy(hasSynced = true) } if (connected) _exitStateGeneration.update { it + 1 } refresh() - if (!hasSyncedActivities) hasSyncedActivities = syncActivities() + // Only a full sync settles a pending withdrawal journal, so the sync runs until the journal clears. Only a + // sync that saved every write marks the activities synced, so a failed write is redone on the next start. + if (!hasSyncedActivities || cacheStore.data.first().pendingSparkWithdrawal != null) { + if (syncActivities(settleJournal = synced)) hasSyncedActivities = true + } }.onFailure { Logger.error("Failed to start Spark wallet", it, context = TAG) } @@ -236,6 +279,9 @@ class SparkRepo @Inject constructor( fun canSend(amountSats: ULong): Boolean = _state.value.canSend(amountSats) + /** A withdrawal's debit already holds its fees, so it is weighed against the whole balance. */ + fun canWithdraw(debitSats: ULong): Boolean = _state.value.isReady && _state.value.balanceSats >= debitSats + suspend fun createInvoice(amountSats: ULong?, description: String, expirySecs: UInt): Result = withContext(bgDispatcher) { runSuspendCatching { sparkService.receiveBolt11(amountSats, description, expirySecs) } @@ -629,6 +675,194 @@ class SparkRepo @Inject constructor( return feeSats } + /** + * A Paykit route that withdraws exactly [amountSats] to the contact's on-chain [endpoint] at medium speed, with + * Spark's fee on top, or null while Spark cannot send it. Fails with [SparkError.WithdrawalOverBalance] when the + * balance covers the amount but not the fee on top, and with [SparkError.WithdrawalPending] while an earlier + * contact withdrawal's journal is open, as [withdraw] would refuse it. bitkit-core weighs it against the Pubky + * Swaps providers. + */ + suspend fun withdrawalRouteLeg(endpoint: PaykitEndpoint, amountSats: ULong): Result = + withContext(bgDispatcher) { + runSuspendCatching { + if (cacheStore.data.first().pendingSparkWithdrawal != null) throw SparkError.WithdrawalPending() + if (!canWithdraw(amountSats)) return@runSuspendCatching null + val method = sparkService.prepareSend(endpoint.value, amountSats).paymentMethod + val quote = (method as SendPaymentMethod.BitcoinAddress).feeQuote + // Spark charges its fee and the L1 broadcast fee on top of what reaches the contact. + val speed = quote.speedMedium + val debitSats = amountSats.safe() + (speed.userFeeSat.safe() + speed.l1BroadcastFeeSat.safe()).safe() + if (quote.isEstimate) return@runSuspendCatching null + if (!canWithdraw(debitSats)) throw SparkError.WithdrawalOverBalance() + ServiceRouteLeg( + service = ROUTE_SERVICE, + endpoint = endpoint, + deliveredSat = amountSats, + debitSat = debitSats, + atomicity = ROUTE_ATOMICITY, + validUntilUnix = quote.expiresAt, + ) + } + } + + /** + * Txids of the withdrawals Spark lists or the app recorded as sent to [address], so a new attempt to it can tell + * its own withdrawal apart, also while Spark's list lacks one after a restart. + */ + suspend fun withdrawalTxidsTo(address: String): Set = withContext(bgDispatcher) { + val listed = sparkService.listPayments().mapNotNull { payment -> + (payment.details as? PaymentDetails.Withdraw)?.takeIf { it.destinationAddress == address }?.txId + } + val recorded = cacheStore.data.first().sentSparkWithdrawals.filter { it.address == address }.map { it.txid } + (listed + recorded).toSet() + } + + /** + * Whether [txid] is the sent side of a Spark withdrawal, which LDK never held and so cannot boost. Savings owns the + * output a withdrawal to it pays, so its receipt, not [isSent], can be boosted. + */ + suspend fun isWithdrawal(txid: String, isSent: Boolean): Boolean = withContext(bgDispatcher) { + if (!isSent) return@withContext false + if (cacheStore.data.first().sentSparkWithdrawals.any { it.txid == txid }) return@withContext true + if (!_state.value.isReady) return@withContext false + runSuspendCatching { sparkService.listPayments() } + .onFailure { Logger.warn("Failed to list Spark payments for '$txid'", it, context = TAG) } + .getOrDefault(emptyList()) + .any { (it.details as? PaymentDetails.Withdraw)?.txId == txid } + } + + /** + * What became of an attempt to withdraw exactly [amountSats] to [address]: sent once Spark's synced list holds a + * completed withdrawal to it that is not one of [earlierTxids], unsent once Spark synced and no journaled or + * pending withdrawal to [address] is still settling, else unknown. + */ + suspend fun withdrawalOutcome( + address: String, + amountSats: ULong, + earlierTxids: Set, + ): SparkWithdrawalOutcome = withContext(bgDispatcher) { + // A withdrawal recorded as sent stays sent, also once Spark's list lacks it after a restart. + cacheStore.data.first().sentSparkWithdrawals.firstOrNull { + it.address == address && it.amountSats == amountSats && it.txid !in earlierTxids + }?.let { return@withContext SparkWithdrawalOutcome.Sent(it.txid) } + if (!_state.value.hasSynced || isWithdrawing) return@withContext SparkWithdrawalOutcome.Unknown + val attempts = sparkService.listPayments().filter { payment -> + val withdraw = payment.details as? PaymentDetails.Withdraw ?: return@filter false + withdraw.destinationAddress == address && payment.amount.toLong().toULong() == amountSats && + withdraw.txId !in earlierTxids + } + // Spark keeps a withdrawal pending until its provider accepts the payout, which can still fail it. + val txid = attempts.firstOrNull { it.status == PaymentStatus.COMPLETED } + ?.let { (it.details as PaymentDetails.Withdraw).txId } + when { + txid != null -> SparkWithdrawalOutcome.Sent(txid) + attempts.any { it.status == PaymentStatus.PENDING } -> SparkWithdrawalOutcome.Unknown + cacheStore.data.first().pendingSparkWithdrawal?.address == address -> SparkWithdrawalOutcome.Unknown + else -> SparkWithdrawalOutcome.Unsent + } + } + + /** + * Withdraws exactly [amountSats] to a Paykit [contact]'s on-chain [address] at medium speed and returns the + * withdrawal's txid. A journal entry written before the send lets the next start settle a withdrawal the app was + * killed during, from Spark's payment list, and refuses another withdrawal until then. Past [paymentDeadlineAt], + * it sends nothing. + */ + suspend fun withdraw( + address: String, + amountSats: ULong, + contact: String?, + maxDebitSats: ULong? = null, + tags: List = emptyList(), + paymentDeadlineAt: Instant? = null, + onBeforeSend: suspend () -> Boolean = { true }, + ): Result = + withContext(bgDispatcher) { + runSuspendCatching { + // Claimed before anything suspends, so a second withdrawal started while this one prepares is refused + // instead of overwriting its journal. + if (!isClaimingWithdrawal.compareAndSet(false, true)) throw SparkError.WithdrawalPending() + var journal: PendingSparkWithdrawal? = null + var sendReturned = false + val sent = try { + if (cacheStore.data.first().pendingSparkWithdrawal != null) throw SparkError.WithdrawalPending() + val prepared = sparkService.prepareSend(address, amountSats) + val speed = prepared.withdrawalQuote().speedMedium + val debitSats = + amountSats.safe() + (speed.userFeeSat.safe() + speed.l1BroadcastFeeSat.safe()).safe() + // The user confirmed the leg's debit; a quote that rose since then needs a new confirmation. + if (maxDebitSats != null && debitSats > maxDebitSats) throw SparkError.WithdrawalFeeChanged() + val earlierTxids = withdrawalTxidsTo(address) + // The proof onBeforeSend starts has no journal yet, so the attempt reads as in flight from here on + // and a reconcile meanwhile never drops that proof as unsent. + isWithdrawing = true + if (!onBeforeSend()) throw PaymentAbortedBeforeSend() + // A quote can expire while the request and its allowance are checked. + ensurePaymentDeadline(paymentDeadlineAt) + val opened = PendingSparkWithdrawal( + address, + amountSats, + contact, + earlierTxids, + tags, + startedAt = clock.now().epochSeconds, + paymentId = UUID.randomUUID().toString(), + ) + journal = opened + cacheStore.update { it.copy(pendingSparkWithdrawal = opened) } + // Saving the journal suspends, so the deadline is checked last, before the send. + runCatching { ensurePaymentDeadline(paymentDeadlineAt) }.onFailure { + clearJournal(opened) + throw it + } + runSuspendCatching { sparkService.send(prepared, opened.paymentId) }.also { sendReturned = true } + } finally { + if (!sendReturned) endWithdrawalSend() + isClaimingWithdrawal.set(false) + } + val payment = sent.getOrElse { + endWithdrawalSend() + // Spark selects the leaves to spend before anything goes to the operators, so a short balance left + // nothing and the journal closes at once, as on the Lightning rail. + if (it is SdkException.InsufficientFunds) { + clearJournal(journal) + throw SparkError.SendRefused("Spark balance can't cover the withdrawal", it) + } + // Spark refreshes an expiring quote and checks its fee against the prepared one before it + // withdraws, so a fee rise left nothing too. + if (it.isWithdrawalFeeRise()) { + clearJournal(journal) + throw SparkError.SendRefused("Spark's withdrawal fee rose past its quote", it) + } + // Spark's synced list settles the journal: a listed withdrawal records, an unlisted one drops. A + // sync that never reached Spark still returns, so only one done after the failure drops it. + val failedAt = clock.now().epochSeconds.toULong() + runSuspendCatching { sparkService.syncWallet() } + .onSuccess { syncActivities(settleJournal = hasSyncedSince(failedAt)) } + throw it + } + Logger.info("Sent Spark withdrawal '${payment.id}' with status '${payment.status}'", context = TAG) + // The withdrawal stays in flight until it is recorded, so a sync with an older list can't drop it. + try { + recordActivity(payment) + } finally { + endWithdrawalSend() + } + runSuspendCatching { refresh() }.onFailure { + Logger.warn("Failed to refresh Spark after withdrawal '${payment.id}'", it, context = TAG) + } + // A failed withdrawal paid nothing: its journal closed as recorded, so the caller sees it unsent and + // releases the proof, private list and allowance attempt instead of showing success. + if (payment.status == PaymentStatus.FAILED) throw SparkError.WithdrawalNotSent() + // One still pending can fail until its provider accepts the payout, so its outcome stays unknown, on + // the pending screen, until its journal settles. + if (payment.status != PaymentStatus.COMPLETED) throw SparkError.WithdrawalNotCompleted() + (payment.details as? PaymentDetails.Withdraw)?.txId ?: payment.id + }.onFailure { + Logger.error("Failed to withdraw to a Paykit contact with Spark", it, context = TAG) + } + } + /** * Lists a deposit the app just broadcast as pending right away, then syncs so Spark sees it sooner than its * minute-long background sync; Spark's own deposit state replaces it once listed. @@ -746,6 +980,10 @@ class SparkRepo @Inject constructor( .filter { (it.txid.lowercase() to it.vout) !in claimedOutputs } .map { SparkDeposit(txid = it.txid, amountSats = it.amountSats, isClaimed = false) } (pending + claimed).forEach { broadcastDeposits.remove(it.txid) } + // The open journal's withdrawal pays a contact, also before its send activity is written. + val journal = cacheStore.data.first().pendingSparkWithdrawal + val transfers = payments.filterNot { journal?.matches(it) == true }.toWithdrawals() + .filterNot { isContactWithdrawal(it.txid) }.toImmutableList() val failedAt = withdrawalFailedAtSecs val hasSyncedSince = failedAt != null && info.lastSyncError == null && (info.lastSyncedAt ?: 0uL) > failedAt if (info.balanceSats > 0uL || hasSyncedSince) withdrawalFailedAtSecs = null @@ -763,16 +1001,52 @@ class SparkRepo @Inject constructor( }, pendingDepositSats = pending.sumOf { deposit -> deposit.amountSats }, deposits = (pending + claimed).toImmutableList(), - withdrawals = payments.toWithdrawals(), + withdrawals = transfers, ).withBroadcastDeposits() } markClaimedDeposits(claimed) payments .filter { it.id in unsavedPayments || (it.id in sendsRecordedWithoutFee && it.fees.toLong() > 0) } .forEach { recordActivity(it) } + // Off the refresh, so a slow Electrum server never holds a send that waits for it. + scope.launch { confirmMinedPayouts(payments) } markTransfers(payments) } + /** + * Spark lists a withdrawal completed once its provider took the payout on, which can be before the payout + * transaction is broadcast or mined, so a contact withdrawal's sent activity is confirmed only once its payout is + * in a block. The payout address's unspent outputs show that first; an output missing there, such as one the + * contact spent before Bitkit saw it mined, is looked up by its transaction instead. + */ + private suspend fun confirmMinedPayouts(payments: List) { + payments.filter { it.status == PaymentStatus.COMPLETED && it.paymentType == SparkPaymentType.SEND } + .forEach { payment -> + val withdraw = payment.details as? PaymentDetails.Withdraw ?: return@forEach + unconfirmedSent(withdraw.txId) ?: return@forEach + val outputs = runSuspendCatching { + coreService.get().onchain.unspentOutputs( + address = withdraw.destinationAddress, + electrumUrl = settingsStore.data.first().electrumServer, + network = Env.network, + ) + }.onFailure { + Logger.warn("Failed to look up Spark withdrawal payout '${withdraw.txId}'", it, context = TAG) + }.getOrNull() + // A failed Electrum lookup falls through to the transaction's status, as a missing output does. + val payout = outputs?.firstOrNull { it.txid == withdraw.txId && it.vout == withdraw.vout } + val isMined = payout?.let { it.confirmations > 0u } ?: (payoutChain.isMined(withdraw.txId) == true) + if (!isMined) return@forEach + // Read again after the lookups, so a seen time written meanwhile isn't written back over. + val latest = unconfirmedSent(withdraw.txId) ?: return@forEach + activityRepo.get().upsertActivity(Activity.Onchain(latest.copy(confirmed = true))) + } + } + + private suspend fun unconfirmedSent(txid: String) = + (activityRepo.get().getActivity(txid).getOrNull() as? Activity.Onchain)?.v1 + ?.takeIf { it.txType == PaymentType.SENT && !it.confirmed } + private fun markClaimedDeposits(claimed: List) { val claimedTxids = claimed.map { it.txid.lowercase() }.toSet() _depositClaims.update { claims -> @@ -794,6 +1068,10 @@ class SparkRepo @Inject constructor( } .toImmutableList() + /** A withdrawal to a Paykit contact is recorded as an on-chain send: it is no Transfer to Savings. */ + private suspend fun isContactWithdrawal(txid: String): Boolean = + (activityRepo.get().getActivity(txid).getOrNull() as? Activity.Onchain)?.v1?.txType == PaymentType.SENT + /** * Marks the on-chain receive [txid] as a transfer from Spending when it is a Spark withdrawal, so it shows no * Received sheet and reads as a transfer in Activity. Returns whether it is one. @@ -802,7 +1080,7 @@ class SparkRepo @Inject constructor( val isWithdrawal = txid in withdrawalTxids || _state.value.withdrawals.any { it.txid == txid } if (!isWithdrawal) return@withContext false val activities = activityRepo.get() - activities.getOnchainActivityByTxId(txid)?.takeUnless { it.isTransfer }?.let { + activities.getOnchainActivityByTxId(txid)?.takeUnless { it.isTransfer || it.txType == PaymentType.SENT }?.let { activities.updateActivity(it.id, Activity.Onchain(it.copy(isTransfer = true))) } true @@ -813,7 +1091,9 @@ class SparkRepo @Inject constructor( payments.filter { it.status != PaymentStatus.FAILED } .mapNotNull { (it.details as? PaymentDetails.Withdraw)?.txId } .forEach { txid -> - val activity = activities.getOnchainActivityByTxId(txid)?.takeUnless { it.isTransfer } ?: return@forEach + // A withdrawal to a Paykit contact is a send of its own; only an arrival in Savings is a transfer. + val activity = activities.getOnchainActivityByTxId(txid) + ?.takeUnless { it.isTransfer || it.txType == PaymentType.SENT } ?: return@forEach activities.updateActivity(activity.id, Activity.Onchain(activity.copy(isTransfer = true))) } } @@ -1104,16 +1384,72 @@ class SparkRepo @Inject constructor( cacheStore.seedSparkSendHashes(sends.mapNotNull { it.sendHash() }, expiries) } - /** Records every Spark payment, returning whether all were saved, so a failed write leaves the sync to redo. */ - private suspend fun syncActivities(): Boolean { + /** + * Records Spark's payments as activity, returning whether all were saved, so a failed write leaves the sync to + * redo. With [settleJournal], after a sync that just succeeded, a journaled withdrawal the list still lacks never + * sent, unless it is still being sent in this process or started less than [UNLISTED_WITHDRAWAL_GRACE] ago. + */ + private suspend fun syncActivities(settleJournal: Boolean): Boolean { // Read after the records, as a send counts as in flight before it is recorded, so one of the two shows it. val recordsBefore = sendRecords.get() val inFlightBefore = sendsInFlight.keys.toSet() + // A list read while a withdrawal was in flight, or before one ended, may lack it, so it settles no journal. + val sendsEndedBefore = withdrawalSendsEnded.get() + val wasWithdrawing = isWithdrawing // Read before the list, as one read before Spark's first sync can lack its restored sends. val isSynced = canListPayments() val payments = sparkService.listPayments() if (isSynced) seedSendHashes(payments) val isSaved = payments.map { recordActivity(it) }.all { it } + releaseFailedSends(payments, recordsBefore, inFlightBefore) + if (!settleJournal || wasWithdrawing || isWithdrawing || withdrawalSendsEnded.get() != sendsEndedBefore) { + return isSaved + } + val journal = cacheStore.data.first().pendingSparkWithdrawal ?: return isSaved + // A listed withdrawal whose activity failed to save keeps its journal for the next sync to retry; one Spark + // failed before it had withdrawal details never pays out. + val isListed = payments.any { + journal.matches(it) && (it.details is PaymentDetails.Withdraw || it.status != PaymentStatus.FAILED) + } + if (isListed) return isSaved + // Spark may list a withdrawal it just sent only on a later sync, so an unlisted one stays open for a while. + if (clock.now().epochSeconds < journal.startedAt + UNLISTED_WITHDRAWAL_GRACE.inWholeSeconds) return isSaved + Logger.warn("Dropped Spark withdrawal to '${journal.address}' that Spark never sent", context = TAG) + if (clearJournal(journal)) { + _withdrawalSettlements.emit(SparkWithdrawalSettlement(journal.address, journal.amountSats, null)) + } + return isSaved + } + + private fun endWithdrawalSend() { + isWithdrawing = false + withdrawalSendsEnded.incrementAndGet() + } + + /** + * Clears [journal] only while it is still the open one, so a stale settle never drops a newer withdrawal's. Returns + * whether it cleared it: only then is the settlement this attempt's to announce. + */ + private suspend fun clearJournal(journal: PendingSparkWithdrawal, sentTxid: String? = null): Boolean { + var cleared = false + cacheStore.update { + cleared = it.pendingSparkWithdrawal == journal + if (!cleared) return@update it + // The request's proof completes after the journal clears, so the sent withdrawal it records outlives it. + val sent = sentTxid?.let { txid -> SentSparkWithdrawal(journal.address, journal.amountSats, txid) } + it.copy( + pendingSparkWithdrawal = null, + sentSparkWithdrawals = (it.sentSparkWithdrawals + listOfNotNull(sent)).takeLast(MAX_SENT_WITHDRAWALS), + ) + } + return cleared + } + + private suspend fun releaseFailedSends( + payments: List, + recordsBefore: Long, + inFlightBefore: Set, + ) { val sendHashes = { status: PaymentStatus -> payments.mapNotNullTo(mutableSetOf()) { it.sendHash(status)?.lowercase() } } @@ -1133,18 +1469,17 @@ class SparkRepo @Inject constructor( // retry of it is still live. val failed = payments.mapNotNull { it.sendHash(PaymentStatus.FAILED) }.distinct() .filter { payments.latestSend(it)?.status == PaymentStatus.FAILED } - if (failed.isEmpty()) return isSaved + if (failed.isEmpty()) return // A retry can start while the list is recorded, so the release reads Spark's sends again first. val recordsBeforeCurrent = sendRecords.get() val inFlightBeforeCurrent = sendsInFlight.keys.toSet() - val current = runSuspendCatching { sparkService.listPayments() }.getOrNull() ?: return isSaved + val current = runSuspendCatching { sparkService.listPayments() }.getOrNull() ?: return val liveCurrent = sendsInFlight.keys + inFlightBeforeCurrent + recordedSince(recordsBeforeCurrent) + uncertainSendHashes() failed .filter { it.lowercase() !in liveCurrent } .filter { current.latestSend(it)?.status == PaymentStatus.FAILED } .forEach { cacheStore.removeSparkSendHash(it) } - return isSaved } private fun recordedSince(records: Long): Set = sendRecordedAt.filterValues { it > records }.keys @@ -1164,10 +1499,16 @@ class SparkRepo @Inject constructor( refresh() // A send whose outcome stayed unknown past its polling settles on a later sync. uncertainSends.keys.toList().forEach { trySettleUncertainSend(it) } + // A journal left open past its grace period would block every later withdrawal until a restart. + // Spark emits Synced after a sync that never reached it too, so only one since the journal + // drops it. + cacheStore.data.first().pendingSparkWithdrawal?.let { + syncActivities(settleJournal = hasSyncedSince(it.startedAt.toULong())) + } } is SdkEvent.PaymentSucceeded -> onPayment(event.payment) is SdkEvent.PaymentFailed -> onPayment(event.payment) - is SdkEvent.PaymentPending -> recordActivity(event.payment) + is SdkEvent.PaymentPending -> recordActivity(event.payment, settlesJournal = false) is SdkEvent.UnclaimedDeposits -> Logger.warn( "Found '${event.unclaimedDeposits.size}' unclaimed Spark deposits", context = TAG, @@ -1186,7 +1527,7 @@ class SparkRepo @Inject constructor( // The event carries its outcome, so a failed balance read never holds back its settlement. runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after payment '${payment.id}'", it, context = TAG) } - recordActivity(payment) + recordActivity(payment, settlesJournal = false) // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. payment.sendHash()?.let { uncertainSends.remove(it.lowercase()) @@ -1201,8 +1542,13 @@ class SparkRepo @Inject constructor( payment.toNodeEvent()?.let { _nodeEvents.emit(it) } } - /** Returns whether the payment's activity is saved; a failed write is kept in [unsavedPayments]. */ - private suspend fun recordActivity(payment: Payment): Boolean { + /** + * Records [payment] as activity and returns whether it is saved; a failed write is kept in [unsavedPayments]. Only + * Spark's list or its send response [settlesJournal]: a payment event can come before the list holds the + * withdrawal, which recovery reads, so its journal stays open until the list shows it. + */ + private suspend fun recordActivity(payment: Payment, settlesJournal: Boolean = true): Boolean { + (payment.details as? PaymentDetails.Withdraw)?.let { return recordWithdrawal(payment, it, settlesJournal) } val lightning = payment.details as? PaymentDetails.Lightning ?: return true if (payment.status == PaymentStatus.PENDING && payment.paymentType == SparkPaymentType.RECEIVE) { return true @@ -1266,6 +1612,67 @@ class SparkRepo @Inject constructor( return true } + /** + * Records a withdrawal to a Paykit contact as an on-chain send, settling the journal entry it matches. Transfers to + * Savings have no row here: the node lists their arrival as the transfer. + */ + private suspend fun recordWithdrawal( + payment: Payment, + withdraw: PaymentDetails.Withdraw, + settlesJournal: Boolean, + ): Boolean { + val txid = withdraw.txId + // A failed read would drop the stored contact and seen time, so the write waits for the next refresh. + val stored = activityRepo.get().getActivity(txid).getOrElse { + unsavedPayments.add(payment.id) + return false + } + val existing = (stored as? Activity.Onchain)?.v1?.takeIf { it.txType == PaymentType.SENT } + val journal = cacheStore.data.first().pendingSparkWithdrawal?.takeIf { it.matches(payment) } + if (existing == null && journal == null) return true + val activity = OnchainActivity.create( + id = txid, + txType = PaymentType.SENT, + txId = txid, + value = payment.amount.toLong().toULong(), + fee = payment.fees.toLong().toULong(), + address = withdraw.destinationAddress, + timestamp = payment.timestamp, + // Spark completes a withdrawal before its payout is mined, so only the chain confirms it. + confirmed = existing?.confirmed == true, + doesExist = payment.status != PaymentStatus.FAILED, + contact = existing?.contact ?: journal?.contact, + seenAt = existing?.seenAt, + ) + // The journal stays until the activity is saved, so a failed save is retried from Spark's list and on refresh. + val upserted = activityRepo.get().upsertActivity(Activity.Onchain(activity)) + .onFailure { Logger.warn("Failed to record Spark withdrawal '$txid'", it, context = TAG) } + val isDeleted = upserted.exceptionOrNull() is ActivityDeletedError + val saved = upserted.isSuccess || isDeleted + if (!saved) { + unsavedPayments.add(payment.id) + return false + } + unsavedPayments.remove(payment.id) + // A pending withdrawal can still fail, so only a completed or failed one closes its journal. + if (journal != null && settlesJournal && payment.status != PaymentStatus.PENDING) { + // The tags picked on Confirm travel with the journal, so a recovered withdrawal keeps them too. + // A failed tag write keeps the journal, so the next refresh tags it again; a deleted activity takes none. + if (journal.tags.isNotEmpty() && !isDeleted) { + activityRepo.get().addTagsToActivity(txid, journal.tags).onFailure { + Logger.warn("Failed to tag Spark withdrawal '$txid'", it, context = TAG) + unsavedPayments.add(payment.id) + return false + } + } + val sentTxid = txid.takeIf { payment.status == PaymentStatus.COMPLETED } + if (clearJournal(journal, sentTxid)) { + _withdrawalSettlements.emit(SparkWithdrawalSettlement(journal.address, journal.amountSats, sentTxid)) + } + } + return true + } + private suspend fun receivedContact(payment: Payment, paymentHash: String): String? { if (payment.paymentType != SparkPaymentType.RECEIVE || payment.status == PaymentStatus.FAILED) return null if (cacheStore.data.first().isContactDetached(paymentHash, WalletScope.default)) return null @@ -1298,6 +1705,57 @@ class SparkRepo @Inject constructor( private fun PrepareSendPaymentResponse.withdrawalQuote(): SendOnchainFeeQuote = (paymentMethod as SendPaymentMethod.BitcoinAddress).feeQuote +/** A withdrawal to a Paykit contact that started and that Spark's payment list has not settled yet. */ +@Serializable +data class PendingSparkWithdrawal( + val address: String, + val amountSats: ULong, + val contact: String?, + /** Withdrawals to [address] listed before this attempt, which never settle it. */ + val earlierTxids: Set = emptySet(), + val tags: List = emptyList(), + /** Epoch seconds the attempt started, which keeps it open while Spark may still list it. */ + val startedAt: Long = 0, + /** The idempotency key the send passed, which Spark keeps as the payment's id. */ + val paymentId: String? = null, +) { + /** + * Whether Spark lists [payment] for this attempt: by [paymentId], also while Spark lists it without withdrawal + * details, or by address and amount. + */ + fun matches(payment: Payment): Boolean { + if (paymentId != null && payment.id == paymentId) return true + val withdraw = payment.details as? PaymentDetails.Withdraw ?: return false + return address == withdraw.destinationAddress && amountSats == payment.amount.toLong().toULong() && + withdraw.txId !in earlierTxids + } +} + +/** A withdrawal to a Paykit contact that Spark sent as [txid]. */ +@Serializable +data class SentSparkWithdrawal( + val address: String, + val amountSats: ULong, + val txid: String, +) + +/** A journaled withdrawal to [address] closed: sent as [txid], or never sent when [txid] is null. */ +data class SparkWithdrawalSettlement( + val address: String, + val amountSats: ULong, + val txid: String?, +) + +/** What became of a Spark withdrawal attempt, from Spark's payment list. */ +sealed interface SparkWithdrawalOutcome { + data class Sent(val txid: String) : SparkWithdrawalOutcome + + /** Spark synced, holds no withdrawal for the attempt and has none settling: it never sent. */ + data object Unsent : SparkWithdrawalOutcome + + data object Unknown : SparkWithdrawalOutcome +} + private class PreparedWithdrawal( val address: String, val balanceSats: ULong, @@ -1525,6 +1983,13 @@ sealed interface SparkClaimStep { internal fun SdkException.InvalidInput.isBelowMinimum(): Boolean = v1.startsWith("Amount is below the minimum", ignoreCase = true) +/** + * Spark refuses a withdrawal whose refreshed fee quote costs more than the prepared one, even at its slowest speed, + * with this input error before it withdraws (`affordable_speed` in the 0.28.0 SDK's `send/bitcoin_address.rs`). + */ +internal fun Throwable.isWithdrawalFeeRise(): Boolean = + this is SdkException.InvalidInput && v1.contains("onchain fee rose to", ignoreCase = true) + /** Spark refuses an expired Lightning invoice with this input error, at prepare and again at send. */ internal fun Throwable.isInvoiceExpired(): Boolean = this is SdkException.InvalidInput && v1.contains("invoice has expired", ignoreCase = true) diff --git a/app/src/main/java/to/bitkit/services/CoreService.kt b/app/src/main/java/to/bitkit/services/CoreService.kt index c8b3b80eb1..93b58528a3 100644 --- a/app/src/main/java/to/bitkit/services/CoreService.kt +++ b/app/src/main/java/to/bitkit/services/CoreService.kt @@ -1,6 +1,7 @@ package to.bitkit.services import com.synonym.bitkitcore.AccountType +import com.synonym.bitkitcore.AccountUtxo import com.synonym.bitkitcore.Activity import com.synonym.bitkitcore.ActivityFilter import com.synonym.bitkitcore.ActivityTags @@ -45,6 +46,7 @@ import com.synonym.bitkitcore.getTags import com.synonym.bitkitcore.initDb import com.synonym.bitkitcore.insertActivity import com.synonym.bitkitcore.onchainBroadcastRawTx +import com.synonym.bitkitcore.onchainGetAddressInfo import com.synonym.bitkitcore.openChannel import com.synonym.bitkitcore.prepareLegacyRnNativeSegwitRecoverySweep import com.synonym.bitkitcore.refreshActiveCjitEntries @@ -2392,6 +2394,17 @@ class OnchainService { } } + /** The outputs [address] holds unspent on chain, each with its confirmations, as [electrumUrl] lists them. */ + suspend fun unspentOutputs(address: String, electrumUrl: String, network: Network?): List { + return ServiceQueue.CORE.background { + onchainGetAddressInfo( + address = address, + electrumUrl = electrumUrl, + network = network?.toCoreNetwork(), + ).utxos + } + } + suspend fun broadcastRawTx( serializedTx: String, electrumUrl: String, diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index f7488d1ac3..e82d8e302e 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -238,13 +238,14 @@ class SparkService @Inject constructor( ), ) - suspend fun send(prepared: PrepareSendPaymentResponse): Payment { + /** Sends [prepared]; Spark makes one payment per [idempotencyKey], a UUID that becomes the payment's id. */ + suspend fun send(prepared: PrepareSendPaymentResponse, idempotencyKey: String? = null): Payment { val options = when (prepared.paymentMethod) { is SendPaymentMethod.Bolt11Invoice -> bolt11SendOptions(prefersSpark) is SendPaymentMethod.BitcoinAddress -> SendPaymentOptions.BitcoinAddress(OnchainConfirmationSpeed.MEDIUM) else -> null } - return requireSdk().sendPayment(SendPaymentRequest(prepared, options)).payment + return requireSdk().sendPayment(SendPaymentRequest(prepared, options, idempotencyKey)).payment } /** The fastest recommended fee rate, in sat/vB, from the SDK's own fee source. */ @@ -311,6 +312,17 @@ 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") + + /** 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") + + /** Spark's list shows the withdrawal never went out. */ + class WithdrawalNotSent : SparkError("Spark never sent the withdrawal") + + /** Spark returned the withdrawal as pending, which it can still fail, so its outcome is not known yet. */ + class WithdrawalNotCompleted : SparkError("Spark has not completed the withdrawal yet") + /** * Spark refused a Lightning payment before anything left the wallet: it was not connected, could not prepare the * payment, or its fee was over the caller's limit; or the node refused one because Spark hadn't listed its earlier diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt index e1f923fbb6..cc3fdc36b4 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityDetailScreen.kt @@ -188,11 +188,16 @@ fun ActivityDetailScreen( val boostSheetVisible by detailViewModel.boostSheetVisible.collectAsStateWithLifecycle() var showAddTagSheet by remember { mutableStateOf(false) } var isCpfpChild by remember { mutableStateOf(false) } + var isSparkWithdrawal by remember { mutableStateOf(false) } var boostTxDoesExist by remember { mutableStateOf>(persistentMapOf()) } LaunchedEffect(item) { if (item is Activity.Onchain) { isCpfpChild = detailViewModel.isCpfpChildTransaction(item.v1.txId) + isSparkWithdrawal = detailViewModel.isSparkWithdrawal( + item.v1.txId, + isSent = item.v1.txType == PaymentType.SENT, + ) boostTxDoesExist = if (item.v1.boostTxIds.isNotEmpty()) { detailViewModel.getBoostTxDoesExist(item.v1.boostTxIds) } else { @@ -200,6 +205,7 @@ fun ActivityDetailScreen( } } else { isCpfpChild = false + isSparkWithdrawal = false boostTxDoesExist = persistentMapOf() } } @@ -246,6 +252,7 @@ fun ActivityDetailScreen( detailViewModel = detailViewModel, isCpfpChild = isCpfpChild, isHardware = uiState.isHardwareActivity, + isSparkWithdrawal = isSparkWithdrawal, showContactActions = isPaykitEnabled && (!uiState.isHardwareActivity || assignedContact != null), boostTxDoesExist = boostTxDoesExist, @@ -339,6 +346,7 @@ private fun ActivityDetailContent( detailViewModel: ActivityDetailViewModel? = null, isCpfpChild: Boolean = false, isHardware: Boolean = false, + isSparkWithdrawal: Boolean = false, showContactActions: Boolean = true, boostTxDoesExist: ImmutableMap = persistentMapOf(), onCopy: (String) -> Unit, @@ -676,7 +684,8 @@ private fun ActivityDetailContent( } } } - val shouldEnable = shouldEnableBoostButton(item, isCpfpChild, isHardware, boostTxDoesExist) + val shouldEnable = !isSparkWithdrawal && + shouldEnableBoostButton(item, isCpfpChild, isHardware, boostTxDoesExist) PrimaryButton( text = stringResource( if (hasCompletedBoost) { 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 fd0ea27efc..e17a8d0949 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 @@ -272,7 +272,7 @@ internal fun SendConfirmContent( ) .navigationBarsPadding() ) { - val isLnurlPay = uiState.lnurl is LnurlParams.LnurlPay + val isLnurlPay = uiState.paysLnurl SendContactTopBar( titleText = when { @@ -365,7 +365,7 @@ private fun ContentRunning( var showDetails by rememberSaveable(initialShowDetails) { mutableStateOf(initialShowDetails) } val swipeProgress = remember { mutableFloatStateOf(0f) } val isPreparing = preparingRequest != null - val isLnurlPay = !isPreparing && uiState.lnurl is LnurlParams.LnurlPay + val isLnurlPay = !isPreparing && uiState.paysLnurl val isHardwareFeeLoading = uiState.hardwareWalletId != null && uiState.onchainFeeUi.isLoading val accentColor = when { @@ -453,7 +453,8 @@ private fun ContentRunning( onClickTag = onClickTag, onClickAddTag = onClickAddTag, ) - if ((uiState.lnurl as? LnurlParams.LnurlPay)?.data?.commentAllowed() == true) { + val lnurlPay = uiState.lnurl as? LnurlParams.LnurlPay + if (uiState.paysLnurl && lnurlPay?.data?.commentAllowed() == true) { LnurlCommentSection(uiState, onEvent) } } @@ -737,13 +738,14 @@ private fun LightningDetails( onClickAddTag: () -> Unit, modifier: Modifier = Modifier, ) { - val isLnurlPay = uiState.lnurl is LnurlParams.LnurlPay + val isLnurlPay = uiState.paysLnurl val expirySeconds = uiState.decodedInvoice?.expirySeconds val description = uiState.decodedInvoice?.description - val destination = when (val lnurl = uiState.lnurl) { - is LnurlParams.LnurlPay -> lnurl.data.uri - else -> uiState.decodedInvoice?.bolt11.orEmpty() - } + val destination = uiState.routedPaykitRoute?.serviceLeg?.endpoint?.value + ?: when (val lnurl = uiState.lnurl) { + is LnurlParams.LnurlPay -> lnurl.data.uri + else -> uiState.decodedInvoice?.bolt11.orEmpty() + } Column( verticalArrangement = Arrangement.spacedBy(16.dp), @@ -868,6 +870,16 @@ private fun LightningDetails( } } + if (uiState.routedPaykitRoute?.serviceLeg != null) { + SendCell(caption = stringResource(R.string.wallet__send_swap_route)) { + BodySSB( + text = stringResource(R.string.wallet__send_swap_route_spark), + maxLines = 1, + modifier = Modifier.testTag("ReviewSwapRoute") + ) + } + } + if (!isLnurlPay && !description.isNullOrEmpty() && description.trim() != uiState.confirmationRequestNote) { SendCell(caption = stringResource(R.string.wallet__note)) { Row(modifier = Modifier.horizontalScroll(rememberScrollState())) { @@ -911,6 +923,10 @@ private fun ContactRecipient( } } +/** An on-chain pick or a Spark leg keeps the contact's LNURL in state without paying it. */ +private val SendUiState.paysLnurl: Boolean + get() = lnurl is LnurlParams.LnurlPay && payMethod == SendMethod.LIGHTNING && routedPaykitRoute?.serviceLeg == null + private val SendUiState.confirmationRequestNote: String? get() = paymentRequestNote?.trim()?.takeIf { isPaymentRequest && it.isNotEmpty() } diff --git a/app/src/main/java/to/bitkit/viewmodels/ActivityDetailViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/ActivityDetailViewModel.kt index 737ecec921..85f6732e2e 100644 --- a/app/src/main/java/to/bitkit/viewmodels/ActivityDetailViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/ActivityDetailViewModel.kt @@ -33,6 +33,7 @@ import to.bitkit.models.WalletScope import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.BlocktankRepo import to.bitkit.repositories.HwWalletRepo +import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.TransferRepo import to.bitkit.utils.Logger import javax.inject.Inject @@ -46,6 +47,7 @@ class ActivityDetailViewModel @Inject constructor( private val blocktankRepo: BlocktankRepo, private val hwWalletRepo: HwWalletRepo, private val transferRepo: TransferRepo, + private val sparkRepo: SparkRepo, ) : ViewModel() { private val _txDetails = MutableStateFlow(null) val txDetails = _txDetails.asStateFlow() @@ -270,6 +272,8 @@ class ActivityDetailViewModel @Inject constructor( suspend fun getBoostTxDoesExist(boostTxIds: List): ImmutableMap = activityRepo.getBoostTxDoesExist(boostTxIds, currentWalletId).toImmutableMap() + suspend fun isSparkWithdrawal(txId: String, isSent: Boolean): Boolean = sparkRepo.isWithdrawal(txId, isSent) + suspend fun isCpfpChildTransaction(txId: String): Boolean { return activityRepo.isCpfpChildTransaction(txId, currentWalletId) } diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 69a30da646..1c93230e4b 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -27,8 +27,11 @@ import com.synonym.bitkitcore.LnurlChannelData import com.synonym.bitkitcore.LnurlPayData import com.synonym.bitkitcore.LnurlWithdrawData import com.synonym.bitkitcore.OnChainInvoice +import com.synonym.bitkitcore.PaykitEndpoint +import com.synonym.bitkitcore.PaykitRoute import com.synonym.bitkitcore.PaymentType import com.synonym.bitkitcore.Scanner +import com.synonym.bitkitcore.ServiceRouteLeg import com.synonym.bitkitcore.SortDirection import com.synonym.bitkitcore.UsdtQuote import com.synonym.paykit.PaymentConversion @@ -203,6 +206,8 @@ import to.bitkit.repositories.PaykitPaymentRequestId import to.bitkit.repositories.PaykitPaymentRequestRefreshMode import to.bitkit.repositories.PaykitPaymentRequestRepo import to.bitkit.repositories.PaykitPaymentRequestTarget +import to.bitkit.repositories.PaykitRouteRepo +import to.bitkit.repositories.PaykitSparkWithdrawalRelease import to.bitkit.repositories.PaykitSubscription import to.bitkit.repositories.PaykitSubscriptionDraft import to.bitkit.repositories.PaykitSubscriptionId @@ -223,6 +228,8 @@ import to.bitkit.repositories.PublicPaykitRepo import to.bitkit.repositories.QuickPayPaymentFailedError import to.bitkit.repositories.QuickPayRepo import to.bitkit.repositories.SamRockRepo +import to.bitkit.repositories.SparkWithdrawalOutcome +import to.bitkit.repositories.SparkWithdrawalSettlement import to.bitkit.repositories.TransferRepo import to.bitkit.repositories.UsdtPreferencesRepo import to.bitkit.repositories.UsdtRepo @@ -260,6 +267,7 @@ import to.bitkit.utils.AppError import to.bitkit.utils.ClipboardPromptValidator import to.bitkit.utils.Logger import to.bitkit.utils.NetworkValidationHelper +import to.bitkit.utils.ServiceError import to.bitkit.utils.jsonLogOf import to.bitkit.utils.timedsheets.TimedSheetManager import to.bitkit.utils.timedsheets.sheets.AppUpdateTimedSheet @@ -324,6 +332,7 @@ class AppViewModel @Inject constructor( private val paykitPaymentRequestDiagnostics: PaykitPaymentRequestDiagnostics, private val refreshContactPaykitLink: RefreshContactPaykitLinkUseCase, private val usdtRepo: UsdtRepo, + private val paykitRouteRepo: PaykitRouteRepo, val paykitUsdtPayments: PaykitUsdtPaymentRepo, private val samRockRepo: SamRockRepo, private val appUpdateSheet: AppUpdateTimedSheet, @@ -473,6 +482,10 @@ class AppViewModel @Inject constructor( private val processedPaymentsLock = Any() private val processedPayments = mutableSetOf() private val contactPaymentContextLock = Any() + + /** The Paykit router was asked for this payment's way on Continue or a request's confirm, so a switch reroutes. */ + @Volatile + private var paykitRouteDecided = false private var activeContactPaymentContext: ContactPaymentContext? = null val usdtWallet = usdtRepo.state val isUsdtEnabled = usdtPreferences.enabled.stateIn(viewModelScope, SharingStarted.Eagerly, false) @@ -554,6 +567,10 @@ class AppViewModel @Inject constructor( private var deferredSubscriptionNotification: SubscriptionNotificationTarget? = null private var requestedPaymentRequestTags: ImmutableList = persistentListOf() private var uncertainOnchainPaymentRequestId: PaykitPaymentRequestId? = null + + /** The address and amount of the uncertain Spark withdrawal to a contact a pending screen waits on. */ + @Volatile + private var uncertainSparkWithdrawal: Pair? = null private var isPresentingPaymentRequest = false private val isPaymentRequestPollingStopped = MutableStateFlow(false) private var isPaymentRequestOverlayVisible = false @@ -793,6 +810,8 @@ class AppViewModel @Inject constructor( observePaykitPaymentRequestConnectivity() observeIncomingPaykitPaymentRequests() observePaykitOnchainPaymentResolution() + observePaykitSparkWithdrawalReleases() + observeSparkWithdrawalSettlements() observePaykitAllowanceEvents() observeSendEvents() viewModelScope.launch { @@ -1164,6 +1183,52 @@ class AppViewModel @Inject constructor( } } + private fun observeSparkWithdrawalSettlements() { + viewModelScope.launch { + lightningRepo.sparkWithdrawalSettlements.collect(::handleSparkWithdrawalSettlement) + } + } + + private fun handleSparkWithdrawalSettlement(settlement: SparkWithdrawalSettlement) { + if (uncertainSparkWithdrawal != (settlement.address to settlement.amountSats)) return + uncertainSparkWithdrawal = null + if (_currentSheet.value !is Sheet.Send) return + val txid = settlement.txid + if (txid != null) { + onSendSuccess(sparkWithdrawalSent(txid, settlement.amountSats)) + return + } + setSendEffect(SendEffect.NavigateToError(SparkError.WithdrawalNotSent().toSendFailureDetails(context))) + } + + private fun sparkWithdrawalSent(txid: String, amountSats: ULong) = NewTransactionSheetDetails( + type = NewTransactionSheetType.ONCHAIN, + direction = NewTransactionSheetDirection.SENT, + paymentHashOrTxId = txid, + sats = amountSats.toLong(), + ) + + private fun observePaykitSparkWithdrawalReleases() { + viewModelScope.launch { + combine(paykitPaymentProofRepo.sparkWithdrawalReleases, pubkyRepo.publicKey) { releases, _ -> + releases + }.collect { releases -> + releases.forEach(::handlePaykitSparkWithdrawalRelease) + } + } + } + + private fun handlePaykitSparkWithdrawalRelease(release: PaykitSparkWithdrawalRelease) { + if (!PubkyPublicKeyFormat.matches(pubkyRepo.publicKey.value, release.identity)) return + paykitPaymentProofRepo.consumeSparkWithdrawalRelease(release) + if (uncertainOnchainPaymentRequestId != release.requestId || _currentSheet.value !is Sheet.Send) return + uncertainOnchainPaymentRequestId = null + // Spark never sent it and its proof is released, so the request can be tried again. + setSendEffect( + SendEffect.NavigateToError(SparkError.WithdrawalNotSent().toSendFailureDetails(context)), + ) + } + private fun handlePaykitOnchainPaymentResolution(resolution: PaykitOnchainPaymentProofResolution) { if (!PubkyPublicKeyFormat.matches(pubkyRepo.publicKey.value, resolution.identity)) return if (resolution.walletId != WalletScope.default) { @@ -4052,14 +4117,30 @@ class AppViewModel @Inject constructor( val canUseOnchain = address.isNotEmpty() && walletRepo.balanceState.value.maxSendOnchainSats > Defaults.dustLimit.toULong() val useUsdt = recipient != null && prefersUsdt(payment, hasBitcoinEndpoint, canUseLightning || canUseOnchain) - val payMethod = paykitBitcoinMethod(canUseLightning, address, invoice, lnurl) + // The Spark leg stays offered beside USDT, so switching such a contact to Spending can still route through it. + val offersSparkLeg = offersSparkLeg(payment, address) + paykitRouteDecided = false + val route = PaykitRouteUi( + endpoints = payment.endpoints.filter { it.methodId != MethodId.UsdtArbitrum } + .map { PaykitEndpoint(methodId = it.methodId.rawValue, value = it.value) } + .toImmutableList(), + offersSparkLeg = offersSparkLeg, + invoice = invoice, + lnurl = lnurl, + ).takeIf { it.endpoints.isNotEmpty() } + val payMethod = if (offersSparkLeg && !canUseOnchain) { + SendMethod.LIGHTNING + } else { + paykitBitcoinMethod(canUseLightning, address, invoice, lnurl) + } _sendUiState.update { it.copy( address = address, addressInput = address, isAddressInputValid = address.isNotEmpty(), decodedInvoice = invoice, lnurl = lnurl, paykitUsesUsdt = useUsdt, usdtRecipient = recipient, amount = invoice?.amountSatoshis?.takeIf { payMethod == SendMethod.LIGHTNING } ?: 0u, paykitAmount = "", - payMethod = payMethod + payMethod = payMethod, + paykitRoute = route, ) } if (usdtRepo.shouldRefresh(isUsdtEnabled.value)) usdtRepo.refresh(history = false) @@ -4123,6 +4204,13 @@ class AppViewModel @Inject constructor( ) return true } + _sendUiState.value.paykitRoute?.takeIf { _sendUiState.value.routesPaykitPayment }?.let { + preferSparkWhenSavingsShort(it) + val outcome = routePaykitPayment(it) + if (outcome == PaykitRouteOutcome.Refused || outcome == PaykitRouteOutcome.Stale) return false + // Validity was set against the source before routing; the route may have moved the payment to Spark. + _sendUiState.update { state -> state.copy(isAmountInputValid = validateAmount(state.amount)) } + } if (!bindBitcoinRequestTerms()) return false requireCurrentPaymentPreparation(walletGeneration) navigateToSendRoute(fromMainScanner, SendRoute.Confirm, SendEffect.NavigateToConfirm, walletGeneration) @@ -4131,6 +4219,17 @@ class AppViewModel @Inject constructor( return true } + /** + * A request skips the amount step, so its source is picked here: Savings only when it covers the amount with its + * fee, else Spending, where the router can take the Spark leg. + */ + private fun preferSparkWhenSavingsShort(route: PaykitRouteUi) { + val state = _sendUiState.value + if (!route.offersSparkLeg || state.payMethod != SendMethod.ONCHAIN || state.hardwareWalletId != null) return + if (walletRepo.balanceState.value.maxSendOnchainSats >= state.amount) return + _sendUiState.update { it.copy(payMethod = SendMethod.LIGHTNING) } + } + private suspend fun bindUsdtRequestTerms(): Boolean { if (!_sendUiState.value.paykitUsesUsdt || !_sendUiState.value.isAmountInputValid) return false paykitPaymentTerms = null @@ -4170,7 +4269,9 @@ class AppViewModel @Inject constructor( val state = _sendUiState.value if (state.paykitUsesUsdt) return false val lnurl = state.lnurl as? LnurlParams.LnurlPay - if (state.payMethod == SendMethod.LIGHTNING && lnurl != null && state.amount < lnurl.data.minSendableSat()) { + if (state.payMethod == SendMethod.LIGHTNING && lnurl != null && state.routedPaykitRoute?.serviceLeg == null && + !lnurl.accepts(state.amount) + ) { return false } return reviewPaykitAmount() @@ -4192,6 +4293,15 @@ class AppViewModel @Inject constructor( return !canUseBitcoin && balance > 0u } + /** + * Offered whatever Lightning can pay when the payment opens: an amount entered later can pass Lightning's limit, + * and the router still prefers a direct payment that works. + */ + private fun offersSparkLeg(payment: ContactPaymentContext, address: String): Boolean { + if (!paykitRouteRepo.canRouteThroughSpark || address.isEmpty()) return false + return payment.endpoints.any { it.methodId.isOnchain } + } + private fun canFundPaykitLightning(invoice: LightningInvoice?, lnurl: LnurlParams.LnurlPay?): Boolean { if (invoice == null && lnurl == null) return false val amount = invoice?.amountSatoshis?.coerceAtLeast(1u) ?: lnurl?.data?.minSendableSat() ?: 1u @@ -4214,6 +4324,7 @@ class AppViewModel @Inject constructor( private suspend fun onAmountChange(amount: ULong) { if (_sendUiState.value.paykitUsesUsdt || !_sendUiState.value.isAmountEditable) return + paykitRouteDecided = false _sendUiState.update { it.copy( amount = amount, @@ -4373,6 +4484,21 @@ class AppViewModel @Inject constructor( ) } updateCanSwitchWallet() + // A source switch on Confirm asks the router again, for a request (no amount step) or a route already decided. + if (activeIncomingPaymentRequest() != null || paykitRouteDecided) { + _sendUiState.value.paykitRoute?.takeIf { _sendUiState.value.routesPaykitPayment }?.let { + // A refused route leaves no leg or invoice to pay, and a picked LNURL past its limits can't be paid; + // switching the source again recomputes validity. + val outcome = routePaykitPayment(it) + val routed = _sendUiState.value + val lnurl = routed.lnurl as? LnurlParams.LnurlPay + val isPastLnurlLimits = outcome == PaykitRouteOutcome.Direct && lnurl != null && + routed.payMethod == SendMethod.LIGHTNING && !lnurl.accepts(routed.amount) + if (outcome == PaykitRouteOutcome.Refused || isPastLnurlLimits) { + _sendUiState.update { state -> state.copy(isAmountInputValid = false) } + } + } + } reviewFundingSourceChange(current, canReviewInPlace, wasReviewed) } @@ -4596,23 +4722,29 @@ class AppViewModel @Inject constructor( if (!prepareCoinSelection()) return val lnurl = _sendUiState.value.lnurl - if (lnurl is LnurlParams.LnurlPay) { - val minSendable = lnurl.data.minSendableSat() - if (_sendUiState.value.amount < minSendable) { - toast( - type = Toast.ToastType.ERROR, - title = context.getString(R.string.wallet__lnurl_pay__error_min__title), - description = context.getString(R.string.wallet__lnurl_pay__error_min__description) - .replace("{amount}", formatMoneyValue(minSendable)), - testTag = "LnurlPayAmountTooLowToast", - ) - return - } - } if (lnurl is LnurlParams.LnurlWithdraw) { setSendEffect(SendEffect.NavigateToWithdrawConfirm) return } + // A Spark leg pays the on-chain endpoint, so the unselected LNURL's limits never apply to it. + _sendUiState.value.paykitRoute?.takeIf { _sendUiState.value.routesPaykitPayment }?.let { + when (routePaykitPayment(it)) { + PaykitRouteOutcome.Leg -> { + setSendEffect(SendEffect.NavigateToConfirm) + return + } + PaykitRouteOutcome.Refused, PaykitRouteOutcome.Stale -> return + PaykitRouteOutcome.Direct -> Unit + } + } + // The route can restore an LNURL a BOLT11 pick cleared, so its limits are read after routing. An on-chain + // pick keeps the contact's LNURL in state, and its limits never apply to that payment. + val payLnurl = _sendUiState.value.lnurl + if (payLnurl is LnurlParams.LnurlPay && _sendUiState.value.payMethod == SendMethod.LIGHTNING && + !validateLnurlAmount(payLnurl, _sendUiState.value.amount) + ) { + return + } _sendUiState.update { it.copy(isLoading = true) } try { @@ -4627,6 +4759,170 @@ class AppViewModel @Inject constructor( setSendEffect(SendEffect.NavigateToConfirm) } + /** Shows [lnurl]'s too-low or too-high toast when [amount] is outside its limits; true when it accepts it. */ + private suspend fun validateLnurlAmount(lnurl: LnurlParams.LnurlPay, amount: ULong): Boolean { + val minSendable = lnurl.data.minSendableSat() + if (amount < minSendable) { + toast( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.wallet__lnurl_pay__error_min__title), + description = context.getString(R.string.wallet__lnurl_pay__error_min__description) + .replace("{amount}", formatMoneyValue(minSendable)), + testTag = "LnurlPayAmountTooLowToast", + ) + return false + } + if (amount > lnurl.data.maxSendableSat()) { + toast( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.wallet__lnurl_pay__error_max__title), + description = context.getString(R.string.wallet__lnurl_pay__error_max__description), + testTag = "LnurlPayAmountTooHighToast", + ) + return false + } + return true + } + + /** + * Asks bitkit-core's router how to pay the contact from the selected source: Spending offers every endpoint but an + * LNURL whose limits refuse the amount, and a Spark leg to on-chain ones; Savings only the on-chain endpoints. + * Direct pays the endpoint it names. + */ + private suspend fun routePaykitPayment(route: PaykitRouteUi): PaykitRouteOutcome { + val state = _sendUiState.value + val generation = sendStateGeneration + val contact = synchronized(contactPaymentContextLock) { activeContactPaymentContext } + val fromSpending = state.payMethod == SendMethod.LIGHTNING + val lightningSpendable = if (fromSpending) maxSendableLightningSats() else 0uL + val onchainSpendable = if (fromSpending) 0uL else walletRepo.balanceState.value.maxSendOnchainSats + _sendUiState.update { it.copy(isLoading = true) } + // An LNURL whose limits refuse the amount must never win over an affordable Spark leg. + val refusingLnurl = route.lnurl?.takeIf { fromSpending && !it.accepts(state.amount) } + val result = paykitRouteRepo.route( + amountSats = state.amount, + endpoints = when { + !fromSpending -> route.endpoints.filter { it.isOnchain() } + refusingLnurl != null -> route.endpoints.filterNot { it.methodId == MethodId.Lnurl.rawValue } + else -> route.endpoints + }, + lightningSpendableSats = lightningSpendable, + onchainSpendableSats = onchainSpendable, + quoteServiceLegs = fromSpending && route.offersSparkLeg, + ) + // A dismissed or replaced payment's route must never land on the one that followed it. + if (generation != sendStateGeneration || + synchronized(contactPaymentContextLock) { activeContactPaymentContext } !== contact + ) { + return PaykitRouteOutcome.Stale + } + // An amount a rate refresh wrote, or a source picked, while the router answered needs a new route. + val current = _sendUiState.value + if (current.amount != state.amount || current.payMethod != state.payMethod) { + paykitRouteDecided = false + _sendUiState.update { it.copy(isLoading = false) } + return PaykitRouteOutcome.Stale + } + _sendUiState.update { it.copy(isLoading = false) } + // 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 picked = if (isLegOverBalance || isLegSettling) { + PaykitRoute.None(result.exceptionOrNull()?.message.orEmpty()) + } else { + result.getOrElse { + Logger.error("Failed to route Paykit payment", it, context = TAG) + toast(it) + return PaykitRouteOutcome.Refused + } + } + // Once the router answered, even with no route, every later source switch asks it again: a stale source + // must never fall through to a payment the router never picked. + paykitRouteDecided = true + return when (picked) { + is PaykitRoute.Direct -> { + payDirectEndpoint(route, picked.endpoint) + PaykitRouteOutcome.Direct + } + is PaykitRoute.Service -> { + _sendUiState.update { + it.copy( + paykitRoute = route.copy(serviceLeg = picked.leg), + lightningFeeSats = (picked.leg.debitSat - picked.leg.deliveredSat).toLong(), + ) + } + _sendUiState.update { it.copy(isAmountInputValid = validateAmount(it.amount)) } + PaykitRouteOutcome.Leg + } + // The app never offers Pubky Swaps providers, so a Swap route can't come back; it pays nothing either. + is PaykitRoute.None, is PaykitRoute.Swap -> { + val reason = (picked as? PaykitRoute.None)?.reason ?: "Swap routes are unsupported" + Logger.warn("Found no Paykit route: '$reason'", context = TAG) + _sendUiState.update { it.copy(paykitRoute = route.copy(serviceLeg = null)) } + // 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. + if (!isAmountShort && refusingLnurl != null) { + validateLnurlAmount(refusingLnurl, state.amount) + return PaykitRouteOutcome.Refused + } + val isBalanceShort = isAmountShort || isLegOverBalance + toast( + type = Toast.ToastType.ERROR, + title = context.getString( + if (isBalanceShort) { + R.string.wallet__send_amount_exceeded__title + } else { + R.string.wallet__send_paykit_no_route__title + } + ), + description = context.getString( + when { + isBalanceShort -> R.string.wallet__send_amount_exceeded__description + isLegSettling -> R.string.wallet__send_paykit_withdrawal_settling__description + else -> R.string.wallet__send_paykit_no_route__description + } + ), + testTag = when { + isBalanceShort -> "PaykitRouteBalanceToast" + isLegSettling -> "PaykitRouteSettlingToast" + else -> "PaykitRouteNoneToast" + }, + ) + PaykitRouteOutcome.Refused + } + } + } + + private fun payDirectEndpoint(route: PaykitRouteUi, endpoint: PaykitEndpoint) { + _sendUiState.update { + when { + endpoint.isOnchain() -> it.copy( + payMethod = SendMethod.ONCHAIN, + address = endpoint.value, + paykitRoute = route.copy(serviceLeg = null), + ) + // An earlier pick cleared the other Lightning endpoint, so the picked one comes back from the route. + endpoint.methodId == MethodId.Lnurl.rawValue -> it.copy( + payMethod = SendMethod.LIGHTNING, + decodedInvoice = null, + lnurl = route.lnurl ?: it.lnurl, + // No invoice to estimate yet, so an earlier Spark leg's withdrawal fee would stay on Confirm. + lightningFeeSats = null, + paykitRoute = route.copy(serviceLeg = null), + ) + else -> it.copy( + payMethod = SendMethod.LIGHTNING, + decodedInvoice = route.invoice ?: it.decodedInvoice, + lnurl = null, + lightningFeeSats = null, + paykitRoute = route.copy(serviceLeg = null), + ) + } + } + } + private suspend fun reviewPaykitAmount(navigateToUsdtReview: Boolean = true): Boolean { val paykit = synchronized(contactPaymentContextLock) { activeContactPaymentContext } if (paykit == null || paykit.endpoints.isEmpty()) return true @@ -4756,6 +5052,7 @@ class AppViewModel @Inject constructor( return when (payMethod) { SendMethod.LIGHTNING -> { + sparkWithdrawalValidity(amount)?.let { return it } val maxSendable = maxSendableLightningSats() when (val lnurl = _sendUiState.value.lnurl) { null -> amount <= maxSendable && lightningRepo.canSend(amount) @@ -4776,6 +5073,19 @@ class AppViewModel @Inject constructor( } } + /** + * A Spark withdrawal is paid from Spark's whole balance, so Lightning's limit never applies to it: a quoted leg is + * valid only when its debit fits, and before the quote an amount Spark's balance covers lets Continue ask for one. + * Null leaves the amount to the Lightning checks. + */ + private fun sparkWithdrawalValidity(amount: ULong): Boolean? { + val state = _sendUiState.value + val route = state.paykitRoute?.takeIf { state.routesPaykitPayment && it.offersSparkLeg } ?: return null + val leg = route.serviceLeg?.takeIf { it.deliveredSat == amount } + if (leg != null) return lightningRepo.canWithdrawWithSpark(leg.debitSat) + return true.takeIf { lightningRepo.canWithdrawWithSpark(amount) } + } + private fun maxSendableLightningSats(): ULong { val max = walletRepo.balanceState.value.maxSendLightningSats val fee = _sendUiState.value.estimatedRoutingFee @@ -4902,7 +5212,10 @@ class AppViewModel @Inject constructor( resetQuickPay() val fromMainScanner = isMainScanner - if (contactPaymentContext != null && requiresPaykitAssetSelection(contactPaymentContext)) { + if ( + contactPaymentContext != null && + (requiresPaykitAssetSelection(contactPaymentContext) || requiresPaykitServiceRoute(contactPaymentContext)) + ) { openPaykitContactPayment(contactPaymentContext, fromMainScanner, suppressQuickPay, walletGeneration) return@withContext } @@ -5016,6 +5329,12 @@ class AppViewModel @Inject constructor( } } + /** Any on-chain endpoint lets Spark pay an amount the contact's Lightning endpoints or Savings can't. */ + private fun requiresPaykitServiceRoute(payment: ContactPaymentContext): Boolean { + if (!paykitRouteRepo.canRouteThroughSpark) return false + return payment.endpoints.any { it.methodId.isOnchain } + } + private fun requiresPaykitAssetSelection(payment: ContactPaymentContext): Boolean = payment.endpoints.isNotEmpty() && ( payment.endpoints.any { it.methodId == MethodId.UsdtArbitrum } || @@ -5164,6 +5483,8 @@ class AppViewModel @Inject constructor( ) { isSubmittingPaymentRequest = false uncertainOnchainPaymentRequestId = null + // A closed send never takes a late Spark settlement onto the next one. + uncertainSparkWithdrawal = null val interruptedRequest = synchronized(contactPaymentContextLock) { val request = activeContactPaymentContext?.incomingPaymentRequest if (request != null && !retryIncomingRequest) completePaymentRequestPresentation(request) @@ -5663,7 +5984,10 @@ class AppViewModel @Inject constructor( return@buildList } if (state.usdtRecipient != null) add(SendFundingSource.Usdt) - if (state.isUnified || state.decodedInvoice != null || state.lnurl is LnurlParams.LnurlPay) { + if ( + state.isUnified || state.decodedInvoice != null || state.lnurl is LnurlParams.LnurlPay || + state.paykitRoute?.offersSparkLeg == true + ) { add( SendFundingSource.Spending ) @@ -5682,10 +6006,15 @@ class AppViewModel @Inject constructor( source: SendFundingSource = selectedFundingSource(), ): MethodId = when (source) { SendFundingSource.Usdt -> MethodId.UsdtArbitrum - SendFundingSource.Spending -> when (lnurl) { - is LnurlParams.LnurlPay -> MethodId.Lnurl - else -> MethodId.Bolt11 - } + SendFundingSource.Spending -> routedPaykitRoute?.serviceLeg?.let { MethodId.fromRawValue(it.endpoint.methodId) } + ?: when { + lnurl is LnurlParams.LnurlPay -> MethodId.Lnurl + // With no Lightning payment to make, Spending funds the Spark leg to the on-chain endpoint, so it takes + // that endpoint's price before the router picks the leg. + decodedInvoice == null && paykitRoute?.offersSparkLeg == true && address.isNotEmpty() -> + PublicPaykitRepo.onchainMethodId(address) + else -> MethodId.Bolt11 + } SendFundingSource.Savings, is SendFundingSource.Hardware -> PublicPaykitRepo.onchainMethodId(address) } @@ -6135,6 +6464,9 @@ class AppViewModel @Inject constructor( if (_sendUiState.value.showSanityWarningDialog != null) return val settings = settingsStore.data.first() + // A Spark leg spends its debit, the amount plus Spark's fees, from Spark's balance. + val leg = _sendUiState.value.routedPaykitRoute?.serviceLeg + val spentSats = leg?.debitSat ?: amountSats val balanceToCheck = when (_sendUiState.value.payMethod) { SendMethod.ONCHAIN -> { _sendUiState.value.hardwareAvailableSats @@ -6144,7 +6476,7 @@ class AppViewModel @Inject constructor( SendMethod.LIGHTNING -> walletRepo.balanceState.value.maxSendLightningSats } if ( - amountSats > BigDecimal.valueOf(balanceToCheck.toLong()) + spentSats > BigDecimal.valueOf(balanceToCheck.toLong()) .times(BigDecimal(MAX_BALANCE_FRACTION)).toLong().toUInt() && SanityWarning.OVER_HALF_BALANCE !in _sendUiState.value.confirmedWarnings ) { @@ -6167,9 +6499,11 @@ class AppViewModel @Inject constructor( return } - if (_sendUiState.value.payMethod != SendMethod.ONCHAIN) return + if (_sendUiState.value.payMethod != SendMethod.ONCHAIN && leg == null) return - val totalFee = if (_sendUiState.value.hardwareWalletId != null) { + val totalFee = if (leg != null) { + leg.debitSat.safe() - leg.deliveredSat.safe() + } else if (_sendUiState.value.hardwareWalletId != null) { _sendUiState.value.onchainFeeUi.sats?.toULong() ?: return } else { lightningRepo.calculateTotalFee( @@ -6267,7 +6601,9 @@ class AppViewModel @Inject constructor( val amount = _sendUiState.value.amount val lnurl = _sendUiState.value.lnurl - val isLnurlPay = lnurl is LnurlParams.LnurlPay + // An on-chain payment, from Savings or a Spark leg, fetches no invoice from the unselected LNURL. + val isLnurlPay = lnurl is LnurlParams.LnurlPay && _sendUiState.value.payMethod == SendMethod.LIGHTNING && + _sendUiState.value.routedPaykitRoute?.serviceLeg == null if (isLnurlPay) { val amountMsats = lnurl.data.callbackAmountMsats(amount) @@ -6310,6 +6646,17 @@ class AppViewModel @Inject constructor( return } + _sendUiState.value.routedPaykitRoute?.serviceLeg?.let { + proceedWithServiceRoutedPayment( + leg = it, + incomingPaymentRequest = incomingPaymentRequest, + preparedPaymentProofRequest = preparedPaymentProofRequest, + contactPaymentContext = contactPaymentContext, + allowanceAttemptId = allowanceAttemptId, + ) + return + } + when (_sendUiState.value.payMethod) { SendMethod.ONCHAIN -> proceedWithOnchainPayment( incomingPaymentRequest, @@ -6341,6 +6688,7 @@ class AppViewModel @Inject constructor( val endpointIdentifier = paymentProofPreparation(contactPaymentContext).endpointIdentifier val paymentHash = _sendUiState.value.decodedInvoice ?.takeIf { _sendUiState.value.payMethod == SendMethod.LIGHTNING } + ?.takeIf { _sendUiState.value.routedPaykitRoute?.serviceLeg == null } ?.paymentHash?.toHex() return paykitAllowanceRepo.beginManualPayment(request, endpointIdentifier, paymentHash) .recoverCatching { @@ -6717,6 +7065,155 @@ class AppViewModel @Inject constructor( ) } + private suspend fun proceedWithServiceRoutedPayment( + leg: ServiceRouteLeg, + incomingPaymentRequest: PaykitPaymentRequest?, + preparedPaymentProofRequest: PaykitPaymentRequest?, + contactPaymentContext: ContactPaymentContext?, + allowanceAttemptId: String?, + ) { + uncertainSparkWithdrawal = null + var earlierTxids: Set? = null + val txid = paykitRouteRepo.payServiceLeg( + leg, + contactPaymentContext?.publicKey, + _sendUiState.value.selectedTags, + incomingPaymentRequest?.submissionDeadline(paykitPaymentTerms), + ) { + val earlier = lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value) + startSparkOnchainProof( + leg = leg, + incomingPaymentRequest = incomingPaymentRequest, + preparedPaymentProofRequest = preparedPaymentProofRequest, + contactPaymentContext = contactPaymentContext, + earlierTxids = earlier, + ).getOrThrow() + earlierTxids = earlier + true + }.getOrElse { + handleServiceLegFailure( + error = it, + leg = leg, + earlierTxids = earlierTxids, + incomingPaymentRequest = incomingPaymentRequest, + preparedPaymentProofRequest = preparedPaymentProofRequest, + contactPaymentContext = contactPaymentContext, + allowanceAttemptId = allowanceAttemptId, + ) + return + } + incomingPaymentRequest?.let { request -> + // The journaled withdrawal and Spark's payment list let a later reconcile finish a proof that fails here. + viewModelScope.launch { paykitPaymentProofRepo.completeSparkOnchainPayment(request, txid) } + } + finishManualAllowancePayment(allowanceAttemptId, succeeded = true, transactionId = txid) + Logger.info("Paid Paykit contact through '${leg.service}' in '$txid'", context = TAG) + onSendSuccess( + NewTransactionSheetDetails( + type = NewTransactionSheetType.ONCHAIN, + direction = NewTransactionSheetDirection.SENT, + paymentHashOrTxId = txid, + sats = leg.deliveredSat.toLong(), + ), + ) + } + + /** + * Only a withdrawal Spark shows never sent is a definite failure: it releases the started proof, the private list + * and the allowance attempt. Once a send was attempted and Spark can't tell yet, they stay, as on-chain. + */ + @Suppress("LongParameterList") + private suspend fun handleServiceLegFailure( + error: Throwable, + leg: ServiceRouteLeg, + earlierTxids: Set?, + incomingPaymentRequest: PaykitPaymentRequest?, + preparedPaymentProofRequest: PaykitPaymentRequest?, + contactPaymentContext: ContactPaymentContext?, + allowanceAttemptId: String?, + ) { + // Spark refuses a send past its deadline, or one its balance can't cover, before it sends and clears its + // journal, so no listing is needed. + if (error is ServiceError.PaymentDeadlineExpired || error is SparkError.SendRefused) { + incomingPaymentRequest?.let { paykitPaymentProofRepo.releaseRefusedSparkOnchainProof(it) } + failServiceLegBeforeSend(error, preparedPaymentProofRequest, contactPaymentContext, allowanceAttemptId) + return + } + incomingPaymentRequest?.let { paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(it) } + // Registered before the outcome is read, so a journal that closes meanwhile still reaches this send. + val attempt = leg.endpoint.value to leg.deliveredSat + if (incomingPaymentRequest == null && earlierTxids != null) uncertainSparkWithdrawal = attempt + val outcome = earlierTxids?.let { + runSuspendCatching { lightningRepo.sparkWithdrawalOutcome(leg.endpoint.value, leg.deliveredSat, it) } + .onFailure { Logger.warn("Failed to read a Spark withdrawal outcome", it, context = TAG) } + .getOrDefault(SparkWithdrawalOutcome.Unknown) + } + if (incomingPaymentRequest == null && earlierTxids != null && uncertainSparkWithdrawal != attempt) { + Logger.info("Settled a Spark withdrawal while its outcome was read", context = TAG) + return + } + if (outcome == SparkWithdrawalOutcome.Unsent || outcome is SparkWithdrawalOutcome.Sent) { + uncertainSparkWithdrawal = null + } + if (outcome is SparkWithdrawalOutcome.Sent) { + // Spark already lists it, so the send succeeded: its proof's resolution may have gone by already. + incomingPaymentRequest?.let { request -> + viewModelScope.launch { paykitPaymentProofRepo.completeSparkOnchainPayment(request, outcome.txid) } + } + finishManualAllowancePayment(allowanceAttemptId, succeeded = true, transactionId = outcome.txid) + onSendSuccess(sparkWithdrawalSent(outcome.txid, leg.deliveredSat)) + return + } + if (outcome != null && outcome != SparkWithdrawalOutcome.Unsent) { + Logger.warn("Left a Spark withdrawal with an uncertain send result to Spark", error, context = TAG) + finishManualAllowancePayment(allowanceAttemptId, succeeded = null) + showUnresolvedOnchainSend(null, leg.deliveredSat, incomingPaymentRequest) + return + } + failServiceLegBeforeSend(error, preparedPaymentProofRequest, contactPaymentContext, allowanceAttemptId) + } + + private suspend fun failServiceLegBeforeSend( + error: Throwable, + preparedPaymentProofRequest: PaykitPaymentRequest?, + contactPaymentContext: ContactPaymentContext?, + allowanceAttemptId: String?, + ) { + releasePrivatePaymentListIfNeeded(contactPaymentContext) + cancelPaymentProofPreparation(preparedPaymentProofRequest) + finishManualAllowancePayment(allowanceAttemptId, succeeded = false) + handlePaymentPreparationFailure(error, contactPaymentContext) + } + + /** + * Runs once the Spark withdrawal is prepared, right before it sends: checks the request may still be paid, then + * marks its on-chain proof started for the leg's address and checks the original payer. + */ + private suspend fun startSparkOnchainProof( + leg: ServiceRouteLeg, + incomingPaymentRequest: PaykitPaymentRequest?, + preparedPaymentProofRequest: PaykitPaymentRequest?, + contactPaymentContext: ContactPaymentContext?, + earlierTxids: Set, + ): Result = runSuspendCatching { + val request = incomingPaymentRequest ?: return@runSuspendCatching + paykitPaymentRequestRepo.ensurePaymentAllowed(request).getOrThrow() + val prepared = preparedPaymentProofRequest + if (prepared != null) { + val originalPayer = paykitPaymentProofRepo.captureOriginalOnchainPayer(prepared).getOrThrow() + val privateContext = contactPaymentContext?.privatePaymentContext + paykitPaymentProofRepo.markSparkOnchainPaymentStarted( + request = request, + address = leg.endpoint.value, + amountSats = leg.deliveredSat, + privatePaymentListVersion = privateContext?.paymentListVersion, + previousPrivatePaymentListVersion = privateContext?.previousPaymentListVersion, + earlierWithdrawalTxids = earlierTxids, + ).getOrThrow() + paykitPaymentProofRepo.verifyOriginalOnchainPayer(prepared, originalPayer).getOrThrow() + } + } + private suspend fun proceedWithLightningPayment( incomingPaymentRequest: PaykitPaymentRequest?, preparedPaymentProofRequest: PaykitPaymentRequest?, @@ -7443,6 +7940,8 @@ class AppViewModel @Inject constructor( val generation = sendStateGeneration val currentState = _sendUiState.value if (currentState.payMethod != SendMethod.LIGHTNING) return + // A Spark leg pays the contact's other endpoint, so its fee is the leg's, never the retained invoice's. + if (currentState.routedPaykitRoute?.serviceLeg != null) return val decodedInvoice = currentState.decodedInvoice ?: return val feeResult = if (decodedInvoice.amountSatoshis > 0uL) { @@ -7454,7 +7953,7 @@ class AppViewModel @Inject constructor( requireCurrentPaymentPreparation(walletGeneration) feeResult.onSuccess { fee -> _sendUiState.update { - if (generation != sendStateGeneration) return@update it + if (generation != sendStateGeneration || it.routedPaykitRoute?.serviceLeg != null) return@update it it.copy( lightningFeeSats = fee.toLong(), lastLightningFee = fee.toLong(), @@ -9140,7 +9639,16 @@ data class SendUiState( val fixedOnchainAmount: ULong? = null, val initialSubscriptionPaymentNeedsConfirmation: Boolean = false, val incomingPaymentRequestId: PaykitPaymentRequestId? = null, + val paykitRoute: PaykitRouteUi? = null, ) { + /** The Paykit route this payment takes: a Spark leg runs only while Spending is the source. */ + val routedPaykitRoute: PaykitRouteUi? + get() = paykitRoute?.takeIf { payMethod == SendMethod.LIGHTNING } + + /** Whether bitkit-core's router picks how this contact payment is paid; USDT and hardware wallets pay as picked. */ + val routesPaykitPayment: Boolean + get() = !paykitUsesUsdt && hardwareWalletId == null && lnurl !is LnurlParams.LnurlWithdraw + val canSwitchBitcoinFundingSource: Boolean get() = fundingOptions.count { it.enabled && it.source != SendFundingSource.Usdt } > 1 @@ -9169,6 +9677,26 @@ data class SendUiState( !initialSubscriptionPaymentNeedsConfirmation && !requiresAmountReview } +/** + * A contact payment bitkit-core's router picks the way for: the contact's bitcoin endpoints, whether a Spark leg may + * reach its on-chain ones, the leg once the router picked one, and the decoded invoice and LNURL a Direct pick pays. + */ +@Stable +data class PaykitRouteUi( + val endpoints: ImmutableList, + val offersSparkLeg: Boolean = false, + val serviceLeg: ServiceRouteLeg? = null, + val invoice: LightningInvoice? = null, + val lnurl: LnurlParams.LnurlPay? = null, +) + +private enum class PaykitRouteOutcome { Direct, Leg, Refused, Stale } + +private fun PaykitEndpoint.isOnchain(): Boolean = MethodId.fromRawValue(methodId)?.isOnchain == true + +private fun LnurlParams.LnurlPay.accepts(amount: ULong): Boolean = + amount in data.minSendableSat()..data.maxSendableSat() + @Immutable data class OnchainFeeUi( val rate: FeeRate = FeeRate.fromSpeed(TransactionSpeed.default()), diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index d3378518e8..8d1db1415b 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1027,11 +1027,14 @@ انتهاء صلاحية الفاتورة الحد الأقصى القابل للإنفاق أقل قليلاً بسبب الرصيد الاحتياطي المطلوب. الرصيد الاحتياطي + ليس لدى جهة الاتصال هذه أي طريقة دفع يمكن لـ Bitkit استخدامها الآن. + لا يمكن الدفع لجهة الاتصال هذه لم تعد التحويلات إلى رصيد الإنفاق متاحة. يتحقق Bitkit أولًا من الشبكة، ثم يعيد عملات هذا التحويل إلى محفظتك حتى لا يتأكد التحويل الأصلي أبدًا. يكلّف ذلك رسوم شبكة. QuickPay جارٍ دفع\n<accent>الفاتورة...</accent> تأكيد تم إرسال Bitcoin + المسار اسحب للدفع إلى نعم، أرسل 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 06373a467a..a0e250f0ed 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1058,6 +1058,8 @@ Expiración de la factura La cantidad máxima que se puede gastar es un poco más baja debido al saldo de reserva exigido. Saldo de reserva + Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora. + No se puede pagar a este contacto 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. Este pago está tardando un poco más de lo esperado. Puede seguir utilizando Bitkit. Pago pendiente @@ -1065,6 +1067,7 @@ Pagando\n<accent>factura...</accent> Confirmar Bitcoin Enviado + Ruta Deslizar para pagar Para Sí, enviar diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index bd8692100e..97bb3b219d 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1052,12 +1052,15 @@ Caducitat de la factura L\'import màxim gastable és una mica inferior a causa d\'un saldo de reserva requerit. Saldo de reserva + Aquest contacte no té cap mètode de pagament que Bitkit pugui fer servir ara. + No es pot pagar aquest contacte Les transferències al saldo de despesa ja no estan disponibles. Bitkit primer comprova la xarxa i després retorna les monedes d\'aquesta transferència a la teva cartera perquè la transferència original no es pugui confirmar mai. Això té una comissió de xarxa. Pagament pendent QuickPay Pagant\n<accent>factura...</accent> Confirmar Bitcoin enviat + Ruta Desplaça per pagar A Sí, Enviar diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 856dcb4037..c4de5be73c 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1056,6 +1056,8 @@ Expirace faktury Maximální částka, kterou lze utratit, je o něco nižší kvůli požadovanému zůstatku rezervy. Zůstatek rezervy + Tento kontakt nemá žádnou platební metodu, kterou by Bitkit mohl nyní použít. + Tomuto kontaktu nelze zaplatit Převody na útratový zůstatek už nejsou dostupné. Bitkit nejprve zkontroluje síť a pak vrátí mince tohoto převodu do vaší peněženky, aby se původní převod nikdy nepotvrdil. Stojí to síťový poplatek. Tato platba trvá o něco déle, než se očekávalo. Bitkit můžete používat i nadále. Platba čeká na vyřízení @@ -1063,6 +1065,7 @@ Placení\n<accent>faktury...</accent> Potvrdit bitcoin odeslán + Trasa Zaplatit přejetím prstem Komu Ano, odeslat diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index f4dece2f8f..a18b2046bd 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -889,6 +889,8 @@ Senden Empfangen Bitcoin senden + Dieser Kontakt hat derzeit keine Zahlungsmethode, die Bitkit nutzen kann. + Zahlung an diesen Kontakt nicht möglich Überweisungen auf dein Ausgabenguthaben sind nicht mehr verfügbar. Bitkit prüft zuerst das Netzwerk und schickt die Coins dieser Überweisung dann zurück in deine Wallet, damit die ursprüngliche Überweisung nie bestätigt wird. Dafür fällt eine Netzwerkgebühr an. An Kontakt @@ -911,6 +913,7 @@ Bestätigung in Kontakt auswählen Rechnungsverfall + Route Zum Bezahlen wischen Ja, senden Es scheint, dass du über $100 sendest. Möchtest du fortfahren? diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index f57c8552db..ab14bb56e5 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1032,11 +1032,14 @@ Λήξη τιμολογίου Το μέγιστο δαπανήσιμο ποσό είναι λίγο χαμηλότερο λόγω απαιτούμενου αποθεματικού υπολοίπου. Αποθεματικό υπόλοιπο + Αυτή η επαφή δεν έχει τρόπο πληρωμής που μπορεί να χρησιμοποιήσει το Bitkit αυτή τη στιγμή. + Δεν είναι δυνατή η πληρωμή αυτής της επαφής Οι μεταφορές στο υπόλοιπο δαπανών δεν είναι πλέον διαθέσιμες. Το Bitkit ελέγχει πρώτα το δίκτυο και μετά επιστρέφει τα νομίσματα αυτής της μεταφοράς στο πορτοφόλι σας, ώστε η αρχική μεταφορά να μην επιβεβαιωθεί ποτέ. Αυτό έχει χρέωση δικτύου. QuickPay Πληρωμή\n<accent>τιμολογίου...</accent> Επιβεβαίωση Τα Bitcoin στάλθηκαν + Διαδρομή Σύρε για πληρωμή Προς Ναι, Στείλε diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index aaf6ae1955..53b77123cc 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1053,11 +1053,14 @@ Expiración de la factura La cantidad máxima gastable es un poco menor debido a un saldo de reserva requerido. Saldo de reserva + Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora. + No se puede pagar a este contacto Las transferencias al saldo de gasto ya no están disponibles. Bitkit primero comprueba la red y después devuelve las monedas de esta transferencia a tu billetera para que la transferencia original nunca se confirme. Esto tiene una comisión de red. QuickPay Pagando\n<accent>factura...</accent> Confirmar Bitcoin Enviado + Ruta Deslizar para pagar Para Sí, enviar diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 1413ecc1f1..a1ef89554e 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -887,6 +887,8 @@ Recibir Transferencia Entrante: Enviar Bitcoin + Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora. + No se puede pagar a este contacto Las transferencias al saldo de gasto ya no están disponibles. Bitkit primero comprueba la red y después devuelve las monedas de esta transferencia a tu billetera para que la transferencia original nunca se confirme. Esto tiene una comisión de red. Para Contactar @@ -903,6 +905,7 @@ Confirmando en Seleccionar contacto Expiración de la factura + Ruta Deslizar para pagar Sí, enviar Parece que está enviando más de 100 dólares. ¿Desea continuar? diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index e06354e27a..541799bf9f 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -890,6 +890,8 @@ Envoyer Recevoir Envoyer des bitcoins + Ce contact n\'a aucun moyen de paiement que Bitkit peut utiliser pour le moment. + Impossible de payer ce contact Les transferts vers le solde de dépenses ne sont plus disponibles. Bitkit vérifie d\'abord le réseau, puis renvoie les pièces de ce transfert vers votre portefeuille afin que le transfert d\'origine ne soit jamais confirmé. Cela coûte des frais de réseau. Pour Contact @@ -912,6 +914,7 @@ Confirmation en Sélectionnez un contact Expiration de la facture + Itinéraire Glisser pour payer Oui, Envoyer Il apparaît que vous envoyez plus de 100 $. Voulez-vous continuer ? diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 60ce916a1a..3c2c1f0e05 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1054,6 +1054,8 @@ Scadenza invoice L\'importo massimo spendibile e\' leggermente inferiore a causa di un saldo di riserva richiesto. Saldo di Riserva + Questo contatto non ha alcun metodo di pagamento che Bitkit possa usare ora. + Impossibile pagare questo contatto I trasferimenti al saldo di spesa non sono più disponibili. Bitkit controlla prima la rete, poi rimanda le monete di questo trasferimento al tuo wallet, così il trasferimento originale non potrà mai essere confermato. Questo costa una commissione di rete. Questo pagamento sta richiedendo un po\' più tempo del previsto. Puoi continuare a utilizzare Bitkit. Pagamento in sospeso @@ -1061,6 +1063,7 @@ Pagamento\n<accent>fattura...</accent> Conferma Bitcoin Inviati + Percorso Scorri per Pagare A Si, Invia diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index a6936786af..9e38f892dc 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1049,6 +1049,8 @@ Factuutvervaldatum Het maximaal te besteden bedrag is iets lager vanwege een vereist reservesaldo. Reservesaldo + Dit contact heeft nu geen betaalmethode die Bitkit kan gebruiken. + Kan dit contact niet betalen Overboekingen naar je bestedingssaldo zijn niet meer beschikbaar. Bitkit controleert eerst het netwerk en stuurt de munten van deze overboeking dan terug naar je wallet, zodat de oorspronkelijke overboeking nooit bevestigd wordt. Dit kost netwerkkosten. Deze betaling duurt iets langer dan verwacht. U kunt Bitkit blijven gebruiken. Betaling Onderweg @@ -1056,6 +1058,7 @@ Factuur\n<accent>betalen...</accent> Bevestigen Bitcoin verzonden + Route Veeg om te betalen Naar Ja, verzenden diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index df5d13be78..bf3f703ea3 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -892,6 +892,8 @@ Wyślij Otrzymaj Wyślij Bitcoin + Ten kontakt nie ma teraz metody płatności, której Bitkit może użyć. + Nie można zapłacić temu kontaktowi Przelewy na saldo wydatków nie są już dostępne. Bitkit najpierw sprawdza sieć, a potem odsyła monety z tego przelewu do Twojego portfela, aby pierwotny przelew nigdy nie został potwierdzony. Wiąże się to z opłatą sieciową. Do Kontakt @@ -914,6 +916,7 @@ Potwierdzenie w ciągu Wybierz kontakt Termin faktury + Trasa Przesuń, aby zapłacić Tak, wyślij Wygląda na to, że wysyłasz ponad $100. Czy kontynuować? diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index ffd19901c9..111f9e96d3 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1058,6 +1058,8 @@ Vencimento do invoice O valor máximo utilizável é um pouco menor devido a um saldo de reserva obrigatório. Saldo de reserva + Este contato não tem nenhum método de pagamento que o Bitkit possa usar agora. + Não é possível pagar este contato As transferências para o saldo de gastos não estão mais disponíveis. O Bitkit primeiro verifica a rede e depois devolve as moedas desta transferência para sua carteira, para que a transferência original nunca seja confirmada. Isso tem uma taxa de rede. Esse pagamento está demorando mais do que o esperado. Enquanto isso, você pode continuar usando a Bitkit. Pagamento Pendente @@ -1065,6 +1067,7 @@ Pagando \n<accent>invoice...</accent> Confirmar Bitcoin Enviado + Rota Deslize para Pagar Para Sim, Enviar diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index bde9787b3e..3c9a5da83b 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -756,6 +756,8 @@ Enviar Receber Enviar Bitcoin + Este contacto não tem nenhum método de pagamento que a Bitkit possa usar agora. + Não é possível pagar a este contacto As transferências para o saldo de gastos já não estão disponíveis. A Bitkit verifica primeiro a rede e depois devolve as moedas desta transferência à sua carteira, para que a transferência original nunca seja confirmada. Isto tem uma taxa de rede. Para Contato @@ -775,6 +777,7 @@ Confirmar Confirmando em Vencimento do invoice + Rota Deslize para Pagar Sim, Enviar Parece que você está enviando mais de US$ 100. Deseja continuar? diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index b712507be0..ec18cb9518 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1073,6 +1073,8 @@ Срок действия инвойса Максимальная сумма для траты немного меньше из-за необходимого резервного баланса. Резервный баланс + У этого контакта сейчас нет способа оплаты, который может использовать Bitkit. + Невозможно оплатить этому контакту Переводы на баланс расходов больше недоступны. Bitkit сначала проверяет сеть, а затем возвращает монеты этого перевода в ваш кошелёк, чтобы исходный перевод никогда не подтвердился. За это взимается сетевая комиссия. Этот платеж занимает больше времени, чем ожидалось. Вы можете продолжать использовать Bitkit. Платеж в ожидании @@ -1081,6 +1083,7 @@ <accent>счёта...</accent> Подтвердить Биткоины отправлены + Маршрут Отправить Кому Да, Отправить diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index f6192342ca..868c4207f6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1640,6 +1640,9 @@ Invoice expiration The maximum spendable amount is a bit lower due to a required reserve balance. Reserve Balance + This contact has no payment method Bitkit can use right now. + Can\'t pay this contact + An earlier withdrawal from your spending balance is still settling. Try again once it completes. Cancel expired payment Checking the network. This can take up to 30 seconds. Payment cancelled. Its coins are back in your wallet. @@ -1666,6 +1669,8 @@ Paying\n<accent>invoice...</accent> Confirm Bitcoin Sent + Route + Spark Swipe To Pay To Yes, Send diff --git a/app/src/test/java/to/bitkit/models/PaykitPaymentStateBackupTest.kt b/app/src/test/java/to/bitkit/models/PaykitPaymentStateBackupTest.kt index 4246506b4d..9457d7f426 100644 --- a/app/src/test/java/to/bitkit/models/PaykitPaymentStateBackupTest.kt +++ b/app/src/test/java/to/bitkit/models/PaykitPaymentStateBackupTest.kt @@ -52,6 +52,23 @@ class PaykitPaymentStateBackupTest { } } + @Test + fun `spark withdrawal proof keeps its rail through backup`() { + WalletScope.pushTestOverride("wallet0").use { + val backup = Json.decodeFromString( + """ + {"identity":"alice","requestId":{"paymentRequestId":"request","counterparty":"bob"}, + "paymentEndpointIdentifier":"btc-regtest-p2wpkh","kind":"bitcoin-onchain-txid","paymentStarted":true, + "onchainMatchingTransactionIdsBeforeAttempt":[],"sparkWithdrawal":true} + """.trimIndent(), + ) + val restored = backup.restored() + assertTrue(restored.sparkWithdrawal) + val json = Json.encodeToString(PaykitPaymentStateBackup.Proof(restored)) + assertContains(json, "\"sparkWithdrawal\":true") + } + } + @Test fun `shared active operation survives payment backup reader writer roundtrip`() { val wire = """ diff --git a/app/src/test/java/to/bitkit/repositories/ActivityDetailViewModelTest.kt b/app/src/test/java/to/bitkit/repositories/ActivityDetailViewModelTest.kt index 7af4df3e8d..5b933f2e12 100644 --- a/app/src/test/java/to/bitkit/repositories/ActivityDetailViewModelTest.kt +++ b/app/src/test/java/to/bitkit/repositories/ActivityDetailViewModelTest.kt @@ -65,6 +65,7 @@ class ActivityDetailViewModelTest : BaseUnitTest() { settingsStore = settingsStore, hwWalletRepo = hwWalletRepo, transferRepo = transferRepo, + sparkRepo = mock(), ) } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 4bdee90058..92527d1807 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1780,7 +1780,7 @@ class LightningRepoTest : BaseUnitTest() { ) whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) val sending = CompletableDeferred() - whenever(sparkService.send(any())).doSuspendableAnswer { sending.await() } + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { sending.await() } val spark = SparkRepo( bgDispatcher = testDispatcher, sparkService = sparkService, @@ -1789,6 +1789,9 @@ class LightningRepoTest : BaseUnitTest() { contactResolver = { mock() }, pendingPaymentRepo = PendingPaymentRepo(), clock = Clock.System, + coreService = { coreService }, + settingsStore = settingsStore, + payoutChain = mock(), ) sut = LightningRepo( bgDispatcher = testDispatcher, diff --git a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt index c7e213ac29..9b943c78ae 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt @@ -1842,6 +1842,22 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { assertEquals(Stage.FAILED, sut.localState(identity).journal.single().stage) } + @Test + fun `a manual on-chain payment found sent later is recorded succeeded with its txid`() = test { + sut.activate(identity) + val request = fixtures.paymentRequest() + val attemptId = checkNotNull(sut.beginManualPayment(request, fixtures.onchainIdentifier).getOrThrow()) + sut.finishManualPayment(attemptId, PaymentOutcome.UNKNOWN) + recordedOutcomes.clear() + + sut.onchainSendSettled(identity, request.id, "c".repeat(64)) + + assertEquals(listOf(PaymentOutcomeReport(attemptId, PaymentOutcome.SUCCEEDED)), recordedOutcomes) + val entry = sut.localState(identity).journal.single() + assertEquals(Stage.SUCCEEDED, entry.stage) + assertEquals("c".repeat(64), entry.transactionId) + } + @Test fun `manual payment fails when the request is already recorded`() = test { sut.activate(identity) diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index dba969cc83..5f0b45f337 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -901,6 +901,265 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { assertTrue(storedProofs.isEmpty()) } + @Test + fun `onchain proof of a spark withdrawal completes with its txid`() = test { + val txid = "cd".repeat(32) + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + whenever( + paykitSdkService.submitPaymentProof(any(), any(), any(), any(), any(), isNull(), isNull(), isNull(), any()) + ).thenReturn(record) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted(request, ONCHAIN_ADDRESS, request.amount.atomic).getOrThrow() + + assertTrue(repo.completeSparkOnchainPayment(request, txid)) + + runCurrent() + val proofCaptor = argumentCaptor() + verify(paykitSdkService).submitPaymentProof( + any(), any(), any(), any(), proofCaptor.capture(), isNull(), isNull(), isNull(), any(), + ) + assertEquals( + """{"data":"$txid","type":"${PaykitPaymentProofKind.Onchain.type}"}""", + proofCaptor.firstValue, + ) + } + + @Test + fun `onchain proof of a spark withdrawal settles from spark after a restart`() = test { + val txid = "cd".repeat(32) + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + whenever( + paykitSdkService.submitPaymentProof(any(), any(), any(), any(), any(), isNull(), isNull(), isNull(), any()) + ).thenReturn(record) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted( + request, + ONCHAIN_ADDRESS, + request.amount.atomic, + earlierWithdrawalTxids = setOf("ef".repeat(32)), + ).getOrThrow() + + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, setOf("ef".repeat(32)))) + .thenReturn(SparkWithdrawalOutcome.Unknown) + paymentProofRepo().reconcile() + assertTrue(storedProofs.single().paymentStarted) + assertEquals(null, storedProofs.single().proofData) + + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, setOf("ef".repeat(32)))) + .thenReturn(SparkWithdrawalOutcome.Sent(txid)) + paymentProofRepo().reconcile() + runCurrent() + + val proofCaptor = argumentCaptor() + verify(paykitSdkService).submitPaymentProof( + any(), any(), any(), any(), proofCaptor.capture(), isNull(), isNull(), isNull(), any(), + ) + assertEquals( + """{"data":"$txid","type":"${PaykitPaymentProofKind.Onchain.type}"}""", + proofCaptor.firstValue, + ) + } + + @Test + fun `a spark withdrawal proof that never sent is released so the request can be paid again`() = test { + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted(request, ONCHAIN_ADDRESS, request.amount.atomic).getOrThrow() + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Unsent) + + assertTrue(repo.releaseUnsentSparkOnchainProof(request)) + + assertTrue(storedProofs.isEmpty()) + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + } + + @Test + fun `a spark withdrawal refused before its journal releases its proof without reading spark`() = test { + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted(request, ONCHAIN_ADDRESS, request.amount.atomic).getOrThrow() + val identity = storedProofs.single().identity + + assertTrue(repo.releaseRefusedSparkOnchainProof(request)) + + assertTrue(storedProofs.isEmpty()) + verify(lightningRepo, never()).sparkWithdrawalOutcome(any(), any(), any()) + verify(allowanceExecutor).onchainSendReleased(identity, request.id) + } + + @Test + fun `a spark withdrawal that never sent fails its allowance attempt on reconcile`() = test { + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted(request, ONCHAIN_ADDRESS, request.amount.atomic).getOrThrow() + val identity = storedProofs.single().identity + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Unsent) + whenever(allowanceExecutor.onchainSendReleased(any(), any())).thenThrow(RuntimeException("ledger")) + + paymentProofRepo().reconcile() + assertTrue(storedProofs.single().paymentStarted, "A ledger write that fails keeps the proof for the next pass") + + reset(allowanceExecutor) + paymentProofRepo().reconcile() + + verify(allowanceExecutor).onchainSendReleased(identity, request.id) + assertTrue(storedProofs.isEmpty()) + } + + @Test + fun `a spark withdrawal found sent settles its allowance attempt with the txid on reconcile`() = test { + val txid = "cd".repeat(32) + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted(request, ONCHAIN_ADDRESS, request.amount.atomic).getOrThrow() + val identity = storedProofs.single().identity + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Sent(txid)) + + paymentProofRepo().reconcile() + + verify(allowanceExecutor).onchainSendSettled(identity, request.id, txid) + } + + @Test + fun `a spark withdrawal found sent on reconcile resolves the pending payment`() = test { + val txid = "cd".repeat(32) + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted(request, ONCHAIN_ADDRESS, request.amount.atomic).getOrThrow() + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Sent(txid)) + + repo.reconcile() + + val resolution = repo.onchainPaymentResolutions.value.single() + assertEquals(request.id, resolution.requestId) + assertEquals(txid, resolution.transactionId) + } + + @Test + fun `a spark withdrawal found unsent on reconcile fails the pending payment`() = test { + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted(request, ONCHAIN_ADDRESS, request.amount.atomic).getOrThrow() + val identity = storedProofs.single().identity + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Unsent) + + repo.reconcile() + + assertEquals(listOf(PaykitSparkWithdrawalRelease(identity, request.id)), repo.sparkWithdrawalReleases.value) + } + + @Test + fun `a spark withdrawal proof that never sent gives back its private list on reconcile`() = test { + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + whenever(privatePaykitRepo.releasePrivatePaymentListVersion(request.id.counterparty, 7uL, 6uL)) + .thenReturn(Result.success(Unit)) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted( + request, + ONCHAIN_ADDRESS, + request.amount.atomic, + privatePaymentListVersion = 7uL, + previousPrivatePaymentListVersion = 6uL, + ).getOrThrow() + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Unsent) + + paymentProofRepo().reconcile() + + assertTrue(storedProofs.isEmpty()) + verify(privatePaykitRepo).releasePrivatePaymentListVersion(request.id.counterparty, 7uL, 6uL) + } + + @Test + fun `a spark withdrawal released on reconcile lets the request pay from the private list again`() = test { + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + whenever(privatePaykitRepo.releasePrivatePaymentListVersion(request.id.counterparty, 7uL, 6uL)) + .thenReturn(Result.success(Unit)) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted( + request, + ONCHAIN_ADDRESS, + request.amount.atomic, + privatePaymentListVersion = 7uL, + previousPrivatePaymentListVersion = 6uL, + ).getOrThrow() + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Unsent) + val relaunched = paymentProofRepo() + relaunched.reconcile() + + relaunched.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + relaunched.markSparkOnchainPaymentStarted( + request, + ONCHAIN_ADDRESS, + request.amount.atomic, + privatePaymentListVersion = 7uL, + previousPrivatePaymentListVersion = 6uL, + ).getOrThrow() + + assertEquals(7uL, storedProofs.single().privatePaymentListVersion) + verify(privatePaykitRepo, times(1)).releasePrivatePaymentListVersion(request.id.counterparty, 7uL, 6uL) + } + + @Test + fun `a spark withdrawal proof keeps its private list when the release fails on reconcile`() = test { + val record = paymentRequestRecord() + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever(paykitSdkService.paymentRequests()).thenReturn(listOf(record)) + whenever(privatePaykitRepo.releasePrivatePaymentListVersion(request.id.counterparty, 7uL, 6uL)) + .thenReturn(Result.failure(AppError("homeserver unavailable"))) + val repo = paymentProofRepo() + repo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain).getOrThrow() + repo.markSparkOnchainPaymentStarted( + request, + ONCHAIN_ADDRESS, + request.amount.atomic, + privatePaymentListVersion = 7uL, + previousPrivatePaymentListVersion = 6uL, + ).getOrThrow() + whenever(lightningRepo.sparkWithdrawalOutcome(ONCHAIN_ADDRESS, request.amount.atomic, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Unsent) + + paymentProofRepo().reconcile() + + assertEquals(7uL, storedProofs.single().privatePaymentListVersion) + } + @Test fun `a spark retry decides a lightning proof the node failed`() = test { val record = paymentRequestRecord() diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt index 4da1a00f2e..8f7c975488 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt @@ -2466,6 +2466,27 @@ class PaykitPaymentRequestRepoTest : BaseUnitTest(StandardTestDispatcher()) { verifyBlocking(paykitSdkService) { processPendingPrivateMessages() } } + @Test + fun `dismissed request is not presented again when the sdk lists it as proposed again`() = test { + val record = paymentRequestRecord() + whenever(paykitSdkService.allPaymentRequests(anyOrNull())).thenReturn(listOf(record)) + whenever(paykitSdkService.rejectPaymentRequest(COUNTERPARTY, PAYMENT_REQUEST_ID)).thenReturn(record) + sut.refresh().getOrThrow() + val request = sut.pendingRequests.value.single() + assertTrue(sut.markPresented(request)) + + sut.dismiss(request).getOrThrow() + whenever(paykitSdkService.allPaymentRequests(anyOrNull())) + .thenReturn(listOf(paymentRequestRecord(state = PaymentRequestLifecycleState.REJECTED))) + sut.refresh().getOrThrow() + assertTrue(sut.pendingRequests.value.isEmpty()) + + whenever(paykitSdkService.allPaymentRequests(anyOrNull())).thenReturn(listOf(record)) + sut.refresh().getOrThrow() + assertEquals(request.id, sut.pendingRequests.value.single().id) + assertTrue(sut.automaticPendingRequests().isEmpty()) + } + @Test fun `surfaced request stays pending and is excluded from automatic presentation`() = test { whenever(paykitSdkService.allPaymentRequests(anyOrNull())).thenReturn(listOf(paymentRequestRecord())) diff --git a/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt new file mode 100644 index 0000000000..f5e46ecb99 --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/PaykitRouteRepoTest.kt @@ -0,0 +1,119 @@ +package to.bitkit.repositories + +import com.synonym.bitkitcore.PaykitEndpoint +import com.synonym.bitkitcore.PaykitRoute +import com.synonym.bitkitcore.PaykitRouteRequest +import com.synonym.bitkitcore.ServiceRouteLeg +import com.synonym.bitkitcore.paykitRoutePayment +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.mockito.MockedStatic +import org.mockito.Mockito.mockStatic +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import to.bitkit.services.SparkError +import to.bitkit.test.BaseUnitTest +import kotlin.test.assertEquals +import kotlin.test.assertIs + +class PaykitRouteRepoTest : BaseUnitTest() { + private val sparkRepo = mock() + private val sut = PaykitRouteRepo(testDispatcher, sparkRepo) + + private val lightning = PaykitEndpoint(methodId = MethodId.Lnurl.rawValue, value = "lnurl1contact") + private val onchain = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = "bcrt1qcontact") + private lateinit var core: MockedStatic<*> + + @Before + fun setUp() { + // Stands in for bitkit-core's router: Lightning pays directly when it covers the amount, before any leg. + core = mockStatic(Class.forName("com.synonym.bitkitcore.Bitkitcore_androidKt")) + core.`when` { paykitRoutePayment(any(), any()) }.thenAnswer { + val request = it.getArgument(0) + when { + request.lightningSpendableSat >= request.amountSat -> PaykitRoute.Direct(request.contactEndpoints[0]) + request.serviceLegs.isNotEmpty() -> PaykitRoute.Service(request.serviceLegs[0]) + else -> PaykitRoute.None("No balance can reach an endpoint this contact accepts.") + } + } + } + + @After + fun tearDown() = core.close() + + @Test + fun `a contact lightning can pay routes direct without a spark quote`() = test { + whenever(sparkRepo.withdrawalRouteLeg(any(), any())).thenReturn(Result.success(null)) + + val route = sut.route( + amountSats = 1_000uL, + endpoints = listOf(lightning, onchain), + lightningSpendableSats = 5_000uL, + onchainSpendableSats = 0uL, + quoteServiceLegs = true, + ).getOrThrow() + + assertEquals(PaykitRoute.Direct(lightning), route) + verify(sparkRepo, never()).withdrawalRouteLeg(any(), any()) + } + + @Test + fun `an amount past lightning's limit takes the quoted spark leg`() = test { + val leg = ServiceRouteLeg( + service = SparkRepo.ROUTE_SERVICE, + endpoint = onchain, + deliveredSat = 10_000uL, + debitSat = 10_300uL, + atomicity = "trusted", + validUntilUnix = 0uL, + ) + whenever(sparkRepo.withdrawalRouteLeg(onchain, leg.deliveredSat)).thenReturn(Result.success(leg)) + + val route = sut.route( + amountSats = leg.deliveredSat, + endpoints = listOf(lightning, onchain), + lightningSpendableSats = 5_000uL, + onchainSpendableSats = 0uL, + quoteServiceLegs = true, + ).getOrThrow() + + assertEquals(PaykitRoute.Service(leg), route) + } + + @Test + fun `a spark leg whose fee the balance can't cover routes as a short balance`() = test { + whenever(sparkRepo.withdrawalRouteLeg(onchain, 9_000uL)) + .thenReturn(Result.failure(SparkError.WithdrawalOverBalance())) + + val route = sut.route( + amountSats = 9_000uL, + endpoints = listOf(onchain), + // The stand-in router pays any endpoint directly from Lightning, so none is offered. + lightningSpendableSats = 0uL, + onchainSpendableSats = 0uL, + quoteServiceLegs = true, + ) + + assertIs(route.exceptionOrNull()) + } + + @Test + fun `a spark leg refused while an earlier withdrawal settles routes as settling`() = test { + whenever(sparkRepo.withdrawalRouteLeg(onchain, 9_000uL)) + .thenReturn(Result.failure(SparkError.WithdrawalPending())) + + val route = sut.route( + amountSats = 9_000uL, + endpoints = listOf(onchain), + lightningSpendableSats = 0uL, + onchainSpendableSats = 0uL, + quoteServiceLegs = true, + ) + + assertIs(route.exceptionOrNull()) + } +} diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index e43cec702a..4f951f028a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -24,10 +24,13 @@ import breez_sdk_spark.SendPaymentMethod import breez_sdk_spark.SparkHtlcDetails import breez_sdk_spark.SparkHtlcStatus import breez_sdk_spark.SyncError +import com.synonym.bitkitcore.AccountUtxo import com.synonym.bitkitcore.Activity import com.synonym.bitkitcore.LightningActivity import com.synonym.bitkitcore.OnchainActivity +import com.synonym.bitkitcore.PaykitEndpoint import com.synonym.bitkitcore.PaymentState +import com.synonym.bitkitcore.ServiceRouteLeg import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -36,12 +39,15 @@ import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.withTimeoutOrNull import org.junit.Before import org.junit.Rule import org.junit.Test @@ -50,6 +56,8 @@ import org.lightningdevkit.ldknode.Event import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.atLeastOnce +import org.mockito.kotlin.clearInvocations import org.mockito.kotlin.doReturn import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq @@ -63,15 +71,21 @@ import org.mockito.kotlin.whenever import to.bitkit.data.AppCacheData import to.bitkit.data.CacheStore import to.bitkit.data.MAX_SPARK_SEND_HASHES +import to.bitkit.data.SettingsData +import to.bitkit.data.SettingsStore +import to.bitkit.data.SparkPayoutChain import to.bitkit.env.Env import to.bitkit.ext.create import to.bitkit.ext.scopedActivityId import to.bitkit.models.SparkExitBackupV1 import to.bitkit.models.WalletScope +import to.bitkit.services.CoreService +import to.bitkit.services.OnchainService import to.bitkit.services.SparkError import to.bitkit.services.SparkService import to.bitkit.test.BaseUnitTest import to.bitkit.test.InMemoryDataStore +import to.bitkit.utils.AppError import to.bitkit.utils.ServiceError import java.io.File import java.math.BigInteger @@ -79,9 +93,12 @@ import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertIs +import kotlin.test.assertNotEquals +import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock +import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant @@ -100,6 +117,10 @@ class SparkRepoTest : BaseUnitTest() { private val cacheStore = mock { on { data } doReturn cacheData } private val contactResolver = mock() private val pendingPaymentRepo = PendingPaymentRepo() + private val onchainService = mock() + private val coreService = mock { on { onchain } doReturn onchainService } + private val payoutChain = mock() + private val settingsStore = mock { on { data } doReturn flowOf(SettingsData()) } private var now = Instant.fromEpochSeconds(1_800_000_000) private val clock = object : Clock { override fun now() = this@SparkRepoTest.now @@ -113,6 +134,9 @@ class SparkRepoTest : BaseUnitTest() { contactResolver = { contactResolver }, pendingPaymentRepo = pendingPaymentRepo, clock = clock, + coreService = { coreService }, + settingsStore = settingsStore, + payoutChain = payoutChain, ) @get:Rule @@ -251,7 +275,7 @@ class SparkRepoTest : BaseUnitTest() { val expirySecs = 30 * 24 * 60 * 60L val prepared = prepared(feeSats = 0uL, createdAt = createdAt.toULong(), expirySecs = expirySecs.toULong()) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val sut = createSut(store) sut.start(0).getOrThrow() @@ -260,7 +284,7 @@ class SparkRepoTest : BaseUnitTest() { sut.earlierLightningSend("lnbc1280n1send", "hash", createdAt, createdAt + expirySecs) } assertIs(sut.payInvoice("lnbc1280n1send", 128uL).exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -315,13 +339,13 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = null)) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val restarted = createSut(store) restarted.start(0).getOrThrow() restarted.payInvoice("lnbc1280n1send", 128uL) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -331,14 +355,14 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.getInfo() }.thenReturn(info(10_000uL).copy(lastSyncedAt = null)) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val sut = createSut(store) sut.start(0).getOrThrow() val result = sut.payInvoice("lnbc1280n1send", 128uL) assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -350,7 +374,7 @@ class SparkRepoTest : BaseUnitTest() { // Spark reports Synced while its payment-history sync failed, so its list lacks the pre-restore send. val prepared = prepared(feeSats = 0uL, createdAt = (restoredAt - 600).toULong(), expirySecs = 3_600uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val sut = createSut(store) sut.start(0).getOrThrow() assertNull(store.data.first().sparkHistoryUnseededSince) @@ -358,7 +382,7 @@ class SparkRepoTest : BaseUnitTest() { val result = sut.payInvoice("lnbc1280n1send", 128uL) assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -369,7 +393,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL, createdAt = (restoredAt - 600).toULong(), expirySecs = 3_600uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val sut = createSut(store) sut.start(0).getOrThrow() assertNull(store.data.first().sparkHistoryUnseededSince) @@ -378,7 +402,7 @@ class SparkRepoTest : BaseUnitTest() { val result = sut.payInvoice("lnbc1280n1send", 128uL) assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -389,13 +413,13 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL, createdAt = now.epochSeconds.toULong(), expirySecs = 3_600uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val sut = createSut(store) sut.start(0).getOrThrow() sut.payInvoice("lnbc1280n1send", 128uL).getOrThrow() - verify(sparkService).send(any()) + verify(sparkService).send(any(), anyOrNull()) } @Test @@ -464,7 +488,8 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.listPayments() }.thenReturn(listOf(failed)) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0).copy(status = PaymentStatus.PENDING)) + whenever { sparkService.send(any(), anyOrNull()) } + .thenReturn(sentPayment(fees = 0).copy(status = PaymentStatus.PENDING)) val sut = createSut() sut.start(0).getOrThrow() var isRetried = false @@ -498,13 +523,13 @@ class SparkRepoTest : BaseUnitTest() { val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) whenever { sparkService.listPayments() }.thenReturn(emptyList()) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) createSut().payInvoice("lnbc1280n1send", 128uL).getOrThrow() inOrder(cacheStore, sparkService) { verifyBlocking(cacheStore) { addSparkSendHash(eq("hash"), anyOrNull()) } - verifyBlocking(sparkService) { send(any()) } + verifyBlocking(sparkService) { send(any(), anyOrNull()) } } } @@ -618,7 +643,7 @@ class SparkRepoTest : BaseUnitTest() { } val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenReturn(retry) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(retry) val sut = createSut(store) val starting = async { sut.start(0) } runCurrent() @@ -641,7 +666,7 @@ class SparkRepoTest : BaseUnitTest() { val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) val sending = CompletableDeferred() - whenever { sparkService.send(any()) }.doSuspendableAnswer { + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { sending.await() retry } @@ -677,7 +702,7 @@ class SparkRepoTest : BaseUnitTest() { val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) val sending = CompletableDeferred() - whenever { sparkService.send(any()) }.doSuspendableAnswer { + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { sending.await() sentPayment(fees = 0).copy(status = PaymentStatus.PENDING) } @@ -746,7 +771,7 @@ class SparkRepoTest : BaseUnitTest() { val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) val sending = CompletableDeferred() - whenever { sparkService.send(any()) }.doSuspendableAnswer { + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { sending.await() sentPayment(fees = 0).copy(status = PaymentStatus.PENDING) } @@ -769,7 +794,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenAnswer { throw IllegalStateException("lost") } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw IllegalStateException("lost") } // Spark's resync reaches it after the send failed, so a send it doesn't list never went out. whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL)) val sut = createSut() @@ -982,7 +1007,7 @@ class SparkRepoTest : BaseUnitTest() { method = PaymentMethod.WITHDRAW, details = PaymentDetails.Withdraw("withdrawal", 0u, ADDRESS), ) - whenever { sparkService.send(any()) }.thenReturn(sent) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sent) val sut = createSut() assertFalse(sut.markWithdrawalAsTransfer("withdrawal")) @@ -1024,6 +1049,1063 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(listOf(SparkWithdrawal("withdrawal", 128uL, 1_470uL)), sut.state.value.withdrawals) } + @Test + fun `quotes a withdrawal to a Paykit contact as a route leg`() = test { + val sut = readySpark(balanceSats = 50_000uL) + + val leg = sut.withdrawalRouteLeg(contactEndpoint, 20_000uL).getOrThrow() + + assertEquals( + ServiceRouteLeg( + service = "spark", + endpoint = contactEndpoint, + deliveredSat = 20_000uL, + debitSat = 20_500uL, + atomicity = "trusted", + validUntilUnix = 1_900_000_000uL, + ), + leg, + ) + } + + @Test + fun `offers no route leg the balance cannot cover with its fee`() = test { + val sut = readySpark(balanceSats = 20_499uL) + + assertIs(sut.withdrawalRouteLeg(contactEndpoint, 20_000uL).exceptionOrNull()) + } + + @Test + fun `quotes no route leg while an earlier contact withdrawal settles`() = test { + val sut = readySpark(balanceSats = 50_000uL) + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qearlier", 5_000uL, null)) } + + assertIs(sut.withdrawalRouteLeg(contactEndpoint, 20_000uL).exceptionOrNull()) + verify(sparkService, never()).prepareSend(any(), anyOrNull(), anyOrNull()) + } + + @Test + fun `quotes a route leg whose debit takes the whole balance`() = test { + val sut = readySpark(balanceSats = 20_500uL) + + assertEquals(20_500uL, sut.withdrawalRouteLeg(contactEndpoint, 20_000uL).getOrThrow()?.debitSat) + } + + @Test + fun `tells a spark withdrawal from a transaction ldk holds`() = test { + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + val sut = readySpark(balanceSats = 50_000uL) + + assertTrue(sut.isWithdrawal("withdrawal", isSent = true)) + assertFalse(sut.isWithdrawal("ldk-send", isSent = true)) + } + + @Test + fun `the savings receipt of a spark withdrawal stays boostable`() = test { + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + val sut = readySpark(balanceSats = 50_000uL) + + assertFalse(sut.isWithdrawal("withdrawal", isSent = false), "Savings owns the output the withdrawal pays") + } + + @Test + fun `records a withdrawal to a contact with its contact and fee`() = test { + val sut = journaledSpark() + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) + + assertEquals("withdrawal", sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact").getOrThrow()) + + val activity = argumentCaptor() + verify(activityRepo).upsertActivity(activity.capture()) + val onchain = assertIs(activity.firstValue).v1 + assertEquals(ActivityPaymentType.SENT, onchain.txType) + assertEquals(20_000uL, onchain.value) + assertEquals(300uL, onchain.fee) + assertEquals("pubkycontact", onchain.contact) + assertNull(cacheData.value.pendingSparkWithdrawal) + } + + @Test + fun `a completed contact withdrawal stays unconfirmed until its payout is mined`() = test { + val sut = journaledSpark() + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) + + sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact").getOrThrow() + + val activity = argumentCaptor() + verify(activityRepo).upsertActivity(activity.capture()) + assertFalse( + assertIs(activity.firstValue).v1.confirmed, + "Spark completes a withdrawal once its provider takes the payout on, before the payout is mined", + ) + } + + @Test + fun `a contact withdrawal is confirmed once the chain lists its payout in a block`() = test { + val sent = sentContactActivity(confirmed = false) + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + whenever { activityRepo.getActivity(eq("withdrawal"), any()) }.thenReturn(Result.success(sent)) + whenever { onchainService.unspentOutputs(eq("bcrt1qcontact"), any(), anyOrNull()) } + .thenReturn(listOf(payoutOutput(txid = "withdrawal", confirmations = 1u))) + + readySpark(balanceSats = 50_000uL) + advanceUntilIdle() + + val activities = argumentCaptor() + verify(activityRepo, atLeastOnce()).upsertActivity(activities.capture()) + assertTrue(activities.allValues.any { assertIs(it).v1.confirmed }) + } + + @Test + fun `a contact withdrawal whose payout is still in the mempool stays unconfirmed`() = test { + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + whenever { activityRepo.getActivity(eq("withdrawal"), any()) } + .thenReturn(Result.success(sentContactActivity(confirmed = false))) + whenever { onchainService.unspentOutputs(eq("bcrt1qcontact"), any(), anyOrNull()) } + .thenReturn(listOf(payoutOutput(txid = "withdrawal", confirmations = 0u))) + + readySpark(balanceSats = 50_000uL) + advanceUntilIdle() + + val activities = argumentCaptor() + verify(activityRepo, atLeastOnce()).upsertActivity(activities.capture()) + assertTrue(activities.allValues.none { assertIs(it).v1.confirmed }) + } + + @Test + fun `a contact withdrawal is confirmed from its transaction once the contact spent the payout`() = test { + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + whenever { activityRepo.getActivity(eq("withdrawal"), any()) } + .thenReturn(Result.success(sentContactActivity(confirmed = false))) + whenever { onchainService.unspentOutputs(eq("bcrt1qcontact"), any(), anyOrNull()) }.thenReturn(emptyList()) + whenever { payoutChain.isMined("withdrawal") }.thenReturn(true) + + readySpark(balanceSats = 50_000uL) + advanceUntilIdle() + + val activities = argumentCaptor() + verify(activityRepo, atLeastOnce()).upsertActivity(activities.capture()) + assertTrue( + activities.allValues.any { assertIs(it).v1.confirmed }, + "A payout spent before Bitkit saw it mined no longer lists as unspent, so its transaction is asked", + ) + } + + @Test + fun `a payout listed unspent in the mempool is not asked about by its transaction`() = test { + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + whenever { activityRepo.getActivity(eq("withdrawal"), any()) } + .thenReturn(Result.success(sentContactActivity(confirmed = false))) + whenever { onchainService.unspentOutputs(eq("bcrt1qcontact"), any(), anyOrNull()) } + .thenReturn(listOf(payoutOutput(txid = "withdrawal", confirmations = 0u))) + + readySpark(balanceSats = 50_000uL) + advanceUntilIdle() + + verify(payoutChain, never()).isMined(any()) + } + + @Test + fun `a confirmed contact withdrawal is not looked up on chain again`() = test { + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + whenever { activityRepo.getActivity(eq("withdrawal"), any()) } + .thenReturn(Result.success(sentContactActivity(confirmed = true))) + + readySpark(balanceSats = 50_000uL) + advanceUntilIdle() + + verify(onchainService, never()).unspentOutputs(any(), any(), anyOrNull()) + verify(payoutChain, never()).isMined(any()) + } + + @Test + fun `a contact withdrawal is confirmed from its transaction when electrum fails`() = test { + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + whenever { activityRepo.getActivity(eq("withdrawal"), any()) } + .thenReturn(Result.success(sentContactActivity(confirmed = false))) + whenever { onchainService.unspentOutputs(eq("bcrt1qcontact"), any(), anyOrNull()) } + .thenAnswer { throw IllegalStateException("electrum down") } + whenever { payoutChain.isMined("withdrawal") }.thenReturn(true) + + readySpark(balanceSats = 50_000uL) + advanceUntilIdle() + + val activities = argumentCaptor() + verify(activityRepo, atLeastOnce()).upsertActivity(activities.capture()) + assertTrue( + activities.allValues.any { assertIs(it).v1.confirmed }, + "An Electrum failure should fall back to the Esplora lookup of the payout transaction", + ) + } + + @Test + fun `confirming a mined payout keeps a seen time written during the chain lookup`() = test { + val unseen = sentContactActivity(confirmed = false) + val seen = Activity.Onchain(unseen.v1.copy(seenAt = 42uL)) + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + var stored: Activity = unseen + // A Result answer is unboxed, so the stub answers with the activity itself. + whenever { activityRepo.getActivity(eq("withdrawal"), any()) }.thenAnswer { stored } + whenever { onchainService.unspentOutputs(eq("bcrt1qcontact"), any(), anyOrNull()) }.thenAnswer { + // The user opens the activity list while the Electrum lookup is in flight. + stored = seen + listOf(payoutOutput(txid = "withdrawal", confirmations = 1u)) + } + + readySpark(balanceSats = 50_000uL) + advanceUntilIdle() + + val activities = argumentCaptor() + verify(activityRepo, atLeastOnce()).upsertActivity(activities.capture()) + val confirmed = activities.allValues.map { assertIs(it).v1 }.single { it.confirmed } + assertEquals(42uL, confirmed.seenAt, "The confirm upsert reverted a seen time written during its lookup") + } + + private fun sentContactActivity(confirmed: Boolean) = Activity.Onchain( + OnchainActivity.create( + id = "withdrawal", + txType = ActivityPaymentType.SENT, + txId = "withdrawal", + value = 20_000uL, + fee = 300uL, + address = "bcrt1qcontact", + timestamp = 1uL, + confirmed = confirmed, + contact = "pubkycontact", + ) + ) + + private fun payoutOutput(txid: String, confirmations: UInt) = AccountUtxo( + txid = txid, + vout = 0u, + amount = 20_000uL, + blockHeight = if (confirmations > 0u) 100u else 0u, + address = "bcrt1qcontact", + path = "", + confirmations = confirmations, + coinbase = false, + own = false, + required = null, + ) + + @Test + fun `an accepted withdrawal stays sent after a restart whose list lacks it`() = test { + journaledSpark().also { whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) } + .withdraw("bcrt1qcontact", 20_000uL, "pubkycontact").getOrThrow() + assertNull(cacheData.value.pendingSparkWithdrawal) + // After a restart before the request's proof completed, Spark's list lacks the withdrawal. + whenever { sparkService.listPayments() }.thenReturn(emptyList()) + val restarted = createSut() + + whenever { sparkService.getInfo() } + .thenReturn(info(50_000uL).copy(lastSyncError = SyncError.Network("operators unreachable"))) + restarted.start(0).getOrThrow() + assertEquals( + SparkWithdrawalOutcome.Sent("withdrawal"), + restarted.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet()), + "A failed sync after the restart must not release a request Spark accepted", + ) + + whenever { sparkService.getInfo() }.thenReturn(info(50_000uL)) + restarted.start(0).getOrThrow() + assertEquals( + SparkWithdrawalOutcome.Sent("withdrawal"), + restarted.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet()), + "A list that lacks an accepted withdrawal is no proof it never sent", + ) + assertNotEquals( + SparkWithdrawalOutcome.Sent("withdrawal"), + restarted.withdrawalOutcome("bcrt1qcontact", 20_000uL, setOf("withdrawal")), + "An earlier attempt's withdrawal never settles a new one", + ) + } + + @Test + fun `a cached withdrawal never settles a retry after a restart whose list lacks it`() = test { + journaledSpark().also { whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) } + .withdraw("bcrt1qcontact", 20_000uL, "pubkycontact").getOrThrow() + whenever { sparkService.listPayments() }.thenReturn(emptyList()) + val restarted = createSut().also { it.start(0).getOrThrow() } + + val earlierTxids = restarted.withdrawalTxidsTo("bcrt1qcontact") + + assertNotEquals( + SparkWithdrawalOutcome.Sent("withdrawal"), + restarted.withdrawalOutcome("bcrt1qcontact", 20_000uL, earlierTxids), + ) + } + + @Test + fun `refuses a withdrawal while an earlier one is unsettled`() = test { + val sut = journaledSpark() + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null)) } + + assertIs(sut.withdraw("bcrt1qcontact", 20_000uL, null).exceptionOrNull()) + verify(sparkService, never()).send(any(), anyOrNull()) + } + + @Test + fun `settles a journaled withdrawal from Spark's list on start`() = test { + cacheData.update { + it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, "pubkycontact")) + } + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + + journaledSpark() + + val activity = argumentCaptor() + verify(activityRepo).upsertActivity(activity.capture()) + assertEquals("pubkycontact", assertIs(activity.firstValue).v1.contact) + assertNull(cacheData.value.pendingSparkWithdrawal) + } + + @Test + fun `a pending contact withdrawal is no transfer to savings while its journal is open`() = test { + cacheData.update { + it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, "pubkycontact")) + } + whenever { sparkService.listPayments() } + .thenReturn(listOf(contactWithdrawal().copy(status = PaymentStatus.PENDING))) + + val sut = journaledSpark() + + assertEquals( + emptyList(), + sut.state.value.withdrawals, + "The refresh on start runs before the contact's send is written, and the payment pays the contact", + ) + } + + @Test + fun `drops a journaled withdrawal Spark never sent`() = test { + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null)) } + journaledSpark() + + verify(activityRepo, never()).upsertActivity(any()) + assertNull(cacheData.value.pendingSparkWithdrawal) + } + + @Test + fun `keeps a journaled withdrawal while the sync on start never reached spark`() = test { + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null)) } + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) + } + whenever(sparkService.isConnected).thenReturn(true) + // The sync call returns, but Spark could not reach its operators, so its list may lack the withdrawal. + whenever { sparkService.getInfo() } + .thenReturn(info(50_000uL).copy(lastSyncError = SyncError.Network("operators unreachable"))) + + createSut().start(0).getOrThrow() + + assertNotNull( + cacheData.value.pendingSparkWithdrawal, + "A sync that never reached Spark can't show it never sent", + ) + } + + @Test + fun `keeps an unlisted withdrawal open until its grace period passes`() = test { + val sut = journaledSpark() + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { throw SdkException.Generic("timeout") } + + assertTrue(sut.withdraw("bcrt1qcontact", 20_000uL, null).isFailure) + + assertEquals(now.epochSeconds, cacheData.value.pendingSparkWithdrawal?.startedAt) + assertEquals( + SparkWithdrawalOutcome.Unknown, + sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet()), + "A sync right after the send may not list the withdrawal yet, so it is never released as unsent", + ) + cacheData.update { + it.copy( + pendingSparkWithdrawal = it.pendingSparkWithdrawal?.copy( + startedAt = now.epochSeconds - 10.minutes.inWholeSeconds, + ), + ) + } + sut.start(0).getOrThrow() + assertNull(cacheData.value.pendingSparkWithdrawal) + } + + @Test + fun `a sync whose list was read during an aged send never drops the withdrawal it returns`() = test { + val sut = journaledSpark() + whenever { sparkService.getInfo() } + .thenReturn(info(50_000uL).copy(lastSyncedAt = (now + 1.hours).epochSeconds.toULong())) + var isSending = false + var listsDuringSend = 0 + val staleListRead = CompletableDeferred() + val staleListReturns = CompletableDeferred() + var journalWhileRecording: PendingSparkWithdrawal? = null + whenever { sparkService.listPayments() }.doSuspendableAnswer { + // The Synced handler's refresh lists first, then its journal settlement reads the list it settles from. + if (isSending && ++listsDuringSend == 2) { + staleListRead.complete(Unit) + staleListReturns.await() + } + emptyList() + } + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { + isSending = true + now += 11.minutes + backgroundScope.launch { sparkEvents.emit(SdkEvent.Synced) } + staleListRead.await() + isSending = false + contactWithdrawal() + } + whenever { activityRepo.getActivity(eq("withdrawal"), any()) }.doSuspendableAnswer { + // The stale list lands while the returned withdrawal is being recorded. + staleListReturns.complete(Unit) + withTimeoutOrNull(1.seconds) { cacheData.first { it.pendingSparkWithdrawal == null } } + journalWhileRecording = cacheData.value.pendingSparkWithdrawal + Result.success(null) + } + + sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") + advanceUntilIdle() + + assertTrue(staleListReturns.isCompleted) + assertNotNull(journalWhileRecording, "a stale list must not drop the journal of a withdrawal being recorded") + + val activity = argumentCaptor() + verify(activityRepo).upsertActivity(activity.capture()) + assertEquals("pubkycontact", assertIs(activity.firstValue).v1.contact) + } + + @Test + fun `keeps an aged failed withdrawal's journal while spark lists its payment without withdrawal details`() = test { + val sut = journaledSpark() + whenever { sparkService.getInfo() } + .thenReturn(info(50_000uL).copy(lastSyncedAt = (now + 1.hours).epochSeconds.toULong())) + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { + val paymentId = cacheData.value.pendingSparkWithdrawal?.paymentId + // Spark lists the committed withdrawal before its provider request maps it to withdrawal details. + whenever { sparkService.listPayments() }.thenReturn( + listOf( + contactWithdrawal().copy(id = paymentId.toString(), status = PaymentStatus.PENDING, details = null) + ) + ) + now += 11.minutes + throw SdkException.Generic("timeout") + } + + assertTrue(sut.withdraw("bcrt1qcontact", 20_000uL, null).isFailure) + + assertNotNull( + cacheData.value.pendingSparkWithdrawal, + "a withdrawal Spark lists without its details may still pay out, so its journal stays open", + ) + } + + @Test + fun `drops an aged failed withdrawal's journal once spark fails its payment without withdrawal details`() = test { + val sut = journaledSpark() + whenever { sparkService.getInfo() } + .thenReturn(info(50_000uL).copy(lastSyncedAt = (now + 1.hours).epochSeconds.toULong())) + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { + val paymentId = cacheData.value.pendingSparkWithdrawal?.paymentId + whenever { sparkService.listPayments() }.thenReturn( + listOf( + contactWithdrawal().copy(id = paymentId.toString(), status = PaymentStatus.FAILED, details = null) + ) + ) + now += 11.minutes + throw SdkException.Generic("timeout") + } + + assertTrue(sut.withdraw("bcrt1qcontact", 20_000uL, null).isFailure) + + assertNull( + cacheData.value.pendingSparkWithdrawal, + "a withdrawal Spark failed before it had withdrawal details never pays out, so its journal closes", + ) + } + + @Test + fun `keeps an aged failed withdrawal's journal while the sync after it never reached spark`() = test { + val sut = journaledSpark() + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { + now += 11.minutes + throw SdkException.Generic("timeout") + } + // The sync call returns, but the SDK keeps the failed Spark sync in its info. + whenever { sparkService.getInfo() }.thenReturn( + info(50_000uL).copy( + lastSyncError = SyncError.Network("operators unreachable"), + lastSyncedAt = (now + 1.hours).epochSeconds.toULong(), + ) + ) + + assertTrue(sut.withdraw("bcrt1qcontact", 20_000uL, null).isFailure) + + assertNotNull( + cacheData.value.pendingSparkWithdrawal, + "A sync that never reached Spark can't show the aged withdrawal was never sent", + ) + } + + @Test + fun `a journal that closes tells the pending send how its withdrawal ended`() = test { + val settlements = mutableListOf() + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null)) } + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + val sut = createSut() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + sut.withdrawalSettlements.collect { settlements += it } + } + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) + } + whenever { sparkService.getInfo() }.thenReturn(info(50_000uL)) + whenever(sparkService.isConnected).thenReturn(true) + + sut.start(0).getOrThrow() + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 5_000uL, null)) } + sut.start(0).getOrThrow() + + assertEquals( + listOf( + SparkWithdrawalSettlement("bcrt1qcontact", 20_000uL, "withdrawal"), + SparkWithdrawalSettlement("bcrt1qcontact", 5_000uL, null), + ), + settlements, + ) + } + + @Test + fun `a sync in a long foreground session closes an expired unlisted withdrawal`() = test { + val sut = journaledSpark() + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null)) } + whenever { sparkService.getInfo() }.thenReturn(info(50_000uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + + sparkEvents.emit(SdkEvent.Synced) + runCurrent() + + assertNull(cacheData.value.pendingSparkWithdrawal, "An expired journal must not block later withdrawals") + assertNull(sut.withdraw("bcrt1qcontact", 20_000uL, null).exceptionOrNull() as? SparkError.WithdrawalPending) + } + + @Test + fun `a synced event after a sync that never reached spark keeps an expired unlisted withdrawal`() = test { + journaledSpark() + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null)) } + // Spark emits Synced after a sync whose Spark leg failed too, and keeps that failure in its info. + whenever { sparkService.getInfo() }.thenReturn( + info(50_000uL).copy( + lastSyncError = SyncError.Network("operators unreachable"), + lastSyncedAt = now.epochSeconds.toULong(), + ) + ) + + sparkEvents.emit(SdkEvent.Synced) + runCurrent() + + assertNotNull( + cacheData.value.pendingSparkWithdrawal, + "A sync that never reached Spark can't show the withdrawal was never sent", + ) + } + + @Test + fun `a payment event keeps the journal until spark lists the withdrawal`() = test { + val sut = journaledSpark() + cacheData.update { + it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, "pubkycontact")) + } + + sparkEvents.emit(SdkEvent.PaymentSucceeded(contactWithdrawal())) + runCurrent() + + verify(activityRepo).upsertActivity(any()) + assertEquals( + SparkWithdrawalOutcome.Unknown, + sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet()), + "A list that lags the event must not read the withdrawal as unsent", + ) + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + sut.start(0).getOrThrow() + assertNull(cacheData.value.pendingSparkWithdrawal) + } + + @Test + fun `a stale settle never clears a newer withdrawal's journal`() = test { + val newer = PendingSparkWithdrawal("bcrt1qcontact", 30_000uL, "pubkycontact", startedAt = now.epochSeconds) + cacheData.update { + it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, "pubkycontact")) + } + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + // Another settle closes the older journal and the newer withdrawal writes its own while this one saves. + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + cacheData.update { it.copy(pendingSparkWithdrawal = newer) } + Result.success(Unit) + } + + journaledSpark() + + assertEquals(newer, cacheData.value.pendingSparkWithdrawal, "Losing the newer journal could pay it twice") + } + + @Test + fun `a withdrawal that failed to save is written again on refresh and settles its journal once`() = test { + cacheData.update { + it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, "pubkycontact")) + } + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) + } + whenever { activityRepo.upsertActivity(any()) } + .thenReturn(Result.failure(IllegalStateException("write failed")), Result.success(Unit)) + whenever { sparkService.getInfo() }.thenReturn(info(50_000uL)) + whenever(sparkService.isConnected).thenReturn(true) + val settlements = mutableListOf() + val sut = createSut() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + sut.withdrawalSettlements.collect { settlements += it } + } + + sut.start(0).getOrThrow() + assertEquals( + PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, "pubkycontact"), + cacheData.value.pendingSparkWithdrawal, + "A withdrawal whose activity failed to save keeps its journal", + ) + sut.refreshState().getOrThrow() + sut.refreshState().getOrThrow() + + verify(activityRepo, times(2)).upsertActivity(any()) + assertNull(cacheData.value.pendingSparkWithdrawal) + assertEquals(listOf(SparkWithdrawalSettlement("bcrt1qcontact", 20_000uL, "withdrawal")), settlements) + } + + @Test + fun `a stale settle never tells the newer withdrawal's send it ended`() = test { + // A retry to the same address and amount, so a settlement for the older one would read as the newer one's. + val newer = PendingSparkWithdrawal( + "bcrt1qcontact", + 20_000uL, + "pubkycontact", + earlierTxids = setOf("withdrawal"), + startedAt = now.epochSeconds, + ) + cacheData.update { + it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, "pubkycontact")) + } + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) + } + // Another settle closes the older journal and the newer withdrawal writes its own while this one saves. + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + cacheData.update { it.copy(pendingSparkWithdrawal = newer) } + Result.success(Unit) + } + whenever { sparkService.getInfo() }.thenReturn(info(50_000uL)) + whenever(sparkService.isConnected).thenReturn(true) + val settlements = mutableListOf() + val sut = createSut() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + sut.withdrawalSettlements.collect { settlements += it } + } + + sut.start(0).getOrThrow() + + assertEquals(newer, cacheData.value.pendingSparkWithdrawal) + assertEquals(emptyList(), settlements, "The older txid would settle the newer send still in flight") + } + + @Test + fun `keeps a journaled withdrawal Spark lists when its activity fails to save on start`() = test { + cacheData.update { + it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, "pubkycontact")) + } + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.failure(AppError("disk full"))) + + journaledSpark() + + assertEquals("pubkycontact", cacheData.value.pendingSparkWithdrawal?.contact) + } + + @Test + fun `a withdrawal refused right before it sends writes no journal`() = test { + val sut = journaledSpark() + + val result = sut.withdraw("bcrt1qcontact", 20_000uL, null, onBeforeSend = { false }) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any(), anyOrNull()) + assertNull(cacheData.value.pendingSparkWithdrawal) + } + + @Test + fun `a withdrawal whose deadline passes before it sends never leaves`() = test { + val sut = journaledSpark() + + val result = sut.withdraw( + "bcrt1qcontact", + 20_000uL, + null, + paymentDeadlineAt = now + 1.minutes, + onBeforeSend = { + // The quote's deadline passes while the allowance and the request are checked. + now += 2.minutes + true + }, + ) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any(), anyOrNull()) + assertNull(cacheData.value.pendingSparkWithdrawal) + } + + @Test + fun `a withdrawal whose deadline passes while its journal is written never leaves`() = test { + val sut = journaledSpark() + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) + if (cacheData.value.pendingSparkWithdrawal != null) now += 2.minutes + } + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) + + val result = sut.withdraw("bcrt1qcontact", 20_000uL, null, paymentDeadlineAt = now + 1.minutes) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any(), anyOrNull()) + assertNull(cacheData.value.pendingSparkWithdrawal) + } + + @Test + fun `a withdrawal whose proof is starting reads as in flight before its journal is written`() = test { + val sut = journaledSpark() + var outcomeWhileStarting: SparkWithdrawalOutcome? = null + + sut.withdraw("bcrt1qcontact", 20_000uL, null, onBeforeSend = { + // A reconcile in this window must not drop the proof the send is about to pay. + outcomeWhileStarting = sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet()) + true + }) + + assertEquals(SparkWithdrawalOutcome.Unknown, outcomeWhileStarting) + } + + @Test + fun `a withdrawal spark returns as failed is not reported as sent`() = test { + val sut = journaledSpark() + val failed = contactWithdrawal().copy(status = PaymentStatus.FAILED) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(failed) + whenever(sparkService.listPayments()).thenReturn(emptyList(), listOf(failed)) + + val result = sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") + + assertNull(result.getOrNull()) + assertIs(result.exceptionOrNull()) + assertNull(cacheData.value.pendingSparkWithdrawal) + assertEquals( + SparkWithdrawalOutcome.Unsent, + sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet()), + "The proof, private list and allowance attempt are released as for any unsent withdrawal", + ) + } + + @Test + fun `a pending withdrawal stays open until spark completes it`() = test { + val sut = journaledSpark() + val pending = contactWithdrawal().copy(status = PaymentStatus.PENDING) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(pending) + whenever(sparkService.listPayments()).thenReturn(emptyList(), listOf(pending)) + + val result = sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") + + assertNull(result.getOrNull(), "Spark can still fail a withdrawal until its provider accepts the payout") + assertEquals("pubkycontact", cacheData.value.pendingSparkWithdrawal?.contact) + assertEquals(SparkWithdrawalOutcome.Unknown, sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet())) + + whenever(sparkService.listPayments()).thenReturn(listOf(contactWithdrawal())) + sut.start(0).getOrThrow() + + assertNull(cacheData.value.pendingSparkWithdrawal) + assertEquals( + SparkWithdrawalOutcome.Sent("withdrawal"), + sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet()), + ) + } + + @Test + fun `a pending withdrawal spark later fails closes as unsent`() = test { + val sut = journaledSpark() + val pending = contactWithdrawal().copy(status = PaymentStatus.PENDING) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(pending) + whenever(sparkService.listPayments()).thenReturn(emptyList(), listOf(pending)) + sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") + + whenever(sparkService.listPayments()).thenReturn(listOf(pending.copy(status = PaymentStatus.FAILED))) + sut.start(0).getOrThrow() + + assertNull(cacheData.value.pendingSparkWithdrawal) + assertEquals(SparkWithdrawalOutcome.Unsent, sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet())) + } + + @Test + fun `a withdrawal spark refuses for its balance closes its journal at once`() = test { + val sut = journaledSpark() + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.InsufficientFunds(null) } + clearInvocations(sparkService) + + val result = sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") + + // Spark picks the leaves to spend before anything reaches its operators, so nothing left the wallet. + assertIs(result.exceptionOrNull()) + assertNull(cacheData.value.pendingSparkWithdrawal) + verify(sparkService, never()).syncWallet() + } + + @Test + fun `a withdrawal spark refuses for a fee that rose past its quote closes its journal at once`() = test { + val sut = journaledSpark() + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { + throw SdkException.InvalidInput( + "The onchain fee rose to 900 sats at the slowest speed, above the 500 sats quoted for this payment. " + + "Please re-prepare the payment.", + ) + } + clearInvocations(sparkService) + + val result = sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") + + // Spark refreshes an expiring quote and checks its fee before it withdraws, so nothing left the wallet. + assertIs(result.exceptionOrNull()) + assertNull(cacheData.value.pendingSparkWithdrawal) + verify(sparkService, never()).syncWallet() + } + + @Test + fun `a withdrawal to a contact is not marked as a transfer`() = test { + val sent = OnchainActivity.create( + id = "withdrawal", + txType = ActivityPaymentType.SENT, + txId = "withdrawal", + value = 20_000uL, + fee = 500uL, + address = "bcrt1qcontact", + timestamp = 1uL, + ) + whenever { activityRepo.getOnchainActivityByTxId(eq("withdrawal"), any()) }.thenReturn(sent) + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + val sut = journaledSpark() + + assertTrue(sut.markWithdrawalAsTransfer("withdrawal")) + verify(activityRepo, never()).updateActivity(any(), any(), any()) + } + + @Test + fun `lists a withdrawal to a contact with the sends, not as a transfer to savings`() = test { + val sent = OnchainActivity.create( + id = "withdrawal", + txType = ActivityPaymentType.SENT, + txId = "withdrawal", + value = 20_000uL, + fee = 300uL, + address = "bcrt1qcontact", + timestamp = 1uL, + ) + whenever { activityRepo.getActivity(eq("withdrawal"), any()) } + .thenReturn(Result.success(Activity.Onchain(sent))) + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + + val sut = journaledSpark() + + assertTrue(sut.state.value.withdrawals.isEmpty()) + } + + @Test + fun `refuses a withdrawal whose fee rose above the confirmed debit`() = test { + val sut = journaledSpark() + + val result = sut.withdraw("bcrt1qcontact", 20_000uL, null, maxDebitSats = 20_499uL) + + assertIs(result.exceptionOrNull()) + verify(sparkService, never()).send(any(), anyOrNull()) + assertNull(cacheData.value.pendingSparkWithdrawal) + } + + @Test + fun `keeps the journal when the withdrawal's activity fails to save`() = test { + val sut = journaledSpark() + whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.failure(AppError("disk full"))) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) + + sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact").getOrThrow() + + assertEquals("pubkycontact", cacheData.value.pendingSparkWithdrawal?.contact) + } + + @Test + fun `keeps the journal when the withdrawal's tags fail to save`() = test { + val sut = journaledSpark() + whenever { activityRepo.addTagsToActivity(any(), any(), any()) } + .thenReturn(Result.failure(AppError("disk full"))) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) + + sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact", tags = listOf("rent")).getOrThrow() + + assertEquals(listOf("rent"), cacheData.value.pendingSparkWithdrawal?.tags) + } + + @Test + fun `settles the journal of a deleted withdrawal it cannot tag`() = test { + val sut = journaledSpark() + whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.failure(ActivityDeletedError("withdrawal"))) + whenever { activityRepo.addTagsToActivity(any(), any(), any()) } + .thenReturn(Result.failure(AppError("not found"))) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) + + sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact", tags = listOf("rent")).getOrThrow() + + assertNull(cacheData.value.pendingSparkWithdrawal) + } + + @Test + fun `an earlier withdrawal to the same address never settles a new attempt`() = test { + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + val sut = journaledSpark() + cacheData.update { + it.copy( + pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null, setOf("withdrawal")), + ) + } + + assertEquals( + SparkWithdrawalOutcome.Unknown, + sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, setOf("withdrawal")), + ) + cacheData.update { it.copy(pendingSparkWithdrawal = null) } + assertEquals( + SparkWithdrawalOutcome.Unsent, + sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, setOf("withdrawal")), + ) + assertEquals( + SparkWithdrawalOutcome.Sent("withdrawal"), + sut.withdrawalOutcome("bcrt1qcontact", 20_000uL, emptySet()), + ) + } + + @Test + fun `tags a recovered withdrawal with the tags picked on confirmation`() = test { + whenever { activityRepo.addTagsToActivity(any(), any(), any()) }.thenReturn(Result.success(Unit)) + cacheData.update { + it.copy( + pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 20_000uL, null, tags = listOf("rent")), + ) + } + whenever { sparkService.listPayments() }.thenReturn(listOf(contactWithdrawal())) + + journaledSpark() + + verify(activityRepo).addTagsToActivity(eq("withdrawal"), eq(listOf("rent")), any()) + assertNull(cacheData.value.pendingSparkWithdrawal) + } + + @Test + fun `an older open journal refuses a new withdrawal before its proof can start`() = test { + val sut = journaledSpark() + cacheData.update { it.copy(pendingSparkWithdrawal = PendingSparkWithdrawal("bcrt1qcontact", 5_000uL, null)) } + var checked = false + + val result = sut.withdraw("bcrt1qcontact", 20_000uL, null, onBeforeSend = { + checked = true + true + }) + + assertIs(result.exceptionOrNull()) + assertFalse(checked) + verify(sparkService, never()).prepareSend(any(), anyOrNull(), anyOrNull()) + assertEquals(5_000uL, cacheData.value.pendingSparkWithdrawal?.amountSats) + } + + @Test + fun `a second withdrawal started while the first prepares is refused`() = test { + val sut = journaledSpark() + val prepared = sparkService.prepareSend("bcrt1qcontact", 20_000uL, null) + val prepareGate = CompletableDeferred() + whenever { sparkService.prepareSend(eq("bcrt1qcontact"), eq(20_000uL), anyOrNull()) }.doSuspendableAnswer { + prepareGate.await() + prepared + } + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(contactWithdrawal()) + val first = async { sut.withdraw("bcrt1qcontact", 20_000uL, "first") } + runCurrent() + + val second = async { sut.withdraw("bcrt1qcontact", 20_000uL, "second") } + runCurrent() + prepareGate.complete(Unit) + + assertIs(second.await().exceptionOrNull()) + assertEquals("withdrawal", first.await().getOrThrow()) + verify(sparkService, times(1)).send(any(), anyOrNull()) + } + + @Test + fun `a foreground during an in-flight withdrawal keeps its journal until spark lists it`() = test { + val sut = journaledSpark() + val sendGate = CompletableDeferred() + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { + sendGate.await() + contactWithdrawal() + } + val withdrawal = async { sut.withdraw("bcrt1qcontact", 20_000uL, "pubkycontact") } + runCurrent() + assertEquals("pubkycontact", cacheData.value.pendingSparkWithdrawal?.contact) + + var offline = true + whenever { sparkService.syncWallet() }.thenAnswer { if (offline) throw SdkException.Generic("offline") } + sut.start(0).getOrThrow() + assertEquals("pubkycontact", cacheData.value.pendingSparkWithdrawal?.contact) + offline = false + sut.start(0).getOrThrow() + assertEquals("pubkycontact", cacheData.value.pendingSparkWithdrawal?.contact) + + sendGate.complete(Unit) + assertEquals("withdrawal", withdrawal.await().getOrThrow()) + + assertNull(cacheData.value.pendingSparkWithdrawal) + val activity = argumentCaptor() + verify(activityRepo).upsertActivity(activity.capture()) + assertEquals("pubkycontact", assertIs(activity.firstValue).v1.contact) + } + + private suspend fun journaledSpark(): SparkRepo { + whenever { cacheStore.update(any()) }.doSuspendableAnswer { + cacheData.update(it.getArgument<(AppCacheData) -> AppCacheData>(0)) + } + return readySpark(balanceSats = 50_000uL) + } + + private fun contactWithdrawal() = sentPayment(fees = 300).copy( + id = "withdrawal-payment", + amount = BigInteger.valueOf(20_000), + method = PaymentMethod.WITHDRAW, + details = PaymentDetails.Withdraw("withdrawal", 0u, "bcrt1qcontact"), + ) + + private val contactEndpoint = PaykitEndpoint(methodId = "btc-regtest-p2wpkh", value = "bcrt1qcontact") + + private suspend fun readySpark(balanceSats: ULong): SparkRepo { + whenever { sparkService.getInfo() }.thenReturn(info(balanceSats)) + val speed = SendOnchainSpeedFeeQuote(userFeeSat = 300uL, l1BroadcastFeeSat = 200uL) + val prepared = mock() + whenever(prepared.paymentMethod).thenReturn( + SendPaymentMethod.BitcoinAddress( + address = mock(), + feeQuote = SendOnchainFeeQuote("quote", 1_900_000_000uL, speed, speed, speed, isEstimate = false), + ), + ) + whenever { sparkService.prepareSend(eq("bcrt1qcontact"), eq(20_000uL), anyOrNull()) }.thenReturn(prepared) + whenever(sparkService.isConnected).thenReturn(true) + return createSut().also { it.start(0).getOrThrow() } + } + @Test fun `skips an exit backup from another network`() = test { val sut = createSut() @@ -1265,7 +2347,8 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.getInfo() }.thenReturn(info(10_000uL)) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) - whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("operators unreachable") } + whenever { sparkService.send(any(), anyOrNull()) } + .thenAnswer { throw SdkException.Generic("operators unreachable") } val sut = createSut() sut.refreshState().getOrThrow() @@ -1285,7 +2368,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.getInfo() }.thenAnswer { read } whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) - whenever { sparkService.send(any()) }.thenAnswer { + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { read = staleZero sentPayment(fees = 500) } @@ -1313,7 +2396,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.getInfo() }.thenAnswer { read } whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) - whenever { sparkService.send(any()) }.thenAnswer { + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { read = staleZero sentPayment(fees = 500) } @@ -1342,7 +2425,8 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.getInfo() }.thenReturn(info(10_000uL)) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) - whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("operators unreachable") } + whenever { sparkService.send(any(), anyOrNull()) } + .thenAnswer { throw SdkException.Generic("operators unreachable") } val sut = createSut() sut.refreshState().getOrThrow() assertTrue(sut.withdrawAll(ADDRESS, confirmedFeeSats = 500uL).isFailure) @@ -1395,7 +2479,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.getInfo() }.thenReturn(info(10_000uL)) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 500)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 500)) whenever { sparkService.listPayments() }.thenAnswer { throw SdkException.Generic("offline") } assertTrue(createSut().withdrawAll(ADDRESS, confirmedFeeSats = 500uL).isSuccess) @@ -1484,7 +2568,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenAnswer { throw noRoute } assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -1501,7 +2585,7 @@ class SparkRepoTest : BaseUnitTest() { val result = sut.payInvoice("lnbc1", 100uL, onBeforeSend = { !cancelled }) assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -1515,7 +2599,7 @@ class SparkRepoTest : BaseUnitTest() { val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenAnswer { throw expired } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw expired } assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) } @@ -1524,7 +2608,8 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.InvalidInput("Invoice has expired") } + whenever { sparkService.send(any(), anyOrNull()) } + .thenAnswer { throw SdkException.InvalidInput("Invoice has expired") } val sut = createSut() assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) @@ -1537,7 +2622,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.InsufficientFunds(null) } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.InsufficientFunds(null) } val sut = createSut() val error = sut.payInvoice("lnbc1", 100uL).exceptionOrNull() @@ -1554,9 +2639,9 @@ class SparkRepoTest : BaseUnitTest() { val sut = createSut() assertIs(sut.payInvoice("lnbc1", 100uL, maxTotalFeeMsat = 1_999uL).exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 2)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 2)) assertEquals("hash", sut.payInvoice("lnbc1", 100uL, maxTotalFeeMsat = 2_000uL).getOrThrow()) } @@ -1566,7 +2651,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.getInfo() }.thenReturn(info(10_000uL)) val held = withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(held) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val sut = createSut() assertEquals(500uL, sut.estimateWithdrawAllFeeSats(ADDRESS).getOrThrow()) @@ -1605,7 +2690,7 @@ class SparkRepoTest : BaseUnitTest() { val result = sut.payInvoice("lnbc1", 100uL, paymentDeadlineAt = now - 1.minutes) assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -1613,7 +2698,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL)) val sut = createSut() @@ -1654,7 +2739,7 @@ class SparkRepoTest : BaseUnitTest() { val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) val sending = CompletableDeferred() - whenever { sparkService.send(any()) }.doSuspendableAnswer { sending.await() } + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { sending.await() } val sut = createSut() val first = async { sut.payInvoice("lnbc1", 100uL) } @@ -1664,7 +2749,7 @@ class SparkRepoTest : BaseUnitTest() { assertIs(second.exceptionOrNull()) assertEquals("hash", first.await().getOrThrow()) - verify(sparkService, times(1)).send(any()) + verify(sparkService, times(1)).send(any(), anyOrNull()) } @Test @@ -1682,7 +2767,7 @@ class SparkRepoTest : BaseUnitTest() { .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.PENDING))) assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -1699,7 +2784,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL, amountSats = 1_000)) assertIs(sut.estimateWithdrawAllFeeSats(ADDRESS).exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -1778,7 +2863,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } // The SDK reports a wallet sync that failed in its info, not by throwing. whenever { sparkService.getInfo() }.thenReturn( info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable"), lastSyncedAt = 1uL) @@ -1845,7 +2930,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } val sut = createSut() sut.start(0).getOrThrow() // From here every resync fails, so Spark's list stays as it was before the send. @@ -1862,7 +2947,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } val sut = createSut() sut.start(0).getOrThrow() whenever { sparkService.syncWallet() }.thenAnswer { throw SdkException.Generic("operators unreachable") } @@ -1872,7 +2957,7 @@ class SparkRepoTest : BaseUnitTest() { assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) // Spark makes a new transfer for each send call, so a second one may pay the invoice again. - verify(sparkService, times(1)).send(any()) + verify(sparkService, times(1)).send(any(), anyOrNull()) } @Test @@ -1882,7 +2967,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.getInfo() }.thenReturn(info(0uL).copy(lastSyncedAt = null)) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } val sut = createSut() sut.start(0).getOrThrow() assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) @@ -1890,7 +2975,7 @@ class SparkRepoTest : BaseUnitTest() { assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) - verify(sparkService, times(1)).send(any()) + verify(sparkService, times(1)).send(any(), anyOrNull()) } @Test @@ -1905,14 +2990,14 @@ class SparkRepoTest : BaseUnitTest() { ) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } val sut = createSut() sut.start(0).getOrThrow() assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) // Spark makes a new transfer for each send call, so the retry would pay the invoice again. - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -1947,7 +3032,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val deadline = now + 1.seconds val sut = createSut() @@ -1958,7 +3043,7 @@ class SparkRepoTest : BaseUnitTest() { } assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) } @Test @@ -1966,7 +3051,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenReturn(sentPayment(fees = 0)) + whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val deadline = now + 1.seconds whenever { cacheStore.addSparkUncertainSend(any(), any()) }.thenAnswer { now = deadline + 1.seconds @@ -1977,7 +3062,7 @@ class SparkRepoTest : BaseUnitTest() { val result = sut.payInvoice("lnbc1", 100uL, deadline, null) { true } assertIs(result.exceptionOrNull()) - verify(sparkService, never()).send(any()) + verify(sparkService, never()).send(any(), anyOrNull()) verifyBlocking(cacheStore) { removeSparkUncertainSend("hash") } verifyBlocking(cacheStore) { removeSparkSendHash("hash") } } @@ -1988,7 +3073,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } val sut = createSut() sut.start(0).getOrThrow() val events = mutableListOf() @@ -2023,7 +3108,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } // An earlier attempt of the invoice failed, and the retry's outcome is unknown when the app stops. whenever { sparkService.listPayments() } .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) @@ -2054,7 +3139,7 @@ class SparkRepoTest : BaseUnitTest() { val prepared = unexpiredPrepared() whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) // The process dies inside Spark's send call, so the call never returns. - whenever { sparkService.send(any()) }.doSuspendableAnswer { awaitCancellation() } + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { awaitCancellation() } whenever { sparkService.listPayments() } .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) val before = createSut(store) @@ -2082,7 +3167,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = unexpiredPrepared() whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.doSuspendableAnswer { awaitCancellation() } + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { awaitCancellation() } whenever { sparkService.listPayments() } .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) val sut = createSut(store) @@ -2138,7 +3223,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } whenever { sparkService.getInfo() }.thenReturn( info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) ) @@ -2166,7 +3251,7 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isConnected).thenReturn(true) val prepared = prepared(feeSats = 0uL) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) - whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } val sut = createSut() sut.start(0).getOrThrow() whenever { sparkService.getInfo() }.thenReturn( @@ -2196,7 +3281,7 @@ class SparkRepoTest : BaseUnitTest() { val unexpired = prepared(feeSats = 0uL) .copy(paymentMethod = SendPaymentMethod.Bolt11Invoice(details, null, 0uL)) whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(unexpired) - whenever { sparkService.send(any()) }.thenAnswer { throw SdkException.Generic("timeout") } + whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } val sut = createSut() sut.start(0).getOrThrow() val events = mutableListOf() diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt new file mode 100644 index 0000000000..3f24c2b268 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmLnurlOnchainTest.kt @@ -0,0 +1,138 @@ +package to.bitkit.ui.screens.wallets.send + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalInspectionMode +import androidx.compose.ui.test.assertTextEquals +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.test.core.app.ApplicationProvider +import com.synonym.bitkitcore.LnurlPayData +import com.synonym.bitkitcore.PaykitEndpoint +import com.synonym.bitkitcore.ServiceRouteLeg +import kotlinx.collections.immutable.persistentListOf +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import to.bitkit.R +import to.bitkit.ui.shared.modifiers.sheetHeight +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.viewmodels.LnurlParams +import to.bitkit.viewmodels.PaykitRouteUi +import to.bitkit.viewmodels.SendMethod +import to.bitkit.viewmodels.SendUiState + +@RunWith(RobolectricTestRunner::class) +class SendConfirmLnurlOnchainTest { + @get:Rule + val composeRule = createComposeRule() + + @Config(sdk = [34], qualifiers = "w411dp-h891dp") + @Test + fun `an onchain payment to a contact with an lnurl confirms with the onchain details`() { + render( + SendUiState( + amount = 6_000u, + address = ADDRESS, + isAmountInputValid = true, + payMethod = SendMethod.ONCHAIN, + lnurl = LnurlParams.LnurlPay(LNURL), + ), + ) + val lnurlTitle = ApplicationProvider.getApplicationContext() + .getString(R.string.wallet__lnurl_p_title) + + composeRule.onNodeWithText(lnurlTitle).assertDoesNotExist() + composeRule.onNodeWithTag("SendConfirmToggleDetails").assertExists() + composeRule.onNodeWithTag("ReviewUri").assertTextEquals(ADDRESS) + } + + @Config(sdk = [34], qualifiers = "w411dp-h891dp") + @Test + fun `a spark leg to a contact with an lnurl confirms to the leg's onchain address`() { + val endpoint = PaykitEndpoint(methodId = "btc-regtest-p2wpkh", value = ADDRESS) + val leg = ServiceRouteLeg( + service = "spark", + endpoint = endpoint, + deliveredSat = 2_000uL, + debitSat = 2_300uL, + atomicity = "trusted", + validUntilUnix = 0uL, + ) + render( + SendUiState( + amount = 2_000u, + isAmountInputValid = true, + payMethod = SendMethod.LIGHTNING, + lnurl = LnurlParams.LnurlPay(LNURL), + lightningFeeSats = 300, + paykitRoute = PaykitRouteUi(persistentListOf(endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + composeRule.onNodeWithTag("ReviewSwapRoute").assertExists() + composeRule.onNodeWithTag("ReviewUri").assertTextEquals(ADDRESS) + } + + @Config(sdk = [34], qualifiers = "w411dp-h891dp") + @Test + fun `a spark leg to a contact with an lnurl shows tags and no lnurl comment`() { + val endpoint = PaykitEndpoint(methodId = "btc-regtest-p2wpkh", value = ADDRESS) + val leg = ServiceRouteLeg( + service = "spark", + endpoint = endpoint, + deliveredSat = 2_000uL, + debitSat = 2_300uL, + atomicity = "trusted", + validUntilUnix = 0uL, + ) + render( + SendUiState( + amount = 2_000u, + isAmountInputValid = true, + payMethod = SendMethod.LIGHTNING, + lnurl = LnurlParams.LnurlPay(LNURL.copy(commentAllowed = 100u)), + lightningFeeSats = 300, + paykitRoute = PaykitRouteUi(persistentListOf(endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + composeRule.onNodeWithTag("ReviewSwapRoute").assertExists() + composeRule.onNodeWithTag("CommentInput").assertDoesNotExist() + composeRule.onNodeWithTag("TagsAddSend").assertExists() + } + + private fun render(uiState: SendUiState) { + composeRule.setContent { + CompositionLocalProvider(LocalInspectionMode provides true) { + AppThemeSurface { + SendConfirmContent( + uiState = uiState, + isNodeRunning = true, + isLoading = false, + showBiometrics = false, + initialShowDetails = true, + modifier = Modifier.sheetHeight() + ) + } + } + } + } + + private companion object { + const val ADDRESS = "bcrt1qkgfgyxyqhvkdqh04sklnzxphmcds6vft6y7h0r" + val LNURL = LnurlPayData( + uri = "lnurl1mixedcontact", + callback = "https://example.com/pay", + minSendable = 5_000_000u, + maxSendable = 100_000_000u, + metadataStr = "[]", + commentAllowed = null, + allowsNostr = false, + nostrPubkey = null, + ) + } +} diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 6b1f91892e..0fa434ff19 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -21,7 +21,10 @@ import com.synonym.bitkitcore.LnurlAddressData import com.synonym.bitkitcore.LnurlPayData import com.synonym.bitkitcore.NetworkType import com.synonym.bitkitcore.OnChainInvoice +import com.synonym.bitkitcore.PaykitEndpoint +import com.synonym.bitkitcore.PaykitRoute import com.synonym.bitkitcore.Scanner +import com.synonym.bitkitcore.ServiceRouteLeg import com.synonym.bitkitcore.UsdtDestination import com.synonym.bitkitcore.UsdtException import com.synonym.bitkitcore.UsdtPaymentRequest @@ -59,6 +62,7 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runCurrent @@ -189,6 +193,8 @@ import to.bitkit.repositories.PaykitPaymentRequestRefreshMode import to.bitkit.repositories.PaykitPaymentRequestRepo import to.bitkit.repositories.PaykitPaymentRequestTarget import to.bitkit.repositories.PaykitRecurrenceUnit +import to.bitkit.repositories.PaykitRouteRepo +import to.bitkit.repositories.PaykitSparkWithdrawalRelease import to.bitkit.repositories.PaykitSubscription import to.bitkit.repositories.PaykitSubscriptionId import to.bitkit.repositories.PaykitSubscriptionMetadata @@ -214,6 +220,8 @@ import to.bitkit.repositories.QuickPayRepo import to.bitkit.repositories.SamRockRepo import to.bitkit.repositories.SettledReceiveAddress import to.bitkit.repositories.SettledReceiveInvoice +import to.bitkit.repositories.SparkWithdrawalOutcome +import to.bitkit.repositories.SparkWithdrawalSettlement import to.bitkit.repositories.TransferRepo import to.bitkit.repositories.UsdtPreferencesRepo import to.bitkit.repositories.UsdtRepo @@ -231,6 +239,7 @@ import to.bitkit.services.NodeServiceFgState import to.bitkit.services.PaykitSdkOperationLock.Priority import to.bitkit.services.PaykitSdkService import to.bitkit.services.PendingChannelMigration +import to.bitkit.services.SparkError import to.bitkit.test.BaseUnitTest import to.bitkit.ui.Routes import to.bitkit.ui.components.Sheet @@ -254,6 +263,7 @@ import java.net.URLEncoder import java.nio.charset.StandardCharsets import kotlin.test.assertEquals import kotlin.test.assertFalse +import kotlin.test.assertIs import kotlin.test.assertNotEquals import kotlin.test.assertNotNull import kotlin.test.assertNull @@ -308,6 +318,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { private val paykitPaymentProofRepo = mock() private val paykitPaymentRequestDiagnostics = mock() private val usdtRepo = mock() + private val paykitRouteRepo = mock() private val usdtState = MutableStateFlow(UsdtWalletState(balance = 1_000_000u)) private val paykitUsdtPayments = mock() private val samRockRepo = mock() @@ -346,6 +357,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { private val paykitPaymentRequestHistory = MutableStateFlow>(emptyList()) private val paykitSubscriptions = MutableStateFlow>(emptyList()) private val onchainPaymentResolutions = MutableStateFlow>(emptyList()) + private val sparkWithdrawalReleases = MutableStateFlow>(emptyList()) + private val sparkWithdrawalSettlements = MutableSharedFlow(extraBufferCapacity = 8) private val proofStateVersion = MutableStateFlow(0L) private val usdtStateVersion = MutableStateFlow(0L) private val surfacedPaykitPaymentRequestIds = mutableSetOf() @@ -704,6 +717,16 @@ class AppViewModelSendFlowTest : BaseUnitTest() { private var walletGeneration = 0L private fun stubRepositories() { + // The router pays the endpoint of the selected source: Lightning from Spending, on-chain from Savings. + // Result is an inline class, so a suspend answer returns its value unboxed. + whenever { paykitRouteRepo.route(any(), any(), any(), any(), any()) }.thenAnswer { + val endpoints = it.getArgument>(1) + val fromSpending = it.getArgument(3) == 0L + val picked = endpoints.firstOrNull { endpoint -> + MethodId.fromRawValue(endpoint.methodId)?.isOnchain != fromSpending + } ?: endpoints.firstOrNull() + picked?.let { endpoint -> PaykitRoute.Direct(endpoint) } ?: PaykitRoute.None("No endpoint") + } whenever(connectionRecovery.currentGeneration()).thenAnswer { walletGeneration } whenever(connectionRecovery.isCurrentGeneration(anyOrNull())).thenAnswer { it.getArgument(0) == walletGeneration @@ -716,6 +739,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(LightningState())) whenever(lightningRepo.isRecoveryMode).thenReturn(isRecoveryMode) whenever(lightningRepo.isSparkReady).thenReturn(isSparkReady) + whenever(lightningRepo.sparkWithdrawalSettlements).thenReturn(sparkWithdrawalSettlements) whenever(lightningRepo.nodeEventUpdates).thenReturn(nodeEventUpdates) whenever(lightningRepo.nodeEvents).thenReturn(nodeEventUpdates.map { it.event }) whenever(hwWalletRepo.receivedTxs).thenReturn(hwReceivedTxs) @@ -818,6 +842,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(paykitPaymentRequestRepo.isExpired(any())).thenReturn(false) whenever(paykitPaymentRequestRepo.isProcessing(any())).thenReturn(false) whenever(paykitPaymentProofRepo.onchainPaymentResolutions).thenReturn(onchainPaymentResolutions) + whenever(paykitPaymentProofRepo.sparkWithdrawalReleases).thenReturn(sparkWithdrawalReleases) whenever(paykitAllowanceRepo.events).thenReturn(MutableSharedFlow()) whenever(paykitAllowanceRepo.isUpdatingFlow).thenReturn(allowanceUpdating) whenever(paykitAllowanceRepo.offersToAnnounce).thenReturn(MutableStateFlow(emptyList())) @@ -962,6 +987,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { paykitPaymentRequestDiagnostics = paykitPaymentRequestDiagnostics, refreshContactPaykitLink = refreshContactPaykitLink, usdtRepo = usdtRepo, + paykitRouteRepo = paykitRouteRepo, paykitUsdtPayments = paykitUsdtPayments, samRockRepo = samRockRepo, appUpdateSheet = mock { on { type } doReturn TimedSheetType.APP_UPDATE }, @@ -11438,6 +11464,29 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } } + @Test + fun `onchain and USDT contact keeps the spark leg whatever the USDT preference`() = test { + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + balanceState.value = BalanceState(maxSendLightningSats = 50_000u) + for (enabled in listOf(true, false)) { + usdtEnabled.value = enabled + sut.openContactPayment( + paymentRequest = REGTEST_ADDRESS, + publicKey = testPublicKey, + endpoints = listOf( + Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = ""), + Endpoint(MethodId.UsdtArbitrum, "0x1111111111111111111111111111111111111111", rawPayload = ""), + ), + ) + advanceUntilIdle() + + assertEquals(true, sut.sendUiState.value.paykitRoute?.offersSparkLeg, "USDT enabled: $enabled") + } + } + @Test fun `hardware mixed contact uses only its onchain endpoint`() = test { val bolt11 = "lnbcrt1contactfixed" @@ -12204,128 +12253,340 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } @Test - fun `incoming payment request consumes its private list before it is accepted`() = test { - val address = "bcrt1qpaymentrequest" - val request = paymentRequest() - val privateContext = privatePaymentContext(7uL) - balanceState.value = BalanceState(maxSendOnchainSats = 100_000u) - whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) - whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) - .thenReturn(Result.success(Unit)) - stubSuccessfulOnchainSend(address, request.amount.atomic) - setActiveContactPaymentContext(testPublicKey, privateContext, request) + fun `spark route pays the contact while spending is the source`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any(), anyOrNull(), any())) + .thenReturn(Result.success("txid")) + setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) setSendState( SendUiState( - address = address, - amount = request.amount.atomic, - payMethod = SendMethod.ONCHAIN, - speed = TransactionSpeed.Medium, - isPaymentRequest = true, + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), ), ) confirmCurrentPayment() - inOrder(paykitPaymentProofRepo, privatePaykitRepo, paykitPaymentRequestRepo).apply { - verify( - paykitPaymentProofRepo - ).prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain) - verify(privatePaykitRepo).consumePrivatePaymentList(testPublicKey, privateContext) - verify(paykitPaymentRequestRepo).accept(request) - } - verify( - paykitPaymentProofRepo - ).completeOnchainPayment( - request, - "txid", - MethodId.P2wpkh.rawValue, - "bitkit", - OnchainSendOutcome.Accepted("txid") - ) - verify(privatePaykitRepo, never()).releasePrivatePaymentList(any(), any()) + verify(paykitRouteRepo).payServiceLeg(eq(leg), eq("pubkycontact"), any(), anyOrNull(), any()) } @Test - fun `accepted onchain payment survives a contended background proof completion`() = test { - val address = "bcrt1qpaymentrequest" - val request = paymentRequest() - val privateContext = privatePaymentContext(7uL) + fun `spark route stays unused once savings is the source`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") balanceState.value = BalanceState(maxSendOnchainSats = 100_000u) - whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) - whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) - .thenReturn(Result.success(Unit)) - whenever( - paykitPaymentProofRepo.completeOnchainPayment( - request, - "txid", - MethodId.P2wpkh.rawValue, - "bitkit", - OnchainSendOutcome.Accepted("txid"), - ) - ).doSuspendableAnswer { throw PaykitException.SharedStateBusy("shared_state_busy", "Locked") } - stubSuccessfulOnchainSend(address, request.amount.atomic) - setActiveContactPaymentContext(testPublicKey, privateContext, request) + stubSuccessfulOnchainSend(leg.endpoint.value, leg.deliveredSat) + setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) setSendState( SendUiState( - address = address, - amount = request.amount.atomic, + address = leg.endpoint.value, + amount = leg.deliveredSat, payMethod = SendMethod.ONCHAIN, speed = TransactionSpeed.Medium, - isPaymentRequest = true, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + confirmCurrentPayment() + + verify(paykitRouteRepo, never()).payServiceLeg(any(), anyOrNull(), any(), anyOrNull(), any()) + } + + @Test + fun `router direct pays the lightning endpoint it picks`() = test { + val bolt11 = PaykitEndpoint(methodId = MethodId.Bolt11.rawValue, value = "lnbcrt1routed") + val onchain = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = "bcrt1qrouted") + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(bolt11))) + setSendState( + SendUiState( + amount = 1_000u, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(persistentListOf(bolt11, onchain)), ), ) + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + + verify(paykitRouteRepo).route(eq(1_000uL), eq(listOf(bolt11, onchain)), any(), eq(0uL), eq(false)) + assertEquals(SendMethod.LIGHTNING, sut.sendUiState.value.payMethod) + assertNull(sut.sendUiState.value.paykitRoute?.serviceLeg) + } + + @Test + fun `a reroute from lnurl back to bolt11 pays the contact's invoice`() = test { + val (bolt11, lnurl) = openLightningContact() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(lnurl))) + continueWithAmount(2_000u) + assertNull(sut.sendUiState.value.decodedInvoice) + + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(bolt11))) + continueWithAmount(3_000u) + + assertEquals(bolt11.value, sut.sendUiState.value.decodedInvoice?.bolt11) + assertNull(sut.sendUiState.value.lnurl) + } + + @Test + fun `a reroute from bolt11 back to lnurl pays the contact's lnurl`() = test { + val (bolt11, lnurl) = openLightningContact() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(bolt11))) + continueWithAmount(2_000u) + assertNull(sut.sendUiState.value.lnurl) + + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(lnurl))) + continueWithAmount(3_000u) + + assertEquals(lnurl.value, (sut.sendUiState.value.lnurl as? LnurlParams.LnurlPay)?.data?.uri) + assertNull(sut.sendUiState.value.decodedInvoice) + } + + @Test + fun `a reroute from bolt11 to lnurl below its minimum shows the minimum toast`() = test { + val (bolt11, lnurl) = openLightningContact() + whenever(context.getString(R.string.wallet__lnurl_pay__error_min__title)).thenReturn("Amount Too Low") + whenever(context.getString(R.string.wallet__lnurl_pay__error_min__description)).thenReturn("Min {amount}") + whenever(formatMoneyValue(1_000uL)).thenReturn("1000") + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(bolt11))) + continueWithAmount(2_000u) + assertNull(sut.sendUiState.value.lnurl) + + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(lnurl))) sut.sendEffect.test { - confirmCurrentPayment() - assertEquals(SendEffect.PaymentSuccess, awaitItem()) + continueWithAmount(500u) + + assertEquals(lnurl.value, (sut.sendUiState.value.lnurl as? LnurlParams.LnurlPay)?.data?.uri) expectNoEvents() } + verify(toastManager).enqueue(check { assertEquals("LnurlPayAmountTooLowToast", it.testTag) }) + } - assertEquals("txid", sut.successSendUiState.value.paymentHashOrTxId) - assertEquals(request.amount.atomic.toLong(), sut.successSendUiState.value.sats) - verify(paykitPaymentProofRepo, never()).failOnchainPayment(request) - verify(paykitPaymentProofRepo, never()).cancelPreparation(request) - verify(privatePaykitRepo, never()).releasePrivatePaymentList(any(), any()) - verify(lightningRepo).sendOnChain( - any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), any(), any(), any(), any(), - anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), - paymentDeadlineAt = anyOrNull(), - contactPublicKey = anyOrNull(), - approvedMiningFeeSats = anyOrNull(), - ) + @Test + fun `a reroute from bolt11 to lnurl above its maximum shows the maximum toast`() = test { + val (bolt11, lnurl) = openLightningContact() + whenever(context.getString(R.string.wallet__lnurl_pay__error_max__title)).thenReturn("Amount Too High") + whenever(context.getString(R.string.wallet__lnurl_pay__error_max__description)).thenReturn("Max") + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(bolt11))) + continueWithAmount(2_000u) + assertNull(sut.sendUiState.value.lnurl) + + balanceState.value = BalanceState(maxSendLightningSats = 200_000u) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(lnurl))) + sut.sendEffect.test { + continueWithAmount(150_000u) + + assertEquals(lnurl.value, (sut.sendUiState.value.lnurl as? LnurlParams.LnurlPay)?.data?.uri) + expectNoEvents() + } + verify(toastManager).enqueue(check { assertEquals("LnurlPayAmountTooHighToast", it.testTag) }) } @Test - fun `proof preparation failure blocks incoming onchain payment`() = test { - val address = "bcrt1qpaymentrequest" - val request = paymentRequest() - val privateContext = privatePaymentContext(7uL) + fun `router direct pays the onchain endpoint it picks from savings`() = test { + val bolt11 = PaykitEndpoint(methodId = MethodId.Bolt11.rawValue, value = "lnbcrt1routed") + val onchain = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = REGTEST_ADDRESS) balanceState.value = BalanceState(maxSendOnchainSats = 100_000u) - whenever( - paykitPaymentProofRepo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain) - ) - .thenReturn(Result.failure(IllegalStateException("proof unavailable"))) - whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) - whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) - .thenReturn(Result.success(Unit)) - stubSuccessfulOnchainSend(address, request.amount.atomic) - setActiveContactPaymentContext(testPublicKey, privateContext, request) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(onchain))) setSendState( SendUiState( - address = address, - amount = request.amount.atomic, + amount = 1_000u, payMethod = SendMethod.ONCHAIN, - speed = TransactionSpeed.Medium, - isPaymentRequest = true, + paykitRoute = PaykitRouteUi(persistentListOf(bolt11, onchain)), + ), + ) + + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + + verify(paykitRouteRepo).route(eq(1_000uL), eq(listOf(onchain)), eq(0uL), eq(100_000uL), eq(false)) + assertEquals(SendMethod.ONCHAIN, sut.sendUiState.value.payMethod) + assertEquals(REGTEST_ADDRESS, sut.sendUiState.value.address) + } + + @Test + fun `a spark withdrawal is weighed against spark's balance, not the lightning limit`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact").copy(deliveredSat = 999_000uL, debitSat = 999_500uL) + balanceState.value = BalanceState(maxSendLightningSats = 997_506u) + whenever(lightningRepo.canWithdrawWithSpark(leg.deliveredSat)).thenReturn(true) + whenever(lightningRepo.canWithdrawWithSpark(leg.debitSat)).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) + setSendState( + SendUiState( + address = leg.endpoint.value, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true), + ), + ) + + sut.setSendEvent(SendEvent.AmountChange(leg.deliveredSat)) + advanceUntilIdle() + assertTrue(sut.sendUiState.value.isAmountInputValid, "continue asks spark for a quote") + + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + assertTrue(sut.sendUiState.value.isAmountInputValid, "the quoted debit fits spark's balance") + + whenever(lightningRepo.canWithdrawWithSpark(leg.debitSat)).thenReturn(false) + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertFalse(sut.sendUiState.value.isAmountInputValid, "a debit past spark's balance can't be swiped") + } + + @Test + fun `a contact whose lnurl minimum lightning pays still takes spark past the lightning limit`() = test { + val lnurl = LnurlPayData( + uri = "lnurl1sparkpastlimit", + callback = "https://example.com/pay", + minSendable = 1_000_000u, + maxSendable = 2_000_000_000u, + metadataStr = "[]", + commentAllowed = null, + allowsNostr = false, + nostrPubkey = null, + ) + val leg = sparkRouteLeg(REGTEST_ADDRESS).copy(deliveredSat = 999_000uL, debitSat = 999_500uL) + whenever(coreService.decode(lnurl.uri)).thenReturn(Scanner.LnurlPay(lnurl)) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(lightningRepo.canSend(any())).thenReturn(true) + whenever(lightningRepo.canWithdrawWithSpark(leg.deliveredSat)).thenReturn(true) + whenever(lightningRepo.canWithdrawWithSpark(leg.debitSat)).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + balanceState.value = BalanceState(maxSendLightningSats = 997_506u) + usdtEnabled.value = false + sut.openContactPayment( + paymentRequest = lnurl.uri, + publicKey = testPublicKey, + endpoints = listOf( + Endpoint(MethodId.Lnurl, lnurl.uri, rawPayload = ""), + Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = ""), + Endpoint(MethodId.UsdtArbitrum, "0x1111111111111111111111111111111111111111", rawPayload = ""), ), ) + advanceUntilIdle() + + sut.setSendEvent(SendEvent.AmountChange(leg.deliveredSat)) + advanceUntilIdle() + assertTrue(sut.sendUiState.value.isAmountInputValid, "spark covers what lightning can't") + + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + verify(paykitRouteRepo).route(any(), any(), any(), any(), eq(true)) + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + } + + @Test + fun `a mixed contact below its lnurl minimum takes spark's onchain leg`() = test { + openMixedContact() + val leg = sparkRouteLeg(REGTEST_ADDRESS).copy(deliveredSat = 2_000uL, debitSat = 2_300uL) + whenever(lightningRepo.canWithdrawWithSpark(any())).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + + sut.setSendEvent(SendEvent.AmountChange(leg.deliveredSat)) + advanceUntilIdle() + assertTrue(sut.sendUiState.value.isAmountInputValid, "spark covers what the lnurl minimum refuses") + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg, "the spark onchain leg pays") + assertEquals(SendEffect.NavigateToConfirm, expectMostRecentItem()) + } + verify(toastManager, never()).enqueue(any()) + } + + @Test + fun `a mixed contact below its lnurl minimum offers the router only its onchain endpoint`() = test { + openMixedContact() + val leg = sparkRouteLeg(REGTEST_ADDRESS).copy(deliveredSat = 2_000uL, debitSat = 2_300uL) + whenever(lightningRepo.canWithdrawWithSpark(any())).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + + continueWithAmount(leg.deliveredSat) + + // An LNURL whose minimum refuses the amount would win over an affordable Spark leg. + verify(paykitRouteRepo).route( + eq(leg.deliveredSat), + eq(listOf(PaykitEndpoint(MethodId.P2wpkh.rawValue, REGTEST_ADDRESS))), + any(), + any(), + any(), + ) + } + + @Test + fun `a mixed contact no route pays below its lnurl minimum shows the lnurl minimum`() = test { + openMixedContact() + whenever(context.getString(R.string.wallet__lnurl_pay__error_min__title)).thenReturn("Amount Too Low") + whenever(context.getString(R.string.wallet__lnurl_pay__error_min__description)).thenReturn("Min {amount}") + whenever(formatMoneyValue(5_000uL)).thenReturn("5000") + whenever(lightningRepo.canWithdrawWithSpark(any())).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.None("Spark can't cover the fee"))) + + continueWithAmount(2_000u) + + verify(toastManager).enqueue(check { assertEquals("LnurlPayAmountTooLowToast", it.testTag) }) + } + + @Test + fun `a savings payment to a mixed contact below its lnurl minimum is not blocked by the lnurl`() = test { + openMixedContact() + balanceState.value = BalanceState(maxSendLightningSats = 100_000u, maxSendOnchainSats = 100_000u) + whenever(formatMoneyValue(any())).thenReturn("5,000 sats") + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(PaykitEndpoint(MethodId.P2wpkh.rawValue, REGTEST_ADDRESS)))) + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Savings)) + advanceUntilIdle() + + sut.sendEffect.test { + continueWithAmount(2_000u) + + assertEquals(SendMethod.ONCHAIN, sut.sendUiState.value.payMethod) + verify(toastManager, never()).enqueue(argThat { testTag == "LnurlPayAmountTooLowToast" }) + assertEquals(SendEffect.NavigateToConfirm, expectMostRecentItem()) + } + } + + @Test + fun `a savings payment to a mixed contact below its lnurl minimum sends on-chain without the lnurl`() = test { + openMixedContact() + balanceState.value = BalanceState(maxSendLightningSats = 100_000u, maxSendOnchainSats = 100_000u) + whenever(formatMoneyValue(any())).thenReturn("5,000 sats") + whenever(lightningRepo.fetchLnurlInvoice(any(), any(), anyOrNull())) + .thenReturn(Result.failure(AppError("Amount is below the LNURL minimum"))) + stubSuccessfulOnchainSend(REGTEST_ADDRESS, 2_000uL) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(PaykitEndpoint(MethodId.P2wpkh.rawValue, REGTEST_ADDRESS)))) + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Savings)) + advanceUntilIdle() + continueWithAmount(2_000u) confirmCurrentPayment() - verify(privatePaykitRepo, never()).consumePrivatePaymentList(testPublicKey, privateContext) - verify(paykitPaymentRequestRepo, never()).accept(request) - verify(lightningRepo, never()).sendOnChain( - address = any(), + verify(lightningRepo, never()).fetchLnurlInvoice(any(), any(), anyOrNull()) + verify(lightningRepo).sendOnChain( + address = eq(REGTEST_ADDRESS), sats = any(), speed = anyOrNull(), utxosToSpend = anyOrNull(), @@ -12344,20 +12605,1272 @@ class AppViewModelSendFlowTest : BaseUnitTest() { contactPublicKey = anyOrNull(), approvedMiningFeeSats = anyOrNull(), ) - verify(paykitPaymentProofRepo, never()).markOnchainPaymentStarted( - any(), - any(), - any(), - any(), - anyOrNull(), - anyOrNull(), - anyOrNull(), + } + + @Test + fun `a direct lnurl pick after a spark leg drops the leg's withdrawal fee`() = test { + val lnurl = openMixedContact() + val leg = sparkRouteLeg(REGTEST_ADDRESS).copy(deliveredSat = 2_000uL, debitSat = 2_300uL) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + continueWithAmount(2_000u) + assertEquals(300L, sut.sendUiState.value.lightningFeeSats) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(PaykitEndpoint(MethodId.Lnurl.rawValue, lnurl.uri)))) + + continueWithAmount(6_000u) + + assertNull(sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + assertNull( + sut.sendUiState.value.lightningFeeSats, + "Confirm must not show the Spark withdrawal fee for the LNURL", ) } @Test - fun `atomic acceptance claim failure blocks versionless request before sending`() = test { - val request = paymentRequest() + fun `a direct bolt11 pick after a spark leg drops the leg's withdrawal fee`() = test { + val bolt11 = "lnbcrt1legthenbolt11" + stubLightningScan(bolt11, amountSats = 0u) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(lightningRepo.canSend(any())).thenReturn(true) + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + usdtEnabled.value = false + sut.openContactPayment( + paymentRequest = bolt11, + publicKey = testPublicKey, + endpoints = listOf( + Endpoint(MethodId.Bolt11, bolt11, rawPayload = ""), + Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = ""), + ), + ) + advanceUntilIdle() + val leg = sparkRouteLeg(REGTEST_ADDRESS).copy(deliveredSat = 2_000uL, debitSat = 2_300uL) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + continueWithAmount(2_000u) + assertEquals(300L, sut.sendUiState.value.lightningFeeSats) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(PaykitEndpoint(MethodId.Bolt11.rawValue, bolt11)))) + + continueWithAmount(6_000u) + + assertNull(sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + assertEquals(bolt11, sut.sendUiState.value.decodedInvoice?.bolt11) + assertNull( + sut.sendUiState.value.lightningFeeSats, + "Confirm must not show the Spark withdrawal fee for the BOLT11 invoice", + ) + } + + @Test + fun `a mixed contact lightning can pay routes direct`() = test { + val lnurl = openMixedContact() + val direct = PaykitEndpoint(MethodId.Lnurl.rawValue, lnurl.uri) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(direct))) + + continueWithAmount(6_000u) + + verify(paykitRouteRepo).route(eq(6_000uL), any(), any(), any(), any()) + assertNull(sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + assertEquals(SendMethod.LIGHTNING, sut.sendUiState.value.payMethod) + } + + /** A contact offering LNURL with a 5,000-sat minimum and on-chain, no USDT, with Spark funded and Savings empty. */ + private suspend fun TestScope.openMixedContact(): LnurlPayData { + val lnurl = LnurlPayData( + uri = "lnurl1mixedcontact", + callback = "https://example.com/pay", + minSendable = 5_000_000u, + maxSendable = 100_000_000u, + metadataStr = "[]", + commentAllowed = null, + allowsNostr = false, + nostrPubkey = null, + ) + whenever(coreService.decode(lnurl.uri)).thenReturn(Scanner.LnurlPay(lnurl)) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(lightningRepo.canSend(any())).thenReturn(true) + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + usdtEnabled.value = false + sut.openContactPayment( + paymentRequest = lnurl.uri, + publicKey = testPublicKey, + endpoints = listOf( + Endpoint(MethodId.Lnurl, lnurl.uri, rawPayload = ""), + Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = ""), + ), + ) + advanceUntilIdle() + return lnurl + } + + @Test + fun `a request paid by a spark leg keeps the leg's fee over the invoice's estimate`() = test { + val bolt11 = "lnbcrt1requestspark" + val leg = sparkRouteLeg(REGTEST_ADDRESS).copy(deliveredSat = 2_000uL, debitSat = 2_300uL) + val endpoints = listOf( + Endpoint(MethodId.Bolt11, bolt11, rawPayload = ""), + Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = ""), + ) + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, 2_000uL), + acceptedPaymentEndpointIdentifiers = endpoints.map { it.methodId.rawValue }, + ) + stubLightningScan(bolt11, amountSats = 2_000u) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(lightningRepo.canSend(any())).thenReturn(true) + whenever(lightningRepo.canWithdrawWithSpark(any())).thenReturn(true) + whenever(lightningRepo.estimateRoutingFees(any())).thenReturn(Result.success(7uL)) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + usdtEnabled.value = false + + sut.openContactPayment(bolt11, testPublicKey, incomingPaymentRequest = request, endpoints = endpoints) + advanceUntilIdle() + + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + assertEquals( + 300L, + sut.sendUiState.value.lightningFeeSats, + "Confirm shows the withdrawal's fee, not the fee of the invoice the leg doesn't pay", + ) + } + + @Test + fun `a request above a routed lnurl's maximum does not open a swipeable confirm`() = test { + val lnurl = LnurlPayData( + uri = "lnurl1requestpastmax", + callback = "https://example.com/pay", + minSendable = 1_000_000u, + maxSendable = 100_000_000u, + metadataStr = "[]", + commentAllowed = null, + allowsNostr = false, + nostrPubkey = null, + ) + val endpoints = listOf( + Endpoint(MethodId.Lnurl, lnurl.uri, rawPayload = ""), + Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = ""), + Endpoint(MethodId.UsdtArbitrum, "0x1111111111111111111111111111111111111111", rawPayload = ""), + ) + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, 150_000uL), + acceptedPaymentEndpointIdentifiers = endpoints.map { it.methodId.rawValue }, + ) + whenever(coreService.decode(lnurl.uri)).thenReturn(Scanner.LnurlPay(lnurl)) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(lightningRepo.canSend(any())).thenReturn(true) + whenever(lightningRepo.canWithdrawWithSpark(150_000uL)).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(PaykitEndpoint(MethodId.Lnurl.rawValue, lnurl.uri)))) + balanceState.value = BalanceState(maxSendLightningSats = 200_000u) + usdtEnabled.value = false + + sut.openContactPayment(lnurl.uri, testPublicKey, incomingPaymentRequest = request, endpoints = endpoints) + advanceUntilIdle() + + val state = sut.sendUiState.value + assertEquals(150_000uL, state.amount) + assertEquals(lnurl.uri, (state.lnurl as? LnurlParams.LnurlPay)?.data?.uri) + assertNull(state.routedPaykitRoute?.serviceLeg) + assertFalse( + sut.currentSheet.value == Sheet.Send(SendRoute.Confirm) && state.isAmountInputValid, + "confirm opened swipeable for 150,000 sats past the lnurl's 100,000-sat maximum " + + "(sheet=${sut.currentSheet.value}, isAmountInputValid=${state.isAmountInputValid})", + ) + } + + @Test + fun `router service leg opens the confirm screen with the leg's fee`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + setSendState( + SendUiState( + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true), + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + assertEquals(300L, sut.sendUiState.value.lightningFeeSats) + } + verify(paykitRouteRepo).route(eq(leg.deliveredSat), eq(listOf(leg.endpoint)), any(), eq(0uL), eq(true)) + } + + @Test + fun `router none with a short balance says the balance is short`() = test { + routerNone(maxSendLightningSats = 500u) + + verify(toastManager).enqueue( + check { + assertEquals("PaykitRouteBalanceToast", it.testTag) + assertFalse(it.description.orEmpty().contains("Nothing can pay this contact")) + }, + ) + } + + @Test + fun `router none with enough balance says the contact cannot be paid`() = test { + routerNone(maxSendLightningSats = 100_000u) + + verify(toastManager).enqueue( + check { + assertEquals("PaykitRouteNoneToast", it.testTag) + assertFalse(it.description.orEmpty().contains("Nothing can pay this contact")) + }, + ) + } + + @Test + fun `a spark leg refused while an earlier withdrawal settles says it is still settling`() = test { + val onchain = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = "bcrt1qrouted") + balanceState.value = BalanceState(maxSendLightningSats = 10_000u) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.failure(SparkError.WithdrawalPending())) + setSendState( + SendUiState( + amount = 9_000u, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(persistentListOf(onchain), offersSparkLeg = true), + ), + ) + + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + + verify(toastManager).enqueue(check { assertEquals("PaykitRouteSettlingToast", it.testTag) }) + assertNull(sut.sendUiState.value.paykitRoute?.serviceLeg) + } + + @Test + fun `a spark leg whose fee the balance can't cover says the balance is short`() = test { + // A Spark-only wallet with 10,000 sendable pays an on-chain-only contact 9,000, and the leg fee is about 2,190. + val onchain = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = "bcrt1qrouted") + balanceState.value = BalanceState(maxSendLightningSats = 10_000u) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.failure(SparkError.WithdrawalOverBalance())) + setSendState( + SendUiState( + amount = 9_000u, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(persistentListOf(onchain), offersSparkLeg = true), + ), + ) + + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + + verify(toastManager).enqueue(check { assertEquals("PaykitRouteBalanceToast", it.testTag) }) + } + + private suspend fun TestScope.routerNone(maxSendLightningSats: ULong) { + val onchain = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = "bcrt1qrouted") + balanceState.value = BalanceState(maxSendLightningSats = maxSendLightningSats) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.None("Nothing can pay this contact"))) + setSendState( + SendUiState( + amount = 1_000u, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(persistentListOf(onchain), offersSparkLeg = true), + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + + expectNoEvents() + } + assertNull(sut.sendUiState.value.paykitRoute?.serviceLeg) + } + + @Test + fun `spark route pays an onchain request and completes its proof`() = test { + val leg = sparkRouteLeg("bcrt1qroutedrequest") + val txid = "ab".repeat(32) + val deadline = Instant.parse("2099-01-01T00:00:00Z") + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, leg.deliveredSat), + acceptedPaymentEndpointIdentifiers = listOf(MethodId.P2wpkh.rawValue), + paymentDeadlineAt = deadline, + ) + val privateContext = privatePaymentContext(7uL) + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(paykitPaymentRequestRepo.ensurePaymentAllowed(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.captureOriginalOnchainPayer(request)).thenReturn(Result.success(testPublicKey)) + whenever(lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value)).thenReturn(emptySet()) + whenever( + paykitPaymentProofRepo.markSparkOnchainPaymentStarted(any(), any(), any(), anyOrNull(), anyOrNull(), any()), + ) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.verifyOriginalOnchainPayer(request, testPublicKey)) + .thenReturn(Result.success(Unit)) + whenever( + paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), anyOrNull(), any()), + ).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(4) + if (onBeforeSend()) Result.success(txid) else Result.failure(AppError("refused")) + } + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + isPaymentRequest = true, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + confirmCurrentPayment() + advanceUntilIdle() + + inOrder(paykitPaymentRequestRepo, paykitPaymentProofRepo).apply { + verify(paykitPaymentRequestRepo).ensurePaymentAllowed(request) + verify(paykitPaymentProofRepo).markSparkOnchainPaymentStarted( + eq(request), + eq(leg.endpoint.value), + eq(leg.deliveredSat), + anyOrNull(), + anyOrNull(), + any(), + ) + verify(paykitPaymentProofRepo).completeSparkOnchainPayment(request, txid) + } + // Spark checks the request's deadline right before it sends. + verify(paykitRouteRepo).payServiceLeg(eq(leg), eq(testPublicKey), any(), eq(deadline), any()) + } + + @Test + fun `a pending spark send of a request fails once its withdrawal is found unsent`() = test { + val leg = sparkRouteLeg("bcrt1qroutedrequest") + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, leg.deliveredSat), + acceptedPaymentEndpointIdentifiers = listOf(MethodId.P2wpkh.rawValue), + ) + val release = PaykitSparkWithdrawalRelease(testPublicKey, request.id) + val privateContext = privatePaymentContext(7uL) + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(paykitPaymentRequestRepo.ensurePaymentAllowed(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.captureOriginalOnchainPayer(request)).thenReturn(Result.success(testPublicKey)) + whenever(lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value)).thenReturn(emptySet()) + whenever(paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(request)).thenReturn(false) + whenever(lightningRepo.sparkWithdrawalOutcome(leg.endpoint.value, leg.deliveredSat, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Unknown) + whenever( + paykitPaymentProofRepo.markSparkOnchainPaymentStarted(any(), any(), any(), anyOrNull(), anyOrNull(), any()), + ) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.verifyOriginalOnchainPayer(request, testPublicKey)) + .thenReturn(Result.success(Unit)) + whenever( + paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), anyOrNull(), any()), + ).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(4) + onBeforeSend() + Result.failure(AppError("send outcome lost")) + } + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + isPaymentRequest = true, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + val effects = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { sut.sendEffect.collect { effects += it } } + + confirmCurrentPayment() + val pending = assertIs(effects.last()) + sut.showSheet(Sheet.Send(SendRoute.Pending(pending.paymentHash, pending.amount, false, isOnchain = true))) + pubkyPublicKey.value = testPublicKey + sparkWithdrawalReleases.value = listOf(release) + runCurrent() + + assertIs(effects.last(), "a withdrawal that never sent can be tried again") + verify(paykitPaymentProofRepo).consumeSparkWithdrawalRelease(release) + } + + @Test + fun `a route that returns after its payment was dismissed never lands on the next payment`() = test { + val legA = sparkRouteLeg("bcrt1qcontacta") + val endpointB = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = "bcrt1qcontactb") + val quote = CompletableDeferred>() + balanceState.value = BalanceState(maxSendLightningSats = 10_000u) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())).doSuspendableAnswer { quote.await() } + setActiveContactPaymentContext("pubkycontacta", privatePaymentContext(7uL)) + setSendState( + SendUiState( + address = legA.endpoint.value, + amount = legA.deliveredSat, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(persistentListOf(legA.endpoint), offersSparkLeg = true), + ), + ) + sut.showSheet(Sheet.Send(SendRoute.Amount)) + sut.setSendEvent(SendEvent.AmountContinue) + runCurrent() + + sut.hideSheet() + setActiveContactPaymentContext("pubkycontactb", privatePaymentContext(8uL)) + val stateB = SendUiState( + address = endpointB.value, + amount = 2_000uL, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(persistentListOf(endpointB), offersSparkLeg = true), + ) + setSendState(stateB) + quote.complete(Result.success(PaykitRoute.Service(legA))) + advanceUntilIdle() + + assertEquals( + stateB.paykitRoute, + sut.sendUiState.value.paykitRoute, + "contact A's quote must not route B's payment", + ) + assertEquals(endpointB.value, sut.sendUiState.value.address) + } + + @Test + fun `a route quoted for an amount that changed meanwhile never lands`() = test { + val leg = sparkRouteLeg("bcrt1qcontact") + val quote = CompletableDeferred>() + balanceState.value = BalanceState(maxSendLightningSats = 10_000u) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())).doSuspendableAnswer { quote.await() } + setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) + val route = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + paykitRoute = route, + ), + ) + sut.showSheet(Sheet.Send(SendRoute.Amount)) + sut.setSendEvent(SendEvent.AmountContinue) + runCurrent() + + // A request's rate refresh writes a new amount while Spark quotes the old one. + setSendState(sut.sendUiState.value.copy(amount = 2_000uL)) + quote.complete(Result.success(PaykitRoute.Service(leg))) + advanceUntilIdle() + + assertNull( + sut.sendUiState.value.paykitRoute?.serviceLeg, + "a leg quoted for the old amount must not pay the new one", + ) + assertEquals(2_000uL, sut.sendUiState.value.amount) + } + + @Test + fun `an uncertain spark send to a contact that spark already lists opens success`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + val effects = uncertainContactSparkSend(leg, SparkWithdrawalOutcome.Sent("ab".repeat(32))) + + assertEquals(SendEffect.PaymentSuccess, effects.last()) + assertEquals("ab".repeat(32), sut.successSendUiState.value.paymentHashOrTxId) + } + + @Test + fun `an uncertain spark send to a contact settles from the spark journal`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + val effects = uncertainContactSparkSend(leg, SparkWithdrawalOutcome.Unknown) + val pending = assertIs(effects.last()) + sut.showSheet(Sheet.Send(SendRoute.Pending(pending.paymentHash, pending.amount, false, isOnchain = true))) + + sparkWithdrawalSettlements.emit(SparkWithdrawalSettlement("bcrt1qother", leg.deliveredSat, null)) + runCurrent() + assertIs(effects.last(), "another withdrawal's close leaves the screen") + sparkWithdrawalSettlements.emit(SparkWithdrawalSettlement(leg.endpoint.value, leg.deliveredSat, null)) + runCurrent() + + assertIs(effects.last(), "a withdrawal that never sent can be tried again") + } + + @Test + fun `a late spark settlement leaves a send sheet opened after its pending one closed`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + val effects = uncertainContactSparkSend(leg, SparkWithdrawalOutcome.Unknown) + val pending = assertIs(effects.last()) + sut.showSheet(Sheet.Send(SendRoute.Pending(pending.paymentHash, pending.amount, false, isOnchain = true))) + sut.hideSheet() + runCurrent() + sut.showSheet(Sheet.Send(SendRoute.Amount)) + val before = effects.size + + sparkWithdrawalSettlements.emit(SparkWithdrawalSettlement(leg.endpoint.value, leg.deliveredSat, null)) + runCurrent() + + assertEquals(before, effects.size, "the settlement belongs to the closed pending screen") + } + + @Test + fun `a journal that settles while the outcome is read still resolves the send`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + val effects = uncertainContactSparkSend(leg, SparkWithdrawalOutcome.Unknown) { + sut.showSheet(Sheet.Send(SendRoute.Confirm)) + sparkWithdrawalSettlements.emit(SparkWithdrawalSettlement(leg.endpoint.value, leg.deliveredSat, null)) + // Reading the outcome suspends, so the settlement is handled before it returns. + yield() + } + + assertIs( + effects.last(), + "the screen must not stay pending after the journal closed", + ) + } + + @Test + fun `a failed spark outcome read leaves the send pending until its journal settles`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + val effects = uncertainContactSparkSend(leg, SparkWithdrawalOutcome.Unknown) { + throw AppError("payment list read failed") + } + val pending = assertIs(effects.last()) + sut.showSheet(Sheet.Send(SendRoute.Pending(pending.paymentHash, pending.amount, false, isOnchain = true))) + + sparkWithdrawalSettlements.emit(SparkWithdrawalSettlement(leg.endpoint.value, leg.deliveredSat, null)) + runCurrent() + + assertIs(effects.last(), "a withdrawal that never sent can be tried again") + } + + private suspend fun TestScope.uncertainContactSparkSend( + leg: ServiceRouteLeg, + outcome: SparkWithdrawalOutcome, + whileOutcomeIsRead: suspend () -> Unit = {}, + ): List { + whenever(lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value)).thenReturn(emptySet()) + whenever(lightningRepo.sparkWithdrawalOutcome(leg.endpoint.value, leg.deliveredSat, emptySet())) + .doSuspendableAnswer { + whileOutcomeIsRead() + outcome + } + whenever( + paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any(), anyOrNull(), any()), + ).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(4) + onBeforeSend() + Result.failure(AppError("send outcome lost")) + } + setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + val effects = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { sut.sendEffect.collect { effects += it } } + confirmCurrentPayment() + return effects + } + + @Test + fun `a spark leg to the onchain endpoint ignores the unselected lnurl's limits`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + val lnurl = LnurlPayData( + uri = "lnurl1contact", + callback = "https://example.com/callback", + minSendable = 5_000_000uL, + maxSendable = 100_000_000uL, + metadataStr = "[]", + commentAllowed = null, + allowsNostr = false, + nostrPubkey = null, + ) + balanceState.value = BalanceState(maxSendLightningSats = 10_000u) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any(), anyOrNull(), any())) + .thenReturn(Result.success("txid")) + setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + lnurl = LnurlParams.LnurlPay(lnurl), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true), + ), + ) + + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg, "the lnurl's minimum is not the leg's") + confirmCurrentPayment() + + verify(lightningRepo, never()).fetchLnurlInvoice(any(), any(), anyOrNull()) + verify(paykitRouteRepo).payServiceLeg(eq(leg), eq("pubkycontact"), any(), anyOrNull(), any()) + } + + @Test + fun `a request's spark send that reconcile finds sent opens success`() = test { + val leg = sparkRouteLeg("bcrt1qroutedrequest") + val txid = "ab".repeat(32) + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, leg.deliveredSat), + acceptedPaymentEndpointIdentifiers = listOf(MethodId.P2wpkh.rawValue), + ) + val privateContext = privatePaymentContext(7uL) + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(paykitPaymentRequestRepo.ensurePaymentAllowed(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.captureOriginalOnchainPayer(request)).thenReturn(Result.success(testPublicKey)) + whenever(lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value)).thenReturn(emptySet()) + whenever(lightningRepo.sparkWithdrawalOutcome(leg.endpoint.value, leg.deliveredSat, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Sent(txid)) + whenever( + paykitPaymentProofRepo.markSparkOnchainPaymentStarted(any(), any(), any(), anyOrNull(), anyOrNull(), any()), + ) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.verifyOriginalOnchainPayer(request, testPublicKey)) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.consumeOnchainPaymentResolution(any())).then { call -> + onchainPaymentResolutions.update { it - call.getArgument(0) } + } + // Reconcile completes the proof and publishes its only resolution before the send is marked uncertain. + whenever(paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(request)).doSuspendableAnswer { + onchainPaymentResolutions.value = listOf( + PaykitOnchainPaymentProofResolution(testPublicKey, request.id, txid), + ) + yield() + false + } + whenever( + paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), anyOrNull(), any()), + ).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(4) + onBeforeSend() + Result.failure(AppError("send outcome lost")) + } + pubkyPublicKey.value = testPublicKey + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + isPaymentRequest = true, + incomingPaymentRequestId = request.id, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + val effects = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { sut.sendEffect.collect { effects += it } } + sut.showSheet(Sheet.Send(SendRoute.Confirm)) + + confirmCurrentPayment() + + assertEquals( + listOf(SendEffect.PaymentSuccess), + effects, + "Spark lists it, so the request never waits on Pending", + ) + } + + @Test + fun `spark route saves the tags picked on confirmation`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), eq(listOf("rent")), anyOrNull(), any())) + .thenReturn(Result.success("txid")) + setActiveContactPaymentContext("pubkycontact", privatePaymentContext(7uL)) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + selectedTags = persistentListOf("rent"), + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + confirmCurrentPayment() + + verify(paykitRouteRepo).payServiceLeg(eq(leg), eq("pubkycontact"), eq(listOf("rent")), anyOrNull(), any()) + } + + @Test + fun `a spark leg refused at its deadline releases the request proof without a spark sync`() = test { + refuseSparkLeg(ServiceError.PaymentDeadlineExpired()) + } + + @Test + fun `a spark leg spark refuses before sending releases the request proof without a spark sync`() = test { + refuseSparkLeg(SparkError.SendRefused("Spark balance can't cover the withdrawal")) + } + + private suspend fun TestScope.refuseSparkLeg(error: Throwable) { + val leg = sparkRouteLeg("bcrt1qroutedrequest") + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, leg.deliveredSat), + acceptedPaymentEndpointIdentifiers = listOf(MethodId.P2wpkh.rawValue), + ) + val privateContext = privatePaymentContext(7uL) + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(paykitPaymentRequestRepo.ensurePaymentAllowed(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.captureOriginalOnchainPayer(request)).thenReturn(Result.success(testPublicKey)) + whenever(lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value)).thenReturn(emptySet()) + whenever( + paykitPaymentProofRepo.markSparkOnchainPaymentStarted(any(), any(), any(), anyOrNull(), anyOrNull(), any()), + ) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.verifyOriginalOnchainPayer(request, testPublicKey)) + .thenReturn(Result.success(Unit)) + // Spark hasn't synced, so it can't yet say the withdrawal never sent. + whenever(lightningRepo.sparkWithdrawalOutcome(any(), any(), any())).thenReturn(SparkWithdrawalOutcome.Unknown) + whenever(paykitPaymentProofRepo.releaseRefusedSparkOnchainProof(request)).thenReturn(true) + whenever( + paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), anyOrNull(), any()), + ).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(4) + onBeforeSend() + Result.failure(error) + } + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + isPaymentRequest = true, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + confirmCurrentPayment() + advanceUntilIdle() + + verify(paykitPaymentProofRepo).releaseRefusedSparkOnchainProof(request) + verify(lightningRepo, never()).sparkWithdrawalOutcome(any(), any(), any()) + } + + @Test + fun `a failed spark leg releases a request proof spark never sent`() = test { + val leg = sparkRouteLeg("bcrt1qroutedrequest") + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, leg.deliveredSat), + acceptedPaymentEndpointIdentifiers = listOf(MethodId.P2wpkh.rawValue), + ) + val privateContext = privatePaymentContext(7uL) + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), anyOrNull(), any())) + .thenReturn(Result.failure(AppError("send failed"))) + whenever(paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(request)).thenReturn(true) + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + isPaymentRequest = true, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + confirmCurrentPayment() + advanceUntilIdle() + + verify(paykitPaymentProofRepo).releaseUnsentSparkOnchainProof(request) + } + + @Test + fun `a source switch on confirmation reroutes a contact payment`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u, maxSendLightningSats = 10_000u) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(leg.endpoint))) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.ONCHAIN, + speed = TransactionSpeed.Medium, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true), + ), + ) + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Spending)) + advanceUntilIdle() + + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + } + + @Test + fun `a refused reroute on confirmation blocks the swipe before the private list is consumed`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + val privateContext = privatePaymentContext(7uL) + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u, maxSendLightningSats = 10_000u) + whenever(lightningRepo.canSend(any())).thenReturn(true) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(leg.endpoint))) + setActiveContactPaymentContext(testPublicKey, privateContext) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.ONCHAIN, + speed = TransactionSpeed.Medium, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true), + ), + ) + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.None("Spark can't cover the fee"))) + + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Spending)) + advanceUntilIdle() + sut.setSendEvent(SendEvent.SwipeToPay) + advanceUntilIdle() + // SendConfirmScreen sends PayConfirmed only once the swipe set shouldConfirmPay. + if (sut.sendUiState.value.shouldConfirmPay) sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + assertFalse(sut.sendUiState.value.isAmountInputValid, "a refused route must keep the swipe disabled") + verify(privatePaykitRepo, never()).consumePrivatePaymentList(any(), any()) + } + + @Test + fun `switching back after a refused reroute pays the contact from its private list`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + val privateContext = privatePaymentContext(7uL) + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u, maxSendLightningSats = 10_000u) + whenever(lightningRepo.canSend(any())).thenReturn(true) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + stubSuccessfulOnchainSend(leg.endpoint.value, leg.deliveredSat) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(leg.endpoint))) + setActiveContactPaymentContext(testPublicKey, privateContext) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.ONCHAIN, + speed = TransactionSpeed.Medium, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true), + ), + ) + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.None("Spark can't cover the fee"))) + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Spending)) + advanceUntilIdle() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(leg.endpoint))) + + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Savings)) + advanceUntilIdle() + assertTrue(sut.sendUiState.value.isAmountInputValid, "switching back must re-enable the swipe") + confirmCurrentPayment() + + verify(privatePaykitRepo).consumePrivatePaymentList(testPublicKey, privateContext) + verify(lightningRepo).sendOnChain( + address = eq(leg.endpoint.value), + 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(), + ) + } + + @Test + fun `spending retried after a refused reroute and a switch back routes through spark again`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u, maxSendLightningSats = 10_000u) + whenever(paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), anyOrNull(), any())) + .thenReturn(Result.success("txid")) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(leg.endpoint))) + setActiveContactPaymentContext(testPublicKey, privatePaymentContext(7uL)) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.ONCHAIN, + speed = TransactionSpeed.Medium, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true), + ), + ) + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.None("Spark quote failed"))) + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Spending)) + advanceUntilIdle() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Direct(leg.endpoint))) + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Savings)) + advanceUntilIdle() + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + + sut.setSendEvent(SendEvent.PaymentMethodSelect(SendFundingSource.Spending)) + advanceUntilIdle() + + assertEquals( + leg, + sut.sendUiState.value.routedPaykitRoute?.serviceLeg, + "the quote recovered, so Spark carries it", + ) + confirmCurrentPayment() + verify(paykitRouteRepo).payServiceLeg(eq(leg), eq(testPublicKey), any(), anyOrNull(), any()) + } + + @Test + fun `spark leg fees count in the payment warnings`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact").copy(deliveredSat = 1_000uL, debitSat = 2_000uL) + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + isAmountInputValid = true, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + sut.setSendEvent(SendEvent.SwipeToPay) + advanceUntilIdle() + + assertEquals(SanityWarning.FEE_OVER_HALF_VALUE, sut.sendUiState.value.showSanityWarningDialog) + } + + @Test + fun `a spark proof whose payer check fails is released so the request can be retried`() = test { + val leg = sparkRouteLeg("bcrt1qroutedrequest") + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, leg.deliveredSat), + acceptedPaymentEndpointIdentifiers = listOf(MethodId.P2wpkh.rawValue), + ) + val privateContext = privatePaymentContext(7uL) + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(paykitPaymentRequestRepo.ensurePaymentAllowed(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.captureOriginalOnchainPayer(request)).thenReturn(Result.success(testPublicKey)) + whenever(lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value)).thenReturn(emptySet()) + whenever( + paykitPaymentProofRepo.markSparkOnchainPaymentStarted(any(), any(), any(), anyOrNull(), anyOrNull(), any()), + ).thenReturn(Result.success(Unit)) + whenever(paykitPaymentProofRepo.verifyOriginalOnchainPayer(request, testPublicKey)) + .thenReturn(Result.failure(PaykitPaymentRequestError.RequestUnavailable)) + whenever(paykitPaymentProofRepo.releaseUnsentSparkOnchainProof(request)).thenReturn(true) + whenever( + paykitRouteRepo.payServiceLeg(eq(leg), eq(testPublicKey), any(), anyOrNull(), any()), + ).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(4) + runSuspendCatching { onBeforeSend() }.map { "never" } + } + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + isPaymentRequest = true, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + confirmCurrentPayment() + advanceUntilIdle() + + verify(paykitPaymentProofRepo).releaseUnsentSparkOnchainProof(request) + verify(lightningRepo, never()).sparkWithdrawalOutcome(any(), any(), any()) + verify(privatePaykitRepo).releasePrivatePaymentList(any(), any()) + } + + @Test + fun `an uncertain spark send keeps the request in flight`() = test { + val leg = sparkRouteLeg("bcrt1qroutedcontact") + whenever(lightningRepo.sparkWithdrawalTxidsTo(leg.endpoint.value)).thenReturn(emptySet()) + whenever(lightningRepo.sparkWithdrawalOutcome(leg.endpoint.value, leg.deliveredSat, emptySet())) + .thenReturn(SparkWithdrawalOutcome.Unknown) + whenever( + paykitRouteRepo.payServiceLeg(eq(leg), eq("pubkycontact"), any(), anyOrNull(), any()), + ).doSuspendableAnswer { + val onBeforeSend = it.getArgument Boolean>(4) + onBeforeSend() + Result.failure(AppError("send outcome lost")) + } + val privateContext = privatePaymentContext(7uL) + whenever(privatePaykitRepo.consumePrivatePaymentList("pubkycontact", privateContext)) + .thenReturn(Result.success(Unit)) + setActiveContactPaymentContext("pubkycontact", privateContext) + setSendState( + SendUiState( + address = leg.endpoint.value, + amount = leg.deliveredSat, + payMethod = SendMethod.LIGHTNING, + paykitRoute = PaykitRouteUi(persistentListOf(leg.endpoint), offersSparkLeg = true, serviceLeg = leg), + ), + ) + + confirmCurrentPayment() + advanceUntilIdle() + + verify(privatePaykitRepo, never()).releasePrivatePaymentList(any(), any()) + } + + private suspend fun TestScope.openLightningContact(): Pair { + val bolt11 = "lnbcrt1contactreroute" + val lnurl = LnurlPayData( + uri = "lnurl1contactreroute", + callback = "https://example.com/pay", + minSendable = 1_000_000u, + maxSendable = 100_000_000u, + metadataStr = "[]", + commentAllowed = null, + allowsNostr = false, + nostrPubkey = null, + ) + stubLightningScan(bolt11, amountSats = 0u) + whenever(coreService.decode(lnurl.uri)).thenReturn(Scanner.LnurlPay(lnurl)) + whenever(lightningRepo.canSend(any())).thenReturn(true) + balanceState.value = BalanceState(maxSendLightningSats = 100_000u) + sut.openContactPayment( + paymentRequest = bolt11, + publicKey = testPublicKey, + endpoints = listOf( + Endpoint(MethodId.Bolt11, bolt11, rawPayload = ""), + Endpoint(MethodId.Lnurl, lnurl.uri, rawPayload = ""), + // A USDT endpoint has the router pick the contact's bitcoin endpoint. + Endpoint(MethodId.UsdtArbitrum, "0x1111111111111111111111111111111111111111", rawPayload = ""), + ), + ) + advanceUntilIdle() + return PaykitEndpoint(MethodId.Bolt11.rawValue, bolt11) to PaykitEndpoint(MethodId.Lnurl.rawValue, lnurl.uri) + } + + private fun TestScope.continueWithAmount(amount: ULong) { + sut.setSendEvent(SendEvent.AmountChange(amount)) + sut.setSendEvent(SendEvent.AmountContinue) + advanceUntilIdle() + } + + private fun sparkRouteLeg(address: String) = ServiceRouteLeg( + service = "spark", + endpoint = PaykitEndpoint(methodId = MethodId.P2wpkh.rawValue, value = address), + deliveredSat = 1_000uL, + debitSat = 1_300uL, + atomicity = "trusted", + validUntilUnix = 0uL, + ) + + @Test + fun `incoming payment request consumes its private list before it is accepted`() = test { + val address = "bcrt1qpaymentrequest" + val request = paymentRequest() + val privateContext = privatePaymentContext(7uL) + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u) + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + stubSuccessfulOnchainSend(address, request.amount.atomic) + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = address, + amount = request.amount.atomic, + payMethod = SendMethod.ONCHAIN, + speed = TransactionSpeed.Medium, + isPaymentRequest = true, + ), + ) + + confirmCurrentPayment() + + inOrder(paykitPaymentProofRepo, privatePaykitRepo, paykitPaymentRequestRepo).apply { + verify( + paykitPaymentProofRepo + ).prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain) + verify(privatePaykitRepo).consumePrivatePaymentList(testPublicKey, privateContext) + verify(paykitPaymentRequestRepo).accept(request) + } + verify( + paykitPaymentProofRepo + ).completeOnchainPayment( + request, + "txid", + MethodId.P2wpkh.rawValue, + "bitkit", + OnchainSendOutcome.Accepted("txid") + ) + verify(privatePaykitRepo, never()).releasePrivatePaymentList(any(), any()) + } + + @Test + fun `accepted onchain payment survives a contended background proof completion`() = test { + val address = "bcrt1qpaymentrequest" + val request = paymentRequest() + val privateContext = privatePaymentContext(7uL) + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u) + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + whenever( + paykitPaymentProofRepo.completeOnchainPayment( + request, + "txid", + MethodId.P2wpkh.rawValue, + "bitkit", + OnchainSendOutcome.Accepted("txid"), + ) + ).doSuspendableAnswer { throw PaykitException.SharedStateBusy("shared_state_busy", "Locked") } + stubSuccessfulOnchainSend(address, request.amount.atomic) + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = address, + amount = request.amount.atomic, + payMethod = SendMethod.ONCHAIN, + speed = TransactionSpeed.Medium, + isPaymentRequest = true, + ), + ) + + sut.sendEffect.test { + confirmCurrentPayment() + assertEquals(SendEffect.PaymentSuccess, awaitItem()) + expectNoEvents() + } + + assertEquals("txid", sut.successSendUiState.value.paymentHashOrTxId) + assertEquals(request.amount.atomic.toLong(), sut.successSendUiState.value.sats) + verify(paykitPaymentProofRepo, never()).failOnchainPayment(request) + verify(paykitPaymentProofRepo, never()).cancelPreparation(request) + verify(privatePaykitRepo, never()).releasePrivatePaymentList(any(), any()) + verify(lightningRepo).sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), any(), any(), any(), any(), + anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), + ) + } + + @Test + fun `proof preparation failure blocks incoming onchain payment`() = test { + val address = "bcrt1qpaymentrequest" + val request = paymentRequest() + val privateContext = privatePaymentContext(7uL) + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u) + whenever( + paykitPaymentProofRepo.prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain) + ) + .thenReturn(Result.failure(IllegalStateException("proof unavailable"))) + whenever(paykitPaymentRequestRepo.accept(request)).thenReturn(Result.success(Unit)) + whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) + .thenReturn(Result.success(Unit)) + stubSuccessfulOnchainSend(address, request.amount.atomic) + setActiveContactPaymentContext(testPublicKey, privateContext, request) + setSendState( + SendUiState( + address = address, + amount = request.amount.atomic, + payMethod = SendMethod.ONCHAIN, + speed = TransactionSpeed.Medium, + isPaymentRequest = true, + ), + ) + + confirmCurrentPayment() + + verify(privatePaykitRepo, never()).consumePrivatePaymentList(testPublicKey, privateContext) + verify(paykitPaymentRequestRepo, never()).accept(request) + verify(lightningRepo, never()).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(), + ) + verify(paykitPaymentProofRepo, never()).markOnchainPaymentStarted( + any(), + any(), + any(), + any(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + ) + } + + @Test + fun `atomic acceptance claim failure blocks versionless request before sending`() = test { + val request = paymentRequest() val privateContext = privatePaymentContext(null) pubkyPublicKey.value = testPublicKey enablePaykitUi() @@ -17550,6 +19063,170 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(paykitPaymentProofRepo, never()).prepare(any(), any(), any(), any(), anyOrNull(), anyOrNull()) } + @Test + fun `request confirmation pays the endpoint the router picks`() = test { + enablePaykitUi() + usdtEnabled.value = false + pubkyPublicKey.value = testPublicKey + sut.setIsAuthenticated(true) + runCurrent() + val endpoint = Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = REGTEST_ADDRESS) + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.USD, 250u), + pricing = PaykitRequestPricing(PaymentConversion.Fixed(listOf(ConversionRate("btc", "0.00001")))), + acceptedPaymentEndpointIdentifiers = listOf(endpoint.methodId.rawValue), + ) + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + val resolution = CompletableDeferred>() + whenever(privatePaykitRepo.beginPaymentRequest(request)).doSuspendableAnswer { resolution.await() } + pendingPaykitPaymentRequests.value = listOf(request) + runCurrent() + assertEquals(request, (sut.currentSheet.value as? Sheet.Send)?.preparingRequest) + resolution.complete( + Result.success(PublicPaykitPaymentResult.Opened(endpoint.value, endpoints = listOf(endpoint))) + ) + runCurrent() + + assertEquals(Sheet.Send(SendRoute.Confirm), sut.currentSheet.value) + assertEquals(2_500uL, sut.sendUiState.value.amount) + assertTrue(sut.sendUiState.value.isAmountInputValid) + assertFalse(sut.sendUiState.value.shouldAutomaticallyPay) + assertFalse(sut.sendUiState.value.shouldConfirmPay) + verify(paykitPaymentRequestRepo, never()).accept(any()) + verify(paykitRouteRepo).route( + eq(2_500uL), + eq(listOf(PaykitEndpoint(MethodId.P2wpkh.rawValue, REGTEST_ADDRESS))), + eq(0uL), + eq(100_000uL), + eq(false), + ) + } + + @Test + fun `an onchain request savings cannot cover goes to spark`() = test { + enablePaykitUi() + usdtEnabled.value = false + pubkyPublicKey.value = testPublicKey + sut.setIsAuthenticated(true) + runCurrent() + val endpoint = Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = REGTEST_ADDRESS) + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, 20_000u), + acceptedPaymentEndpointIdentifiers = listOf(endpoint.methodId.rawValue), + ) + balanceState.value = BalanceState(maxSendOnchainSats = 5_000u, maxSendLightningSats = 50_000u) + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + val resolution = CompletableDeferred>() + whenever(privatePaykitRepo.beginPaymentRequest(request)).doSuspendableAnswer { resolution.await() } + pendingPaykitPaymentRequests.value = listOf(request) + runCurrent() + assertEquals(request, (sut.currentSheet.value as? Sheet.Send)?.preparingRequest) + resolution.complete( + Result.success(PublicPaykitPaymentResult.Opened(endpoint.value, endpoints = listOf(endpoint))) + ) + runCurrent() + + verify(paykitRouteRepo).route( + eq(20_000uL), + eq(listOf(PaykitEndpoint(MethodId.P2wpkh.rawValue, REGTEST_ADDRESS))), + any(), + eq(0uL), + eq(true), + ) + } + + @Test + fun `an onchain request routed to spark opens confirmation with the swipe on`() = test { + enablePaykitUi() + usdtEnabled.value = false + pubkyPublicKey.value = testPublicKey + sut.setIsAuthenticated(true) + runCurrent() + val endpoint = Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = REGTEST_ADDRESS) + val leg = sparkRouteLeg(REGTEST_ADDRESS).copy(deliveredSat = 20_000uL, debitSat = 20_300uL) + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.BTC, 20_000u), + acceptedPaymentEndpointIdentifiers = listOf(endpoint.methodId.rawValue), + ) + balanceState.value = BalanceState(maxSendOnchainSats = 5_000u, maxSendLightningSats = 50_000u) + whenever(lightningRepo.canSend(any())).thenReturn(true) + whenever(lightningRepo.canWithdrawWithSpark(any())).thenReturn(true) + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + whenever(privatePaykitRepo.beginPaymentRequest(request)).thenReturn( + Result.success(PublicPaykitPaymentResult.Opened(endpoint.value, endpoints = listOf(endpoint))), + ) + + pendingPaykitPaymentRequests.value = listOf(request) + runCurrent() + advanceUntilIdle() + + assertEquals(SendMethod.LIGHTNING, sut.sendUiState.value.payMethod) + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + assertTrue( + sut.sendUiState.value.isAmountInputValid, + "a spark leg that covers the request must enable the swipe", + ) + } + + @Test + fun `an onchain dollar request priced for onchain only goes to spark at its onchain rate`() = test { + enablePaykitUi() + usdtEnabled.value = false + pubkyPublicKey.value = testPublicKey + sut.setIsAuthenticated(true) + runCurrent() + val endpoint = Endpoint(MethodId.P2wpkh, REGTEST_ADDRESS, rawPayload = REGTEST_ADDRESS) + val leg = sparkRouteLeg(REGTEST_ADDRESS).copy(deliveredSat = 2_500uL, debitSat = 2_800uL) + val request = paymentRequest().copy( + amount = PaykitAmount(PaykitAsset.USD, 250u), + pricing = PaykitRequestPricing( + PaymentConversion.Fixed( + listOf(ConversionRate(MethodId.P2wpkh.rawValue.substringBeforeLast("-"), "0.00001")), + ), + ), + acceptedPaymentEndpointIdentifiers = listOf(endpoint.methodId.rawValue), + ) + balanceState.value = BalanceState(maxSendOnchainSats = 0u, maxSendLightningSats = 50_000u) + whenever(lightningRepo.canSend(any())).thenReturn(true) + whenever(lightningRepo.canWithdrawWithSpark(any())).thenReturn(true) + whenever(paykitRouteRepo.canRouteThroughSpark).thenReturn(true) + whenever(paykitRouteRepo.route(any(), any(), any(), any(), any())) + .thenReturn(Result.success(PaykitRoute.Service(leg))) + whenever(coreService.decode(REGTEST_ADDRESS)).thenReturn( + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 0u, null, null, null)), + ) + whenever(privatePaykitRepo.beginPaymentRequest(request)).thenReturn( + Result.success(PublicPaykitPaymentResult.Opened(endpoint.value, endpoints = listOf(endpoint))), + ) + + pendingPaykitPaymentRequests.value = listOf(request) + runCurrent() + advanceUntilIdle() + + assertFalse(sut.sendUiState.value.paykitRateUnavailable) + assertEquals(2_500uL, sut.sendUiState.value.amount) + assertEquals(leg, sut.sendUiState.value.routedPaykitRoute?.serviceLeg) + assertTrue(sut.sendUiState.value.isAmountInputValid) + verify(paykitRouteRepo).route( + eq(2_500uL), + eq(listOf(PaykitEndpoint(MethodId.P2wpkh.rawValue, REGTEST_ADDRESS))), + any(), + eq(0uL), + eq(true), + ) + } + @Test fun `fixed dollar request accepting USDT opens bitcoin confirmation while USDT is off`() = test { enablePaykitUi() @@ -17867,6 +19544,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { balanceState.value = BalanceState(maxSendLightningSats = 100_000u) whenever(lightningRepo.canSend(any())).thenReturn(true) whenever(coreService.decode(lnurl.uri)).thenReturn(Scanner.LnurlPay(lnurl)) + // Below the minimum, the router gets no endpoint and the LNURL's minimum toast names the amount. + whenever(formatMoneyValue(any())).thenReturn("1,000 sats") for ((cents, route) in listOf(50uL to SendRoute.Amount, 250uL to SendRoute.Confirm)) { val request = paymentRequest().copy( amount = PaykitAmount(PaykitAsset.USD, cents), diff --git a/changelog.d/next/1754.added.md b/changelog.d/next/1754.added.md new file mode 100644 index 0000000000..ceedc45d9c --- /dev/null +++ b/changelog.d/next/1754.added.md @@ -0,0 +1 @@ +Paykit contacts and payment requests can be paid from Spark, including contacts and requests that only accept on-chain bitcoin. diff --git a/journeys/paykit-spark-route.xml b/journeys/paykit-spark-route.xml new file mode 100644 index 0000000000..814c9a75d0 --- /dev/null +++ b/journeys/paykit-spark-route.xml @@ -0,0 +1,27 @@ + + + Proves that paying a Paykit contact whose only endpoint is on-chain, from a wallet whose spending balance is held + on Spark, routes through a Spark withdrawal straight to the contact's address, without the user picking a route, + and that the contact receives the exact amount on chain. + + Preconditions: a dev debug build with E2E=true, E2E_BACKEND=local, E2E_HOMESERVER_PUBKY set to the local + marketplace homeserver; bitkit-docker's default stack with the marketplace and + payment-requests profiles; adb reverse for 6286, 6287, 6288, 15411, 15412, 60001, 23735, 23000 and 23010. + The wallet has no channels and an empty savings balance, a Spark balance of at least 25 000 sats from Lightspark's + regtest faucet sent to the deposit address on the Spark screen, a Pubky profile on the local homeserver, and the + fixture-issuer's pubky saved as a contact. The contact is bitkit-docker's fixture-issuer, which publishes only a + btc-regtest-p2wpkh endpoint; Spark pays it on Lightspark's regtest chain. + + + Verify the savings balance (tag "ActivitySavings") shows 0 and the spending balance (tag "ActivitySpending") is above 25 000 + Tap Send (tag "Send"), then Contact (tag "RecipientContact") + Tap the fixture-issuer (tag "SendContact_" followed by its pubky) + Verify the amount screen (tag "send_amount_screen") offers SPENDING as the source + Enter 20000 and tap Continue (tag "ContinueAmount") + Verify the Confirm screen (tag "SendConfirm") is visible, then tap Show Details (tag "SendConfirmToggleDetails") + Verify FROM is SPENDING, TO is the contact, and ROUTE (tag "ReviewSwapRoute") reads "Spark" + Swipe to pay (tag "GRAB") + Verify the Bitcoin Sent screen (tag "SendSuccess") shows 20 000 + Verify Lightspark's regtest mempool shows the withdrawal transaction paying exactly 20 000 sats to the fixture-issuer's address + +