diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index bfd48cbb6..d468b2264 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -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 @@ -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 { @@ -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, @@ -829,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 @@ -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 { diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 9b6158e9a..2c1bef5f3 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] @@ -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) @@ -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. @@ -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() 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..4c357e047 100644 --- a/Bitkit/Services/PaykitAllowanceExecutor.swift +++ b/Bitkit/Services/PaykitAllowanceExecutor.swift @@ -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) } 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/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/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..fdb0d1c7d 100644 --- a/Bitkit/Views/Wallets/Send/LnurlPayConfirm.swift +++ b/Bitkit/Views/Wallets/Send/LnurlPayConfirm.swift @@ -36,9 +36,9 @@ 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 { do { @@ -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 { @@ -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( @@ -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) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 4cf7dc3f7..6b63b77d9 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,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( @@ -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() } } @@ -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( @@ -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) @@ -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, @@ -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 @@ -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 +} diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 10a76cecf..bd9a2e443 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1316,6 +1316,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 @@ -2460,7 +2480,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) @@ -2572,11 +2592,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?() for _ in 0 ..< submissionChecks { try beforeSubmission() 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() diff --git a/BitkitTests/PaykitPaymentProofServiceTests.swift b/BitkitTests/PaykitPaymentProofServiceTests.swift index 5552f93fa..afda33cd1 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"), @@ -3312,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 8ebeff643..ad7918e4a 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,129 @@ 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 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]) + 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) @@ -2495,11 +2618,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/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/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) 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 diff --git a/changelog.d/next/1455.fixed.md b/changelog.d/next/1455.fixed.md new file mode 100644 index 000000000..b6a0ea9aa --- /dev/null +++ b/changelog.d/next/1455.fixed.md @@ -0,0 +1 @@ +Payment requests, paid by hand or through an allowance, now stop if the contact is blocked while the payment is being prepared.