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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 62 additions & 4 deletions app/src/main/java/to/bitkit/repositories/LightningRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ import to.bitkit.utils.LdkError
import to.bitkit.utils.Logger
import to.bitkit.utils.ServiceError
import to.bitkit.utils.UrlValidator
import to.bitkit.utils.isStoppedAtSubmission
import java.io.File
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
Expand Down Expand Up @@ -343,7 +344,7 @@ class LightningRepo @Inject constructor(
}.onFailure {
// Cancellation is expected during pull-to-refresh, rethrow per Kotlin best practices
if (it is CancellationException) throw it
if (it is PaymentAbortedBeforeSend) {
if (it is PaymentAbortedBeforeSend || it.isStoppedAtSubmission()) {
Logger.debug("Aborted '$operationName' before dispatch", context = TAG)
} else if (it.cause is OnchainSendReviewEndedError) {
Logger.info("Ended '$operationName' unsent at its fee review", context = TAG)
Expand Down Expand Up @@ -1589,6 +1590,27 @@ class LightningRepo @Inject constructor(
onBeforeSend = onBeforeSend,
)

/**
* Like [payInvoice], with [onBeforeSend] run again right before the send is submitted, after the last journal
* write on either rail, for a check with no side effects such as a payment request's authorization. When it is
* false there, nothing is sent and the result fails with [ServiceError.PaymentStoppedAtSubmission].
*/
suspend fun payInvoiceRecheckedAtSubmission(
bolt11: String,
sats: ULong?,
paymentDeadlineAt: Instant?,
maxTotalRoutingFeeMsat: ULong? = null,
onBeforeSend: suspend () -> Boolean,
): Result<PaymentId> = payInvoiceChecked(
bolt11 = bolt11,
sats = sats,
paymentDeadlineAt = paymentDeadlineAt,
maxTotalRoutingFeeMsat = maxTotalRoutingFeeMsat,
isAuthorizedAtSubmission = null,
rechecksBeforeSend = true,
onBeforeSend = onBeforeSend,
)

suspend fun payInvoice(
bolt11: String,
sats: ULong?,
Expand All @@ -1611,6 +1633,7 @@ class LightningRepo @Inject constructor(
paymentDeadlineAt: Instant?,
maxTotalRoutingFeeMsat: ULong?,
isAuthorizedAtSubmission: (() -> Boolean)?,
rechecksBeforeSend: Boolean = false,
onBeforeSend: suspend () -> Boolean,
): Result<PaymentId> {
// The rail is picked again on every attempt, so each one checks the other holds no live send of the invoice.
Expand All @@ -1634,8 +1657,12 @@ class LightningRepo @Inject constructor(
var isChecked = false
val authorizeSend: suspend () -> Boolean = authorize@{
// Spark's check right before it sends, and its retry of a send whose leaves it couldn't select, keep
// the send's admission and recheck only the caller's check at submission, which has no side effects.
if (isChecked) return@authorize isAuthorizedAtSubmission?.invoke() ?: true
// the send's admission and recheck only the caller's check at submission, which has no side effects:
// the whole check for a caller that rechecks it, else its check at submission.
if (isChecked) {
if (rechecksBeforeSend) return@authorize onBeforeSend()
return@authorize isAuthorizedAtSubmission?.invoke() ?: true
}
isChecked = true
val isAuthorized = onBeforeSend().also { if (it) requireWalletRestoreComplete() }
if (isAuthorized) {
Expand Down Expand Up @@ -1684,6 +1711,7 @@ class LightningRepo @Inject constructor(
paymentDeadlineAt,
maxTotalRoutingFeeMsat,
isAuthorizedAtSubmission = isAuthorizedAtSubmission,
rechecksBeforeSend = rechecksBeforeSend,
onBeforeSend = onBeforeSend,
)
}
Expand Down Expand Up @@ -1807,6 +1835,7 @@ class LightningRepo @Inject constructor(
paymentDeadlineAt: Instant?,
maxTotalRoutingFeeMsat: ULong?,
isAuthorizedAtSubmission: (() -> Boolean)? = null,
rechecksBeforeSend: Boolean = false,
onBeforeSend: suspend () -> Boolean,
): Result<PaymentId> = executeWhenNodeRunning("payInvoice") {
requireWalletRestoreComplete()
Expand Down Expand Up @@ -1836,8 +1865,27 @@ class LightningRepo @Inject constructor(
try {
ldkSendsInFlight.merge(key, 1, Int::plus)
isCounted = true
ldkSendRecordedAt[key] = ldkSendRecords.incrementAndGet()
val wasRecorded = key in cacheStore.data.first().ldkSendHashes
val recordedAt = ldkSendRecords.incrementAndGet()
val recordedAtBefore = ldkSendRecordedAt.put(key, recordedAt)
cacheStore.addLdkSendHash(key, invoiceExpiresAt(bolt11))
// After the hash write, the last step that suspends before the node's queue.
if (rechecksBeforeSend && !onBeforeSend()) {
// Nothing was sent, so only this send's record goes: one another send of the invoice made before or
// after it, or still has in flight, stays.
ldkSendRecordedAt.computeIfPresent(key) { _, at ->
if (at == recordedAt) recordedAtBefore else at
}
// This send's record is gone by now, so a record left is another send's, whatever its order.
val isHeldElsewhere = { (ldkSendsInFlight[key] ?: 0) > 1 || ldkSendRecordedAt.containsKey(key) }
if (!wasRecorded && recordedAtBefore == null) {
// The refusal reaches the caller even when this write fails: a hash left behind only holds a
// Spark retry until the node's payments show no send.
runSuspendCatching { cacheStore.removeLdkSendHash(key, isKept = isHeldElsewhere) }
.onFailure { Logger.warn("Failed to drop refused node send '$key'", it, context = TAG) }
}
return@executeWhenNodeRunning Result.failure(ServiceError.PaymentStoppedAtSubmission())
}
runCatching {
if (isAuthorizedAtSubmission == null) {
lightningService.send(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat)
Expand Down Expand Up @@ -2066,6 +2114,7 @@ class LightningRepo @Inject constructor(
contactPublicKey: String? = null,
approvedMiningFeeSats: ULong? = null,
reviewHigherFee: (suspend (OnchainPreparedReceipt) -> Unit)? = null,
recheckBeforeSubmission: suspend () -> Unit = {},
): Result<OnchainSendOutcome> = executeWhenNodeRunning("sendOnChain") {
requireWalletRestoreComplete()
require(address.isNotEmpty()) { "Send address cannot be empty" }
Expand Down Expand Up @@ -2145,6 +2194,15 @@ class LightningRepo @Inject constructor(
if (approvedMiningFeeSats != null) {
checkApprovedSpend(prepared, sats, satsPerVByte, approvedMiningFeeSats, reviewHigherFee)
}
// Preparing suspends, so a payment request is authorized again before its receipt is kept.
var isAuthorized = false
try {
recheckBeforeSubmission()
isAuthorized = true
} finally {
// A refused send frees its inputs and change now, not when its handle is collected.
if (!isAuthorized) prepared.release()
}
onchainSendAttemptStore.retainPreparedReceipt(
attempt.attemptId,
attempt.walletIndex,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,19 @@ class PaykitAllowancePayer @Inject constructor(
): Result<Unit> =
paymentProofRepo.associateLightningPayment(request, paymentHash, paymentEndpointIdentifier, paymentAppId)

/** Pays [bolt11], checking again right before submission that [request]'s contact is not blocked. */
suspend fun payLightning(
request: PaykitPaymentRequest,
bolt11: String,
sats: ULong?,
paymentDeadlineAt: Instant?,
maxTotalRoutingFeeMsat: ULong,
): Result<String> = lightningRepo.payInvoice(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) { true }
): Result<String> = lightningRepo.payInvoiceRecheckedAtSubmission(
bolt11,
sats,
paymentDeadlineAt,
maxTotalRoutingFeeMsat,
) { paymentRequestRepo.ensureAutomaticPaymentAllowed(request).isSuccess }

/** Clears the proof when [error] proves the payment never left; returns whether it did. */
suspend fun failLightningPayment(
Expand Down Expand Up @@ -984,6 +991,7 @@ class PaykitAllowanceExecutor @Inject constructor(
// Routing fees fall outside the allowance's accounting, so they are capped at 1% of the requested amount.
val maxRoutingFeeMsat = amountSats.safe() * MAX_ROUTING_FEE_MSAT_PER_SAT.safe()
payer.payLightning(
request,
payment.endpoint.value,
sats,
request.submissionDeadline(null),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -947,10 +947,15 @@ class PaykitPaymentProofRepo @Inject constructor(
requestId: PaykitPaymentRequestId? = null,
): Boolean {
val error = generateSequence(submissionError) { it.cause }
.firstOrNull { it is ServiceError.PaymentDeadlineExpired || it is SparkError.SendRefused }
.firstOrNull {
it is ServiceError.PaymentDeadlineExpired || it is SparkError.SendRefused ||
it is ServiceError.PaymentStoppedAtSubmission || it is PaymentAbortedBeforeSend
}
?: submissionError.asNodeException() ?: submissionError
when (error) {
is SparkError.SendRefused,
is ServiceError.PaymentStoppedAtSubmission,
is PaymentAbortedBeforeSend,
is NodeNotRunningError,
is NodeRunTimeoutError,
is ServiceError.NodeNotSetup,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1191,14 +1191,7 @@ class PaykitPaymentRequestRepo @Inject constructor(
if (forExecution && !hasCurrentExecutionContext(request)) {
throw PaykitPaymentRequestError.RequestUnavailable
}
if (
paykitSdkService.linkedPeers().any {
it.state == LinkedPeerState.BLOCKED &&
PubkyPublicKeyFormat.matches(it.counterparty, request.counterparty)
}
) {
throw PaykitPaymentRequestError.RequestUnavailable
}
if (isBlocked(request)) throw PaykitPaymentRequestError.RequestUnavailable
if (!isCurrentState(generation, identity)) throw PaykitPaymentRequestError.RequestUnavailable
if (forExecution && !hasCurrentExecutionContext(request)) {
throw PaykitPaymentRequestError.RequestUnavailable
Expand All @@ -1207,6 +1200,18 @@ class PaykitPaymentRequestRepo @Inject constructor(
}
}

/** Allows an allowance's automatic payment of [request] while it is unexpired and its contact is not blocked. */
suspend fun ensureAutomaticPaymentAllowed(request: PaykitPaymentRequest): Result<Unit> = withContext(ioDispatcher) {
runSuspendCatching {
if (request.isPaymentDeadlineExpired(clock.now())) throw PaykitPaymentRequestError.RequestExpired
if (isBlocked(request)) throw PaykitPaymentRequestError.RequestUnavailable
}
}

private suspend fun isBlocked(request: PaykitPaymentRequest): Boolean = paykitSdkService.linkedPeers().any {
it.state == LinkedPeerState.BLOCKED && PubkyPublicKeyFormat.matches(it.counterparty, request.counterparty)
}

suspend fun claimForPayment(request: PaykitPaymentRequest): Result<Unit> = withContext(ioDispatcher) {
runSuspendCatching {
ensurePaymentAllowed(request, forExecution = false).getOrThrow()
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/java/to/bitkit/repositories/PaykitRouteRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ class PaykitRouteRepo @Inject constructor(
contact: String?,
tags: List<String> = emptyList(),
paymentDeadlineAt: Instant? = null,
recheckBeforeSend: suspend () -> Boolean = { true },
onBeforeSend: suspend () -> Boolean = { true },
): Result<String> = when (leg.service) {
SparkRepo.ROUTE_SERVICE -> sparkRepo.withdraw(
Expand All @@ -106,6 +107,7 @@ class PaykitRouteRepo @Inject constructor(
tags = tags,
paymentDeadlineAt = paymentDeadlineAt,
onBeforeSend = onBeforeSend,
recheckBeforeSend = recheckBeforeSend,
)
else -> Result.failure(AppError("Unsupported route service '${leg.service}'"))
}
Expand Down
20 changes: 18 additions & 2 deletions app/src/main/java/to/bitkit/repositories/SparkRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -806,8 +806,9 @@ class SparkRepo @Inject constructor(
if (result.exceptionOrNull()?.isLeafSelectionFailure() != true || !canRetry()) return result
Logger.info("Retrying Spark send '$attemptId' as Spark could not select its leaves", context = TAG)
delay(LEAF_SELECTION_RETRY_DELAY)
// A cancel, block or identity change can land during the delay, so each resend is checked again.
if (!canRetry() || !onBeforeSend()) return result
// A cancel, block or identity change can land during the delay, so each resend is checked again. The
// authorization check can suspend, so the deadline and an exit hold are read after it.
if (!onBeforeSend() || !canRetry()) return result
val retried = runSuspendCatching { sparkService.send(prepared, attemptId) }
// A failed try can have committed a transfer before Spark selected leaves again, so a short balance or an
// expiry on a retry, which would read as nothing sent, ends with the earlier leaf failure instead.
Expand Down Expand Up @@ -1419,6 +1420,7 @@ class SparkRepo @Inject constructor(
maxDebitSats: ULong? = null,
tags: List<String> = emptyList(),
paymentDeadlineAt: Instant? = null,
recheckBeforeSend: suspend () -> Boolean = { true },
onBeforeSend: suspend () -> Boolean = { true },
): Result<String> =
withContext(bgDispatcher) {
Expand Down Expand Up @@ -1455,6 +1457,20 @@ class SparkRepo @Inject constructor(
)
journal = opened
cacheStore.update { it.copy(pendingSparkWithdrawal = opened) }
// The proof and journal writes suspend, so the authorization is checked again after them.
var isAllowed = false
try {
isAllowed = runSuspendCatching { recheckBeforeSend() }.getOrDefault(false)
} finally {
// Nothing was sent, so a refusal or a cancel closes the journal at once, and the refusal
// reaches the caller even when that write fails.
if (!isAllowed) {
withContext(NonCancellable) {
bestEffort("close the refused Spark withdrawal's journal") { clearJournal(opened) }
}
}
}
if (!isAllowed) throw ServiceError.PaymentStoppedAtSubmission()
spending {
// Saving the journal suspends, so the deadline and an exit that started meanwhile are checked
// last, before the send.
Expand Down
Loading