Skip to content
Merged
28 changes: 22 additions & 6 deletions Bitkit/Managers/SparkManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -675,13 +675,14 @@ final class SparkManager: ChannelFreeLightningRail {
return try await requireSdk().receivePayment(request: ReceivePaymentRequest(paymentMethod: method)).paymentRequest
}

/// Errors before `sendPayment` are `ChannelFreeRailSendRefused`, since nothing left the wallet; a failure inside it
/// stays uncertain, as the payment may have been dispatched, unless it is one raised before dispatch
/// (`sendPaymentFailure`).
/// Errors before `sendPayment` are `ChannelFreeRailSendRefused`, since nothing left the wallet, apart from a
/// `recheckBeforeSubmission` refusal, which is rethrown as it is; a failure inside it stays uncertain, as the payment
/// may have been dispatched, unless it is one raised before dispatch (`sendPaymentFailure`).
nonisolated func send(
bolt11: String,
sats: UInt64?,
maxFeeSats: UInt64?,
recheckBeforeSubmission: @escaping () async throws -> Void,
beforeSubmission: @escaping () throws -> Void
) async throws -> PaymentHash {
let prepared: PrepareSendPaymentResponse
Expand Down Expand Up @@ -738,6 +739,8 @@ final class SparkManager: ChannelFreeLightningRail {
}
let (sum, overflows) = invoiceDetails.timestamp.addingReportingOverflow(invoiceDetails.expiry)
let expiresAt = overflows ? UInt64.max : sum
// After the quote, balance and failed-attempt awaits, so a payment refused meanwhile never reaches `spends.run`.
try await recheckBeforeSubmission()
// An exit that started while the quote was prepared refuses it here, before its hash is recorded.
let response: SendPaymentResponse
do {
Expand All @@ -749,7 +752,11 @@ final class SparkManager: ChannelFreeLightningRail {
paymentHash: paymentHash, attempt: attempt, amountSats: amountSats, expiresAt: expiresAt, now: Self.nowSecs()
)
do {
return try await Self.sendRetryingLeafSelection(canRetry: { (try? beforeSubmission()) != nil }) {
// A retry waits first, so it checks the request's authorization again, then the deadline after that
// await; a refused retry ends with the leaf failure, as the first try may have committed a transfer.
return try await Self.sendRetryingLeafSelection(canRetry: {
await Self.canRetrySend(recheckBeforeSubmission: recheckBeforeSubmission, beforeSubmission: beforeSubmission)
}) {
try await sdk.sendPayment(request: SendPaymentRequest(
prepareResponse: prepared,
options: Self.bolt11SendOptions,
Expand Down Expand Up @@ -829,7 +836,7 @@ final class SparkManager: ChannelFreeLightningRail {
/// never left.
nonisolated static func sendRetryingLeafSelection<T>(
retryDelay: Duration = .seconds(2),
canRetry: () -> Bool,
canRetry: () async -> Bool,
_ send: () async throws -> T
) async throws -> T {
var retries = 0
Expand All @@ -846,13 +853,22 @@ final class SparkManager: ChannelFreeLightningRail {
retries += 1
Logger.info("Retrying a Spark send as Spark could not select its leaves", context: "SparkManager")
try? await Task.sleep(for: retryDelay)
guard !Task.isCancelled, canRetry() else { throw error }
guard !Task.isCancelled, await canRetry() else { throw error }
}
}
}

nonisolated static let leafSelectionRetries = 3

/// Whether a send may retry: the request's authorization first, then cancellation and the deadline after that await.
nonisolated static func canRetrySend(
recheckBeforeSubmission: () async throws -> Void,
beforeSubmission: () throws -> Void
) async -> Bool {
guard await (try? recheckBeforeSubmission()) != nil, !Task.isCancelled else { return false }
return (try? beforeSubmission()) != nil
}

/// Spark fails a send with this error when it holds the balance but can't select leaves to spend, before anything
/// reaches the operators (`select_leaves_with_retry` in the 0.28.3 SDK's `spark-wallet/src/wallet.rs`).
nonisolated static func isLeafSelectionFailure(_ error: Error) -> Bool {
Expand Down
16 changes: 13 additions & 3 deletions Bitkit/Services/LightningService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,15 @@ protocol ChannelFreeLightningRail: AnyObject {
@MainActor var isReady: Bool { get }
@MainActor var balanceSats: UInt64 { get }
func receive(amountSats: UInt64?, description: String, expirySecs: UInt32) async throws -> String
/// Refuses before sending when the prepared fee is above `maxFeeSats`, and runs `beforeSubmission` right before the
/// payment goes out, as the node path does.
func send(bolt11: String, sats: UInt64?, maxFeeSats: UInt64?, beforeSubmission: @escaping () throws -> Void) async throws -> PaymentHash
/// Refuses before sending when the prepared fee is above `maxFeeSats`, runs `recheckBeforeSubmission` after its last
/// await before the payment goes out, and `beforeSubmission` right before it does, as the node path does.
func send(
bolt11: String,
sats: UInt64?,
maxFeeSats: UInt64?,
recheckBeforeSubmission: @escaping () async throws -> Void,
beforeSubmission: @escaping () throws -> Void
) async throws -> PaymentHash
func estimateRoutingFees(bolt11: String, amountSats: UInt64?) async throws -> UInt64
/// Throws when the rail could not list its payments, so a duplicate-payment check can tell that from none.
func lightningPayments() async throws -> [ChannelFreeRailPayment]
Expand Down Expand Up @@ -1233,6 +1239,7 @@ class LightningService: NodeLifecycleService {
sats: UInt64? = nil,
params: RouteParametersConfig? = nil,
channelsOnly: Bool = false,
recheckBeforeSubmission: @escaping () async throws -> Void = {},
beforeSubmission: @escaping () throws -> Void = {}
) async throws -> PaymentHash {
let invoice = try? Bolt11Invoice.fromStr(invoiceStr: bolt11)
Expand Down Expand Up @@ -1287,6 +1294,7 @@ class LightningService: NodeLifecycleService {
sats: sats,
maxFeeSats: params?.maxTotalRoutingFeeMsat.map { $0 / 1000 }
?? Self.paymentAmountSats(bolt11: bolt11, sats: sats).map(Self.defaultMaxFeeSats),
recheckBeforeSubmission: recheckBeforeSubmission,
beforeSubmission: { [weak self] in
try beforeSubmission()
// Spark checks again before it retries the same attempt, which is already admitted.
Expand Down Expand Up @@ -1362,6 +1370,8 @@ class LightningService: NodeLifecycleService {
endLdkSend(paymentHash: sendKey)
}
}
// After this send's last await before the queue, so a refusal since the caller's checks leaves nothing recorded.
try await recheckBeforeSubmission()
Comment thread
ovitrif marked this conversation as resolved.
Resolved
do {
return try await Self.submitPayment(beforeSubmission: { [weak self] in
try beforeSubmission()
Expand Down
14 changes: 14 additions & 0 deletions Bitkit/Services/PaykitAllowanceExecutor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -418,10 +418,24 @@ struct PaykitAllowanceLivePayer: PaykitAllowancePaying {
bolt11: bolt11,
sats: sats,
params: Self.routeParameters(amountSats: request.allowanceAmountSats),
// Checked again after the send's last await, so a contact blocked since the executor's check isn't paid.
// Any failure here sent nothing, so it ends as a refusal the proof service treats as unsent.
recheckBeforeSubmission: { try await Self.recheckBeforeSubmission { try await ensurePaymentAllowed(request) } },
beforeSubmission: { try PaykitPaymentRequest.checkPaymentDeadline(request.paymentDeadline) }
)
}

/// Runs `check` as a refusal: an expired request stays expired and any other failure becomes `requestUnavailable`.
static func recheckBeforeSubmission(_ check: () async throws -> Void) async throws {
do {
try await check()
} catch PaykitPaymentRequestError.requestExpired {
throw PaykitPaymentRequestError.requestExpired
} catch {
throw PaykitPaymentRequestError.requestUnavailable
}
}

func failLightningPayment(paymentHash: String, submissionError: Error) async -> Bool {
await PaykitPaymentProofService.shared.failLightningPayment(paymentHash: paymentHash, submissionError: submissionError)
}
Expand Down
2 changes: 2 additions & 0 deletions Bitkit/Services/PaykitPaymentProofService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1385,6 +1385,8 @@ actor PaykitPaymentProofService {
let underlyingError = (submissionError as? AppError)?.underlyingError ?? submissionError
if underlyingError as? PaykitPaymentRequestError == .requestExpired {
// The local deadline gate runs before submitting to the node.
} else if underlyingError as? PaykitPaymentRequestError == .requestUnavailable {
// The authorization recheck before submission refused it, for instance for a contact blocked meanwhile.
} else if underlyingError is ChannelFreeRailSendRefused {
// Spark refused it before sending: not connected, not preparable, or over the fee limit.
} else if underlyingError is MoveToSparkError {
Expand Down
2 changes: 2 additions & 0 deletions Bitkit/Services/PaykitRouteService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,8 @@ enum PaykitRouteService {
try await authorize()
if let attemptId {
await markSending(attemptId)
// Marking it sending awaits, so the request is authorized again after it, right before Spark sends.
try await authorize()
}
}
if let attemptId {
Expand Down
2 changes: 2 additions & 0 deletions Bitkit/ViewModels/WalletViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1180,11 +1180,13 @@ class WalletViewModel: ObservableObject {
sats: UInt64? = nil,
timeoutSeconds: TimeInterval = 10,
paymentDeadline: PaykitPreciseInstant? = nil,
recheckBeforeSubmission: @escaping () async throws -> Void = {},
afterListening: (@MainActor (String) -> Void)? = nil,
onTimeout: (@MainActor (String) -> Void)? = nil
) async throws -> SettledLightningPayment {
let hash = try await lightningService.send(
bolt11: bolt11, sats: sats,
recheckBeforeSubmission: recheckBeforeSubmission,
beforeSubmission: { try PaykitPaymentRequest.checkPaymentDeadline(paymentDeadline) }
)
let paymentHash = String(hash)
Expand Down
29 changes: 24 additions & 5 deletions Bitkit/Views/Wallets/Send/LnurlPayConfirm.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ struct LnurlPayConfirm: View {

static func sendLightningPayment<Result>(
request: PaykitPaymentRequest?,
authorize: (PaykitPaymentRequest) async throws -> Void,
onAuthorizationFailure: (Error) async -> Void,
send: () async throws -> Result
authorize: @escaping (PaykitPaymentRequest) async throws -> Void,
onAuthorizationFailure: @escaping (Error) async -> Void,
send: (_ recheckBeforeSubmission: @escaping () async throws -> Void) async throws -> Result
) async throws -> Result {
if let request {
do {
Expand All @@ -48,7 +48,22 @@ struct LnurlPayConfirm: View {
throw error
}
}
return try await send()
// The send runs it again after its last await before submission, so a contact blocked meanwhile isn't paid.
do {
return try await send {
guard let request else { return }
do {
try await authorize(request)
} catch {
throw SubmissionRecheckRefusal(error: error)
}
}
} catch let refusal as SubmissionRecheckRefusal {
// Ended as a refusal only when the refusal comes back: a retry of a send still in doubt comes back pending,
// and keeps its proof.
await onAuthorizationFailure(refusal.error)
throw refusal.error
}
}

private var shouldAutomaticallyPay: Bool {
Expand Down Expand Up @@ -409,9 +424,12 @@ struct LnurlPayConfirm: View {
request: incomingPaymentRequest,
authorize: { try await paykitPaymentRequestManager.ensurePaymentAllowed($0) },
onAuthorizationFailure: { _ in
// A refusal at the recheck before submission sent nothing, so it ends as a refusal up front does.
lightningPaymentHash = nil
privatePaymentListOutcome = .definitePreBroadcastFailure
await PaykitPaymentProofService.shared.failLightningPayment(paymentHash: paymentHash)
}
) {
) { recheckBeforeSubmission in
lightningPaymentHash = paymentHash
// After the allowance check above, so a refused request moves nothing.
try await MoveToSparkManager.shared.updateSpendingBalanceIfNeeded(
Expand All @@ -428,6 +446,7 @@ struct LnurlPayConfirm: View {
bolt11: bolt11,
sats: nil,
paymentDeadline: incomingPaymentRequest?.submissionDeadline(quoteId: app.paykitPaymentTerms?.quoteId),
recheckBeforeSubmission: recheckBeforeSubmission,
afterListening: { _ in lightningPaymentSubmitted = true },
onTimeout: { timedOutHash in
app.addPendingPaymentHash(timedOutHash, contactPaymentContext: contactPaymentContext)
Expand Down
66 changes: 55 additions & 11 deletions Bitkit/Views/Wallets/Send/SendConfirmationView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1356,9 +1356,9 @@ struct SendConfirmationView: View {
invoiceAmountSats: UInt64,
reviewedAmountSats: UInt64,
request: PaykitPaymentRequest?,
authorize: (PaykitPaymentRequest) async throws -> Void,
onAuthorizationFailure: (Error) async -> Void,
send: () async throws -> Result
authorize: @escaping (PaykitPaymentRequest) async throws -> Void,
onAuthorizationFailure: @escaping (Error) async -> Void,
send: (_ recheckBeforeSubmission: @escaping () async throws -> Void) async throws -> Result
) async throws -> Result {
do {
guard invoiceAmountSats == 0 || invoiceAmountSats == reviewedAmountSats else {
Expand All @@ -1371,7 +1371,22 @@ struct SendConfirmationView: View {
await onAuthorizationFailure(error)
throw error
}
return try await send()
// The send runs this again after its last await before submission, so a contact blocked meanwhile isn't paid.
do {
return try await send {
guard let request else { return }
do {
try await authorize(request)
} catch {
throw SubmissionRecheckRefusal(error: error)
}
}
} catch let refusal as SubmissionRecheckRefusal {
// Ended as a refusal only when the refusal comes back: a retry of a send still in doubt comes back pending,
// and keeps its proof.
await onAuthorizationFailure(refusal.error)
throw refusal.error
}
}

static func sendOnchainPayment<Result>(
Expand All @@ -1384,14 +1399,21 @@ struct SendConfirmationView: View {
) async throws -> Result {
try await send {
guard let request else { return }
try await prepareBroadcast(request)
do {
try await authorize(request)
} catch {
try await onAuthorizationFailure(error)
throw error
// A refusal fails the started proof before the send's guard is cleared, so a kill between the two can't
// leave a started proof without its guard.
func authorizeOrRollBack() async throws {
do {
try await authorize(request)
} catch {
try await onAuthorizationFailure(error)
throw error
}
}
try await prepareBroadcast(request)
try await authorizeOrRollBack()
await onAuthorized(request)
// `onAuthorized` awaits, so the request is authorized again after it, right before the broadcast.
try await authorizeOrRollBack()
}
}

Expand Down Expand Up @@ -2079,9 +2101,11 @@ struct SendConfirmationView: View {
request: incomingPaymentRequest,
authorize: { try await paykitPaymentRequestManager.ensurePaymentAllowed($0) },
onAuthorizationFailure: { _ in
// A refusal at the recheck before submission sent nothing, so it ends as a refusal up front does.
privatePaymentListOutcome = .definitePreBroadcastFailure
await PaykitPaymentProofService.shared.failLightningPayment(paymentHash: paymentHash)
}
) {
) { recheckBeforeSubmission in
do {
// After the allowance check above, so a refused request moves nothing.
try await MoveToSparkManager.shared.updateSpendingBalanceIfNeeded(
Expand All @@ -2098,6 +2122,7 @@ struct SendConfirmationView: View {
bolt11: invoice.bolt11,
sats: paymentSats,
paymentDeadline: incomingPaymentRequest?.submissionDeadline(quoteId: app.paykitPaymentTerms?.quoteId),
recheckBeforeSubmission: recheckBeforeSubmission,
afterListening: { _ in lightningPaymentSubmitted = true },
onTimeout: { timedOutHash in
app.addPendingPaymentHash(timedOutHash, contactPaymentContext: contactPaymentContext)
Expand All @@ -2118,6 +2143,9 @@ struct SendConfirmationView: View {
} catch is CancellationError {
throw CancellationError()
} catch {
if error is SubmissionRecheckRefusal {
throw error
}
if incomingPaymentRequest != nil, !lightningPaymentSubmitted {
let proofFailureWasDefinite = await PaykitPaymentProofService.shared.failLightningPayment(
paymentHash: paymentHash,
Expand Down Expand Up @@ -2170,9 +2198,19 @@ struct SendConfirmationView: View {
authorize: { try await paykitPaymentRequestManager.ensurePaymentAllowed($0) },
onAuthorizationFailure: { _ in
guard let incomingPaymentRequest else { return }
// A refusal after the manual allowance is marked sending ends it as failed before the proof
// rolls back, so a kill in between can't leave it sending with nothing sent.
// A failed outcome that isn't recorded keeps the proof, so the allowance settles from it later.
if onchainPaymentStarted, let manualAllowanceAttemptId {
guard await PaykitAllowanceExecutor.shared.finishManualPayment(attemptId: manualAllowanceAttemptId, outcome: .failed)
else { throw OnchainSendAttemptError.preDispatchCleanupFailed }
}
guard await PaykitPaymentProofService.shared.failOnchainPayment(
incomingPaymentRequest, paymentIdentity: originalPaymentIdentity
) else { throw OnchainSendAttemptError.preDispatchCleanupFailed }
// Rolled back, so the send ends as one that never started rather than as uncertain.
onchainPaymentStarted = false
privatePaymentListOutcome = .definitePreBroadcastFailure
},
onAuthorized: { _ in
onchainPaymentStarted = true
Expand Down Expand Up @@ -3398,3 +3436,9 @@ struct SendUpdateFeeSection: View {
.environment(HwWalletManager())
.preferredColorScheme(.dark)
}

/// A payment request refused by the recheck right before submission. It reaches the send's caller only when nothing of the
/// payment is in doubt.
struct SubmissionRecheckRefusal: Error {
let error: Error
}
Loading
Loading