From 3096a28be153d3f4293bc3be53cf8193314dee56 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 24 Nov 2026 17:31:00 +0100 Subject: [PATCH 1/7] fix: close spark send hold gaps A retry that took its hold while Spark's list was read now reads pending, so Paykit no longer reads it as the earlier attempt's failure and drops a proof it may still need. An expired send stays held until a sync after its invoice expired, as a sync from before expiry can predate the send's success. The releases after a listing skip an attempt recorded or in flight since the listing's mark, on Spark and on the node, so a send admitted meanwhile keeps its record. A Spark send refused before submission recorded nothing, so it no longer releases another send's attempt and hold of the invoice. The timestamped retry test now also retries once Spark's history can't be read. Closes synonymdev/bitkit-ios#1407 Verified: ChannelFreeRailTests and the full unit suite on an iOS 26 simulator; each new test fails with its fix reverted. --- Bitkit/Services/LightningService.swift | 44 +++++++++++------ BitkitTests/ChannelFreeRailTests.swift | 68 ++++++++++++++++++++++++++ 2 files changed, 97 insertions(+), 15 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 03976e123..d4962dd57 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) } @@ -1386,8 +1389,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 +1458,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 +1531,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 +1543,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 +1571,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 +1828,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 +1840,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. @@ -2545,13 +2554,18 @@ extension LightningService { 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 hold taken during the read is a retry this list predates, so it reads pending until a later list settles it. + let unsettledHashes = Set(unsettled.map { $0.paymentHash.lowercased() }) + let heldDuringRead = holdsAfter.filter { heldBefore[$0.key] != $0.value && !unsettledHashes.contains($0.key) }.keys.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 +2576,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..2c244f298 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. @@ -1806,6 +1811,66 @@ 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 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 +2227,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 +2249,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 } From 0e952d4ddbb29d634ea266bb37a30e091025decc Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 24 Nov 2026 17:31:00 +0100 Subject: [PATCH 2/7] test: cover failing a pending send and the sheet re-check Verified: both tests pass in the full unit suite on an iOS 26 simulator. --- .../FailPendingLightningSendTests.swift | 54 +++++++++++++++++++ BitkitTests/TimedSheetManagerTests.swift | 52 ++++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 BitkitTests/FailPendingLightningSendTests.swift create mode 100644 BitkitTests/TimedSheetManagerTests.swift 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..20a531357 --- /dev/null +++ b/BitkitTests/TimedSheetManagerTests.swift @@ -0,0 +1,52 @@ +@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 { + TimedSheetManager.shared.onPrimaryScreenExited() + TimedSheetManager.shared.removeSheet(withId: .appUpdate) + TimedSheetManager.shared.removeSheet(withId: .moveToSpark) + 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(), 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 keeps the first check from showing anything. + sheets.showSheet(.receive) + manager.onPrimaryScreenEntered() + try await Task.sleep(nanoseconds: 2_500_000_000) + XCTAssertEqual(sheets.activeSheetConfiguration?.id, .receive) + + sheets.hideSheet() + manager.onSheetDismissed() + try await Task.sleep(nanoseconds: 2_500_000_000) + + XCTAssertEqual(sheets.activeSheetConfiguration?.id, .moveToSpark) + } +} From ac34057c967e13d11d7db60ee16f3d0afa9a7de5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 24 Nov 2026 17:31:07 +0100 Subject: [PATCH 3/7] chore: changelog for the spark hold fixes Verified: one fragment for this change in changelog.d/next. --- changelog.d/next/1407.fixed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/next/1407.fixed.md 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. From a9eb3eb3fda2a6f6d8c9965218e50601fd7811e6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 24 Nov 2026 17:46:27 +0100 Subject: [PATCH 4/7] fix: read spark holds before an expiry check settles them The holds are now read before Spark's unsettled sends are checked, so a retry that takes its hold during that check reads as taken during the read. A Spark send that fails before recording its attempt no longer takes a hold, as nothing of it reached Spark. The expired-send retry test pins Spark's last sync between the expiry and the retry, so it still exercises the retry's hold. The sheet test no longer fetches rates and clears every sheet it registered. Verified: ChannelFreeRailTests, TimedSheetManagerTests and FailPendingLightningSendTests on an iOS 26 simulator. --- Bitkit/Services/LightningService.swift | 10 ++++++---- BitkitTests/ChannelFreeRailTests.swift | 5 +++-- BitkitTests/TimedSheetManagerTests.swift | 12 ++++++++---- 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index d4962dd57..58eba957d 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1177,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 @@ -2547,10 +2548,11 @@ 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 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) diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 2c244f298..7ec1d0fc3 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1709,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 } diff --git a/BitkitTests/TimedSheetManagerTests.swift b/BitkitTests/TimedSheetManagerTests.swift index 20a531357..f1289ee46 100644 --- a/BitkitTests/TimedSheetManagerTests.swift +++ b/BitkitTests/TimedSheetManagerTests.swift @@ -17,9 +17,12 @@ final class TimedSheetManagerTests: XCTestCase { } override func tearDown() async throws { - TimedSheetManager.shared.onPrimaryScreenExited() - TimedSheetManager.shared.removeSheet(withId: .appUpdate) - TimedSheetManager.shared.removeSheet(withId: .moveToSpark) + let manager = TimedSheetManager.shared + manager.onPrimaryScreenExited() + manager.onSheetDismissed() + for id in manager.getQueueStatus().map(\.id) { + manager.removeSheet(withId: id) + } try await super.tearDown() } @@ -33,7 +36,8 @@ final class TimedSheetManagerTests: XCTestCase { transferService: transfers, sheetViewModel: sheets, feeEstimatesManager: FeeEstimatesManager() ), - currencyViewModel: CurrencyViewModel(), paykitPaymentRequestManager: PaykitPaymentRequestManager() + currencyViewModel: CurrencyViewModel(currencyService: OfflineCurrencyService()), + paykitPaymentRequestManager: PaykitPaymentRequestManager() ) manager.registerSheet(FakeSheet(id: .appUpdate, priority: .critical, sheetItem: AppUpdateSheetItem())) manager.registerSheet(FakeSheet(id: .moveToSpark, priority: .low, sheetItem: MoveToSparkSheetItem())) From f31c58da2ed2170044795c0a47e76350a4390c5c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 24 Nov 2026 18:30:38 +0100 Subject: [PATCH 5/7] fix: read a spark retry recorded during a list read as pending A retry that recorded its attempt while Spark's list was read, and whose success ended its hold before the read returned, read as the earlier attempt's failure when the list showed only that failure. It now reads pending until a later list shows its result. Tests cover that retry and a Spark send that fails before recording its attempt taking no hold. The sheet test polls for the Move to Spark intro instead of waiting a fixed time. Verified: full unit suite on an iOS 26 simulator; both new tests fail with the fix reverted. --- Bitkit/Services/LightningService.swift | 10 ++++++-- BitkitTests/ChannelFreeRailTests.swift | 29 ++++++++++++++++++++++++ BitkitTests/TimedSheetManagerTests.swift | 5 +++- 3 files changed, 41 insertions(+), 3 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 58eba957d..a4b9377d7 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -2551,6 +2551,7 @@ extension LightningService { // 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 heldBefore = railSendHolds + let mark = attemptMark let unsettledBefore = await unsettledUncertainRailSends() let kept = unexpiredRailAttempts() let payments = try await rail.lightningPayments() @@ -2564,9 +2565,14 @@ extension LightningService { stillUnsettled.contains($0.paymentHash) || !Self.listsResult(payments, paymentHash: $0.paymentHash, startedAt: heldBefore[$0.paymentHash]) } - // A hold taken during the read is a retry this list predates, so it reads pending until a later list settles it. + // A retry that took a hold or recorded its attempt during the read 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 heldDuringRead = holdsAfter.filter { heldBefore[$0.key] != $0.value && !unsettledHashes.contains($0.key) }.keys.sorted() + let recordedDuringRead = eventCallbackLock.withLock { attemptsRecorded(since: mark.records, 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. diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 7ec1d0fc3..ec3b8f886 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1826,6 +1826,35 @@ extension ChannelFreeRailTests { 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 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. + rail.onSend = { + service.recordRailAttempt(paymentHash: hash) + } + + _ = try? await service.send(bolt11: Self.invoice, beforeSubmission: { throw NSError(domain: "request", code: 1) }) + + 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 diff --git a/BitkitTests/TimedSheetManagerTests.swift b/BitkitTests/TimedSheetManagerTests.swift index f1289ee46..f19a6482d 100644 --- a/BitkitTests/TimedSheetManagerTests.swift +++ b/BitkitTests/TimedSheetManagerTests.swift @@ -49,7 +49,10 @@ final class TimedSheetManagerTests: XCTestCase { sheets.hideSheet() manager.onSheetDismissed() - try await Task.sleep(nanoseconds: 2_500_000_000) + 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) } From 83681af88a37afe8563ef4bc369345b2c9a6fd0c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 24 Nov 2026 18:56:29 +0100 Subject: [PATCH 6/7] fix: read a spark retry in flight during a list read as pending The list read takes its attempt mark first and reads a Spark send in flight at the mark, or since, as pending too, so a retry that recorded its attempt just before the mark and ended during the read no longer reads as the earlier attempt's failure. The sheet test cancels the first check as a shown sheet does instead of waiting it out, and the failed-check test asserts the send reached Spark's send call. Verified: full unit suite on an iOS 26 simulator. --- Bitkit/Services/LightningService.swift | 8 ++++---- BitkitTests/ChannelFreeRailTests.swift | 11 ++++++++++- BitkitTests/TimedSheetManagerTests.swift | 7 +++---- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index a4b9377d7..d884b6609 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -2550,8 +2550,8 @@ extension LightningService { 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, // and a hold taken meanwhile reads as taken during the read. - let heldBefore = railSendHolds let mark = attemptMark + let heldBefore = railSendHolds let unsettledBefore = await unsettledUncertainRailSends() let kept = unexpiredRailAttempts() let payments = try await rail.lightningPayments() @@ -2565,10 +2565,10 @@ extension LightningService { stillUnsettled.contains($0.paymentHash) || !Self.listsResult(payments, paymentHash: $0.paymentHash, startedAt: heldBefore[$0.paymentHash]) } - // A retry that took a hold or recorded its attempt during the read is one this list predates, so it reads - // pending until a later list shows its result, also when it already ended. + // 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 { attemptsRecorded(since: mark.records, key: Self.railAttemptsKey) } + 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)) diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index ec3b8f886..4506cc8dd 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1846,12 +1846,21 @@ extension ChannelFreeRailTests { 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) } - _ = try? await service.send(bolt11: Self.invoice, beforeSubmission: { throw NSError(domain: "request", code: 1) }) + 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") } diff --git a/BitkitTests/TimedSheetManagerTests.swift b/BitkitTests/TimedSheetManagerTests.swift index f19a6482d..0238c0663 100644 --- a/BitkitTests/TimedSheetManagerTests.swift +++ b/BitkitTests/TimedSheetManagerTests.swift @@ -41,11 +41,10 @@ final class TimedSheetManagerTests: XCTestCase { ) manager.registerSheet(FakeSheet(id: .appUpdate, priority: .critical, sheetItem: AppUpdateSheetItem())) manager.registerSheet(FakeSheet(id: .moveToSpark, priority: .low, sheetItem: MoveToSparkSheetItem())) - // A sheet shown at cold start keeps the first check from showing anything. - sheets.showSheet(.receive) + // A sheet shown at cold start cancels the first check. manager.onPrimaryScreenEntered() - try await Task.sleep(nanoseconds: 2_500_000_000) - XCTAssertEqual(sheets.activeSheetConfiguration?.id, .receive) + sheets.showSheet(.receive) + manager.onSheetShown() sheets.hideSheet() manager.onSheetDismissed() From 5a2277c07c9d9f1b5de841612bb7152f4563d3c5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 24 Nov 2026 19:03:47 +0100 Subject: [PATCH 7/7] test: cover a spark retry in flight during a list read The sheet test drives the manager directly, so the sheet model's own calls into it can't race the test's. Verified: ChannelFreeRailTests and TimedSheetManagerTests on an iOS 26 simulator; the new test fails with the in-flight read reverted. --- BitkitTests/ChannelFreeRailTests.swift | 16 ++++++++++++++++ BitkitTests/TimedSheetManagerTests.swift | 5 +---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 4506cc8dd..e4b4c9106 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1841,6 +1841,22 @@ extension ChannelFreeRailTests { 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 diff --git a/BitkitTests/TimedSheetManagerTests.swift b/BitkitTests/TimedSheetManagerTests.swift index 0238c0663..cb0ce38aa 100644 --- a/BitkitTests/TimedSheetManagerTests.swift +++ b/BitkitTests/TimedSheetManagerTests.swift @@ -41,12 +41,9 @@ final class TimedSheetManagerTests: XCTestCase { ) 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. + // A sheet shown at cold start cancels the first check, then is dismissed. manager.onPrimaryScreenEntered() - sheets.showSheet(.receive) manager.onSheetShown() - - sheets.hideSheet() manager.onSheetDismissed() let deadline = Date().addingTimeInterval(10) while sheets.activeSheetConfiguration?.id != .moveToSpark, Date() < deadline {