diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 03976e123..d884b6609 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1132,6 +1132,7 @@ class LightningService: NodeLifecycleService { } } var isRefusedAtAdmission = false + var didRecordAttempt = false do { return try await rail.send( bolt11: bolt11, @@ -1149,6 +1150,7 @@ class LightningService: NodeLifecycleService { // Noted once admitted, so a refused attempt never takes the place of the one that went out. self?.noteAttempt(on: .channelFree, bolt11: bolt11) self?.recordRailAttempt(paymentHash: paymentHash, expiresAt: expiresAt) + didRecordAttempt = true // Kept until Spark settles the attempt, so no retry of the invoice starts meanwhile, also after a // relaunch. if let paymentHash { @@ -1157,8 +1159,9 @@ class LightningService: NodeLifecycleService { } ) } catch let refusal as ChannelFreeRailSendRefused { - // Nothing left the wallet, and the checks above leave no earlier live attempt under this hash. - if let paymentHash { + // Nothing left the wallet. Refused before submission, this send recorded nothing, so another send's + // attempt and hold of the invoice stay. + if let paymentHash, didRecordAttempt { endRailSendUncertainty(paymentHash: paymentHash) releaseRailAttempt(paymentHash: paymentHash, unlessInFlight: false) } @@ -1174,8 +1177,9 @@ class LightningService: NodeLifecycleService { guard let paid = try await settledRecordedRailSend(paymentHash: paymentHash, since: mark) else { throw error } return paid } catch { - // A send that failed once submitted may still go out, so its outcome waits for a later sync. - if let paymentHash { + // A send that failed once submitted may still go out, so its outcome waits for a later sync. One that + // failed before it recorded its attempt never reached Spark. + if let paymentHash, didRecordAttempt { markRailSendUncertain(paymentHash: paymentHash, since: mark) } throw error @@ -1386,8 +1390,13 @@ class LightningService: NodeLifecycleService { eventCallbackLock.withLock { AttemptMark(records: attemptRecords, railInFlight: railSendsInFlight, ldkInFlight: ldkSendsInFlight) } } - private func releaseLdkAttempt(paymentHash: String) { - eventCallbackLock.withLock { removeAttempt(paymentHash: paymentHash.lowercased(), key: Self.ldkAttemptsKey) } + /// Skipped when a node send of the invoice is in flight, or was recorded since `mark`, as that send holds it again. + private func releaseLdkAttempt(paymentHash: String, since mark: AttemptMark) { + let hash = paymentHash.lowercased() + eventCallbackLock.withLock { + guard !attemptsLive(since: mark, key: Self.ldkAttemptsKey).contains(hash) else { return } + removeAttempt(paymentHash: hash, key: Self.ldkAttemptsKey) + } } /// Callers hold `eventCallbackLock`. @@ -1450,11 +1459,11 @@ class LightningService: NodeLifecycleService { /// The node's payments, after keeping its attempts from them, with the hashes still holding Spark (`live`); nil /// while the node can't list them. @discardableResult - private func listNodePaymentsKeepingAttempts() async -> (payments: [PaymentDetails], live: Set)? { + private func listNodePaymentsKeepingAttempts() async -> (payments: [PaymentDetails], live: Set, mark: AttemptMark)? { let mark = attemptMark guard let payments = await nodePayments() else { return nil } let live = keepLdkAttempts(from: payments, since: mark) - return (payments, live) + return (payments, live, mark) } /// Keeps the hashes of the node's pending and paid outbound payments, once, so those made before hashes were kept @@ -1523,7 +1532,7 @@ class LightningService: NodeLifecycleService { guard let paymentHash else { return nil } var statuses: [PaymentStatus] = rails.contains(.channelFree) && isRailSendInFlight(paymentHash: paymentHash) ? [.pending] : [] if rails.contains(.ldk) { - if let (payments, live) = await listNodePaymentsKeepingAttempts() { + if let (payments, live, mark) = await listNodePaymentsKeepingAttempts() { let payment = payments.first { $0.direction == .outbound && $0.id.caseInsensitiveCompare(paymentHash) == .orderedSame } @@ -1535,7 +1544,7 @@ class LightningService: NodeLifecycleService { if live.contains(paymentHash.lowercased()) { statuses.append(.pending) } else { - releaseLdkAttempt(paymentHash: paymentHash) + releaseLdkAttempt(paymentHash: paymentHash, since: mark) } } } else if hasAttempt(paymentHash: paymentHash, key: Self.ldkAttemptsKey) { @@ -1563,7 +1572,8 @@ class LightningService: NodeLifecycleService { Logger.info("Held '\(paymentHash)' until Spark syncs after its unknown send", context: "LightningService") statuses.append(.pending) } else { - releaseRailAttempt(paymentHash: paymentHash) + // A retry recorded while Spark synced keeps its attempt. + releaseRailAttempt(paymentHash: paymentHash, since: mark) if !isPaidOverTheNode { try await refuseUnverifiedRestoredInvoice( paymentHash: paymentHash, bolt11: bolt11, sats: sats, @@ -1819,8 +1829,8 @@ class LightningService: NodeLifecycleService { } } - /// True unless the hash's last rail send failed after it was submitted and may still go out: no sync has reached the - /// rail since, or its invoice hasn't expired. + /// True unless the hash's last rail send failed after it was submitted and may still go out: its invoice hasn't + /// expired, or no sync has reached the rail since it did. private func railSyncedSinceUncertainSend(paymentHash: String) async -> Bool { let hash = paymentHash.lowercased() let uncertain = eventCallbackLock.withLock { @@ -1831,7 +1841,7 @@ class LightningService: NodeLifecycleService { // can still fail to resume it, so only an expired invoice shows a missing send will never go out. guard let expiresAt = uncertain.expiresAt, Int(now().timeIntervalSince1970) >= expiresAt else { return false } // During an exit Spark no longer sends but still syncs its history, which settles the send the same way. - guard let rail = channelFreeRail ?? channelFreePaymentHistory, await rail.hasSynced(after: UInt64(uncertain.startedAt)) else { + guard let rail = channelFreeRail ?? channelFreePaymentHistory, await rail.hasSynced(after: UInt64(max(uncertain.startedAt, expiresAt))) else { return false } // Its Activity row is written first, so a stop in between finds the send held and writes it again. @@ -2538,20 +2548,32 @@ extension LightningService { // A restored wallet fills its list on its first sync, so before a sync reaches Spark a missing send proves // nothing. guard await rail.hasSynced(after: nil) else { throw ChannelFreeRailUnavailable() } - // Read before the listing, so a sync that ends while it is read can't settle a send the listing predates. + // Read before the listing, so a sync that ends while it is read can't settle a send the listing predates, + // and a hold taken meanwhile reads as taken during the read. + let mark = attemptMark + let heldBefore = railSendHolds let unsettledBefore = await unsettledUncertainRailSends() let kept = unexpiredRailAttempts() - let heldBefore = railSendHolds let payments = try await rail.lightningPayments() // A send Spark lists a settled attempt of is no longer held; the others read pending until then. settleListedRailSends(payments, heldBefore: heldBefore) - let stillUnsettled = eventCallbackLock.withLock { Set(uncertainRailSendFailedAt().keys) } + let holdsAfter = eventCallbackLock.withLock { uncertainRailSendFailedAt() } + let stillUnsettled = Set(holdsAfter.keys) // A hold that ended during the read without its result in the list (a success Spark lists later) stays // pending, so it never reads as an earlier attempt's failure. let unsettled = unsettledBefore.filter { stillUnsettled.contains($0.paymentHash) || !Self.listsResult(payments, paymentHash: $0.paymentHash, startedAt: heldBefore[$0.paymentHash]) } + // A retry in flight during the read, or that took a hold or recorded its attempt meanwhile, is one this list + // predates, so it reads pending until a later list shows its result, also when it already ended. + let unsettledHashes = Set(unsettled.map { $0.paymentHash.lowercased() }) + let recordedDuringRead = eventCallbackLock.withLock { attemptsLive(since: mark, key: Self.railAttemptsKey) } + let paidHashes = Set(payments.filter { $0.direction == .outbound && $0.status == .succeeded }.map { $0.paymentHash.lowercased() }) + let heldDuringRead = Set(holdsAfter.filter { heldBefore[$0.key] != $0.value }.keys) + .union(recordedDuringRead.subtracting(paidHashes)) + .subtracting(unsettledHashes).sorted() + .map { ChannelFreeRailPayment(paymentHash: $0, direction: .outbound, status: .pending, preimage: nil) } if let since = sparkHistoryUnseededSince, await rail.hasSynced(after: UInt64(clamping: since)) { // Kept, so after a relaunch the sends Spark listed hold the node until Spark syncs again. let seeded = payments.filter { $0.direction == .outbound && $0.status != .failed }.map { $0.paymentHash.lowercased() } @@ -2562,10 +2584,10 @@ extension LightningService { } clearSparkHistoryUnseeded() } - let listed = Set((payments + unsettled).filter { $0.direction == .outbound }.map { $0.paymentHash.lowercased() }) + let listed = Set((payments + unsettled + heldDuringRead).filter { $0.direction == .outbound }.map { $0.paymentHash.lowercased() }) let unlisted = kept.subtracting(listed).sorted() .map { ChannelFreeRailPayment(paymentHash: $0, direction: .outbound, status: .pending, preimage: nil) } - return payments + unsettled + unlisted + return payments + unsettled + heldDuringRead + unlisted } if await channelFreeRailSupported() { throw ChannelFreeRailUnavailable() diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 8496709b4..e4b4c9106 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -862,6 +862,11 @@ extension ChannelFreeRailTests { rail.balanceSats = 0 await assertReachesTheNode() + + // The listed failure released the hold, so a retry still reaches the node once Spark's history can't be read. + rail.listError = NSError(domain: "spark", code: 1) + + await assertReachesTheNode() } /// Keeps only what the service stores across launches: the rail's kept keys survive, everything in memory goes. @@ -1704,12 +1709,13 @@ extension ChannelFreeRailTests { defer { service.railSendExpired = previousRecord } let expiresAt = try Self.invoiceExpiresAt() service.now = { Date(timeIntervalSince1970: expiresAt) } - // Spark's last sync came before the retry, so only a lost hold lets the invoice go out again. - rail.syncedAfter = { seconds in seconds.map { $0 < UInt64(expiresAt) } ?? true } + // Spark's last sync came after the expiry but before the retry, so only a lost hold lets the invoice go out again. + rail.syncedAfter = { seconds in seconds.map { $0 <= UInt64(expiresAt) } ?? true } // While the expired send's row is written, its own failure ends it and a retry of the invoice goes to Spark. service.railSendExpired = { [self] _ in service.railSendExpired = nil service.emitChannelFreeRailEvent(.paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), paymentCreatedAt: Self.sparkNow()) + service.now = { Date(timeIntervalSince1970: expiresAt + 5) } try? await sendOverSpark() return true } @@ -1806,6 +1812,120 @@ extension ChannelFreeRailTests { XCTAssertTrue(payments.contains { $0.status == .pending }, "the retry read as A's failure") } + func testARetryHeldWhileSparksListIsReadReadsPending() async throws { + let (hash, startedAt) = try await sendARetryFiveSecondsAfterAFailedAttempt() + let service = Bitkit.LightningService.shared + // No hold before the read; a retry takes one while Spark's list, showing only A's failure, is read. + service.railAttemptsStore.set([String: Int](), forKey: Self.uncertainRailSendsKey) + rail.onList = { + service.railAttemptsStore.set([hash: Int(startedAt) + 30], forKey: Self.uncertainRailSendsKey) + } + + let payments = try await service.channelFreeRailPayments().filter { $0.paymentHash == hash } + + XCTAssertTrue(payments.contains { $0.status == .pending }, "the retry held during the read read as A's failure") + } + + func testARetryThatStartsAndEndsWhileSparksListIsReadReadsPending() async throws { + let (hash, _) = try await sendARetryFiveSecondsAfterAFailedAttempt() + let service = Bitkit.LightningService.shared + // No hold before the read; a retry records its attempt and its success ends its hold while the list, showing + // only A's failure, is read. + service.railAttemptsStore.set([String: Int](), forKey: Self.uncertainRailSendsKey) + rail.onList = { + service.recordRailAttempt(paymentHash: hash) + } + + let payments = try await service.channelFreeRailPayments().filter { $0.paymentHash == hash } + + XCTAssertTrue(payments.contains { $0.status == .pending }, "the retry read as A's failure") + } + + func testARetryInFlightWhenSparksListIsReadReadsPendingAfterItEnds() async throws { + let (hash, _) = try await sendARetryFiveSecondsAfterAFailedAttempt() + let service = Bitkit.LightningService.shared + // No hold before the read; a retry in flight when it starts ends while the list, showing only A's failure, is read. + service.railAttemptsStore.set([String: Int](), forKey: Self.uncertainRailSendsKey) + XCTAssertTrue(service.beginRailSend(paymentHash: hash)) + defer { service.endRailSend(paymentHash: hash) } + rail.onList = { + service.endRailSend(paymentHash: hash) + } + + let payments = try await service.channelFreeRailPayments().filter { $0.paymentHash == hash } + + XCTAssertTrue(payments.contains { $0.status == .pending }, "the retry read as A's failure") + } + + func testASparkSendFailingBeforeItRecordsItsAttemptTakesNoHold() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + rail.balanceSats = 100_000 + // Another send records its attempt after this one's checks; this one's own check then fails before submission. + final class Entered: @unchecked Sendable { var value = false } + let entered = Entered() + rail.onSend = { + entered.value = true + service.recordRailAttempt(paymentHash: hash) + } + + do { + _ = try await service.send(bolt11: Self.invoice, beforeSubmission: { throw NSError(domain: "request", code: 1) }) + XCTFail("Expected the send's own check to fail") + } catch { + XCTAssertEqual((error as NSError).domain, "request", "\(error)") + } + + XCTAssertTrue(entered.value, "the send never reached Spark's send call") + XCTAssertNil(service.railSendHolds[hash], "a send that never reached Spark took a hold") + } + + func testAnExpiredSendStaysHeldUntilASyncAfterItsExpiry() async throws { + let (hash, _) = try await sendARetryFiveSecondsAfterAFailedAttempt() + let service = Bitkit.LightningService.shared + let previousRecord = service.railSendExpired + defer { service.railSendExpired = previousRecord } + final class Calls: @unchecked Sendable { var count = 0 } + let calls = Calls() + service.railSendExpired = { _ in + calls.count += 1 + return true + } + let expiresAt = try Self.invoiceExpiresAt() + service.now = { Date(timeIntervalSince1970: expiresAt) } + // Spark's last sync came after the send, but before its invoice expired. + rail.syncedAfter = { ($0 ?? 0) < UInt64(expiresAt) } + + await service.endExpiredRailSendUncertainties() + + XCTAssertEqual(calls.count, 0, "a sync before the expiry settled the send") + XCTAssertNotNil(service.railSendHolds[hash]) + + rail.syncedAfter = { _ in true } + await service.endExpiredRailSendUncertainties() + + XCTAssertEqual(calls.count, 1) + XCTAssertNil(service.railSendHolds[hash]) + } + + func testASparkSendRefusedBeforeSubmissionKeepsAnotherSendsAttemptAndHold() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + rail.balanceSats = 100_000 + // Send A of the invoice went out and returned after this send's checks, then Spark refuses this one before + // submission, as A spent the balance. + rail.onSend = { + service.railAttemptsStore.set([hash], forKey: Self.railAttemptsKey) + service.railAttemptsStore.set([hash: 1000], forKey: Self.uncertainRailSendsKey) + } + rail.refusal = Bitkit.ChannelFreeRailSendRefused(reason: "insufficient balance") + + _ = try? await service.send(bolt11: Self.invoice) + + XCTAssertEqual(service.railAttemptsStore.stringArray(forKey: Self.railAttemptsKey), [hash], "A's attempt was released") + XCTAssertNotNil(service.railSendHolds[hash], "A's hold was ended") + } + func testAnExpiredRetryFailsItsOwnRowWhenSparkListsOnlyTheFailureFiveSecondsBeforeIt() async throws { let (hash, startedAt) = try await sendARetryFiveSecondsAfterAFailedAttempt() let service = Bitkit.LightningService.shared @@ -2162,6 +2282,8 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { var refusalAfterSubmission: Bitkit.ChannelFreeRailSendRefused? /// Runs while a listing is read, before it returns `payments`. var onList: (() -> Void)? + /// Runs as a send enters Spark, before `refusal`. + var onSend: (() -> Void)? /// Runs as a send is about to be submitted, before `beforeSubmission`. var beforeSubmit: (() -> Void)? /// Thrown after the send was submitted, as when the connection drops inside Spark's send. @@ -2182,6 +2304,7 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { } func send(bolt11: String, sats: UInt64?, maxFeeSats: UInt64?, beforeSubmission: @escaping () throws -> Void) async throws -> PaymentHash { + onSend?() if let refusal { throw refusal } diff --git a/BitkitTests/FailPendingLightningSendTests.swift b/BitkitTests/FailPendingLightningSendTests.swift new file mode 100644 index 000000000..da301ad77 --- /dev/null +++ b/BitkitTests/FailPendingLightningSendTests.swift @@ -0,0 +1,54 @@ +@testable import Bitkit +import BitkitCore +import XCTest + +final class FailPendingLightningSendTests: XCTestCase { + private let database = FileManager.default.temporaryDirectory + .appendingPathComponent("FailPendingLightningSendTests-\(UUID().uuidString)", isDirectory: true) + + override func setUp() async throws { + try await super.setUp() + _ = Bitkit.CoreService.shared + await drainCoreServiceQueue() + try FileManager.default.createDirectory(at: database, withIntermediateDirectories: true) + _ = try initDb(basePath: database.path) + } + + override func tearDown() async throws { + await drainCoreServiceQueue() + await repointCoreToAppStorage() + try? FileManager.default.removeItem(at: database) + try await super.tearDown() + } + + func testFailsOnlyAPendingSend() async throws { + let activity = Bitkit.CoreService.shared.activity + let rows: [(id: String, txType: PaymentType, status: PaymentState)] = [ + ("pending-send", .sent, .pending), + ("paid-send", .sent, .succeeded), + ("failed-send", .sent, .failed), + ("pending-receive", .received, .pending), + ] + for row in rows { + try await activity.insert(.lightning(LightningActivity( + walletId: WalletScope.default, id: row.id, txType: row.txType, status: row.status, value: 1000, fee: 0, + invoice: "invoice", message: "", timestamp: 1000, preimage: nil, contact: nil, + createdAt: 1000, updatedAt: 1000, seenAt: nil + ))) + } + + for row in rows { + try await activity.failPendingLightningSend(id: row.id) + } + + let expected: [String: PaymentState] = [ + "pending-send": .failed, "paid-send": .succeeded, "failed-send": .failed, "pending-receive": .pending, + ] + for (id, status) in expected { + guard case let .lightning(stored) = try await activity.getActivity(id: id) else { + return XCTFail("\(id) is missing") + } + XCTAssertEqual(stored.status, status, id) + } + } +} diff --git a/BitkitTests/TimedSheetManagerTests.swift b/BitkitTests/TimedSheetManagerTests.swift new file mode 100644 index 000000000..cb0ce38aa --- /dev/null +++ b/BitkitTests/TimedSheetManagerTests.swift @@ -0,0 +1,55 @@ +@testable import Bitkit +import XCTest + +@MainActor +final class TimedSheetManagerTests: XCTestCase { + private struct FakeSheet: TimedSheetItem { + let id: SheetID + let priority: TimedSheetPriority + let sheetItem: any SheetItem + + func shouldShow() async -> Bool { + true + } + + func onShown() {} + func onDismissed() {} + } + + override func tearDown() async throws { + let manager = TimedSheetManager.shared + manager.onPrimaryScreenExited() + manager.onSheetDismissed() + for id in manager.getQueueStatus().map(\.id) { + manager.removeSheet(withId: id) + } + try await super.tearDown() + } + + func testDismissingASheetChecksOnlyTheMoveToSparkIntro() async throws { + let manager = TimedSheetManager.shared + let sheets = SheetViewModel() + let transfers = try Bitkit.TransferService(storage: Bitkit.TransferStorage(defaults: makeIsolatedDefaults()), lightningService: .shared) + manager.setup( + sheetViewModel: sheets, appViewModel: AppViewModel(), settingsViewModel: .shared, + walletViewModel: WalletViewModel( + transferService: transfers, + sheetViewModel: sheets, feeEstimatesManager: FeeEstimatesManager() + ), + currencyViewModel: CurrencyViewModel(currencyService: OfflineCurrencyService()), + paykitPaymentRequestManager: PaykitPaymentRequestManager() + ) + manager.registerSheet(FakeSheet(id: .appUpdate, priority: .critical, sheetItem: AppUpdateSheetItem())) + manager.registerSheet(FakeSheet(id: .moveToSpark, priority: .low, sheetItem: MoveToSparkSheetItem())) + // A sheet shown at cold start cancels the first check, then is dismissed. + manager.onPrimaryScreenEntered() + manager.onSheetShown() + manager.onSheetDismissed() + let deadline = Date().addingTimeInterval(10) + while sheets.activeSheetConfiguration?.id != .moveToSpark, Date() < deadline { + try await Task.sleep(nanoseconds: 100_000_000) + } + + XCTAssertEqual(sheets.activeSheetConfiguration?.id, .moveToSpark) + } +} diff --git a/changelog.d/next/1407.fixed.md b/changelog.d/next/1407.fixed.md new file mode 100644 index 000000000..e02183557 --- /dev/null +++ b/changelog.d/next/1407.fixed.md @@ -0,0 +1 @@ +Fixed rare cases where a retried Lightning payment could be paid twice.