From 3830e514915bb23c2fc7f44e36301f2e87062da3 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Thu, 26 Nov 2026 13:07:01 +0100 Subject: [PATCH 1/7] fix: recheck paykit request authorization at submission A payment request's Lightning send, manual or by an allowance, checks its authorization again after its last await before submission: on Spark right before spends.run, on the node right before its queue. Refused there, nothing is sent and it ends like a refusal up front. Verified: PaykitPaymentRequestServiceTests, ChannelFreeRailTests, PaykitPaymentProofServiceTests (new tests fail with the recheck off), unit test selection on the simulator, swiftformat --lint --- Bitkit/Managers/SparkManager.swift | 9 ++-- Bitkit/Services/LightningService.swift | 16 ++++-- Bitkit/Services/PaykitAllowanceExecutor.swift | 2 + .../Services/PaykitPaymentProofService.swift | 2 + Bitkit/ViewModels/WalletViewModel.swift | 2 + .../Views/Wallets/Send/LnurlPayConfirm.swift | 19 ++++--- .../Wallets/Send/SendConfirmationView.swift | 27 ++++++++-- BitkitTests/ChannelFreeRailTests.swift | 31 +++++++++++- .../PaykitPaymentProofServiceTests.swift | 1 + .../PaykitPaymentRequestServiceTests.swift | 50 +++++++++++++++++-- BitkitTests/SendConfirmationViewTests.swift | 2 +- 11 files changed, 137 insertions(+), 24 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 519efb493..cd8963bb0 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -664,13 +664,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 @@ -698,6 +699,8 @@ final class SparkManager: ChannelFreeLightningRail { } // The fee limit is checked on the quote that is sent, not only on the earlier estimate. try Self.checkSendFee(feeSats, maxFeeSats: maxFeeSats) + // After the quote and balance 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 = try await spends.run { // A deadline that passed while the quote was prepared stops the payment here, before anything leaves. diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 835c5c3ae..1835b2f85 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -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] @@ -1229,6 +1235,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) @@ -1281,6 +1288,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() do { @@ -1351,6 +1359,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() do { return try await Self.submitPayment(beforeSubmission: { [weak self] in try beforeSubmission() diff --git a/Bitkit/Services/PaykitAllowanceExecutor.swift b/Bitkit/Services/PaykitAllowanceExecutor.swift index 0a395312c..31faf6174 100644 --- a/Bitkit/Services/PaykitAllowanceExecutor.swift +++ b/Bitkit/Services/PaykitAllowanceExecutor.swift @@ -418,6 +418,8 @@ 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. + recheckBeforeSubmission: { try await ensurePaymentAllowed(request) }, beforeSubmission: { try PaykitPaymentRequest.checkPaymentDeadline(request.paymentDeadline) } ) } diff --git a/Bitkit/Services/PaykitPaymentProofService.swift b/Bitkit/Services/PaykitPaymentProofService.swift index 06db47a1f..37fbd965f 100644 --- a/Bitkit/Services/PaykitPaymentProofService.swift +++ b/Bitkit/Services/PaykitPaymentProofService.swift @@ -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 { diff --git a/Bitkit/ViewModels/WalletViewModel.swift b/Bitkit/ViewModels/WalletViewModel.swift index d15b8b6c4..f2c439fa7 100644 --- a/Bitkit/ViewModels/WalletViewModel.swift +++ b/Bitkit/ViewModels/WalletViewModel.swift @@ -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) diff --git a/Bitkit/Views/Wallets/Send/LnurlPayConfirm.swift b/Bitkit/Views/Wallets/Send/LnurlPayConfirm.swift index b1c3fe40d..21145345b 100644 --- a/Bitkit/Views/Wallets/Send/LnurlPayConfirm.swift +++ b/Bitkit/Views/Wallets/Send/LnurlPayConfirm.swift @@ -36,11 +36,12 @@ struct LnurlPayConfirm: View { static func sendLightningPayment( 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 { + let checkAuthorization: () async throws -> Void = { + guard let request else { return } do { try await authorize(request) } catch { @@ -48,7 +49,9 @@ struct LnurlPayConfirm: View { throw error } } - return try await send() + try await checkAuthorization() + // The send runs it again after its last await before submission, so a contact blocked meanwhile isn't paid. + return try await send(checkAuthorization) } private var shouldAutomaticallyPay: Bool { @@ -409,9 +412,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( @@ -428,6 +434,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) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 4cf7dc3f7..1eab0f752 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -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 { @@ -1371,7 +1371,16 @@ 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. + return try await send { + guard let request else { return } + do { + try await authorize(request) + } catch { + await onAuthorizationFailure(error) + throw error + } + } } static func sendOnchainPayment( @@ -1997,6 +2006,7 @@ struct SendConfirmationView: View { var preparedPaymentProof: (endpointIdentifier: String, kind: PaykitPaymentProofKind, appId: String)? var onchainPaymentStarted = false var lightningPaymentSubmitted = false + var lightningAuthorizationRefused = false var originalPaymentIdentity: String? var privatePaymentListOutcome = PrivatePaymentListSendOutcome.definitePreBroadcastFailure var manualAllowanceAttemptId: String? @@ -2079,9 +2089,12 @@ 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. + lightningAuthorizationRefused = true + 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( @@ -2098,6 +2111,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) @@ -2118,6 +2132,9 @@ struct SendConfirmationView: View { } catch is CancellationError { throw CancellationError() } catch { + if lightningAuthorizationRefused { + throw error + } if incomingPaymentRequest != nil, !lightningPaymentSubmitted { let proofFailureWasDefinite = await PaykitPaymentProofService.shared.failLightningPayment( paymentHash: paymentHash, diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 4c3385ab0..180680764 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1119,6 +1119,26 @@ extension ChannelFreeRailTests { XCTAssertEqual(rail.sends, 1, "A send stopped before submission must not hold the invoice") } + func testASendRefusedAtTheRecheckBeforeSubmissionLeavesNoHold() async { + rail.balanceSats = 100_000 + var submissionChecks = 0 + do { + _ = try await Bitkit.LightningService.shared.send( + bolt11: Self.invoice, + recheckBeforeSubmission: { throw PaykitPaymentRequestError.requestUnavailable }, + beforeSubmission: { submissionChecks += 1 } + ) + XCTFail("Expected the recheck to stop the payment") + } catch { + XCTAssertEqual(error as? PaykitPaymentRequestError, .requestUnavailable) + } + XCTAssertEqual(rail.sends, 0) + XCTAssertEqual(submissionChecks, 0) + + _ = try? await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + XCTAssertEqual(rail.sends, 1, "A send refused at the recheck must not hold the invoice") + } + func testSparkHistoryReadsAsUnavailableWhileSparkIsDisconnected() async { Bitkit.LightningService.shared.channelFreeRail = nil @@ -2244,7 +2264,7 @@ extension ChannelFreeRailTests { struct Expired: Error {} do { - _ = try await Bitkit.LightningService.shared.send(bolt11: "lnbcrt1rail", sats: 100) { throw Expired() } + _ = try await Bitkit.LightningService.shared.send(bolt11: "lnbcrt1rail", sats: 100, beforeSubmission: { throw Expired() }) XCTFail("Expected the submission check to stop the payment") } catch { XCTAssertTrue(error is Expired) @@ -2348,11 +2368,18 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { "lnbcrt1fake" } - func send(bolt11: String, sats: UInt64?, maxFeeSats: UInt64?, beforeSubmission: @escaping () throws -> Void) async throws -> PaymentHash { + func send( + bolt11: String, + sats: UInt64?, + maxFeeSats: UInt64?, + recheckBeforeSubmission: @escaping () async throws -> Void, + beforeSubmission: @escaping () throws -> Void + ) async throws -> PaymentHash { onSend?() if let refusal { throw refusal } + try await recheckBeforeSubmission() beforeSubmit?() try beforeSubmission() if let refusalAfterSubmission { diff --git a/BitkitTests/PaykitPaymentProofServiceTests.swift b/BitkitTests/PaykitPaymentProofServiceTests.swift index 5552f93fa..17557da96 100644 --- a/BitkitTests/PaykitPaymentProofServiceTests.swift +++ b/BitkitTests/PaykitPaymentProofServiceTests.swift @@ -1772,6 +1772,7 @@ final class PaykitPaymentProofServiceTests: XCTestCase { let errors: [Error] = [ PaykitPaymentRequestError.requestExpired, Bitkit.AppError(error: PaykitPaymentRequestError.requestExpired), + PaykitPaymentRequestError.requestUnavailable, Bitkit.CustomServiceError.nodeNotSetup, Bitkit.AppError(serviceError: .nodeNotStarted), NodeError.NotRunning(message: "stopped"), diff --git a/BitkitTests/PaykitPaymentRequestServiceTests.swift b/BitkitTests/PaykitPaymentRequestServiceTests.swift index 8ebeff643..7f85bbfe6 100644 --- a/BitkitTests/PaykitPaymentRequestServiceTests.swift +++ b/BitkitTests/PaykitPaymentRequestServiceTests.swift @@ -2187,7 +2187,7 @@ final class PaykitPaymentRequestServiceTests: XCTestCase { request: request, authorize: { try await manager.ensurePaymentAllowed($0) }, onAuthorizationFailure: { _ in authorizationFailureCalls += 1 } - ) { + ) { _ in lightningSendCalls += 1 } XCTFail("Expected the Lightning send to be rejected") @@ -2199,7 +2199,7 @@ final class PaykitPaymentRequestServiceTests: XCTestCase { request: request, authorize: { try await manager.ensurePaymentAllowed($0) }, onAuthorizationFailure: { _ in authorizationFailureCalls += 1 } - ) { + ) { _ in lnurlSendCalls += 1 } XCTFail("Expected the LNURL send to be rejected") @@ -2232,6 +2232,48 @@ final class PaykitPaymentRequestServiceTests: XCTestCase { XCTAssertFalse(manager.isApprovedForPayment(request)) } + func testLightningSendRechecksAuthorizationBeforeSubmissionAfterItsAwaits() async throws { + for route in ["lightning", "lnurl"] { + let record = try paymentRequestRecord(counterparty: "pubky3rsduhcxpw74snwyct86m38c63j3pq8x4ycqikxg64roik8yw5xy") + let sdk = PaymentRequestSdkMock(records: [record]) + let manager = paymentRequestManager(sdk: sdk) + await manager.refresh() + let request = try XCTUnwrap(manager.pendingRequests.first) + try await manager.prepareForPayment(request) + var sent = false + var authorizationFailureCalls = 0 + let authorize: (PaykitPaymentRequest) async throws -> Void = { try await manager.ensurePaymentAllowed($0) } + let onFailure: (Error) async -> Void = { _ in authorizationFailureCalls += 1 } + // Allowed up front, then the contact is blocked while the send awaits, as during a spending balance update. + let send: (@escaping () async throws -> Void) async throws -> Void = { recheckBeforeSubmission in + await sdk.configureRecipients( + peers: [self.linkedPeer(counterparty: record.counterparty, state: .blocked)], + requestCapabilitiesByPublicKey: [:] + ) + try await recheckBeforeSubmission() + sent = true + } + do { + if route == "lightning" { + try await SendConfirmationView.sendLightningPayment( + invoiceAmountSats: 1000, reviewedAmountSats: 1000, + request: request, authorize: authorize, onAuthorizationFailure: onFailure, send: send + ) + } else { + try await LnurlPayConfirm.sendLightningPayment( + request: request, authorize: authorize, onAuthorizationFailure: onFailure, send: send + ) + } + XCTFail("Expected the \(route) send to be refused before submission") + } catch { + XCTAssertEqual(error as? PaykitPaymentRequestError, .requestUnavailable, route) + } + XCTAssertFalse(sent, route) + XCTAssertEqual(authorizationFailureCalls, 1, route) + XCTAssertFalse(manager.isApprovedForPayment(request), route) + } + } + func testRefreshMapsSupportedOneTimeBitcoinRequest() async throws { let now = Date(timeIntervalSince1970: 1_800_000_000) let currentOnchain = PublicPaykitService.MethodId.onchainMethodId(network: Env.network, scriptType: .p2wpkh) @@ -2495,11 +2537,11 @@ final class PaykitPaymentRequestServiceTests: XCTestCase { try await SendConfirmationView.sendLightningPayment( invoiceAmountSats: 1000, reviewedAmountSats: 1000, request: request, authorize: authorize, onAuthorizationFailure: onFailure - ) { sent = true } + ) { _ in sent = true } case "lnurl": try await LnurlPayConfirm.sendLightningPayment( request: request, authorize: authorize, onAuthorizationFailure: onFailure - ) { sent = true } + ) { _ in sent = true } default: try await SendConfirmationView.sendOnchainPayment( request: request, prepareBroadcast: { _ in }, authorize: authorize, diff --git a/BitkitTests/SendConfirmationViewTests.swift b/BitkitTests/SendConfirmationViewTests.swift index 3972109c4..6d0449440 100644 --- a/BitkitTests/SendConfirmationViewTests.swift +++ b/BitkitTests/SendConfirmationViewTests.swift @@ -78,7 +78,7 @@ final class SendConfirmationViewTests: XCTestCase { request: nil, authorize: { _ in }, onAuthorizationFailure: { _ in } - ) { sent = true } + ) { _ in sent = true } XCTAssertTrue(expectedSend) } catch { XCTAssertFalse(expectedSend) From 9a22873e8d09735630fe8cb521ecd61c2c1d5b8d Mon Sep 17 00:00:00 2001 From: ovitrif Date: Thu, 26 Nov 2026 13:18:56 +0100 Subject: [PATCH 2/7] fix: end a failed allowance recheck as unsent Verified: PaykitPaymentRequestServiceTests, SendConfirmationViewTests, ChannelFreeRailTests, PaykitPaymentProofServiceTests, PaykitAllowanceExecutorTests; swiftformat --lint --- Bitkit/Services/PaykitAllowanceExecutor.swift | 11 ++++++++++- changelog.d/next/1455.fixed.md | 1 + 2 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 changelog.d/next/1455.fixed.md diff --git a/Bitkit/Services/PaykitAllowanceExecutor.swift b/Bitkit/Services/PaykitAllowanceExecutor.swift index 31faf6174..8d056b562 100644 --- a/Bitkit/Services/PaykitAllowanceExecutor.swift +++ b/Bitkit/Services/PaykitAllowanceExecutor.swift @@ -419,7 +419,16 @@ struct PaykitAllowanceLivePayer: PaykitAllowancePaying { 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. - recheckBeforeSubmission: { try await ensurePaymentAllowed(request) }, + // Any failure here sent nothing, so it ends as a refusal the proof service treats as unsent. + recheckBeforeSubmission: { + do { + try await ensurePaymentAllowed(request) + } catch PaykitPaymentRequestError.requestExpired { + throw PaykitPaymentRequestError.requestExpired + } catch { + throw PaykitPaymentRequestError.requestUnavailable + } + }, beforeSubmission: { try PaykitPaymentRequest.checkPaymentDeadline(request.paymentDeadline) } ) } diff --git a/changelog.d/next/1455.fixed.md b/changelog.d/next/1455.fixed.md new file mode 100644 index 000000000..29517b895 --- /dev/null +++ b/changelog.d/next/1455.fixed.md @@ -0,0 +1 @@ +Payment requests paid over Lightning, by hand or through an allowance, now stop if the contact is blocked while the payment is being prepared. From 8d42b2725643429686894ec5eb3d7547a2ef9465 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Thu, 26 Nov 2026 13:56:37 +0100 Subject: [PATCH 3/7] test: cover the allowance recheck refusal mapping Verified: PaykitAllowanceExecutorTests, ChannelFreeRailTests, PaykitPaymentProofServiceTests, PaykitPaymentRequestServiceTests, SendConfirmationViewTests; swiftformat --lint --- Bitkit/Services/PaykitAllowanceExecutor.swift | 21 +++++++++++-------- .../PaykitAllowanceExecutorTests.swift | 19 +++++++++++++++++ 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/Bitkit/Services/PaykitAllowanceExecutor.swift b/Bitkit/Services/PaykitAllowanceExecutor.swift index 8d056b562..4c357e047 100644 --- a/Bitkit/Services/PaykitAllowanceExecutor.swift +++ b/Bitkit/Services/PaykitAllowanceExecutor.swift @@ -420,19 +420,22 @@ struct PaykitAllowanceLivePayer: PaykitAllowancePaying { 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: { - do { - try await ensurePaymentAllowed(request) - } catch PaykitPaymentRequestError.requestExpired { - throw PaykitPaymentRequestError.requestExpired - } catch { - throw PaykitPaymentRequestError.requestUnavailable - } - }, + 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) } diff --git a/BitkitTests/PaykitAllowanceExecutorTests.swift b/BitkitTests/PaykitAllowanceExecutorTests.swift index 489bf662a..f3ba3d82f 100644 --- a/BitkitTests/PaykitAllowanceExecutorTests.swift +++ b/BitkitTests/PaykitAllowanceExecutorTests.swift @@ -25,6 +25,25 @@ final class PaykitAllowanceExecutorTests: XCTestCase { // MARK: Admission + func testAFailedRecheckBeforeSubmissionEndsAsARefusalTheProofTreatsAsUnsent() async throws { + struct StorageFailure: Error {} + let cases: [(Error, PaykitPaymentRequestError)] = [ + (PaykitPaymentRequestError.requestExpired, .requestExpired), + (PaykitPaymentRequestError.requestUnavailable, .requestUnavailable), + (StorageFailure(), .requestUnavailable), + (CancellationError(), .requestUnavailable), + ] + for (thrown, expected) in cases { + do { + try await PaykitAllowanceLivePayer.recheckBeforeSubmission { throw thrown } + XCTFail("expected \(expected)") + } catch { + XCTAssertEqual(error as? PaykitPaymentRequestError, expected) + } + } + try await PaykitAllowanceLivePayer.recheckBeforeSubmission {} + } + func testUncoveredRequestNeverReachesTheSdk() async throws { let harness = AllowanceHarness() let request = try Fixtures.paymentRequest() From 9f4bd279b9d53605223f377a1c9fe30d3c18095c Mon Sep 17 00:00:00 2001 From: ovitrif Date: Thu, 26 Nov 2026 15:32:19 +0100 Subject: [PATCH 4/7] fix: recheck an on-chain request's authorization before sending An on-chain payment request checked its authorization once, then awaited more before the send. The node send now checks it again after its allowance attempt is marked sending, right before the broadcast, and the Spark withdrawal after the same mark, right before Spark sends. A refusal there sends nothing and releases the request. Verified: PaykitRouteTests, PaykitPaymentRequestServiceTests, PaykitPaymentProofServiceTests, SendConfirmationViewTests, PaykitAllowanceExecutorTests, ChannelFreeRailTests; swiftformat --lint --- Bitkit/Services/PaykitRouteService.swift | 2 + .../Wallets/Send/SendConfirmationView.swift | 24 +++-- .../PaykitPaymentProofServiceTests.swift | 102 ++++++++++-------- .../PaykitPaymentRequestServiceTests.swift | 36 +++++++ BitkitTests/PaykitRouteTests.swift | 22 +++- changelog.d/next/1455.fixed.md | 2 +- 6 files changed, 131 insertions(+), 57 deletions(-) diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift index 9cefeaf61..2e4b60919 100644 --- a/Bitkit/Services/PaykitRouteService.swift +++ b/Bitkit/Services/PaykitRouteService.swift @@ -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 { diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 1eab0f752..a16793fbb 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -1393,14 +1393,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() } } @@ -2187,6 +2194,11 @@ 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. + if onchainPaymentStarted, let manualAllowanceAttemptId { + await PaykitAllowanceExecutor.shared.finishManualPayment(attemptId: manualAllowanceAttemptId, outcome: .failed) + } guard await PaykitPaymentProofService.shared.failOnchainPayment( incomingPaymentRequest, paymentIdentity: originalPaymentIdentity ) else { throw OnchainSendAttemptError.preDispatchCleanupFailed } diff --git a/BitkitTests/PaykitPaymentProofServiceTests.swift b/BitkitTests/PaykitPaymentProofServiceTests.swift index 17557da96..afda33cd1 100644 --- a/BitkitTests/PaykitPaymentProofServiceTests.swift +++ b/BitkitTests/PaykitPaymentProofServiceTests.swift @@ -3313,54 +3313,62 @@ final class PaykitPaymentProofServiceTests: XCTestCase { } func testAuthorizationRollbackFailureKeepsMatchingAttemptWithoutBroadcast() async throws { - let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue - let record = try paymentRequestRecord(endpoints: [endpoint]) - let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) - let store = PaymentProofMemoryStore() - let attemptsStore = MemoryAttemptStore() - let attempts = OnchainSendAttemptService(store: attemptsStore) - let sender = PreparedAttemptNodeMock() - sender.amount = request.amount.atomic - let service = paymentProofService( - sdk: PaymentProofSdkMock(identity: identity, records: [record]), store: store, attemptService: attempts - ) - try await service.prepare(request: request, paymentAppId: "bitkit", paymentEndpointIdentifier: endpoint, kind: .onchain) - do { - _ = try await SendConfirmationView.sendOnchainPayment( - request: request, - prepareBroadcast: { request in - try await service.markOnchainPaymentStarted(request, address: self.onchainAddress, paymentIdentity: self.identity) - }, - authorize: { _ in - await store.failNextSave() - throw CancellationError() - }, - onAuthorizationFailure: { _ in - guard await service.failOnchainPayment(request, paymentIdentity: self.identity) else { - throw OnchainSendAttemptError.preDispatchCleanupFailed - } - }, - onAuthorized: { _ in }, - send: { beforeBroadcast in - try await attempts.send( - using: sender, address: self.onchainAddress, amountSats: request.amount.atomic, - satsPerVbyte: 2, utxosToSpend: nil, isMaxAmount: false, - requestId: request.id, paymentIdentity: self.identity, beforeBroadcastAttempt: beforeBroadcast - ) - } + // Refused up front, or at the recheck right before the broadcast, after the allowance attempt is marked sending. + for refusedAtRecheck in [false, true] { + var authorizations = 0 + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let store = PaymentProofMemoryStore() + let attemptsStore = MemoryAttemptStore() + let attempts = OnchainSendAttemptService(store: attemptsStore) + let sender = PreparedAttemptNodeMock() + sender.amount = request.amount.atomic + let service = paymentProofService( + sdk: PaymentProofSdkMock(identity: identity, records: [record]), store: store, attemptService: attempts ) - XCTFail("Cancelled authorization completed") - } catch {} - let proofs = await store.snapshot() - XCTAssertEqual(proofs.first?.paymentStarted, true) - XCTAssertNil(proofs.first?.paymentIdentifier) - XCTAssertEqual(attemptsStore.snapshot().first?.requestId, request.id, - "Failed proof rollback must keep its matching recovery guard") - XCTAssertEqual(sender.broadcasts, 0) - let rolledBack = await service.failOnchainPayment(request, paymentIdentity: identity) - XCTAssertTrue(rolledBack, "A later successful cleanup must remove the retained proof") - let remainingProofs = await store.snapshot() - XCTAssertTrue(remainingProofs.isEmpty) + try await service.prepare(request: request, paymentAppId: "bitkit", paymentEndpointIdentifier: endpoint, kind: .onchain) + do { + _ = try await SendConfirmationView.sendOnchainPayment( + request: request, + prepareBroadcast: { request in + try await service.markOnchainPaymentStarted(request, address: self.onchainAddress, paymentIdentity: self.identity) + }, + authorize: { _ in + authorizations += 1 + if refusedAtRecheck, authorizations == 1 { + return + } + await store.failNextSave() + throw CancellationError() + }, + onAuthorizationFailure: { _ in + guard await service.failOnchainPayment(request, paymentIdentity: self.identity) else { + throw OnchainSendAttemptError.preDispatchCleanupFailed + } + }, + onAuthorized: { _ in }, + send: { beforeBroadcast in + try await attempts.send( + using: sender, address: self.onchainAddress, amountSats: request.amount.atomic, + satsPerVbyte: 2, utxosToSpend: nil, isMaxAmount: false, + requestId: request.id, paymentIdentity: self.identity, beforeBroadcastAttempt: beforeBroadcast + ) + } + ) + XCTFail("Cancelled authorization completed") + } catch {} + let proofs = await store.snapshot() + XCTAssertEqual(proofs.first?.paymentStarted, true) + XCTAssertNil(proofs.first?.paymentIdentifier) + XCTAssertEqual(attemptsStore.snapshot().first?.requestId, request.id, + "Failed proof rollback must keep its matching recovery guard") + XCTAssertEqual(sender.broadcasts, 0, "\(refusedAtRecheck)") + let rolledBack = await service.failOnchainPayment(request, paymentIdentity: identity) + XCTAssertTrue(rolledBack, "A later successful cleanup must remove the retained proof") + let remainingProofs = await store.snapshot() + XCTAssertTrue(remainingProofs.isEmpty) + } } func testDefiniteOnchainFailureClearsStartedProof() async throws { diff --git a/BitkitTests/PaykitPaymentRequestServiceTests.swift b/BitkitTests/PaykitPaymentRequestServiceTests.swift index 7f85bbfe6..1a837d623 100644 --- a/BitkitTests/PaykitPaymentRequestServiceTests.swift +++ b/BitkitTests/PaykitPaymentRequestServiceTests.swift @@ -2274,6 +2274,42 @@ final class PaykitPaymentRequestServiceTests: XCTestCase { } } + func testOnchainSendRechecksAuthorizationAfterItsAttemptIsMarkedSending() async throws { + let record = try paymentRequestRecord(counterparty: "pubky3rsduhcxpw74snwyct86m38c63j3pq8x4ycqikxg64roik8yw5xy") + let sdk = PaymentRequestSdkMock(records: [record]) + let manager = paymentRequestManager(sdk: sdk) + await manager.refresh() + let request = try XCTUnwrap(manager.pendingRequests.first) + try await manager.prepareForPayment(request) + var sent = false + var authorizationFailureCalls = 0 + do { + try await SendConfirmationView.sendOnchainPayment( + request: request, + prepareBroadcast: { _ in }, + authorize: { try await manager.ensurePaymentAllowed($0) }, + onAuthorizationFailure: { _ in authorizationFailureCalls += 1 }, + onAuthorized: { _ in + // Allowed up front, then the contact is blocked while the allowance attempt is marked sending. + await sdk.configureRecipients( + peers: [self.linkedPeer(counterparty: record.counterparty, state: .blocked)], + requestCapabilitiesByPublicKey: [:] + ) + }, + send: { beforeBroadcastAttempt in + try await beforeBroadcastAttempt() + sent = true + } + ) + XCTFail("Expected the on-chain send to be refused before its broadcast") + } catch { + XCTAssertEqual(error as? PaykitPaymentRequestError, .requestUnavailable) + } + XCTAssertFalse(sent) + XCTAssertEqual(authorizationFailureCalls, 1, "The started proof fails before the send's guard is cleared") + XCTAssertFalse(manager.isApprovedForPayment(request)) + } + func testRefreshMapsSupportedOneTimeBitcoinRequest() async throws { let now = Date(timeIntervalSince1970: 1_800_000_000) let currentOnchain = PublicPaykitService.MethodId.onchainMethodId(network: Env.network, scriptType: .p2wpkh) diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift index beb228003..c2acd1d0e 100644 --- a/BitkitTests/PaykitRouteTests.swift +++ b/BitkitTests/PaykitRouteTests.swift @@ -355,7 +355,7 @@ final class PaykitRouteTests: XCTestCase { let txid = await pay { beforeSend in try await beforeSend(); return "txid" } XCTAssertEqual(txid, "txid") - XCTAssertEqual(events, ["begin", "authorize", "sending attempt", "finish attempt succeeded txid"]) + XCTAssertEqual(events, ["begin", "authorize", "sending attempt", "authorize", "finish attempt succeeded txid"]) events = [] _ = await pay(authorize: { throw Refused() }) { beforeSend in @@ -364,6 +364,22 @@ final class PaykitRouteTests: XCTestCase { } XCTAssertEqual(events, ["begin", "authorize", "finish attempt failed -"], "A send Spark refused paid nothing") + events = [] + var authorizations = 0 + // Allowed up front, then the contact is blocked while the attempt is marked sending. + _ = await pay(authorize: { + authorizations += 1 + guard authorizations == 1 else { throw Refused() } + }) { beforeSend in + do { try await beforeSend() } catch { throw SparkWithdrawalNotSent(underlying: error) } + return "txid" + } + XCTAssertEqual( + events, + ["begin", "authorize", "sending attempt", "authorize", "finish attempt failed -"], + "A request refused once its attempt is marked sending paid nothing" + ) + events = [] _ = await pay { beforeSend in try await beforeSend() @@ -371,7 +387,7 @@ final class PaykitRouteTests: XCTestCase { } XCTAssertEqual( events, - ["begin", "authorize", "sending attempt", "finish attempt failed -"], + ["begin", "authorize", "sending attempt", "authorize", "finish attempt failed -"], "A withdrawal Spark returned as failed paid nothing either" ) @@ -379,7 +395,7 @@ final class PaykitRouteTests: XCTestCase { _ = await pay { beforeSend in try await beforeSend(); throw Lost() } XCTAssertEqual( events, - ["begin", "authorize", "sending attempt", "finish attempt unknown -"], + ["begin", "authorize", "sending attempt", "authorize", "finish attempt unknown -"], "A send that may have gone out stays unknown until recovery settles it" ) } diff --git a/changelog.d/next/1455.fixed.md b/changelog.d/next/1455.fixed.md index 29517b895..b6a0ea9aa 100644 --- a/changelog.d/next/1455.fixed.md +++ b/changelog.d/next/1455.fixed.md @@ -1 +1 @@ -Payment requests paid over Lightning, by hand or through an allowance, now stop if the contact is blocked while the payment is being prepared. +Payment requests, paid by hand or through an allowance, now stop if the contact is blocked while the payment is being prepared. From 8b1e9361ab5356639319f131a7d0a2d1c01c95b6 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Thu, 26 Nov 2026 18:41:22 +0100 Subject: [PATCH 5/7] fix: keep a pending retry's proof when its recheck refuses Verified: xcodebuild test of PaykitPaymentRequestService, PaykitPaymentProofService, SendConfirmationView, PaykitAllowanceExecutor, ChannelFreeRail and SparkSendKey tests (755 pass); the new test fails on the previous head --- .../Views/Wallets/Send/LnurlPayConfirm.swift | 20 +++++++-- .../Wallets/Send/SendConfirmationView.swift | 30 ++++++++----- .../PaykitPaymentRequestServiceTests.swift | 45 +++++++++++++++++++ 3 files changed, 81 insertions(+), 14 deletions(-) diff --git a/Bitkit/Views/Wallets/Send/LnurlPayConfirm.swift b/Bitkit/Views/Wallets/Send/LnurlPayConfirm.swift index 21145345b..fdb0d1c7d 100644 --- a/Bitkit/Views/Wallets/Send/LnurlPayConfirm.swift +++ b/Bitkit/Views/Wallets/Send/LnurlPayConfirm.swift @@ -40,8 +40,7 @@ struct LnurlPayConfirm: View { onAuthorizationFailure: @escaping (Error) async -> Void, send: (_ recheckBeforeSubmission: @escaping () async throws -> Void) async throws -> Result ) async throws -> Result { - let checkAuthorization: () async throws -> Void = { - guard let request else { return } + if let request { do { try await authorize(request) } catch { @@ -49,9 +48,22 @@ struct LnurlPayConfirm: View { throw error } } - try await checkAuthorization() // The send runs it again after its last await before submission, so a contact blocked meanwhile isn't paid. - return try await send(checkAuthorization) + 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 { diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index a16793fbb..e9b2ef9a8 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -1372,14 +1372,20 @@ struct SendConfirmationView: View { throw error } // The send runs this again after its last await before submission, so a contact blocked meanwhile isn't paid. - return try await send { - guard let request else { return } - do { - try await authorize(request) - } catch { - await onAuthorizationFailure(error) - throw error + 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 } } @@ -2013,7 +2019,6 @@ struct SendConfirmationView: View { var preparedPaymentProof: (endpointIdentifier: String, kind: PaykitPaymentProofKind, appId: String)? var onchainPaymentStarted = false var lightningPaymentSubmitted = false - var lightningAuthorizationRefused = false var originalPaymentIdentity: String? var privatePaymentListOutcome = PrivatePaymentListSendOutcome.definitePreBroadcastFailure var manualAllowanceAttemptId: String? @@ -2097,7 +2102,6 @@ struct SendConfirmationView: View { 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. - lightningAuthorizationRefused = true privatePaymentListOutcome = .definitePreBroadcastFailure await PaykitPaymentProofService.shared.failLightningPayment(paymentHash: paymentHash) } @@ -2139,7 +2143,7 @@ struct SendConfirmationView: View { } catch is CancellationError { throw CancellationError() } catch { - if lightningAuthorizationRefused { + if error is SubmissionRecheckRefusal { throw error } if incomingPaymentRequest != nil, !lightningPaymentSubmitted { @@ -3427,3 +3431,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 +} diff --git a/BitkitTests/PaykitPaymentRequestServiceTests.swift b/BitkitTests/PaykitPaymentRequestServiceTests.swift index 1a837d623..ad7918e4a 100644 --- a/BitkitTests/PaykitPaymentRequestServiceTests.swift +++ b/BitkitTests/PaykitPaymentRequestServiceTests.swift @@ -2274,6 +2274,51 @@ final class PaykitPaymentRequestServiceTests: XCTestCase { } } + func testLightningRecheckRefusalOfARetryInDoubtStaysPending() async throws { + for route in ["lightning", "lnurl"] { + let record = try paymentRequestRecord(counterparty: "pubky3rsduhcxpw74snwyct86m38c63j3pq8x4ycqikxg64roik8yw5xy") + let sdk = PaymentRequestSdkMock(records: [record]) + let manager = paymentRequestManager(sdk: sdk) + await manager.refresh() + let request = try XCTUnwrap(manager.pendingRequests.first) + try await manager.prepareForPayment(request) + var authorizationFailureCalls = 0 + let authorize: (PaykitPaymentRequest) async throws -> Void = { try await manager.ensurePaymentAllowed($0) } + let onFailure: (Error) async -> Void = { _ in authorizationFailureCalls += 1 } + // Refused at the recheck, but an earlier attempt of the invoice is in doubt, so the send reports it pending. + let pending = NodeError.DuplicatePayment(message: "An earlier attempt is still pending") + let send: (@escaping () async throws -> Void) async throws -> Void = { recheckBeforeSubmission in + await sdk.configureRecipients( + peers: [self.linkedPeer(counterparty: record.counterparty, state: .blocked)], + requestCapabilitiesByPublicKey: [:] + ) + do { + try await recheckBeforeSubmission() + } catch { + throw pending + } + } + do { + if route == "lightning" { + try await SendConfirmationView.sendLightningPayment( + invoiceAmountSats: 1000, reviewedAmountSats: 1000, + request: request, authorize: authorize, onAuthorizationFailure: onFailure, send: send + ) + } else { + try await LnurlPayConfirm.sendLightningPayment( + request: request, authorize: authorize, onAuthorizationFailure: onFailure, send: send + ) + } + XCTFail("Expected the \(route) send to come back pending") + } catch { + guard case .DuplicatePayment = error as? NodeError else { + return XCTFail("Expected the pending error for \(route), got \(error)") + } + } + XCTAssertEqual(authorizationFailureCalls, 0, route) + } + } + func testOnchainSendRechecksAuthorizationAfterItsAttemptIsMarkedSending() async throws { let record = try paymentRequestRecord(counterparty: "pubky3rsduhcxpw74snwyct86m38c63j3pq8x4ycqikxg64roik8yw5xy") let sdk = PaymentRequestSdkMock(records: [record]) From 45b5a3b9298515b13540550b0a6f6e656fdad0e4 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Thu, 26 Nov 2026 18:41:22 +0100 Subject: [PATCH 6/7] fix: recheck a request before a spark leaf retry Verified: xcodebuild test of the same six test classes (755 pass), swiftformat --lint --- Bitkit/Managers/SparkManager.swift | 19 ++++++++++++++++--- BitkitTests/SparkSendKeyTests.swift | 25 +++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 39fa8652c..d468b2264 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -752,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, @@ -832,7 +836,7 @@ final class SparkManager: ChannelFreeLightningRail { /// never left. nonisolated static func sendRetryingLeafSelection( retryDelay: Duration = .seconds(2), - canRetry: () -> Bool, + canRetry: () async -> Bool, _ send: () async throws -> T ) async throws -> T { var retries = 0 @@ -849,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 { diff --git a/BitkitTests/SparkSendKeyTests.swift b/BitkitTests/SparkSendKeyTests.swift index a1c6fd1f4..92b3e1155 100644 --- a/BitkitTests/SparkSendKeyTests.swift +++ b/BitkitTests/SparkSendKeyTests.swift @@ -129,6 +129,31 @@ final class SparkSendKeyTests: XCTestCase { XCTAssertNoThrow(try Bitkit.SparkManager.checkSentPayment(.completed)) } + func testALeafRetryRechecksTheRequestBeforeItsDeadline() async { + struct Refused: Error {} + var calls: [String] = [] + let allowed = await Bitkit.SparkManager.canRetrySend( + recheckBeforeSubmission: { calls.append("recheck") }, + beforeSubmission: { calls.append("deadline") } + ) + XCTAssertTrue(allowed) + XCTAssertEqual(calls, ["recheck", "deadline"]) + + calls = [] + let refused = await Bitkit.SparkManager.canRetrySend( + recheckBeforeSubmission: { calls.append("recheck"); throw Refused() }, + beforeSubmission: { calls.append("deadline") } + ) + XCTAssertFalse(refused) + XCTAssertEqual(calls, ["recheck"]) + + let expired = await Bitkit.SparkManager.canRetrySend( + recheckBeforeSubmission: {}, + beforeSubmission: { throw Refused() } + ) + XCTAssertFalse(expired) + } + func testAnInvoiceExpiringDuringALeafRetryEndsWithTheLeafFailure() async { var sends = 0 From 7905714eced45cc0cd417f87c23d4a02c98a0104 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Thu, 26 Nov 2026 19:06:45 +0100 Subject: [PATCH 7/7] fix: end an on-chain refusal at its recheck as unsent Verified: xcodebuild test of PaykitPaymentRequestService, PaykitPaymentProofService, SendConfirmationView, PaykitAllowanceExecutor, ChannelFreeRail and SparkSendKey tests (756 pass), swiftformat --lint --- Bitkit/Views/Wallets/Send/SendConfirmationView.swift | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index e9b2ef9a8..6b63b77d9 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -2200,12 +2200,17 @@ struct SendConfirmationView: View { 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 { - await PaykitAllowanceExecutor.shared.finishManualPayment(attemptId: manualAllowanceAttemptId, outcome: .failed) + 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