From a2a595535493d41db0b84d1b213dba6d447d5dd5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 14:53:31 +0100 Subject: [PATCH 01/64] fix: move to spark row, re-check and kept hashes Shows a move as a Move to Spark transfer row, re-checks the Move to Spark sheet after a cold-start sheet closes, keeps move payment hashes across relaunches, and injects the quote services so makeQuote is tested. --- Bitkit/Managers/MoveToSparkManager.swift | 89 +++++++--- .../TimedSheets/TimedSheetManager.swift | 15 +- .../Localization/en.lproj/Localizable.strings | 1 + Bitkit/ViewModels/ActivityListViewModel.swift | 6 +- Bitkit/ViewModels/AppViewModel.swift | 1 + .../Views/Wallets/Activity/ActivityIcon.swift | 4 +- .../Wallets/Activity/ActivityItemView.swift | 4 + .../Activity/ActivityRowLightning.swift | 11 ++ BitkitTests/MoveToSparkQuoteTests.swift | 158 ++++++++++++++++++ 9 files changed, 258 insertions(+), 31 deletions(-) create mode 100644 BitkitTests/MoveToSparkQuoteTests.swift diff --git a/Bitkit/Managers/MoveToSparkManager.swift b/Bitkit/Managers/MoveToSparkManager.swift index ca27187549..498a035052 100644 --- a/Bitkit/Managers/MoveToSparkManager.swift +++ b/Bitkit/Managers/MoveToSparkManager.swift @@ -1,8 +1,11 @@ +import BitkitCore import Foundation import LDKNode /// The amounts behind moving the channels' balance to Spark, kept apart so they can be tested without a node. enum MoveToSparkMath { + /// The move invoice's description, which is also how Activity tells a move's send from other payments. + static let invoiceDescription = "Move to Spark" /// Below this a move is not offered: what is left is about the routing fee. static let minMoveSats: UInt64 = 1000 /// The fee guessed for the first quote of a full move, as a share of the amount in parts per million. @@ -72,6 +75,13 @@ struct MoveToSparkQuote: Equatable { let feeSats: UInt64 } +extension LightningActivity { + /// The channel send of a move to Spark, which Activity shows as a transfer rather than a payment. + var isMoveToSpark: Bool { + txType == .sent && message == MoveToSparkMath.invoiceDescription + } +} + enum MoveToSparkError: Error { case nothingToMove case sparkUnavailable @@ -80,20 +90,61 @@ enum MoveToSparkError: Error { } /// The payments that move a channel balance to Spark, whose send and receive the app does not announce as payments. +/// Kept on disk, so a move that settles after a relaunch is still known as one. @MainActor enum MoveToSparkPayments { - private static var paymentHashes = Set() + private static let storageKey = "moveToSparkPaymentHashes" + /// Far beyond the move invoice's expiry, so Spark reporting a receive late, after a relaunch, still finds its move. + static let retention: TimeInterval = 30 * 24 * 60 * 60 + static var defaults: UserDefaults = .standard + + static func insert(_ paymentHash: String, now: Date = Date()) { + var hashes = stored(now: now) + hashes[paymentHash.lowercased()] = now.timeIntervalSince1970 + defaults.set(hashes, forKey: storageKey) + } - static func insert(_ paymentHash: String) { - paymentHashes.insert(paymentHash.lowercased()) + static func contains(_ paymentHash: String?, now: Date = Date()) -> Bool { + paymentHash.map { stored(now: now)[$0.lowercased()] != nil } ?? false } - static func contains(_ paymentHash: String?) -> Bool { - paymentHash.map { paymentHashes.contains($0.lowercased()) } ?? false + /// Forgets a move whose payment failed: its amount stays in the channel, and Spark receives nothing for it. + static func remove(_ paymentHash: String?, now: Date = Date()) { + guard let paymentHash else { return } + var hashes = stored(now: now) + guard hashes.removeValue(forKey: paymentHash.lowercased()) != nil else { return } + defaults.set(hashes, forKey: storageKey) } static func removeAll() { - paymentHashes.removeAll() + defaults.removeObject(forKey: storageKey) + } + + private static func stored(now: Date) -> [String: Double] { + let hashes = defaults.dictionary(forKey: storageKey) as? [String: Double] ?? [:] + return hashes.filter { now.timeIntervalSince1970 - $0.value < retention } + } +} + +/// What a move quote needs from Spark and the channels, apart so the quote can be tested without either. +protocol MoveToSparkServices { + @MainActor var isSparkUsable: Bool { get } + func receiveInvoice(description: String, expirySecs: UInt32) async throws -> String + /// The routing fee LDK estimates for paying `bolt11` with `amountSats` over the channels only. + func estimateChannelFee(bolt11: String, amountSats: UInt64) async throws -> UInt64 +} + +struct LiveMoveToSparkServices: MoveToSparkServices { + @MainActor var isSparkUsable: Bool { + MoveToSparkMath.isSparkUsable(SparkManager.shared) + } + + func receiveInvoice(description: String, expirySecs: UInt32) async throws -> String { + try await SparkManager.shared.receive(amountSats: nil, description: description, expirySecs: expirySecs) + } + + func estimateChannelFee(bolt11: String, amountSats: UInt64) async throws -> UInt64 { + try await LightningService.shared.estimateRoutingFees(bolt11: bolt11, amountSats: amountSats, channelsOnly: true) } } @@ -134,7 +185,6 @@ final class MoveToSparkManager { /// Shared so a move and its outcome outlive the screen, which is rebuilt when the app is unlocked. static let shared = MoveToSparkManager() - private static let invoiceDescription = "Move to Spark" private static let invoiceExpirySecs: UInt32 = 3600 private static let maxQuoteRounds = 4 @@ -147,12 +197,10 @@ final class MoveToSparkManager { /// A swiped payment that has not settled yet; leaving the screen keeps it, so it is never quoted over. private var isMoveInFlight = false - private let lightningService: LightningService - private let spark: SparkManager + private let services: any MoveToSparkServices - init() { - lightningService = .shared - spark = .shared + init(services: any MoveToSparkServices = LiveMoveToSparkServices()) { + self.services = services } /// Opens the screen: quotes a new move, unless a quote is still running or a move started earlier is still running @@ -214,9 +262,11 @@ final class MoveToSparkManager { } } state = .confirm(quote, isMoving: true) + var paymentHash: String? do { - let paymentHash = try Bolt11Invoice.fromStr(invoiceStr: quote.invoice).paymentHash() - MoveToSparkPayments.insert(String(describing: paymentHash)) + let hash = try String(describing: Bolt11Invoice.fromStr(invoiceStr: quote.invoice).paymentHash()) + paymentHash = hash + MoveToSparkPayments.insert(hash) guard let settled = try await wallet.sendOverChannels( bolt11: quote.invoice, sats: quote.amountSats, @@ -245,6 +295,7 @@ final class MoveToSparkManager { state = Self.doneState(amountSats: quote.amountSats, feeSats: settled.feePaidSats, channels: wallet.channels) } catch { Logger.error("Failed to move '\(quote.amountSats)' sats to Spark: \(error)", context: "MoveToSpark") + MoveToSparkPayments.remove(paymentHash) guard moveGeneration == generation else { return } state = Self.isNoRoute(error) || Self.isSendWithoutRoute(error, invoice: quote.invoice) ? .tooLarge(amountSats: quote.amountSats, smallerSats: MoveToSparkMath.smallerAmount(quote.amountSats)) @@ -266,20 +317,16 @@ final class MoveToSparkManager { guard wantedSats >= MoveToSparkMath.minMoveSats, MoveToSparkMath.hasMovableBalance(limitSats: limitSats) else { throw MoveToSparkError.nothingToMove } - guard MoveToSparkMath.isSparkUsable(spark) else { throw MoveToSparkError.sparkUnavailable } + guard services.isSparkUsable else { throw MoveToSparkError.sparkUnavailable } - let invoice = try await spark.receive( - amountSats: nil, - description: Self.invoiceDescription, - expirySecs: Self.invoiceExpirySecs - ) + let invoice = try await services.receiveInvoice(description: MoveToSparkMath.invoiceDescription, expirySecs: Self.invoiceExpirySecs) var amountSats = MoveToSparkMath.firstCandidate(wantedSats: wantedSats, limitSats: limitSats) var fitting: MoveToSparkQuote? // The first amount leaves room for a guessed fee; once the real fee is known, the amount grows to fit it. for _ in 0 ..< Self.maxQuoteRounds where amountSats >= MoveToSparkMath.minMoveSats { let estimateSats: UInt64 do { - estimateSats = try await lightningService.estimateRoutingFees(bolt11: invoice, amountSats: amountSats, channelsOnly: true) + estimateSats = try await services.estimateChannelFee(bolt11: invoice, amountSats: amountSats) } catch { if let fitting { return fitting diff --git a/Bitkit/Managers/TimedSheets/TimedSheetManager.swift b/Bitkit/Managers/TimedSheets/TimedSheetManager.swift index bc9cf01de0..de31396124 100644 --- a/Bitkit/Managers/TimedSheets/TimedSheetManager.swift +++ b/Bitkit/Managers/TimedSheets/TimedSheetManager.swift @@ -152,23 +152,28 @@ class TimedSheetManager: ObservableObject { currentSheet.onDismissed() currentlyShowingSheet = nil } + // A sheet shown at cold start, before channels and Spark load, kept the Move to Spark intro from being checked. + // A check already pending covers it. + if isOnPrimaryScreen, settleTimer?.isValid != true, queuedSheets.contains(where: { $0.id == .moveToSpark }) { + scheduleSettleCheck(only: .moveToSpark) + } } - /// (Re)start the settle timer that runs the queue check after a short delay. - private func scheduleSettleCheck() { + /// (Re)start the settle timer that runs the queue check after a short delay, for every queued sheet or only `id`. + private func scheduleSettleCheck(only id: SheetID? = nil) { // Cancel any existing timer settleTimer?.invalidate() // Start timer to check for sheets after delay settleTimer = Timer.scheduledTimer(withTimeInterval: checkDelay, repeats: false) { [weak self] _ in Task { @MainActor in - await self?.checkAndShowNextSheet() + await self?.checkAndShowNextSheet(only: id) } } } /// Check the queue and show the highest priority sheet that should be shown - private func checkAndShowNextSheet() async { + private func checkAndShowNextSheet(only id: SheetID? = nil) async { guard let sheetViewModel else { Logger.error("SheetViewModel not configured for TimedSheetManager") return @@ -187,7 +192,7 @@ class TimedSheetManager: ObservableObject { } // Find the highest priority sheet that should be shown - for sheet in queuedSheets { + for sheet in queuedSheets where id == nil || sheet.id == id { if await sheet.shouldShow() { Logger.debug("Showing timed sheet: \(sheet.id.rawValue) with priority: \(sheet.priority.rawValue)") diff --git a/Bitkit/Resources/Localization/en.lproj/Localizable.strings b/Bitkit/Resources/Localization/en.lproj/Localizable.strings index ec5b29cc79..7f80844018 100644 --- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings @@ -1584,6 +1584,7 @@ "wallet__activity_failed" = "Failed"; "wallet__activity_transfer" = "Transfer"; "wallet__activity_transferring" = "Transferring"; +"wallet__activity_move_to_spark" = "Move to Spark"; "wallet__activity_transfer_savings_pending" = "From Spending ({duration})"; "wallet__activity_transfer_savings_done" = "From Spending"; "wallet__activity_transfer_spending_pending" = "From Savings ({duration})"; diff --git a/Bitkit/ViewModels/ActivityListViewModel.swift b/Bitkit/ViewModels/ActivityListViewModel.swift index 1a303bb6c3..827b05baab 100644 --- a/Bitkit/ViewModels/ActivityListViewModel.swift +++ b/Bitkit/ViewModels/ActivityListViewModel.swift @@ -494,7 +494,7 @@ extension ActivityListViewModel { return activities.filter { activity in switch activity { case let .lightning(ln): - return ln.txType == .sent + return ln.txType == .sent && !ln.isMoveToSpark case let .onchain(on): return on.txType == .sent && !on.isTransfer } @@ -511,8 +511,8 @@ extension ActivityListViewModel { case .other: return activities.filter { activity in switch activity { - case .lightning: - return false // Lightning activities are never transfers + case let .lightning(ln): + return ln.isMoveToSpark case let .onchain(on): return on.isTransfer } diff --git a/Bitkit/ViewModels/AppViewModel.swift b/Bitkit/ViewModels/AppViewModel.swift index cb54b9135c..07b0c75ebc 100644 --- a/Bitkit/ViewModels/AppViewModel.swift +++ b/Bitkit/ViewModels/AppViewModel.swift @@ -1981,6 +1981,7 @@ extension AppViewModel { ) } case let .paymentFailed(paymentId, paymentHash, reason): + MoveToSparkPayments.remove(paymentHash) let outcome = QuickPayPaymentCoordinator.shared.complete( paymentId: paymentId, paymentHash: paymentHash, diff --git a/Bitkit/Views/Wallets/Activity/ActivityIcon.swift b/Bitkit/Views/Wallets/Activity/ActivityIcon.swift index c905a757c7..d8d501f337 100644 --- a/Bitkit/Views/Wallets/Activity/ActivityIcon.swift +++ b/Bitkit/Views/Wallets/Activity/ActivityIcon.swift @@ -32,7 +32,7 @@ struct ActivityIcon: View { confirmed = nil txType = ln.txType isBoosted = false - isTransfer = false + isTransfer = ln.isMoveToSpark doesExist = true case let .onchain(onchain): isLightning = false @@ -100,7 +100,7 @@ struct ActivityIcon: View { CircularIcon(icon: "hourglass-simple", iconColor: .purpleAccent, backgroundColor: .purple16, size: size) } else { CircularIcon( - icon: txType == .sent ? "arrow-up" : "arrow-down", + icon: isTransfer ? "arrow-up-down" : txType == .sent ? "arrow-up" : "arrow-down", iconColor: .purpleAccent, backgroundColor: .purple16, size: size diff --git a/Bitkit/Views/Wallets/Activity/ActivityItemView.swift b/Bitkit/Views/Wallets/Activity/ActivityItemView.swift index 821dd7d425..e1c48dc1bd 100644 --- a/Bitkit/Views/Wallets/Activity/ActivityItemView.swift +++ b/Bitkit/Views/Wallets/Activity/ActivityItemView.swift @@ -124,6 +124,10 @@ struct ActivityItemView: View { return t("wallet__activity_boost_fee") } + if case let .lightning(activity) = viewModel.activity, activity.isMoveToSpark { + return t("wallet__activity_move_to_spark") + } + if case let .lightning(activity) = viewModel.activity, activity.status == .pending { return t("wallet__activity_pending_nav_title") } diff --git a/Bitkit/Views/Wallets/Activity/ActivityRowLightning.swift b/Bitkit/Views/Wallets/Activity/ActivityRowLightning.swift index f031ef41eb..5810cb61e8 100644 --- a/Bitkit/Views/Wallets/Activity/ActivityRowLightning.swift +++ b/Bitkit/Views/Wallets/Activity/ActivityRowLightning.swift @@ -33,6 +33,10 @@ struct ActivityRowLightning: View { return titleOverride } + if item.isMoveToSpark { + return t("wallet__activity_move_to_spark") + } + switch item.status { case .failed: return t("wallet__activity_failed") @@ -44,6 +48,13 @@ struct ActivityRowLightning: View { } private var description: String { + if item.isMoveToSpark { + switch item.status { + case .failed: return t("wallet__activity_failed") + case .pending: return t("wallet__activity_pending") + case .succeeded: return formattedTime + } + } return item.message.isEmpty ? formattedTime : item.message } diff --git a/BitkitTests/MoveToSparkQuoteTests.swift b/BitkitTests/MoveToSparkQuoteTests.swift new file mode 100644 index 0000000000..5b59b50137 --- /dev/null +++ b/BitkitTests/MoveToSparkQuoteTests.swift @@ -0,0 +1,158 @@ +@testable import Bitkit +import LDKNode +import XCTest + +@MainActor +final class MoveToSparkQuoteTests: XCTestCase { + private final class FakeServices: MoveToSparkServices, @unchecked Sendable { + var isSparkUsable = true + var estimate: (UInt64) throws -> UInt64 = { _ in 30 } + private(set) var quotedAmounts: [UInt64] = [] + + func receiveInvoice(description _: String, expirySecs _: UInt32) async throws -> String { + "lnbcrt1move" + } + + func estimateChannelFee(bolt11 _: String, amountSats: UInt64) async throws -> UInt64 { + quotedAmounts.append(amountSats) + return try estimate(amountSats) + } + } + + private struct OtherError: Error {} + + /// Channels that can send 100,000 sats. + private let channels = [ChannelDetails.mock(outboundCapacityMsat: 100_000_000)] + + func testQuoteGrowsToFitTheRealFee() async throws { + let services = FakeServices() + let quote = try await MoveToSparkManager(services: services).makeQuote(channels: channels, targetSats: nil) + XCTAssertEqual(quote, MoveToSparkQuote(invoice: "lnbcrt1move", amountSats: 99968, feeSats: 32)) + XCTAssertEqual(services.quotedAmounts, [99498, 99968]) + } + + func testQuoteKeepsASmallerTarget() async throws { + let services = FakeServices() + let quote = try await MoveToSparkManager(services: services).makeQuote(channels: channels, targetSats: 50000) + XCTAssertEqual(quote.amountSats, 50000) + XCTAssertEqual(quote.feeSats, 32) + XCTAssertEqual(services.quotedAmounts, [50000]) + } + + func testQuoteFallsBackToTheLastFittingAmount() async throws { + let services = FakeServices() + services.estimate = { amount in + guard amount == 99498 else { throw NodeError.RouteNotFound(message: "no route") } + return 30 + } + let quote = try await MoveToSparkManager(services: services).makeQuote(channels: channels, targetSats: nil) + XCTAssertEqual(quote.amountSats, 99498) + XCTAssertEqual(quote.feeSats, 32) + } + + func testNoRouteOnTheFirstRoundIsTooLarge() async { + let services = FakeServices() + services.estimate = { _ in throw NodeError.RouteNotFound(message: "no route") } + await assertQuoteThrows(services, expected: .tooLarge(amountSats: 99498)) + } + + func testAFeeThatNeverFitsIsTooLarge() async { + let services = FakeServices() + var estimate: UInt64 = 500 + services.estimate = { _ in + estimate += 100 + return estimate + } + await assertQuoteThrows(services, expected: .tooLarge(amountSats: 99098)) + XCTAssertEqual(services.quotedAmounts, [99498, 99398, 99298, 99198]) + } + + func testOtherEstimateErrorsAreRethrown() async { + let services = FakeServices() + services.estimate = { _ in throw OtherError() } + do { + _ = try await MoveToSparkManager(services: services).makeQuote(channels: channels, targetSats: nil) + XCTFail("Expected an error") + } catch { + XCTAssertTrue(error is OtherError) + } + } + + func testNothingToMoveWithoutChannels() async { + await assertQuoteThrows(FakeServices(), channels: [], expected: .nothingToMove) + } + + func testSparkUnavailableStopsTheQuote() async { + let services = FakeServices() + services.isSparkUsable = false + await assertQuoteThrows(services, expected: .sparkUnavailable) + XCTAssertTrue(services.quotedAmounts.isEmpty) + } + + private func assertQuoteThrows( + _ services: FakeServices, + channels: [ChannelDetails]? = nil, + expected: MoveToSparkError, + line: UInt = #line + ) async { + do { + _ = try await MoveToSparkManager(services: services).makeQuote(channels: channels ?? self.channels, targetSats: nil) + XCTFail("Expected \(expected)", line: line) + } catch let error as MoveToSparkError { + switch (error, expected) { + case let (.tooLarge(a), .tooLarge(b)): XCTAssertEqual(a, b, line: line) + case (.nothingToMove, .nothingToMove), (.sparkUnavailable, .sparkUnavailable): break + default: XCTFail("Expected \(expected), got \(error)", line: line) + } + } catch { + XCTFail("Expected \(expected), got \(error)", line: line) + } + } +} + +@MainActor +final class MoveToSparkPaymentsTests: XCTestCase { + private var suiteName = "" + private var savedDefaults = UserDefaults.standard + + override func setUp() async throws { + suiteName = "MoveToSparkPaymentsTests-\(UUID().uuidString)" + savedDefaults = MoveToSparkPayments.defaults + MoveToSparkPayments.defaults = try XCTUnwrap(UserDefaults(suiteName: suiteName)) + } + + override func tearDown() async throws { + MoveToSparkPayments.defaults.removePersistentDomain(forName: suiteName) + MoveToSparkPayments.defaults = savedDefaults + } + + func testHashSurvivesARelaunch() throws { + MoveToSparkPayments.insert("ABCD") + // A relaunch reads the same store anew. + MoveToSparkPayments.defaults = try XCTUnwrap(UserDefaults(suiteName: suiteName)) + XCTAssertTrue(MoveToSparkPayments.contains("abcd")) + XCTAssertFalse(MoveToSparkPayments.contains("ef01")) + XCTAssertFalse(MoveToSparkPayments.contains(nil)) + } + + func testFailedMoveIsForgotten() { + MoveToSparkPayments.insert("abcd") + MoveToSparkPayments.insert("ef01") + MoveToSparkPayments.remove("ABCD") + XCTAssertFalse(MoveToSparkPayments.contains("abcd")) + XCTAssertTrue(MoveToSparkPayments.contains("ef01")) + } + + func testHashIsKeptUntilItsRetentionEnds() { + let start = Date(timeIntervalSince1970: 1_000_000) + MoveToSparkPayments.insert("abcd", now: start) + XCTAssertTrue(MoveToSparkPayments.contains("abcd", now: start.addingTimeInterval(MoveToSparkPayments.retention - 1))) + XCTAssertFalse(MoveToSparkPayments.contains("abcd", now: start.addingTimeInterval(MoveToSparkPayments.retention))) + } + + func testWipeForgetsEveryHash() { + MoveToSparkPayments.insert("abcd") + MoveToSparkPayments.removeAll() + XCTAssertFalse(MoveToSparkPayments.contains("abcd")) + } +} From 7936297a010216d72f2213630915a26ec59704d1 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 14:53:31 +0100 Subject: [PATCH 02/64] fix: spark claim poll, exit backup, retry hold and key check Stops quoting after a waiting early claim, sets aside exit data Spark rejects so backups go on, keeps a retry in doubt held against an earlier attempt's late failure, and fails the Release key check on a blank keychain item. --- Bitkit.xcodeproj/project.pbxproj | 2 +- Bitkit/Managers/SparkManager.swift | 45 ++++++++++-- Bitkit/Services/BackupService.swift | 53 ++++++++++++-- Bitkit/Services/LightningService.swift | 37 +++++++++- Bitkit/ViewModels/SparkTransferFlow.swift | 18 +++++ BitkitTests/ChannelFreeRailTests.swift | 26 +++++++ BitkitTests/SparkExitBackupTests.swift | 88 ++++++++++++++++++++++- BitkitTests/SparkTransferFlowTests.swift | 52 +++++++++++--- 8 files changed, 296 insertions(+), 25 deletions(-) diff --git a/Bitkit.xcodeproj/project.pbxproj b/Bitkit.xcodeproj/project.pbxproj index ae80d4f6bf..929566e384 100644 --- a/Bitkit.xcodeproj/project.pbxproj +++ b/Bitkit.xcodeproj/project.pbxproj @@ -602,7 +602,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "if [ \"$CONFIGURATION\" = \"Release\" ] && [ -z \"$(echo \"${BREEZ_API_KEY}\" | tr -d ' ')\" ] && ! /usr/bin/security find-generic-password -a \"$USER\" -s BREEZ_API_KEY >/dev/null 2>&1; then\n echo \"error: BREEZ_API_KEY is empty. Store it in the keychain item BREEZ_API_KEY or set it in Secrets.xcconfig before a Release build or archive (Docs/RELEASE.md).\"\n exit 1\nfi\n"; + shellScript = "# Reads the keychain value only to test it for blank, so a missing, blank or unreadable (locked) item fails here,\n# before the target compiles. The value is never printed.\nif [ \"$CONFIGURATION\" = \"Release\" ] && [ -z \"$(echo \"${BREEZ_API_KEY}\" | tr -d ' ')\" ] \\\n && [ -z \"$(/usr/bin/security find-generic-password -a \"$USER\" -s BREEZ_API_KEY -w 2>/dev/null | tr -d '[:space:]')\" ]; then\n echo \"error: BREEZ_API_KEY is empty. Store it in the keychain item BREEZ_API_KEY (unlocked, not blank) or set it in Secrets.xcconfig before a Release build or archive (Docs/RELEASE.md).\"\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; B17C0F1A2EAE000000000003 /* Breez API Key From Keychain */ = { diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index a147eb664d..7f54300e04 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -830,6 +830,12 @@ final class SparkManager: ChannelFreeLightningRail { return SparkClaimOffer(txid: deposit.txid, vout: deposit.vout, quote: quote) } + /// Whether Spark still lists the deposit in `txid` as unclaimed. Asks no provider for a quote. + func isDepositUnclaimed(txid: String) async throws -> Bool { + let unclaimed = try await requireSdk().listUnclaimedDeposits(request: ListUnclaimedDepositsRequest()).deposits + return unclaimed.contains { $0.txid.caseInsensitiveCompare(txid) == .orderedSame } + } + /// Clears the fee cap an early claim of `offer` left on its deposit, back to the configured one, which never claims /// early (`sdkConfig`): a claim that names no cap clears the stored one before it is attempted. False when the cap /// may still be there: the call failed, or another claim of the deposit held it, which leaves the cap unchanged. @@ -1477,15 +1483,21 @@ final class SparkManager: ChannelFreeLightningRail { } } - /// Whether restored exit data is still waiting for its import, after trying that again while connected. - func hasStagedExitState(walletIndex: Int) async -> Bool { + /// Tries the import of restored exit data again while connected, and says what became of it. + func importStagedExitState(walletIndex: Int) async -> SparkStagedExitImport { await importRestoredExitState(walletIndex: walletIndex) - return FileManager.default.fileExists(atPath: Env.sparkExitRestore(walletIndex: walletIndex).path) } - private func importRestoredExitState(walletIndex: Int) async { + /// Drops restored exit data Spark rejected, once the backup set its remote copy aside. + func discardStagedExitState(walletIndex: Int) { + try? FileManager.default.removeItem(at: Env.sparkExitRestore(walletIndex: walletIndex)) + } + + @discardableResult + private func importRestoredExitState(walletIndex: Int) async -> SparkStagedExitImport { let file = Env.sparkExitRestore(walletIndex: walletIndex) - guard let sdk, let data = FileManager.default.contents(atPath: file.path) else { return } + guard let data = FileManager.default.contents(atPath: file.path) else { return .nothingStaged } + guard let sdk else { return .pending } do { let imported = try await sdk.importUnilateralExitState( request: ImportUnilateralExitStateRequest(exitState: String(decoding: data, as: UTF8.self)) @@ -1496,8 +1508,10 @@ final class SparkManager: ChannelFreeLightningRail { + "'\(imported.skippedConflictingLeaves)' conflicting, '\(imported.skippedChains)' already held", context: "SparkManager" ) + return .imported } catch { Logger.error("Failed to import Spark exit data: \(error)", context: "SparkManager") + return SparkStagedExitImport(importError: error) } } @@ -1902,7 +1916,7 @@ final class SparkManager: ChannelFreeLightningRail { await Self.handleSettledPayment( payment, record: { await self.recordActivity($0) }, - emit: { LightningService.shared.emitChannelFreeRailEvent($0) }, + emit: { LightningService.shared.emitChannelFreeRailEvent($0, paymentCreatedAt: payment.timestamp) }, refresh: { try await self.refresh() } ) case let .paymentPending(payment): @@ -2080,6 +2094,25 @@ struct SparkClaimFees: Equatable { let laterSats: UInt64 } +/// What became of restored exit data staged for import. +enum SparkStagedExitImport: Equatable { + case nothingStaged + case imported + /// Spark can never import it: an exit state version this SDK doesn't support, or a payload it can't parse. + case rejected + /// Not imported yet, as while Spark is not connected or the import failed for a reason that may pass. + case pending + + /// Spark runs the import without its operators, so only invalid input fails it every time. + init(importError: Error) { + if case SdkError.InvalidInput = importError { + self = .rejected + } else { + self = .pending + } + } +} + /// What accepting an early claim did. enum SparkEarlyClaim: Equatable { /// The claim settled, so the deposit is in the balance. diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 95a0cb040b..e5b898b4a3 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -134,7 +134,12 @@ class BackupService { /// Set while the Spark exit data restore hasn't succeeded or found no older backup, kept across launches, so a fresh /// export never replaces the remote backup it couldn't read yet. private static let sparkExitRestorePendingKey = "sparkExitRestorePending" + /// The remote key of exit data Spark rejected for good, read and written alike by bitkit-android. + static let sparkExitRejectedKey = "SPARK_EXIT_REJECTED" private let backupData: ((BackupCategory) async throws -> Data)? + private let importStagedSparkExit: () async -> SparkStagedExitImport + private let discardStagedSparkExit: () async -> Void + private let restoreExitBackup: (SparkExitBackupV1) async throws -> Void private let isSparkExitActive: () async -> Bool private let uploadBackup: (String, Data) async throws -> Void private let waitForBackupDelay: () async throws -> Void @@ -182,9 +187,21 @@ class BackupService { }, fetchBackup: @escaping (String) async throws -> Data? = { key in try await VssBackupClient.shared.getObject(key: key)?.value + }, + importStagedSparkExit: @escaping () async -> SparkStagedExitImport = { @MainActor in + await SparkManager.shared.importStagedExitState(walletIndex: LightningService.shared.currentWalletIndex) + }, + discardStagedSparkExit: @escaping () async -> Void = { @MainActor in + SparkManager.shared.discardStagedExitState(walletIndex: LightningService.shared.currentWalletIndex) + }, + restoreExitBackup: @escaping (SparkExitBackupV1) async throws -> Void = { @MainActor backup in + try await SparkManager.shared.restoreExitBackup(backup, walletIndex: LightningService.shared.currentWalletIndex) } ) { self.defaults = defaults + self.importStagedSparkExit = importStagedSparkExit + self.discardStagedSparkExit = discardStagedSparkExit + self.restoreExitBackup = restoreExitBackup self.isSparkExitActive = isSparkExitActive self.fetchBackup = fetchBackup self.backupData = backupData @@ -434,9 +451,16 @@ class BackupService { await restoreSparkExit() } guard !defaults.bool(forKey: Self.sparkExitRestorePendingKey) else { throw SparkExitBackupError.restorePending } - // Restored exit data Spark couldn't import yet lives only in the remote backup, so nothing replaces it. - guard await !SparkManager.shared.hasStagedExitState(walletIndex: LightningService.shared.currentWalletIndex) else { + // Restored exit data Spark couldn't import yet lives only in the remote backup, so nothing replaces it, unless + // Spark can never import it: then the remote copy is set aside and fresh exports go up again. + switch await importStagedSparkExit() { + case .pending: throw SparkExitBackupError.restorePending + case .rejected: + try await setAsideRejectedSparkExit(fetchBackup(BackupCategory.sparkExit.rawValue)) + await discardStagedSparkExit() + case .nothingStaged, .imported: + break } // Nothing to back up until Spark connects, which marks this category required again. if let data = try await sparkExitBackupData() { @@ -1468,8 +1492,17 @@ class BackupService { defaults.set(true, forKey: Self.sparkExitRestorePendingKey) do { if let data = try await fetchBackup(BackupCategory.sparkExit.rawValue) { - let backup = try JSONDecoder().decode(SparkExitBackupV1.self, from: data) - try await SparkManager.shared.restoreExitBackup(backup, walletIndex: LightningService.shared.currentWalletIndex) + let backup: SparkExitBackupV1 + do { + backup = try JSONDecoder().decode(SparkExitBackupV1.self, from: data) + } catch let error as DecodingError { + // A layout this app can't read never becomes readable here, so it is kept apart for an app that can. + Logger.warn("Unreadable '\(BackupCategory.sparkExit.rawValue)' backup: \(error)", context: "BackupService") + try await setAsideRejectedSparkExit(data) + defaults.removeObject(forKey: Self.sparkExitRestorePendingKey) + return + } + try await restoreExitBackup(backup) Logger.info("Restore success for: '\(BackupCategory.sparkExit.rawValue)'", context: "BackupService") } else { Logger.warn("Restore null for: '\(BackupCategory.sparkExit.rawValue)'", context: "BackupService") @@ -1480,6 +1513,18 @@ class BackupService { } } + /// Keeps remote exit data Spark can never import under its own key, so a fresh export doesn't replace it and an app that + /// can import it still finds it. The first such copy stays; a later one doesn't overwrite it. + private func setAsideRejectedSparkExit(_ data: Data?) async throws { + guard let data else { return } + guard try await fetchBackup(Self.sparkExitRejectedKey) == nil else { + Logger.info("Kept the earlier '\(Self.sparkExitRejectedKey)' backup", context: "BackupService") + return + } + try await uploadBackup(Self.sparkExitRejectedKey, data) + Logger.warn("Set Spark exit data Spark can't import aside as '\(Self.sparkExitRejectedKey)'", context: "BackupService") + } + /// Nothing while an exit runs: the operators may stop reporting a leaf once it is being exited, so a fresh export /// could drop the very leaf a restored wallet needs. The backup from before the exit stays. private func sparkExitBackupData() async throws -> Data? { diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 8c0664faf0..b5f1d90757 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1235,6 +1235,9 @@ class LightningService: NodeLifecycleService { /// were submitted or failed in seconds since 1970. Kept across launches, as Spark may still resume one after a /// relaunch while its list shows an earlier failed attempt. private static let uncertainRailSendsKey = "channelFreeRailUncertainSendFailedAt" + /// When each of those sends was submitted, in seconds since 1970, so a failure Spark reports for a payment it created + /// before then is known to belong to an earlier attempt. + private static let uncertainRailSendsStartedKey = "channelFreeRailUncertainSendStartedAt" /// A listing drops the hashes it shows failed only, or paid once the invoice has expired, so the other rail can't /// pay it again, and ones it doesn't show once the invoice expired `unlistedAttemptSettleSeconds` ago. Paid or /// unlisted hashes with no known expiry (kept before expiries were, or whose invoice can't be parsed) are dropped @@ -1426,6 +1429,7 @@ class LightningService: NodeLifecycleService { func forgetRailAttempts() { eventCallbackLock.withLock { railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsKey) + railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsStartedKey) railAttemptsStore.removeObject(forKey: Self.railAttemptsKey) railAttemptsStore.removeObject(forKey: Self.expiriesKey(Self.railAttemptsKey)) attemptRecordedAt[Self.railAttemptsKey] = nil @@ -1655,11 +1659,31 @@ class LightningService: NodeLifecycleService { eventCallbackLock.withLock { guard attemptsRecorded(since: mark.records, key: Self.railAttemptsKey).contains(hash) else { return } var uncertain = uncertainRailSendFailedAt() + if uncertain[hash] == nil { + var started = uncertainRailSendStartedAt() + started[hash] = failedAt + railAttemptsStore.set(started, forKey: Self.uncertainRailSendsStartedKey) + } uncertain[hash] = failedAt railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) } } + /// Callers hold `eventCallbackLock`. + private func uncertainRailSendStartedAt() -> [String: Int] { + railAttemptsStore.dictionary(forKey: Self.uncertainRailSendsStartedKey) as? [String: Int] ?? [:] + } + + /// Whether Spark created the payment of a failure at `createdAt` before the send of `paymentHash` still in doubt went + /// out: the failure ended an earlier attempt, and Spark may still finish the later one. + func isEarlierThanUncertainRailSend(paymentHash: String, createdAt: UInt64) -> Bool { + eventCallbackLock.withLock { + let hash = paymentHash.lowercased() + guard uncertainRailSendFailedAt()[hash] != nil, let startedAt = uncertainRailSendStartedAt()[hash] else { return false } + return createdAt < UInt64(max(0, startedAt)) + } + } + /// Rail sends whose outcome stayed unknown, listed as pending until a sync after them reaches the rail: Spark may /// still finish one, while its own list shows only an earlier attempt, or nothing. private func unsettledUncertainRailSends() async -> [ChannelFreeRailPayment] { @@ -1686,6 +1710,10 @@ class LightningService: NodeLifecycleService { private func endRailSendUncertainty(paymentHash: String) { eventCallbackLock.withLock { + var started = uncertainRailSendStartedAt() + if started.removeValue(forKey: paymentHash.lowercased()) != nil { + railAttemptsStore.set(started, forKey: Self.uncertainRailSendsStartedKey) + } var uncertain = uncertainRailSendFailedAt() guard uncertain.removeValue(forKey: paymentHash.lowercased()) != nil else { return } railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) @@ -2331,7 +2359,14 @@ extension LightningService { } /// Spark runs before the node starts, so its events wait until the node's event callback is set rather than being lost. - func emitChannelFreeRailEvent(_ event: Event) { + /// `paymentCreatedAt` is when Spark created the payment the event is about, in seconds since 1970. + func emitChannelFreeRailEvent(_ event: Event, paymentCreatedAt: UInt64? = nil) { + if case let .paymentFailed(_, paymentHash?, _) = event, let paymentCreatedAt, + isEarlierThanUncertainRailSend(paymentHash: paymentHash, createdAt: paymentCreatedAt) + { + Logger.info("Ignored a Spark failure of an attempt before the send still in doubt: \(event)", context: "LightningService") + return + } switch event { case let .paymentFailed(_, paymentHash?, _): // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. diff --git a/Bitkit/ViewModels/SparkTransferFlow.swift b/Bitkit/ViewModels/SparkTransferFlow.swift index ed8a6f19bd..b2c25acb5b 100644 --- a/Bitkit/ViewModels/SparkTransferFlow.swift +++ b/Bitkit/ViewModels/SparkTransferFlow.swift @@ -133,6 +133,8 @@ enum SparkClaimDecision { struct SparkClaimOperations { var offer: (String) async throws -> SparkClaimOffer? var claimEarly: (SparkClaimOffer) async throws -> SparkEarlyClaim + /// Whether Spark still lists the deposit as unclaimed, without asking the provider for a quote. + var isUnclaimed: (String) async throws -> Bool var refresh: () async -> Void var sleep: (Duration) async -> Void /// Clears the early-claim fee cap `claimEarly` left on the deposit, so only the claim at maturity is made. False when @@ -143,6 +145,7 @@ struct SparkClaimOperations { SparkClaimOperations( offer: { try await SparkManager.shared.depositClaimOffer(txid: $0) }, claimEarly: { try await SparkManager.shared.claimEarly($0) }, + isUnclaimed: { try await SparkManager.shared.isDepositUnclaimed(txid: $0) }, refresh: { await SparkManager.shared.refreshState() }, sleep: { try? await Task.sleep(for: $0) }, releaseEarlyClaim: { await SparkManager.shared.releaseEarlyClaim($0) } @@ -486,11 +489,25 @@ final class SparkTransferFlow { } private func pollDeposit(txid: String) async { + // After a waiting claim the fee ceiling stays on the deposit and Spark claims it early by itself once the provider + // offers it, so the poll only watches for the claim instead of quoting again. + var isClaimLeftToSpark = false for _ in 0 ..< pollAttempts { if Task.isCancelled { return } do { + if isClaimLeftToSpark { + let isUnclaimed = try await operations.isUnclaimed(txid) + guard !Task.isCancelled else { return } + if !isUnclaimed { + setClaimState(.added, for: txid) + return + } + await operations.refresh() + await operations.sleep(Self.pollInterval) + continue + } let found = try await operations.offer(txid) guard !Task.isCancelled else { return } if found == nil, offers[txid] != nil { @@ -513,6 +530,7 @@ final class SparkTransferFlow { setClaimState(state, for: txid) return } + isClaimLeftToSpark = true } } catch { Logger.warn("Failed to claim Spark deposit \(txid) early: \(error)", context: "SparkTransferFlow") diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 56f222a972..14eb476235 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -812,6 +812,32 @@ extension ChannelFreeRailTests { await assertReachesTheNode() } + func testALateFailureOfAnEarlierAttemptKeepsARetryInDoubtHeld() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: 1000) } + rail.balanceSats = 100_000 + rail.errorAfterSubmission = NSError(domain: "spark", code: 2) + _ = try? await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + rail.errorAfterSubmission = nil + rail.syncedAfter = { ($0 ?? 0) < 1000 } + rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil)] + rail.balanceSats = 0 + + // Spark reports the failure of a payment it created before this send went out. + Bitkit.LightningService.shared.emitChannelFreeRailEvent( + .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), + paymentCreatedAt: 900 + ) + await assertRefusedAsDuplicate() + + // The failure of the send itself ends the hold. + Bitkit.LightningService.shared.emitChannelFreeRailEvent( + .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), + paymentCreatedAt: 1000 + ) + await assertReachesTheNode() + } + func testAnUnknownSparkSendStaysHeldAfterARelaunchWhenSparkListsOnlyAnOlderFailedAttempt() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared diff --git a/BitkitTests/SparkExitBackupTests.swift b/BitkitTests/SparkExitBackupTests.swift index cf102eb526..df0b90ad06 100644 --- a/BitkitTests/SparkExitBackupTests.swift +++ b/BitkitTests/SparkExitBackupTests.swift @@ -1,4 +1,5 @@ @testable import Bitkit +import BreezSdkSpark import XCTest @MainActor @@ -135,7 +136,7 @@ final class SparkExitBackupTests: XCTestCase { XCTAssertTrue(uploads.isEmpty, "A fresh export replaced the remote backup whose exit data Spark hasn't imported") } - func testAnUnreadableRemoteExitBackupBacksOffInsteadOfRetryingEveryFewSeconds() async throws { + func testAnUnreachableRemoteExitBackupBacksOffInsteadOfRetryingEveryFewSeconds() async throws { let suite = "SparkExitBackupTests.\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) defer { defaults.removePersistentDomain(forName: suite) } @@ -144,7 +145,7 @@ final class SparkExitBackupTests: XCTestCase { defaults: defaults, backupData: { _ in export }, uploadBackup: { _, _ in }, - fetchBackup: { _ in Data("not an exit backup".utf8) } + fetchBackup: { _ in throw URLError(.notConnectedToInternet) } ) await service.restoreSparkExit() @@ -153,6 +154,89 @@ final class SparkExitBackupTests: XCTestCase { XCTAssertEqual(outcome, .temporarilyUnavailable) } + func testAnUnreadableRemoteExitBackupIsSetAsideAndBackupsGoOn() async throws { + let suite = "SparkExitBackupTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let export = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 1000, network: "regtest", exitState: "fresh")) + let unreadable = Data("{\"version\":2}".utf8) + var remote = ["SPARK_EXIT": unreadable] + let service = BackupService( + defaults: defaults, + backupData: { _ in export }, + uploadBackup: { remote[$0] = $1 }, + fetchBackup: { remote[$0] } + ) + + await service.restoreSparkExit() + let outcome = await service.triggerBackup(category: .sparkExit) + + XCTAssertEqual(outcome, .completed) + XCTAssertEqual(remote["SPARK_EXIT_REJECTED"], unreadable, "The exit data this app can't read was lost") + XCTAssertEqual(remote["SPARK_EXIT"], export) + } + + func testExitDataSparkRejectsIsSetAsideAndBackupsGoOn() async throws { + let suite = "SparkExitBackupTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let restored = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 900, network: "regtest", exitState: "newer")) + let export = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 1000, network: "regtest", exitState: "fresh")) + var remote = ["SPARK_EXIT": restored] + var staged: SparkStagedExitImport = .pending + let service = BackupService( + defaults: defaults, + backupData: { _ in export }, + uploadBackup: { remote[$0] = $1 }, + waitForTemporaryFailureDelay: { _ in }, + fetchBackup: { remote[$0] }, + importStagedSparkExit: { staged }, + discardStagedSparkExit: { staged = .nothingStaged }, + restoreExitBackup: { _ in } + ) + + await service.restoreSparkExit() + _ = await service.triggerBackup(category: .sparkExit) + XCTAssertEqual(remote["SPARK_EXIT"], restored, "A transient import failure let a fresh export replace the remote copy") + XCTAssertNil(remote["SPARK_EXIT_REJECTED"]) + + staged = .rejected + let outcome = await service.triggerBackup(category: .sparkExit) + + XCTAssertEqual(outcome, .completed) + XCTAssertEqual(staged, .nothingStaged) + XCTAssertEqual(remote["SPARK_EXIT_REJECTED"], restored) + XCTAssertEqual(remote["SPARK_EXIT"], export) + } + + func testAnEarlierRejectedCopyIsNotOverwritten() async throws { + let suite = "SparkExitBackupTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let export = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 1000, network: "regtest", exitState: "fresh")) + let earlier = Data("earlier".utf8) + var remote = ["SPARK_EXIT": Data("later".utf8), "SPARK_EXIT_REJECTED": earlier] + var staged: SparkStagedExitImport = .rejected + let service = BackupService( + defaults: defaults, + backupData: { _ in export }, + uploadBackup: { remote[$0] = $1 }, + fetchBackup: { remote[$0] }, + importStagedSparkExit: { staged }, + discardStagedSparkExit: { staged = .nothingStaged } + ) + + _ = await service.triggerBackup(category: .sparkExit) + + XCTAssertEqual(remote["SPARK_EXIT_REJECTED"], earlier) + XCTAssertEqual(remote["SPARK_EXIT"], export) + } + + func testOnlyInvalidInputMarksExitDataAsRejected() { + XCTAssertEqual(SparkStagedExitImport(importError: SdkError.InvalidInput("unsupported exit state version")), .rejected) + XCTAssertEqual(SparkStagedExitImport(importError: URLError(.notConnectedToInternet)), .pending) + } + func testTheLatestBackupTimeSkipsTheExitData() { XCTAssertFalse(BackupService.latestBackupTimeCategories.contains(.sparkExit), "Reading the time downloads the exit data") XCTAssertTrue(BackupService.latestBackupTimeCategories.contains(.wallet)) diff --git a/BitkitTests/SparkTransferFlowTests.swift b/BitkitTests/SparkTransferFlowTests.swift index dfa68e491d..3967b49dc5 100644 --- a/BitkitTests/SparkTransferFlowTests.swift +++ b/BitkitTests/SparkTransferFlowTests.swift @@ -75,6 +75,7 @@ final class SparkTransferFlowTests: XCTestCase { earlyFeeSats: 900, earlyConfirmations: 0, standardFeeSats: 198, standardConfirmations: 3 )) }, claimEarly: { _ in .repriced(requiredFeeSats: 1500) }, + isUnclaimed: { _ in true }, refresh: {}, sleep: { _ in }, releaseEarlyClaim: { released.append($0.txid) @@ -103,6 +104,7 @@ final class SparkTransferFlowTests: XCTestCase { earlyFeeSats: 900, earlyConfirmations: 0, standardFeeSats: 198, standardConfirmations: 3 )) }, claimEarly: { _ in .repriced(requiredFeeSats: 1500) }, + isUnclaimed: { _ in true }, refresh: {}, sleep: { _ in }, releaseEarlyClaim: { _ in @@ -132,6 +134,7 @@ final class SparkTransferFlowTests: XCTestCase { earlyFeeSats: 1500, earlyConfirmations: 0, standardFeeSats: 198, standardConfirmations: 3 )) }, claimEarly: { _ in .claimed }, + isUnclaimed: { _ in true }, refresh: {}, sleep: { _ in }, releaseEarlyClaim: { released.append($0.txid) @@ -159,30 +162,34 @@ final class SparkTransferFlowTests: XCTestCase { @MainActor func testListedDepositWhoseEarlyClaimKeepsWaitingIsNotUnseen() async { - let flow = pollingFlow( - offers: [choice(earlyFee: 900), choice(earlyFee: 900), choice(earlyFee: 900)], - claims: [.waiting, .waiting, .waiting], - pollAttempts: 3 - ) + let calls = PollCalls() + let flow = pollingFlow(offers: [choice(earlyFee: 900)], claims: [.waiting], pollAttempts: 3, calls: calls) flow.onBroadcast(txid: "txid") await flow.waitForClaim() XCTAssertEqual(flow.claimState, .unavailable) + XCTAssertEqual(calls.offers, 1, "A waiting claim asked the provider for a quote again") + XCTAssertEqual(calls.claims, 1) + XCTAssertEqual(calls.unclaimedChecks, 2) } @MainActor func testDepositListedThenGoneWasAdded() async { - let flow = pollingFlow(offers: [choice(earlyFee: 900), nil], claims: [.waiting]) + let flow = pollingFlow(offers: [choice(earlyFee: 900)], claims: [.waiting], unclaimed: [false]) flow.onBroadcast(txid: "txid") await flow.waitForClaim() XCTAssertEqual(flow.claimState, .added) } @MainActor - func testWaitingKeepsPollingUntilClaimed() async { - let flow = pollingFlow(offers: [choice(earlyFee: 900), choice(earlyFee: 900)], claims: [.waiting, .claimed]) + func testWaitingWatchesTheDepositUntilSparkClaimsIt() async { + let calls = PollCalls() + let flow = pollingFlow(offers: [choice(earlyFee: 900)], claims: [.waiting], unclaimed: [true, false], pollAttempts: 5, calls: calls) flow.onBroadcast(txid: "txid") await flow.waitForClaim() XCTAssertEqual(flow.claimState, .added) + XCTAssertEqual(calls.offers, 1) + XCTAssertEqual(calls.claims, 1) + XCTAssertEqual(calls.unclaimedChecks, 2) } @MainActor @@ -220,6 +227,7 @@ final class SparkTransferFlowTests: XCTestCase { claimed.append(offer.txid) return .claimed }, + isUnclaimed: { _ in true }, refresh: {}, sleep: { _ in } ) @@ -475,17 +483,39 @@ final class SparkTransferFlowTests: XCTestCase { ) } - /// A flow whose poll answers with `offers` in turn (nil once they run out) and whose claims answer with `claims`. + private final class PollCalls { + var offers = 0 + var claims = 0 + var unclaimedChecks = 0 + } + + /// A flow whose poll answers with `offers` in turn (nil once they run out), whose claims answer with `claims`, and + /// whose unclaimed checks answer with `unclaimed` (still unclaimed once they run out). @MainActor - private func pollingFlow(offers: [SparkClaimOffer.Kind?], claims: [SparkEarlyClaim] = [], pollAttempts: Int? = nil) -> SparkTransferFlow { + private func pollingFlow( + offers: [SparkClaimOffer.Kind?], + claims: [SparkEarlyClaim] = [], + unclaimed: [Bool] = [], + pollAttempts: Int? = nil, + calls: PollCalls = PollCalls() + ) -> SparkTransferFlow { var offers = offers var claims = claims + var unclaimed = unclaimed let operations = SparkClaimOperations( offer: { txid in + calls.offers += 1 guard !offers.isEmpty, let kind = offers.removeFirst() else { return nil } return SparkClaimOffer(txid: txid, vout: 0, kind: kind) }, - claimEarly: { _ in claims.isEmpty ? .waiting : claims.removeFirst() }, + claimEarly: { _ in + calls.claims += 1 + return claims.isEmpty ? .waiting : claims.removeFirst() + }, + isUnclaimed: { _ in + calls.unclaimedChecks += 1 + return unclaimed.isEmpty ? true : unclaimed.removeFirst() + }, refresh: {}, sleep: { _ in } ) From 3c61996c7848acff0da4c1399782ea2242a7f084 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 15:06:37 +0100 Subject: [PATCH 03/64] fix: move to spark rows kept across restore, spark copy translated --- Bitkit/Managers/MoveToSparkManager.swift | 56 ++++++++++++------- Bitkit/Models/BackupPayloads.swift | 8 ++- .../Localization/ar.lproj/Localizable.strings | 35 +++++++++++- .../Localization/ca.lproj/Localizable.strings | 37 +++++++++++- .../Localization/cs.lproj/Localizable.strings | 34 ++++++++++- .../Localization/de.lproj/Localizable.strings | 36 +++++++++++- .../Localization/el.lproj/Localizable.strings | 35 +++++++++++- .../es-419.lproj/Localizable.strings | 34 ++++++++++- .../Localization/es.lproj/Localizable.strings | 35 +++++++++++- .../Localization/fr.lproj/Localizable.strings | 36 +++++++++++- .../Localization/it.lproj/Localizable.strings | 37 +++++++++++- .../Localization/nl.lproj/Localizable.strings | 34 ++++++++++- .../Localization/pl.lproj/Localizable.strings | 34 ++++++++++- .../pt-BR.lproj/Localizable.strings | 34 ++++++++++- .../Localization/pt.lproj/Localizable.strings | 35 +++++++++++- .../Localization/ru.lproj/Localizable.strings | 35 +++++++++++- Bitkit/Services/BackupService.swift | 20 +++++-- Bitkit/Services/CoreService.swift | 5 ++ Bitkit/ViewModels/AppViewModel.swift | 1 - BitkitTests/ChannelFreeRailTests.swift | 4 +- BitkitTests/MoveToSparkQuoteTests.swift | 38 +++++++++---- Docs/RELEASE.md | 2 +- changelog.d/next/1249.fixed.md | 1 + journeys/transfer/move-to-spark.xml | 3 +- 24 files changed, 571 insertions(+), 58 deletions(-) create mode 100644 changelog.d/next/1249.fixed.md diff --git a/Bitkit/Managers/MoveToSparkManager.swift b/Bitkit/Managers/MoveToSparkManager.swift index 498a035052..7c33d2bc94 100644 --- a/Bitkit/Managers/MoveToSparkManager.swift +++ b/Bitkit/Managers/MoveToSparkManager.swift @@ -1,4 +1,5 @@ import BitkitCore +import Combine import Foundation import LDKNode @@ -75,10 +76,12 @@ struct MoveToSparkQuote: Equatable { let feeSats: UInt64 } +@MainActor extension LightningActivity { - /// The channel send of a move to Spark, which Activity shows as a transfer rather than a payment. + /// The channel send of a move to Spark, which Activity shows as a transfer rather than a payment. Known by its payment + /// hash, so a paid outside invoice that happens to carry the move's description stays a payment. var isMoveToSpark: Bool { - txType == .sent && message == MoveToSparkMath.invoiceDescription + txType == .sent && MoveToSparkPayments.contains(id) } } @@ -90,42 +93,56 @@ enum MoveToSparkError: Error { } /// The payments that move a channel balance to Spark, whose send and receive the app does not announce as payments. -/// Kept on disk, so a move that settles after a relaunch is still known as one. +/// Kept on disk until a wipe and in the metadata backup, so a move that settles after a relaunch, and its Activity row after +/// a restore, stay known as one. @MainActor enum MoveToSparkPayments { private static let storageKey = "moveToSparkPaymentHashes" - /// Far beyond the move invoice's expiry, so Spark reporting a receive late, after a relaunch, still finds its move. - static let retention: TimeInterval = 30 * 24 * 60 * 60 static var defaults: UserDefaults = .standard + /// Outside the main actor, so the backup observers can subscribe from anywhere. + nonisolated static var savedPublisher: AnyPublisher { + MoveToSparkPaymentsSaved.subject.eraseToAnyPublisher() + } static func insert(_ paymentHash: String, now: Date = Date()) { - var hashes = stored(now: now) + var hashes = stored hashes[paymentHash.lowercased()] = now.timeIntervalSince1970 defaults.set(hashes, forKey: storageKey) + MoveToSparkPaymentsSaved.subject.send() } - static func contains(_ paymentHash: String?, now: Date = Date()) -> Bool { - paymentHash.map { stored(now: now)[$0.lowercased()] != nil } ?? false + /// Sorted, so an unchanged store backs up byte for byte the same. + static func backupSnapshot() -> [String] { + stored.keys.sorted() } - /// Forgets a move whose payment failed: its amount stays in the channel, and Spark receives nothing for it. - static func remove(_ paymentHash: String?, now: Date = Date()) { - guard let paymentHash else { return } - var hashes = stored(now: now) - guard hashes.removeValue(forKey: paymentHash.lowercased()) != nil else { return } + /// Adds the restored hashes to any already known. + static func restore(_ paymentHashes: [String]?, now: Date = Date()) { + guard let paymentHashes, !paymentHashes.isEmpty else { return } + var hashes = stored + for hash in paymentHashes where hashes[hash.lowercased()] == nil { + hashes[hash.lowercased()] = now.timeIntervalSince1970 + } defaults.set(hashes, forKey: storageKey) } + static func contains(_ paymentHash: String?) -> Bool { + paymentHash.map { stored[$0.lowercased()] != nil } ?? false + } + static func removeAll() { defaults.removeObject(forKey: storageKey) } - private static func stored(now: Date) -> [String: Double] { - let hashes = defaults.dictionary(forKey: storageKey) as? [String: Double] ?? [:] - return hashes.filter { now.timeIntervalSince1970 - $0.value < retention } + private static var stored: [String: Double] { + defaults.dictionary(forKey: storageKey) as? [String: Double] ?? [:] } } +private enum MoveToSparkPaymentsSaved { + static let subject = PassthroughSubject() +} + /// What a move quote needs from Spark and the channels, apart so the quote can be tested without either. protocol MoveToSparkServices { @MainActor var isSparkUsable: Bool { get } @@ -262,11 +279,9 @@ final class MoveToSparkManager { } } state = .confirm(quote, isMoving: true) - var paymentHash: String? do { - let hash = try String(describing: Bolt11Invoice.fromStr(invoiceStr: quote.invoice).paymentHash()) - paymentHash = hash - MoveToSparkPayments.insert(hash) + let paymentHash = try Bolt11Invoice.fromStr(invoiceStr: quote.invoice).paymentHash() + MoveToSparkPayments.insert(String(describing: paymentHash)) guard let settled = try await wallet.sendOverChannels( bolt11: quote.invoice, sats: quote.amountSats, @@ -295,7 +310,6 @@ final class MoveToSparkManager { state = Self.doneState(amountSats: quote.amountSats, feeSats: settled.feePaidSats, channels: wallet.channels) } catch { Logger.error("Failed to move '\(quote.amountSats)' sats to Spark: \(error)", context: "MoveToSpark") - MoveToSparkPayments.remove(paymentHash) guard moveGeneration == generation else { return } state = Self.isNoRoute(error) || Self.isSendWithoutRoute(error, invoice: quote.invoice) ? .tooLarge(amountSats: quote.amountSats, smallerSats: MoveToSparkMath.smallerAmount(quote.amountSats)) diff --git a/Bitkit/Models/BackupPayloads.swift b/Bitkit/Models/BackupPayloads.swift index 628345dcd7..da908490d7 100644 --- a/Bitkit/Models/BackupPayloads.swift +++ b/Bitkit/Models/BackupPayloads.swift @@ -30,6 +30,9 @@ struct MetadataBackupV1: Codable { /// The earlier Spark exit addresses each wallet watches, keyed `/wallet` as bitkit-android keys them. /// Nil in envelopes written before this field. var sparkExitEarlierAddresses: [String: [SparkExitEarlierAddressBackupV1]]? + /// The payment hashes of moves to Spark, lowercase hex, which Activity shows as transfers. Nil in envelopes written + /// before this field. + var moveToSparkPaymentHashes: [String]? init( version: Int, @@ -39,7 +42,8 @@ struct MetadataBackupV1: Codable { pubkySession: PubkySessionBackupV1?, pubkyContactProfileOverrides: [String: PubkyProfileData]?, hwWalletNames: [String: String]? = nil, - sparkExitEarlierAddresses: [String: [SparkExitEarlierAddressBackupV1]]? = nil + sparkExitEarlierAddresses: [String: [SparkExitEarlierAddressBackupV1]]? = nil, + moveToSparkPaymentHashes: [String]? = nil ) { self.version = version self.createdAt = createdAt @@ -49,6 +53,7 @@ struct MetadataBackupV1: Codable { self.pubkyContactProfileOverrides = pubkyContactProfileOverrides self.hwWalletNames = hwWalletNames self.sparkExitEarlierAddresses = sparkExitEarlierAddresses + self.moveToSparkPaymentHashes = moveToSparkPaymentHashes } } @@ -67,6 +72,7 @@ extension MetadataBackupV1 { [String: [SparkExitEarlierAddressBackupV1]].self, forKey: .sparkExitEarlierAddresses ) + moveToSparkPaymentHashes = try? c.decodeIfPresent([String].self, forKey: .moveToSparkPaymentHashes) } } diff --git a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings index 21e322b2a8..818bf8f82b 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -200,6 +200,7 @@ "lightning__spending_intro__text" = "حوّل الأموال إلى رصيد إنفاقك للاستمتاع بمعاملات فورية ورخيصة مع الأصدقاء والعائلة والتجار."; "lightning__spending_intro__button" = "ابدأ"; "lightning__spending_amount__quarter" = "25%"; +"lightning__spending_amount__error_min__title" = "الحد الأدنى لرصيد المدخرات"; "lightning__spending_amount__error_max__title" = "الحد الأقصى لرصيد الإنفاق"; "lightning__spending_amount__error_max__description" = "المبلغ الذي يمكنك تحويله إلى رصيد الإنفاق محدود حاليًا بـ ₿ {amount}."; "lightning__spending_amount__error_fee" = "تعذّر الحصول على رسوم الشبكة. انقر للمحاولة مرة أخرى."; @@ -305,6 +306,29 @@ "lightning__transaction" = "المعاملة"; "lightning__order_fee" = "رسوم الطلب"; "lightning__balance" = "الرصيد"; +"lightning__move_to_spark__amount" = "المبلغ"; +"lightning__move_to_spark__confirm_text" = "يُنقل رصيدك إلى Spark عبر Lightning، وهي الطريقة الأقل رسومًا لإبقائه في الإنفاق. رسوم التوجيه أدناه هي الحد الأقصى الذي تدفعه."; +"lightning__move_to_spark__confirm_title" = "النقل إلى\nSpark"; +"lightning__move_to_spark__done_rest_text" = "أصبح جزء من رصيدك على Spark الآن. انقل الباقي بالطريقة نفسها، ثم أغلق الاتصال الذي أُفرغ."; +"lightning__move_to_spark__done_text" = "أصبح رصيدك على Spark الآن. أغلق الاتصال الذي أُفرغ لإعادة احتياطيه إلى المدخرات."; +"lightning__move_to_spark__done_title" = "تم النقل إلى\nSpark"; +"lightning__move_to_spark__failed_nothing" = "لم يتبقَّ في اتصالات Lightning الخاصة بك أي رصيد لنقله."; +"lightning__move_to_spark__failed_spark" = "Spark غير جاهز للاستلام بعد. حاول مرة أخرى بعد لحظات."; +"lightning__move_to_spark__failed_title" = "تعذّر\nالنقل"; +"lightning__move_to_spark__failed_unknown" = "حدث خطأ أثناء التحضير للنقل. حاول مرة أخرى."; +"lightning__move_to_spark__fee" = "رسوم التوجيه"; +"lightning__move_to_spark__intro_text" = "تُغلق Blocktank اتصالات Lightning الخاصة بها. انقل رصيدك إلى Spark الآن: إنه الخيار الأقل رسومًا، ويبقى في الإنفاق."; +"lightning__move_to_spark__intro_title" = "اتصالك\nقيد الإغلاق"; +"lightning__move_to_spark__move_half" = "انقل النصف"; +"lightning__move_to_spark__move_now" = "انقل الآن"; +"lightning__move_to_spark__move_rest" = "انقل الباقي"; +"lightning__move_to_spark__nav_title" = "النقل إلى Spark"; +"lightning__move_to_spark__quoting" = "جارٍ البحث عن مسار ورسومه…"; +"lightning__move_to_spark__swipe" = "اسحب للنقل"; +"lightning__move_to_spark__too_large_none" = "أغلق الاتصال بدلاً من ذلك لإعادة الرصيد إلى المدخرات."; +"lightning__move_to_spark__too_large_smaller" = "يمكنك نقله على دفعات أصغر."; +"lightning__move_to_spark__too_large_text" = "المبلغ {amount} كبير جدًا لتوجيهه إلى Spark في دفعة واحدة."; +"lightning__move_to_spark__too_large_title" = "المبلغ\nكبير جدًا"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "رسوم المطالبة"; "lightning__spark_confirmations" = "{count}/3 تأكيدات"; @@ -358,6 +382,9 @@ "lightning__spark_exit__leftover_swept" = "أُرسل {amount} من رسوم الطوارئ غير المستخدمة إلى المدخرات."; "lightning__spark_exit__leftover_sending" = "جارٍ إرسال {amount} من رسوم الطوارئ غير المستخدمة إلى المدخرات."; "lightning__spark_exit__leftover_dust" = "{amount} من رسوم الطوارئ غير المستخدمة أصغر من أن يُرسل ويبقى في {address}، مسار الاشتقاق {path}."; +"lightning__spark_exit__earlier_addresses" = "عناوين الخروج السابقة"; +"lightning__spark_exit__earlier_addresses_text" = "استخدمت عمليات الخروج الطارئ السابقة عناوين التمويل هذه. تبقى العملات المتروكة في أحدها ملكًا لك: أنفقها باستخدام عبارة الاسترداد ومسار الاشتقاق."; +"lightning__spark_exit__earlier_path" = "مسار الاشتقاق"; "lightning__spark_exit__lost_leaves" = "طالب مالك سابق لهذه الأموال بمبلغ {amount} على السلسلة ولا يمكن استرداده."; "lightning__spark_exit__notification_lost" = "لا يمكن استرداد {amount} من تحويلك القسري. افتح Bitkit لمعرفة السبب."; "lightning__spark_exit__notification_failed" = "توقف التحويل القسري. افتح Bitkit لمعرفة السبب."; @@ -380,6 +407,7 @@ "lightning__spark_exit__rebuilt_from_chain" = "تعذّر على Bitkit قراءة التقدم المحفوظ لهذا التحويل، لذا يعيد بناءه من السلسلة."; "lightning__spark_exit__leftover_rejected" = "تعذّر إرسال {amount} من رسوم الطوارئ غير المستخدمة ويبقى في {address}، مسار الاشتقاق {path}."; "lightning__spark_exit__notification_not_moving" = "التحويل القسري لا يتقدم. افتح Bitkit لمعرفة السبب."; +"lightning__spark_exit__note_notifications_button" = "تفعيل الإشعارات"; "lightning__spark_exit__waiting_operators" = "{amount} الذي نقله مشغّلو Spark إلى السلسلة ينتظر أن يحرروه. يطلب Bitkit ذلك مجددًا لمدة تصل إلى أسبوع."; "lightning__spark_exit__fee_rose" = "ارتفعت رسوم الشبكة فوق رسوم هذا التحويل. قد يتباطأ."; "lightning__spark_exit__fee_bump_button" = "ادفع رسومًا أعلى"; @@ -863,6 +891,7 @@ "wallet__payment_recipient_rejected" = "رفض المستلم دفعة Lightning هذه. تحقق من الفاتورة وحاول مرة أخرى."; "wallet__payment_abandoned" = "تم إيقاف دفعة Lightning قبل اكتمالها."; "wallet__payment_expired" = "انتهت صلاحية دفعة Lightning هذه. اطلب فاتورة جديدة."; +"wallet__payment_restored_invoice" = "لا يستطيع Bitkit التأكد من أن هذه الفاتورة لم تُدفع قبل استعادة محفظتك. يرجى طلب فاتورة جديدة."; "wallet__payment_timeout" = "انتهت مهلة الدفع. حاول مرة أخرى."; "wallet__payment_route_not_found" = "لم يتمكن Bitkit من العثور على مسار Lightning لهذه الدفعة."; "wallet__payment_retries_exhausted" = "جرّب Bitkit عدة مسارات Lightning، لكن تعذر إكمال الدفعة."; @@ -889,7 +918,7 @@ "wallet__receive_note_placeholder" = "ملاحظة اختيارية للدافع"; "wallet__receive_show_qr" = "عرض رمز QR"; "wallet__receive_spending" = "استلام أموال Lightning"; -"wallet__receive_spending_text" = "استمتع بمدفوعات Bitcoin فورية ورخيصة على شبكة Lightning."; +"wallet__receive_spending_text" = "استمتع بمعاملات فورية ورخيصة مع الأصدقاء والعائلة والتجار."; "wallet__receive_spending_title" = "استلم على رصيد الإنفاق"; "settings__backup__category_contacts" = "جهات الاتصال"; "settings__support__title" = "الدعم"; @@ -1183,6 +1212,7 @@ "wallet__swap_route_restored_title" = "أُعيدت الدفعة إلى المدخرات"; "wallet__send_paykit_no_route__title" = "تعذّر الدفع لجهة الاتصال هذه"; "wallet__send_paykit_no_route__description" = "ليس لدى جهة الاتصال هذه طريقة دفع يمكن لـ Bitkit استخدامها حاليًا."; +"wallet__send_paykit_withdrawal_settling__description" = "لا تزال عملية سحب سابقة من رصيد الإنفاق قيد التسوية. حاول مرة أخرى بعد اكتمالها."; "wallet__recipient_contact" = "جهة الاتصال"; "wallet__recipient_invoice" = "لصق فاتورة"; "wallet__recipient_manual" = "إدخال يدوي"; @@ -1688,6 +1718,7 @@ "wallet__activity_failed" = "فشلت"; "wallet__activity_transfer" = "تحويل"; "wallet__activity_transferring" = "جارٍ التحويل"; +"wallet__activity_move_to_spark" = "النقل إلى Spark"; "wallet__activity_transfer_savings_pending" = "من الإنفاق ({duration})"; "wallet__activity_transfer_savings_done" = "من الإنفاق"; "wallet__activity_transfer_spending_pending" = "من المدخرات ({duration})"; @@ -1768,5 +1799,7 @@ "subscriptions__allowance_auto_paid" = "مدفوع تلقائيًا"; "wallet__balance_updating" = "جارٍ تحديث الرصيد…"; +"lightning__move_to_spark__in_flight_text" = "الدفعة في طريقها وستظهر في Spark بمجرد تسويتها. إذا فشلت، يبقى المبلغ في اتصالك."; +"lightning__move_to_spark__in_flight_title" = "جارٍ النقل إلى\nSpark"; "other__error_keychain" = "مشكلة في الاتصال بالبيانات"; "other__error_keychain_msg" = "تعذر تحميل المفتاح الأساسي من سلسلة المفاتيح."; diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings index 3f31c49312..c4a6f4d6e7 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -201,7 +201,7 @@ "lightning__funding__nav_title" = "Saldo de despesa"; "lightning__funding__text" = "La forma més fàcil és utilitzar els teus estalvis de Bitkit o enviar bitcoin des d\'una altra cartera."; "lightning__funding__title" = "Finança el teu saldo de despesa"; -"lightning__funding__button1" = "Transferir des d\'estalvis"; +"lightning__funding__button1" = "Transferir des d'estalvis"; "lightning__funding__button2" = "Utilitza un altre moneder"; "lightning__funding__button3" = "Configuració manual"; "lightning__funding_advanced__button_short" = "Configuració avançada"; @@ -227,6 +227,7 @@ "lightning__spending_intro__button" = "Començar"; "lightning__transfer_failed__continue" = "Torna a intentar"; "lightning__spending_amount__quarter" = "25%"; +"lightning__spending_amount__error_min__title" = "Mínim del saldo d'estalvis"; "lightning__spending_amount__error_max__title" = "Màxim del saldo de despesa"; "lightning__spending_amount__error_max__description" = "L'import que pots transferir al teu saldo de despesa està limitat a ₿ {amount}."; "lightning__spending_amount__error_fee" = "No s'ha pogut obtenir la comissió de xarxa. Toca per tornar-ho a provar."; @@ -342,6 +343,29 @@ "lightning__transaction" = "Transacció"; "lightning__order_fee" = "Comissió de comanda"; "lightning__balance" = "Saldo"; +"lightning__move_to_spark__amount" = "Import"; +"lightning__move_to_spark__confirm_text" = "El teu saldo es mou a Spark a través de Lightning, la manera amb menys comissions de mantenir-lo a Despesa. La comissió d'encaminament de sota és el màxim que pagues."; +"lightning__move_to_spark__confirm_title" = "Moure a\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Part del teu saldo ja és a Spark. Mou la resta de la mateixa manera i després tanca la connexió buidada."; +"lightning__move_to_spark__done_text" = "El teu saldo ja és a Spark. Tanca la connexió buidada per retornar-ne la reserva a Estalvis."; +"lightning__move_to_spark__done_title" = "Mogut a\nSpark"; +"lightning__move_to_spark__failed_nothing" = "Les teves connexions Lightning no tenen saldo per moure."; +"lightning__move_to_spark__failed_spark" = "Spark encara no està preparat per rebre. Torna-ho a provar d'aquí a un moment."; +"lightning__move_to_spark__failed_title" = "No s'ha pogut\nmoure"; +"lightning__move_to_spark__failed_unknown" = "Alguna cosa ha fallat en preparar el moviment. Torna-ho a provar."; +"lightning__move_to_spark__fee" = "Comissió d'encaminament"; +"lightning__move_to_spark__intro_text" = "Blocktank està tancant les seves connexions Lightning. Mou ara el teu saldo a Spark: és l'opció amb menys comissions i es queda a Despesa."; +"lightning__move_to_spark__intro_title" = "La teva connexió\nes tanca"; +"lightning__move_to_spark__move_half" = "Mou la meitat"; +"lightning__move_to_spark__move_now" = "Mou ara"; +"lightning__move_to_spark__move_rest" = "Mou la resta"; +"lightning__move_to_spark__nav_title" = "Moure a Spark"; +"lightning__move_to_spark__quoting" = "Cercant una ruta i la seva comissió…"; +"lightning__move_to_spark__swipe" = "Llisca per moure"; +"lightning__move_to_spark__too_large_none" = "Tanca la connexió en lloc d'això per retornar el saldo a Estalvis."; +"lightning__move_to_spark__too_large_smaller" = "El pots moure en parts més petites."; +"lightning__move_to_spark__too_large_text" = "{amount} és massa per encaminar-lo a Spark en un sol pagament."; +"lightning__move_to_spark__too_large_title" = "Import\nmassa gran"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Comissió de reclamació"; "lightning__spark_confirmations" = "{count}/3 confirmacions"; @@ -395,6 +419,9 @@ "lightning__spark_exit__leftover_swept" = "{amount} de comissions d'emergència no utilitzades s'han enviat als estalvis."; "lightning__spark_exit__leftover_sending" = "S'estan enviant {amount} de comissions d'emergència no utilitzades als estalvis."; "lightning__spark_exit__leftover_dust" = "{amount} de comissions d'emergència no utilitzades són massa petits per enviar-se i es queden a {address}, camí de derivació {path}."; +"lightning__spark_exit__earlier_addresses" = "Adreces de sortida anteriors"; +"lightning__spark_exit__earlier_addresses_text" = "Les sortides d'emergència anteriors van fer servir aquestes adreces de finançament. Les monedes que hi quedin continuen sent teves: gasta-les amb la teva frase de recuperació i el camí de derivació."; +"lightning__spark_exit__earlier_path" = "Camí de derivació"; "lightning__spark_exit__lost_leaves" = "Un propietari anterior d'aquests fons ha reclamat {amount} on-chain i no es pot recuperar."; "lightning__spark_exit__notification_lost" = "{amount} de la teva transferència forçosa no es pot recuperar. Obre Bitkit per veure'n el motiu."; "lightning__spark_exit__notification_failed" = "La teva transferència forçosa s'ha aturat. Obre Bitkit per veure'n el motiu."; @@ -417,6 +444,7 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit no ha pogut llegir el progrés desat d'aquesta transferència, així que el reconstrueix a partir de la cadena."; "lightning__spark_exit__leftover_rejected" = "{amount} de comissions d'emergència no utilitzades no s'han pogut enviar i es queden a {address}, camí de derivació {path}."; "lightning__spark_exit__notification_not_moving" = "La teva transferència forçosa no avança. Obre Bitkit per saber per què."; +"lightning__spark_exit__note_notifications_button" = "Activa les notificacions"; "lightning__spark_exit__waiting_operators" = "{amount} que els operadors de Spark han mogut on-chain espera que l'alliberin. Bitkit ho torna a demanar durant una setmana com a màxim."; "lightning__spark_exit__fee_rose" = "Les comissions de xarxa han superat la comissió d'aquesta transferència. Pot alentir-se."; "lightning__spark_exit__fee_bump_button" = "Paga una comissió més alta"; @@ -1302,6 +1330,7 @@ "wallet__swap_route_restored_title" = "Pagament retornat a Estalvis"; "wallet__send_paykit_no_route__title" = "No es pot pagar aquest contacte"; "wallet__send_paykit_no_route__description" = "Aquest contacte no té cap mètode de pagament que Bitkit pugui fer servir ara mateix."; +"wallet__send_paykit_withdrawal_settling__description" = "Una retirada anterior del teu saldo de despesa encara s'està liquidant. Torna-ho a provar quan s'hagi completat."; "wallet__recipient_contact" = "Contacte"; "wallet__recipient_invoice" = "Enganxa factura"; "wallet__recipient_manual" = "Introdueix manualment"; @@ -1386,6 +1415,7 @@ "wallet__payment_recipient_rejected" = "El destinatari ha rebutjat aquest pagament Lightning. Comprova la factura i torna-ho a provar."; "wallet__payment_abandoned" = "El pagament Lightning s'ha aturat abans de completar-se."; "wallet__payment_expired" = "Aquest pagament Lightning ha caducat. Demana una factura nova."; +"wallet__payment_restored_invoice" = "Bitkit no pot confirmar que aquesta factura no s'hagués pagat abans que restauressis la teva cartera. Demana una factura nova."; "wallet__payment_timeout" = "El pagament ha esgotat el temps d'espera. Torna-ho a provar."; "wallet__payment_route_not_found" = "Bitkit no ha pogut trobar cap ruta Lightning per a aquest pagament."; "wallet__payment_retries_exhausted" = "Bitkit ha provat diverses rutes Lightning, però el pagament no s'ha pogut completar."; @@ -1414,7 +1444,7 @@ "wallet__receive_note_placeholder" = "Nota opcional per al pagador"; "wallet__receive_show_qr" = "Mostra el codi QR"; "wallet__receive_spending" = "Rebre fons Lightning"; -"wallet__receive_spending_text" = "Gaudeix de pagaments de bitcoin instantanis i barats a la xarxa Lightning."; +"wallet__receive_spending_text" = "Gaudeix de transaccions instantànies i barates amb amics, família i comerços."; "wallet__receive_spending_title" = "Rebre al saldo de despesa"; "wallet__receive_cjit_error" = "Transacció fallida"; "wallet__minimum" = "MÍNIM"; @@ -1429,6 +1459,7 @@ "wallet__activity_failed" = "Fallit"; "wallet__activity_transfer" = "Transferència"; "wallet__activity_transferring" = "Transferint"; +"wallet__activity_move_to_spark" = "Moure a Spark"; "wallet__activity_transfer_savings_pending" = "Des de despesa ({duration})"; "wallet__activity_transfer_savings_done" = "Des de despesa"; "wallet__activity_transfer_spending_pending" = "Des d\'estalvis ({duration})"; @@ -1952,5 +1983,7 @@ "subscriptions__allowance_auto_paid" = "Pagat automàticament"; "wallet__balance_updating" = "S’està actualitzant el saldo…"; +"lightning__move_to_spark__in_flight_text" = "El pagament està en camí i apareixerà a Spark quan es liquidi. Si falla, l'import es queda a la teva connexió."; +"lightning__move_to_spark__in_flight_title" = "Movent a\nSpark"; "other__error_keychain" = "Problema de connexió de dades"; "other__error_keychain_msg" = "No s'ha pogut carregar la clau principal del clauer."; diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings index dc4f89b280..8cc355d113 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -358,6 +358,29 @@ "lightning__transaction" = "Transakce"; "lightning__order_fee" = "Poplatek za objednávku"; "lightning__balance" = "Zůstatek"; +"lightning__move_to_spark__amount" = "Částka"; +"lightning__move_to_spark__confirm_text" = "Váš zůstatek se přesune na Spark přes Lightning, což je nejlevnější způsob, jak ho ponechat v útratách. Poplatek za směrování níže je maximum, které zaplatíte."; +"lightning__move_to_spark__confirm_title" = "Přesunout na\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Část vašeho zůstatku je nyní na Sparku. Přesuňte zbytek stejným způsobem a pak uzavřete vyprázdněné spojení."; +"lightning__move_to_spark__done_text" = "Váš zůstatek je nyní na Sparku. Uzavřete vyprázdněné spojení, aby se jeho rezerva vrátila do úspor."; +"lightning__move_to_spark__done_title" = "Přesunuto na\nSpark"; +"lightning__move_to_spark__failed_nothing" = "Vaše Lightning spojení už nemají žádný zůstatek k přesunu."; +"lightning__move_to_spark__failed_spark" = "Spark zatím není připraven přijímat. Zkuste to za chvíli znovu."; +"lightning__move_to_spark__failed_title" = "Přesun se\nnezdařil"; +"lightning__move_to_spark__failed_unknown" = "Při přípravě přesunu se něco pokazilo. Zkuste to znovu."; +"lightning__move_to_spark__fee" = "Poplatek za směrování"; +"lightning__move_to_spark__intro_text" = "Blocktank uzavírá svá Lightning spojení. Přesuňte nyní svůj zůstatek na Spark: je to nejlevnější možnost a zůstatek zůstane v útratách."; +"lightning__move_to_spark__intro_title" = "Vaše spojení\nse uzavírá"; +"lightning__move_to_spark__move_half" = "Přesunout polovinu"; +"lightning__move_to_spark__move_now" = "Přesunout nyní"; +"lightning__move_to_spark__move_rest" = "Přesunout zbytek"; +"lightning__move_to_spark__nav_title" = "Přesun na Spark"; +"lightning__move_to_spark__quoting" = "Hledání trasy a jejího poplatku…"; +"lightning__move_to_spark__swipe" = "Přejeďte pro přesun"; +"lightning__move_to_spark__too_large_none" = "Místo toho uzavřete spojení, aby se zůstatek vrátil do úspor."; +"lightning__move_to_spark__too_large_smaller" = "Můžete ji přesunout po menších částech."; +"lightning__move_to_spark__too_large_text" = "Částka {amount} je příliš velká na to, aby se dala na Spark směrovat jednou platbou."; +"lightning__move_to_spark__too_large_title" = "Částka je\npříliš velká"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Poplatek za připsání"; "lightning__spark_confirmations" = "{count}/3 potvrzení"; @@ -411,6 +434,9 @@ "lightning__spark_exit__leftover_swept" = "{amount} nepoužitých nouzových poplatků bylo odesláno do úspor."; "lightning__spark_exit__leftover_sending" = "Odesílání {amount} nepoužitých nouzových poplatků do úspor."; "lightning__spark_exit__leftover_dust" = "{amount} nepoužitých nouzových poplatků je příliš málo na odeslání a zůstává na adrese {address}, derivační cesta {path}."; +"lightning__spark_exit__earlier_addresses" = "Dřívější adresy pro výstup"; +"lightning__spark_exit__earlier_addresses_text" = "Dřívější nouzové výstupy používaly tyto adresy pro krytí poplatků. Mince, které na některé zůstaly, jsou stále vaše: utratíte je pomocí obnovovací fráze a derivační cesty."; +"lightning__spark_exit__earlier_path" = "Derivační cesta"; "lightning__spark_exit__lost_leaves" = "{amount} si on-chain nárokoval dřívější vlastník těchto prostředků a nelze to získat zpět."; "lightning__spark_exit__notification_lost" = "{amount} z vašeho vynuceného převodu nelze obnovit. Otevřete Bitkit a zjistěte proč."; "lightning__spark_exit__notification_failed" = "Váš vynucený převod se zastavil. Otevřete Bitkit a zjistěte proč."; @@ -433,6 +459,7 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit nemohl přečíst uložený průběh tohoto převodu, proto ho znovu sestaví z blockchainu."; "lightning__spark_exit__leftover_rejected" = "{amount} nepoužitých nouzových poplatků se nepodařilo odeslat a zůstává na adrese {address}, derivační cesta {path}."; "lightning__spark_exit__notification_not_moving" = "Váš vynucený převod nepostupuje. Otevřete Bitkit a zjistěte proč."; +"lightning__spark_exit__note_notifications_button" = "Zapnout oznámení"; "lightning__spark_exit__waiting_operators" = "{amount}, které operátoři Spark přesunuli na blockchain, čeká, až je uvolní. Bitkit se bude ptát znovu až týden."; "lightning__spark_exit__fee_rose" = "Síťové poplatky vzrostly nad poplatek tohoto převodu. Může se zpomalit."; "lightning__spark_exit__fee_bump_button" = "Zaplatit vyšší poplatek"; @@ -1409,6 +1436,7 @@ "wallet__swap_route_restored_title" = "Platba vrácena do Úspor"; "wallet__send_paykit_no_route__title" = "Tomuto kontaktu nelze zaplatit"; "wallet__send_paykit_no_route__description" = "Tento kontakt teď nemá žádný platební způsob, který by Bitkit mohl použít."; +"wallet__send_paykit_withdrawal_settling__description" = "Dřívější výběr z vašeho zůstatku na útratu se stále vypořádává. Zkuste to znovu, až bude dokončen."; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Vložit fakturu"; "wallet__recipient_manual" = "Zadat ručně"; @@ -1499,6 +1527,7 @@ "wallet__payment_recipient_rejected" = "Příjemce tuto Lightning platbu odmítl. Zkontrolujte fakturu a zkuste to znovu."; "wallet__payment_abandoned" = "Lightning platba byla zastavena před dokončením."; "wallet__payment_expired" = "Platnost této Lightning platby vypršela. Vyžádejte si novou fakturu."; +"wallet__payment_restored_invoice" = "Bitkit nemůže potvrdit, že tato faktura nebyla zaplacena před obnovením vaší peněženky. Vyžádejte si prosím novou fakturu."; "wallet__payment_timeout" = "Časový limit platby vypršel. Zkuste to znovu."; "wallet__payment_route_not_found" = "Bitkit nenašel pro tuto platbu žádnou Lightning trasu."; "wallet__payment_retries_exhausted" = "Bitkit vyzkoušel několik Lightning tras, ale platbu se nepodařilo dokončit."; @@ -1528,7 +1557,7 @@ "wallet__receive_show_qr" = "Zobrazit QR kód"; "wallet__receive_text_lnfunds" = "Chcete obdržet prostředky lightning?"; "wallet__receive_spending" = "Přijmout Lightning prostředky"; -"wallet__receive_spending_text" = "Užívejte si okamžité a levné bitcoinové platby v síti Lightning."; +"wallet__receive_spending_text" = "Užívejte si okamžité a levné transakce s přáteli, rodinou a obchodníky."; "wallet__receive_spending_title" = "Přijmout na disponibilní zůstatek"; "wallet__receive_cjit_error" = "Transakce selhala"; "wallet__receive_cjit_error_msg" = "Nepodařilo se odeslat prostředky na váš disponibilní účet."; @@ -1545,6 +1574,7 @@ "wallet__activity_failed" = "Selhání"; "wallet__activity_transfer" = "Převod"; "wallet__activity_transferring" = "Probíhá převod"; +"wallet__activity_move_to_spark" = "Přesun na Spark"; "wallet__activity_transfer_savings_pending" = "Z disponibilního zůstatku ({duration})"; "wallet__activity_transfer_savings_done" = "Z útraty"; "wallet__activity_transfer_spending_pending" = "Z úspor ({duration})"; @@ -2091,3 +2121,5 @@ "subscriptions__allowance_auto_paid" = "Zaplaceno automaticky"; "wallet__balance_updating" = "Aktualizace zůstatku…"; +"lightning__move_to_spark__in_flight_text" = "Platba je na cestě a po vypořádání se zobrazí ve Sparku. Pokud selže, částka zůstane ve vašem spojení."; +"lightning__move_to_spark__in_flight_title" = "Přesouvání na\nSpark"; diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings index 00a1a46df2..f7a3dba3e0 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -201,7 +201,7 @@ "lightning__funding__nav_title" = "Spending Balance"; "lightning__funding__text" = "Am einfachsten ist es, deine Bitkit-Ersparnisse zu verwenden oder Bitcoin von einer anderen Wallet zu senden."; "lightning__funding__title" = "Fund your spending balance"; -"lightning__funding__button1" = "Von Sparkonto übertragen"; +"lightning__funding__button1" = "Vom Sparkonto übertragen"; "lightning__funding__button2" = "Anderes Wallet verwenden"; "lightning__funding__button3" = "Manuelle Einrichtung"; "lightning__funding_advanced__button_short" = "Fortgeschrittenes Setup"; @@ -356,6 +356,29 @@ "lightning__transaction" = "Transaktion"; "lightning__order_fee" = "Auftragsgebühr"; "lightning__balance" = "Guthaben"; +"lightning__move_to_spark__amount" = "Betrag"; +"lightning__move_to_spark__confirm_text" = "Dein Guthaben wird über Lightning zu Spark verschoben, der günstigste Weg, es im Ausgabenkonto zu behalten. Die Routing-Gebühr unten ist das Maximum, das du zahlst."; +"lightning__move_to_spark__confirm_title" = "Zu Spark\nverschieben"; +"lightning__move_to_spark__done_rest_text" = "Ein Teil deines Guthabens ist jetzt auf Spark. Verschiebe den Rest auf dieselbe Weise und schließe dann die geleerte Verbindung."; +"lightning__move_to_spark__done_text" = "Dein Guthaben ist jetzt auf Spark. Schließe die geleerte Verbindung, um ihre Reserve ins Sparkonto zurückzuholen."; +"lightning__move_to_spark__done_title" = "Zu Spark\nverschoben"; +"lightning__move_to_spark__failed_nothing" = "Deine Lightning-Verbindungen haben kein Guthaben mehr, das verschoben werden kann."; +"lightning__move_to_spark__failed_spark" = "Spark ist noch nicht bereit zu empfangen. Versuche es gleich noch einmal."; +"lightning__move_to_spark__failed_title" = "Verschieben\nfehlgeschlagen"; +"lightning__move_to_spark__failed_unknown" = "Beim Vorbereiten der Verschiebung ist etwas schiefgelaufen. Versuche es erneut."; +"lightning__move_to_spark__fee" = "Routing-Gebühr"; +"lightning__move_to_spark__intro_text" = "Blocktank schließt seine Lightning-Verbindungen. Verschiebe dein Guthaben jetzt zu Spark: Das ist die günstigste Option, und es bleibt im Ausgabenkonto."; +"lightning__move_to_spark__intro_title" = "Deine Verbindung\nwird geschlossen"; +"lightning__move_to_spark__move_half" = "Hälfte verschieben"; +"lightning__move_to_spark__move_now" = "Jetzt verschieben"; +"lightning__move_to_spark__move_rest" = "Rest verschieben"; +"lightning__move_to_spark__nav_title" = "Verschiebung zu Spark"; +"lightning__move_to_spark__quoting" = "Route und Gebühr werden gesucht…"; +"lightning__move_to_spark__swipe" = "Swipe zum Verschieben"; +"lightning__move_to_spark__too_large_none" = "Schließe stattdessen die Verbindung, um das Guthaben ins Sparkonto zurückzuholen."; +"lightning__move_to_spark__too_large_smaller" = "Du kannst ihn in kleineren Teilen verschieben."; +"lightning__move_to_spark__too_large_text" = "{amount} ist zu groß, um in einer Zahlung zu Spark geroutet zu werden."; +"lightning__move_to_spark__too_large_title" = "Betrag\nzu groß"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Einlösegebühr"; "lightning__spark_confirmations" = "{count}/3 Bestätigungen"; @@ -409,6 +432,9 @@ "lightning__spark_exit__leftover_swept" = "{amount} nicht verbrauchte Notfallgebühren wurden an dein Sparkonto gesendet."; "lightning__spark_exit__leftover_sending" = "{amount} nicht verbrauchte Notfallgebühren werden an dein Sparkonto gesendet."; "lightning__spark_exit__leftover_dust" = "{amount} nicht verbrauchte Notfallgebühren sind zu klein zum Senden und bleiben bei {address}, Ableitungspfad {path}."; +"lightning__spark_exit__earlier_addresses" = "Frühere Ausstiegsadressen"; +"lightning__spark_exit__earlier_addresses_text" = "Frühere Notausstiege nutzten diese Finanzierungsadressen. Coins, die auf einer zurückbleiben, gehören weiterhin dir: Gib sie mit deiner Wiederherstellungsphrase und ihrem Ableitungspfad aus."; +"lightning__spark_exit__earlier_path" = "Ableitungspfad"; "lightning__spark_exit__lost_leaves" = "{amount} wurden von einem früheren Besitzer dieser Mittel on-chain beansprucht und können nicht wiederhergestellt werden."; "lightning__spark_exit__notification_lost" = "{amount} deiner forcierten Übertragung können nicht zurückgeholt werden. Öffne Bitkit, um den Grund zu sehen."; "lightning__spark_exit__notification_failed" = "Deine forcierte Übertragung wurde gestoppt. Öffne Bitkit, um den Grund zu sehen."; @@ -431,6 +457,7 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit konnte den gespeicherten Fortschritt dieser Übertragung nicht lesen und stellt ihn daher aus der Chain wieder her."; "lightning__spark_exit__leftover_rejected" = "{amount} nicht verbrauchte Notfallgebühren konnten nicht gesendet werden und bleiben bei {address}, Ableitungspfad {path}."; "lightning__spark_exit__notification_not_moving" = "Deine forcierte Übertragung kommt nicht voran. Öffne Bitkit, um den Grund zu sehen."; +"lightning__spark_exit__note_notifications_button" = "Benachrichtigungen aktivieren"; "lightning__spark_exit__waiting_operators" = "{amount}, die die Spark-Betreiber on-chain verschoben haben, warten darauf, dass sie sie freigeben. Bitkit fragt bis zu einer Woche lang erneut nach."; "lightning__spark_exit__fee_rose" = "Die Netzgebühren sind über die Gebühr dieser Übertragung gestiegen. Sie kann sich verlangsamen."; "lightning__spark_exit__fee_bump_button" = "Höhere Gebühr zahlen"; @@ -1407,6 +1434,7 @@ "wallet__swap_route_restored_title" = "Zahlung an Ersparnisse zurückgegeben"; "wallet__send_paykit_no_route__title" = "Zahlung an diesen Kontakt nicht möglich"; "wallet__send_paykit_no_route__description" = "Dieser Kontakt hat derzeit keine Zahlungsmethode, die Bitkit nutzen kann."; +"wallet__send_paykit_withdrawal_settling__description" = "Eine frühere Abhebung von deinem Ausgabenguthaben wird noch abgewickelt. Versuche es erneut, sobald sie abgeschlossen ist."; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Rechnung einfügen"; "wallet__recipient_manual" = "Manuell eingeben"; @@ -1497,6 +1525,7 @@ "wallet__payment_recipient_rejected" = "Der Empfänger hat diese Lightning-Zahlung abgelehnt. Bitte prüfe die Rechnung und versuche es erneut."; "wallet__payment_abandoned" = "Die Lightning-Zahlung wurde gestoppt, bevor sie abgeschlossen wurde."; "wallet__payment_expired" = "Diese Lightning-Zahlung ist abgelaufen. Bitte fordere eine neue Rechnung an."; +"wallet__payment_restored_invoice" = "Bitkit kann nicht bestätigen, dass diese Rechnung nicht bezahlt wurde, bevor du deine Wallet wiederhergestellt hast. Bitte fordere eine neue Rechnung an."; "wallet__payment_timeout" = "Zeitüberschreitung bei der Zahlung. Bitte versuche es erneut."; "wallet__payment_route_not_found" = "Bitkit konnte keine Lightning-Route für diese Zahlung finden."; "wallet__payment_retries_exhausted" = "Bitkit hat mehrere Lightning-Routen ausprobiert, aber die Zahlung konnte nicht abgeschlossen werden."; @@ -1526,7 +1555,7 @@ "wallet__receive_show_qr" = "QR-Code anzeigen"; "wallet__receive_text_lnfunds" = "Möchtest du Lightning-Gelder empfangen?"; "wallet__receive_spending" = "Auf Ausgabenkonto empfangen"; -"wallet__receive_spending_text" = "Genieße sofortige und günstige Bitcoin-Zahlungen im Lightning-Netzwerk."; +"wallet__receive_spending_text" = "Genieße sofortige und günstige Transaktionen mit Freunden, Familie und Händlern."; "wallet__receive_spending_title" = "Auf Ausgabenguthaben empfangen"; "wallet__receive_cjit_error" = "Transaktion fehlgeschlagen"; "wallet__receive_cjit_error_msg" = "Fehler beim Senden der Gelder auf dein Ausgabenkonto."; @@ -1543,6 +1572,7 @@ "wallet__activity_failed" = "Fehlgeschlagen"; "wallet__activity_transfer" = "Übertragung"; "wallet__activity_transferring" = "Wird übertragen"; +"wallet__activity_move_to_spark" = "Verschiebung zu Spark"; "wallet__activity_transfer_savings_pending" = "Von Ausgabenkonto ({duration})"; "wallet__activity_transfer_savings_done" = "Von Ausgabenkonto"; "wallet__activity_transfer_spending_pending" = "Von Sparkonto ({duration})"; @@ -2088,3 +2118,5 @@ "subscriptions__allowance_auto_paid" = "Automatisch bezahlt"; "wallet__balance_updating" = "Kontostand wird aktualisiert…"; +"lightning__move_to_spark__in_flight_text" = "Die Zahlung ist unterwegs und erscheint in Spark, sobald sie abgewickelt ist. Schlägt sie fehl, bleibt der Betrag in deiner Verbindung."; +"lightning__move_to_spark__in_flight_title" = "Unterwegs zu\nSpark"; diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings index 798ae2fc22..93c7209070 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -223,6 +223,7 @@ "lightning__spending_intro__button" = "Ξεκινήστε"; "lightning__transfer_failed__continue" = "Προσπαθείστε Ξανά"; "lightning__spending_amount__quarter" = "25%"; +"lightning__spending_amount__error_min__title" = "Ελάχιστο υπόλοιπο αποταμιεύσεων"; "lightning__spending_amount__error_max__title" = "Μέγιστο υπόλοιπο δαπανών"; "lightning__spending_amount__error_max__description" = "Το ποσό που μπορείς να μεταφέρεις στο υπόλοιπο δαπανών περιορίζεται προς το παρόν σε ₿ {amount}."; "lightning__spending_amount__error_fee" = "Δεν ήταν δυνατή η λήψη των τελών δικτύου. Πατήστε για νέα προσπάθεια."; @@ -329,6 +330,29 @@ "lightning__transaction" = "Συναλλαγή"; "lightning__order_fee" = "Τέλος παραγγελίας"; "lightning__balance" = "Υπόλοιπο"; +"lightning__move_to_spark__amount" = "Ποσό"; +"lightning__move_to_spark__confirm_text" = "Το υπόλοιπό σας μετακινείται στο Spark μέσω Lightning, ο τρόπος με τα χαμηλότερα τέλη για να παραμείνει στις Δαπάνες. Το τέλος δρομολόγησης παρακάτω είναι το μέγιστο που πληρώνετε."; +"lightning__move_to_spark__confirm_title" = "Μετακίνηση στο\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Μέρος του υπολοίπου σας βρίσκεται τώρα στο Spark. Μετακινήστε το υπόλοιπο ποσό με τον ίδιο τρόπο και μετά κλείστε την άδεια σύνδεση."; +"lightning__move_to_spark__done_text" = "Το υπόλοιπό σας βρίσκεται τώρα στο Spark. Κλείστε την άδεια σύνδεση για να επιστρέψει το αποθεματικό της στις Αποταμιεύσεις."; +"lightning__move_to_spark__done_title" = "Μετακινήθηκε στο\nSpark"; +"lightning__move_to_spark__failed_nothing" = "Οι συνδέσεις Lightning σας δεν έχουν πλέον υπόλοιπο για μετακίνηση."; +"lightning__move_to_spark__failed_spark" = "Το Spark δεν είναι ακόμα έτοιμο να λάβει. Δοκιμάστε ξανά σε λίγο."; +"lightning__move_to_spark__failed_title" = "Η μετακίνηση\nαπέτυχε"; +"lightning__move_to_spark__failed_unknown" = "Κάτι πήγε στραβά κατά την προετοιμασία της μετακίνησης. Δοκιμάστε ξανά."; +"lightning__move_to_spark__fee" = "Τέλος δρομολόγησης"; +"lightning__move_to_spark__intro_text" = "Το Blocktank κλείνει τις συνδέσεις Lightning του. Μετακινήστε τώρα το υπόλοιπό σας στο Spark: είναι η επιλογή με τα χαμηλότερα τέλη και παραμένει στις Δαπάνες."; +"lightning__move_to_spark__intro_title" = "Η σύνδεσή σας\nκλείνει"; +"lightning__move_to_spark__move_half" = "Μετακίνηση Μισού"; +"lightning__move_to_spark__move_now" = "Μετακίνηση Τώρα"; +"lightning__move_to_spark__move_rest" = "Μετακίνηση Υπολοίπου"; +"lightning__move_to_spark__nav_title" = "Μετακίνηση στο Spark"; +"lightning__move_to_spark__quoting" = "Αναζήτηση διαδρομής και τέλους…"; +"lightning__move_to_spark__swipe" = "Σύρετε για Μετακίνηση"; +"lightning__move_to_spark__too_large_none" = "Κλείστε αντί γι' αυτό τη σύνδεση για να επιστρέψει το υπόλοιπο στις Αποταμιεύσεις."; +"lightning__move_to_spark__too_large_smaller" = "Μπορείτε να το μετακινήσετε σε μικρότερα τμήματα."; +"lightning__move_to_spark__too_large_text" = "Το ποσό {amount} είναι πολύ μεγάλο για δρομολόγηση στο Spark με μία πληρωμή."; +"lightning__move_to_spark__too_large_title" = "Ποσό\nπολύ μεγάλο"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Χρέωση εξαργύρωσης"; "lightning__spark_confirmations" = "{count}/3 επιβεβαιώσεις"; @@ -382,6 +406,9 @@ "lightning__spark_exit__leftover_swept" = "Τα {amount} αχρησιμοποίητων έκτακτων τελών στάλθηκαν στις αποταμιεύσεις."; "lightning__spark_exit__leftover_sending" = "Αποστολή {amount} αχρησιμοποίητων έκτακτων τελών στις αποταμιεύσεις."; "lightning__spark_exit__leftover_dust" = "Τα {amount} αχρησιμοποίητων έκτακτων τελών είναι πολύ μικρά για αποστολή και παραμένουν στη διεύθυνση {address}, διαδρομή παραγωγής {path}."; +"lightning__spark_exit__earlier_addresses" = "Προηγούμενες διευθύνσεις εξόδου"; +"lightning__spark_exit__earlier_addresses_text" = "Οι προηγούμενες έξοδοι έκτακτης ανάγκης χρησιμοποίησαν αυτές τις διευθύνσεις χρηματοδότησης. Τα νομίσματα που έμειναν σε μία παραμένουν δικά σας: ξοδέψτε τα με τη φράση ανάκτησης και τη διαδρομή παραγωγής."; +"lightning__spark_exit__earlier_path" = "Διαδρομή παραγωγής"; "lightning__spark_exit__lost_leaves" = "{amount} διεκδικήθηκε on-chain από προηγούμενο κάτοχο αυτών των κεφαλαίων και δεν μπορεί να ανακτηθεί."; "lightning__spark_exit__notification_lost" = "Τα {amount} της αναγκαστικής μεταφοράς σας δεν μπορούν να ανακτηθούν. Ανοίξτε το Bitkit για να δείτε γιατί."; "lightning__spark_exit__notification_failed" = "Η αναγκαστική μεταφορά σας σταμάτησε. Ανοίξτε το Bitkit για να δείτε γιατί."; @@ -404,6 +431,7 @@ "lightning__spark_exit__rebuilt_from_chain" = "Το Bitkit δεν μπόρεσε να διαβάσει την αποθηκευμένη πρόοδο αυτής της μεταφοράς, γι' αυτό την ανακατασκευάζει από την αλυσίδα."; "lightning__spark_exit__leftover_rejected" = "Τα {amount} αχρησιμοποίητων έκτακτων τελών δεν μπόρεσαν να σταλούν και παραμένουν στη διεύθυνση {address}, διαδρομή παραγωγής {path}."; "lightning__spark_exit__notification_not_moving" = "Η αναγκαστική μεταφορά σας δεν προχωρά. Ανοίξτε το Bitkit για να δείτε γιατί."; +"lightning__spark_exit__note_notifications_button" = "Ενεργοποίηση ειδοποιήσεων"; "lightning__spark_exit__waiting_operators" = "{amount} που μετέφεραν on-chain οι διαχειριστές του Spark περιμένει να το αποδεσμεύσουν. Το Bitkit ζητά ξανά για έως μία εβδομάδα."; "lightning__spark_exit__fee_rose" = "Τα τέλη δικτύου ανέβηκαν πάνω από το τέλος αυτής της μεταφοράς. Μπορεί να καθυστερήσει."; "lightning__spark_exit__fee_bump_button" = "Πληρωμή υψηλότερου τέλους"; @@ -1201,6 +1229,7 @@ "wallet__swap_route_restored_title" = "Η πληρωμή επέστρεψε στις Αποταμιεύσεις"; "wallet__send_paykit_no_route__title" = "Δεν είναι δυνατή η πληρωμή αυτής της επαφής"; "wallet__send_paykit_no_route__description" = "Αυτή η επαφή δεν έχει αυτή τη στιγμή κάποια μέθοδο πληρωμής που μπορεί να χρησιμοποιήσει το Bitkit."; +"wallet__send_paykit_withdrawal_settling__description" = "Μια προηγούμενη ανάληψη από το υπόλοιπο δαπανών σας εκκαθαρίζεται ακόμα. Δοκιμάστε ξανά μόλις ολοκληρωθεί."; "wallet__recipient_contact" = "Επαφή"; "wallet__recipient_invoice" = "Επικόλληση Τιμολογίου"; "wallet__recipient_manual" = "Χειροκίνητη Εισαγωγή"; @@ -1267,6 +1296,7 @@ "wallet__payment_recipient_rejected" = "Ο παραλήπτης απέρριψε αυτήν την πληρωμή Lightning. Ελέγξτε το τιμολόγιο και δοκιμάστε ξανά."; "wallet__payment_abandoned" = "Η πληρωμή Lightning σταμάτησε πριν ολοκληρωθεί."; "wallet__payment_expired" = "Αυτή η πληρωμή Lightning έληξε. Ζητήστε νέο τιμολόγιο."; +"wallet__payment_restored_invoice" = "Το Bitkit δεν μπορεί να επιβεβαιώσει ότι αυτό το τιμολόγιο δεν πληρώθηκε πριν από την επαναφορά του πορτοφολιού σας. Ζητήστε νέο τιμολόγιο."; "wallet__payment_timeout" = "Το χρονικό όριο πληρωμής έληξε. Δοκιμάστε ξανά."; "wallet__payment_route_not_found" = "Το Bitkit δεν μπόρεσε να βρει διαδρομή Lightning για αυτήν την πληρωμή."; "wallet__payment_retries_exhausted" = "Το Bitkit δοκίμασε αρκετές διαδρομές Lightning, αλλά η πληρωμή δεν μπόρεσε να ολοκληρωθεί."; @@ -1293,7 +1323,7 @@ "wallet__receive_note_placeholder" = "Προαιρετική σημείωση στον πληρωτή"; "wallet__receive_show_qr" = "Εμφάνιση Κωδικού QR"; "wallet__receive_spending" = "Λήψη κεφαλαίων Lightning"; -"wallet__receive_spending_text" = "Απολαύστε άμεσες και φθηνές πληρωμές bitcoin στο Lightning Network."; +"wallet__receive_spending_text" = "Απολαύστε άμεσες και φθηνές συναλλαγές με φίλους, οικογένεια και εμπόρους."; "wallet__receive_spending_title" = "Λήψη στο υπόλοιπο δαπανών"; "wallet__receive_cjit_error" = "Η Συναλλαγή Απέτυχε"; "wallet__activity" = "Δραστηριότητα"; @@ -1306,6 +1336,7 @@ "wallet__activity_failed" = "Απέτυχε"; "wallet__activity_transfer" = "Μεταφορά"; "wallet__activity_transferring" = "Μεταφορά σε εξέλιξη"; +"wallet__activity_move_to_spark" = "Μετακίνηση στο Spark"; "wallet__activity_transfer_savings_pending" = "Από Δαπάνες ({duration})"; "wallet__activity_transfer_savings_done" = "Από Δαπάνες"; "wallet__activity_transfer_spending_pending" = "Από Αποταμιεύσεις ({duration})"; @@ -1823,5 +1854,7 @@ "subscriptions__allowance_auto_paid" = "Πληρώθηκε αυτόματα"; "wallet__balance_updating" = "Ενημέρωση υπολοίπου…"; +"lightning__move_to_spark__in_flight_text" = "Η πληρωμή βρίσκεται καθ' οδόν και εμφανίζεται στο Spark μόλις διακανονιστεί. Αν αποτύχει, το ποσό παραμένει στη σύνδεσή σας."; +"lightning__move_to_spark__in_flight_title" = "Μετακινείται στο\nSpark"; "other__error_keychain" = "Πρόβλημα Σύνδεσης Δεδομένων"; "other__error_keychain_msg" = "Δεν ήταν δυνατή η φόρτωση του κύριου κλειδιού από την κλειδοθήκη."; diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings index 5c98969e10..90b75e2500 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -359,6 +359,29 @@ "lightning__transaction" = "Transacción"; "lightning__order_fee" = "Tarifa de pedido"; "lightning__balance" = "Saldo"; +"lightning__move_to_spark__amount" = "Cantidad"; +"lightning__move_to_spark__confirm_text" = "Tu saldo se mueve a Spark a través de Lightning, la forma con menos comisiones de mantenerlo en Gastos. La comisión de enrutamiento de abajo es lo máximo que pagas."; +"lightning__move_to_spark__confirm_title" = "Mover a\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Parte de tu saldo ya está en Spark. Mueve el resto de la misma manera y después cierra la conexión vaciada."; +"lightning__move_to_spark__done_text" = "Tu saldo ya está en Spark. Cierra la conexión vaciada para devolver su reserva a Ahorros."; +"lightning__move_to_spark__done_title" = "Movido a\nSpark"; +"lightning__move_to_spark__failed_nothing" = "A tus conexiones Lightning no les queda saldo que mover."; +"lightning__move_to_spark__failed_spark" = "Spark todavía no está listo para recibir. Vuelve a intentarlo en un momento."; +"lightning__move_to_spark__failed_title" = "No se pudo\nmover"; +"lightning__move_to_spark__failed_unknown" = "Algo salió mal al preparar el movimiento. Vuelve a intentarlo."; +"lightning__move_to_spark__fee" = "Comisión de enrutamiento"; +"lightning__move_to_spark__intro_text" = "Blocktank está cerrando sus conexiones Lightning. Mueve tu saldo a Spark ahora: es la opción con menos comisiones y se queda en Gastos."; +"lightning__move_to_spark__intro_title" = "Tu conexión\nse está cerrando"; +"lightning__move_to_spark__move_half" = "Mover la mitad"; +"lightning__move_to_spark__move_now" = "Mover ahora"; +"lightning__move_to_spark__move_rest" = "Mover el resto"; +"lightning__move_to_spark__nav_title" = "Mover a Spark"; +"lightning__move_to_spark__quoting" = "Buscando una ruta y su comisión…"; +"lightning__move_to_spark__swipe" = "Deslizar para mover"; +"lightning__move_to_spark__too_large_none" = "En su lugar, cierra la conexión para devolver el saldo a Ahorros."; +"lightning__move_to_spark__too_large_smaller" = "Puedes moverla en partes más pequeñas."; +"lightning__move_to_spark__too_large_text" = "{amount} es demasiado para enrutarlo a Spark en un solo pago."; +"lightning__move_to_spark__too_large_title" = "Cantidad\ndemasiado alta"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Comisión de reclamo"; "lightning__spark_confirmations" = "{count}/3 confirmaciones"; @@ -412,6 +435,9 @@ "lightning__spark_exit__leftover_swept" = "{amount} de comisiones de emergencia sin usar se envió a tus ahorros."; "lightning__spark_exit__leftover_sending" = "Enviando {amount} de comisiones de emergencia sin usar a tus ahorros."; "lightning__spark_exit__leftover_dust" = "{amount} de comisiones de emergencia sin usar es demasiado pequeño para enviarse y se queda en {address}, ruta de derivación {path}."; +"lightning__spark_exit__earlier_addresses" = "Direcciones de salida anteriores"; +"lightning__spark_exit__earlier_addresses_text" = "Las salidas de emergencia anteriores usaron estas direcciones de fondeo. Las monedas que queden en una siguen siendo tuyas: gástalas con tu frase de recuperación y su ruta de derivación."; +"lightning__spark_exit__earlier_path" = "Ruta de derivación"; "lightning__spark_exit__lost_leaves" = "Un propietario anterior de estos fondos reclamó {amount} on-chain y no se puede recuperar."; "lightning__spark_exit__notification_lost" = "{amount} de tu transferencia forzada no se puede recuperar. Abre Bitkit para ver por qué."; "lightning__spark_exit__notification_failed" = "Tu transferencia forzada se detuvo. Abre Bitkit para ver por qué."; @@ -434,6 +460,7 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit no pudo leer el progreso guardado de esta transferencia, así que lo reconstruye a partir de la cadena."; "lightning__spark_exit__leftover_rejected" = "{amount} de comisiones de emergencia sin usar no se pudo enviar y se queda en {address}, ruta de derivación {path}."; "lightning__spark_exit__notification_not_moving" = "Tu transferencia forzada no avanza. Abre Bitkit para ver por qué."; +"lightning__spark_exit__note_notifications_button" = "Activar notificaciones"; "lightning__spark_exit__waiting_operators" = "{amount} que los operadores de Spark movieron on-chain espera a que lo liberen. Bitkit vuelve a pedirlo durante hasta una semana."; "lightning__spark_exit__fee_rose" = "Las comisiones de la red superaron la comisión de esta transferencia. Puede ralentizarse."; "lightning__spark_exit__fee_bump_button" = "Pagar una comisión más alta"; @@ -1412,6 +1439,7 @@ "wallet__swap_route_restored_title" = "Pago devuelto a Ahorros"; "wallet__send_paykit_no_route__title" = "No se puede pagar a este contacto"; "wallet__send_paykit_no_route__description" = "Este contacto no tiene ningún método de pago que Bitkit pueda usar en este momento."; +"wallet__send_paykit_withdrawal_settling__description" = "Un retiro anterior de tu saldo para gastos todavía se está liquidando. Vuelve a intentarlo cuando se complete."; "wallet__recipient_contact" = "Contacto"; "wallet__recipient_invoice" = "Pegar factura"; "wallet__recipient_manual" = "Introducir manualmente"; @@ -1502,6 +1530,7 @@ "wallet__payment_recipient_rejected" = "El destinatario rechazó este pago Lightning. Revise la factura e inténtelo de nuevo."; "wallet__payment_abandoned" = "El pago Lightning se detuvo antes de completarse."; "wallet__payment_expired" = "Este pago Lightning venció. Solicite una factura nueva."; +"wallet__payment_restored_invoice" = "Bitkit no puede confirmar que esta factura no se haya pagado antes de que restaurara su cartera. Solicite una factura nueva."; "wallet__payment_timeout" = "El pago agotó el tiempo de espera. Inténtelo de nuevo."; "wallet__payment_route_not_found" = "Bitkit no pudo encontrar una ruta Lightning para este pago."; "wallet__payment_retries_exhausted" = "Bitkit probó varias rutas Lightning, pero el pago no se pudo completar."; @@ -1531,7 +1560,7 @@ "wallet__receive_show_qr" = "Mostrar código QR"; "wallet__receive_text_lnfunds" = "Quiero recibir"; "wallet__receive_spending" = "Recibir en Saldo de Gastos"; -"wallet__receive_spending_text" = "Disfrute de pagos de bitcoin instantáneos y baratos en la red Lightning."; +"wallet__receive_spending_text" = "Disfruta de transacciones instantáneas y baratas con amigos, familia y comercios."; "wallet__receive_spending_title" = "Recibir en saldo de gastos"; "wallet__receive_cjit_error" = "Transacción fallida"; "wallet__receive_cjit_error_msg" = "No se han podido enviar fondos a su cuenta de gastos."; @@ -1548,6 +1577,7 @@ "wallet__activity_failed" = "Fallido"; "wallet__activity_transfer" = "Transferir"; "wallet__activity_transferring" = "Transfiriendo"; +"wallet__activity_move_to_spark" = "Mover a Spark"; "wallet__activity_transfer_savings_pending" = "Del Gastos ({duration})"; "wallet__activity_transfer_savings_done" = "De Gastos"; "wallet__activity_transfer_spending_pending" = "De Ahorros ({duration})"; @@ -2094,3 +2124,5 @@ "subscriptions__allowance_auto_paid" = "Pagado automáticamente"; "wallet__balance_updating" = "Actualizando saldo…"; +"lightning__move_to_spark__in_flight_text" = "El pago está en camino y aparecerá en Spark cuando se liquide. Si falla, la cantidad se queda en tu conexión."; +"lightning__move_to_spark__in_flight_title" = "Moviendo a\nSpark"; diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings index 29ddb78c27..094a104dee 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -225,6 +225,7 @@ "lightning__spending_intro__button" = "Empezar"; "lightning__transfer_failed__continue" = "Inténtelo de nuevo"; "lightning__spending_amount__quarter" = "25%"; +"lightning__spending_amount__error_min__title" = "Mínimo del Saldo de Ahorros"; "lightning__spending_amount__error_max__title" = "Máximo del Saldo de Gastos"; "lightning__spending_amount__error_max__description" = "La cantidad que puedes transferir a tu saldo de gastos está actualmente limitada a ₿ {amount}."; "lightning__spending_amount__error_fee" = "No se pudo obtener la comisión de red. Toque para reintentar."; @@ -343,6 +344,29 @@ "lightning__transaction" = "Transacción"; "lightning__order_fee" = "Tarifa de pedido"; "lightning__balance" = "Saldo"; +"lightning__move_to_spark__amount" = "Cantidad"; +"lightning__move_to_spark__confirm_text" = "Tu saldo se mueve a Spark a través de Lightning, la forma con menos comisiones de mantenerlo en Gasto. La comisión de enrutamiento de abajo es lo máximo que pagas."; +"lightning__move_to_spark__confirm_title" = "Mover a\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Parte de tu saldo ya está en Spark. Mueve el resto de la misma manera y después cierra la conexión vaciada."; +"lightning__move_to_spark__done_text" = "Tu saldo ya está en Spark. Cierra la conexión vaciada para devolver su reserva a Ahorro."; +"lightning__move_to_spark__done_title" = "Movido a\nSpark"; +"lightning__move_to_spark__failed_nothing" = "A tus conexiones Lightning no les queda saldo que mover."; +"lightning__move_to_spark__failed_spark" = "Spark aún no está listo para recibir. Inténtalo de nuevo en un momento."; +"lightning__move_to_spark__failed_title" = "No se pudo\nmover"; +"lightning__move_to_spark__failed_unknown" = "Algo salió mal al preparar el movimiento. Inténtalo de nuevo."; +"lightning__move_to_spark__fee" = "Comisión de enrutamiento"; +"lightning__move_to_spark__intro_text" = "Blocktank está cerrando sus conexiones Lightning. Mueve tu saldo a Spark ahora: es la opción con menos comisiones y se queda en Gasto."; +"lightning__move_to_spark__intro_title" = "Tu conexión\nse está cerrando"; +"lightning__move_to_spark__move_half" = "Mover la mitad"; +"lightning__move_to_spark__move_now" = "Mover ahora"; +"lightning__move_to_spark__move_rest" = "Mover el resto"; +"lightning__move_to_spark__nav_title" = "Mover a Spark"; +"lightning__move_to_spark__quoting" = "Buscando una ruta y su comisión…"; +"lightning__move_to_spark__swipe" = "Deslizar para mover"; +"lightning__move_to_spark__too_large_none" = "En su lugar, cierra la conexión para devolver el saldo a Ahorro."; +"lightning__move_to_spark__too_large_smaller" = "Puedes moverla en partes más pequeñas."; +"lightning__move_to_spark__too_large_text" = "{amount} es demasiado para enrutarlo a Spark en un solo pago."; +"lightning__move_to_spark__too_large_title" = "Cantidad\ndemasiado alta"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Comisión de reclamo"; "lightning__spark_confirmations" = "{count}/3 confirmaciones"; @@ -396,6 +420,9 @@ "lightning__spark_exit__leftover_swept" = "Se han enviado a tus ahorros {amount} de comisiones de emergencia sin usar."; "lightning__spark_exit__leftover_sending" = "Enviando {amount} de comisiones de emergencia sin usar a tus ahorros."; "lightning__spark_exit__leftover_dust" = "{amount} de comisiones de emergencia sin usar es demasiado poco para enviarse y se queda en {address}, ruta de derivación {path}."; +"lightning__spark_exit__earlier_addresses" = "Direcciones de salida anteriores"; +"lightning__spark_exit__earlier_addresses_text" = "Las salidas de emergencia anteriores usaron estas direcciones de fondeo. Las monedas que queden en una siguen siendo tuyas: gástalas con tu frase de recuperación y su ruta de derivación."; +"lightning__spark_exit__earlier_path" = "Ruta de derivación"; "lightning__spark_exit__lost_leaves" = "Un propietario anterior de estos fondos reclamó {amount} on-chain y no se puede recuperar."; "lightning__spark_exit__notification_lost" = "{amount} de tu transferencia forzada no se puede recuperar. Abre Bitkit para ver el motivo."; "lightning__spark_exit__notification_failed" = "Tu transferencia forzada se detuvo. Abre Bitkit para ver el motivo."; @@ -418,6 +445,7 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit no pudo leer el progreso guardado de esta transferencia, así que lo reconstruye a partir de la cadena."; "lightning__spark_exit__leftover_rejected" = "{amount} de comisiones de emergencia sin usar no se pudo enviar y se queda en {address}, ruta de derivación {path}."; "lightning__spark_exit__notification_not_moving" = "Tu transferencia forzada no avanza. Abre Bitkit para ver por qué."; +"lightning__spark_exit__note_notifications_button" = "Activar notificaciones"; "lightning__spark_exit__waiting_operators" = "{amount} que los operadores de Spark movieron on-chain espera a que lo liberen. Bitkit vuelve a pedirlo durante hasta una semana."; "lightning__spark_exit__fee_rose" = "Las comisiones de la red superaron la comisión de esta transferencia. Puede ralentizarse."; "lightning__spark_exit__fee_bump_button" = "Pagar una comisión más alta"; @@ -1320,6 +1348,7 @@ "wallet__swap_route_restored_title" = "Pago devuelto a Ahorros"; "wallet__send_paykit_no_route__title" = "No se puede pagar a este contacto"; "wallet__send_paykit_no_route__description" = "Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora mismo."; +"wallet__send_paykit_withdrawal_settling__description" = "Una retirada anterior de tu saldo de gastos aún se está liquidando. Inténtalo de nuevo cuando se complete."; "wallet__recipient_contact" = "Contactar"; "wallet__recipient_invoice" = "Pegar factura"; "wallet__recipient_manual" = "Introducir manualmente"; @@ -1401,6 +1430,7 @@ "wallet__payment_recipient_rejected" = "El destinatario ha rechazado este pago Lightning. Comprueba la factura e inténtalo de nuevo."; "wallet__payment_abandoned" = "El pago Lightning se detuvo antes de completarse."; "wallet__payment_expired" = "Este pago Lightning ha caducado. Solicita una factura nueva."; +"wallet__payment_restored_invoice" = "Bitkit no puede confirmar que esta factura no se pagara antes de que restauraras tu cartera. Solicita una factura nueva."; "wallet__payment_timeout" = "El pago agotó el tiempo de espera. Inténtalo de nuevo."; "wallet__payment_route_not_found" = "Bitkit no ha podido encontrar una ruta Lightning para este pago."; "wallet__payment_retries_exhausted" = "Bitkit ha probado varias rutas Lightning, pero el pago no se ha podido completar."; @@ -1429,7 +1459,7 @@ "wallet__receive_note_placeholder" = "Nota opcional para el pagador"; "wallet__receive_show_qr" = "Mostrar código QR"; "wallet__receive_spending" = "Recibir Fondos Lightning"; -"wallet__receive_spending_text" = "Disfrute de pagos de bitcoin instantáneos y baratos en la red Lightning."; +"wallet__receive_spending_text" = "Disfruta de transacciones instantáneas y baratas con amigos, familia y comercios."; "wallet__receive_spending_title" = "Recibir en saldo de gasto"; "wallet__receive_cjit_error" = "Transacción ha fallado"; "wallet__receive_cjit_error_msg" = "Fallo al enviar fondos a la cuenta de gastos."; @@ -1445,6 +1475,7 @@ "wallet__activity_failed" = "Fallido"; "wallet__activity_transfer" = "Transferir"; "wallet__activity_transferring" = "Transfiriendo"; +"wallet__activity_move_to_spark" = "Mover a Spark"; "wallet__activity_transfer_savings_pending" = "Desde Gasto ({duration})"; "wallet__activity_transfer_savings_done" = "Desde Gasto"; "wallet__activity_transfer_spending_pending" = "Desde Ahorros ({duration})"; @@ -1973,3 +2004,5 @@ "subscriptions__allowance_auto_paid" = "Pagado automáticamente"; "wallet__balance_updating" = "Actualizando saldo…"; +"lightning__move_to_spark__in_flight_text" = "El pago está en camino y aparecerá en Spark cuando se liquide. Si falla, la cantidad se queda en tu conexión."; +"lightning__move_to_spark__in_flight_title" = "Moviendo a\nSpark"; diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings index 3a655506e1..c4fab2bfa5 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -202,7 +202,7 @@ "lightning__funding__nav_title" = "Solde Dépenses"; "lightning__funding__text" = "Le plus simple est d\'utiliser vos économies Bitkit ou d\'envoyer des bitcoins depuis un autre portefeuille."; "lightning__funding__title" = "Financez votre solde Dépenses"; -"lightning__funding__button1" = "Transfert depuis l\'épargne"; +"lightning__funding__button1" = "Transférer depuis l'Épargne"; "lightning__funding__button2" = "Utiliser un autre portefeuille"; "lightning__funding__button3" = "Configuration manuelle"; "lightning__funding_advanced__button_short" = "Configuration avancée"; @@ -359,6 +359,29 @@ "lightning__transaction" = "Transaction"; "lightning__order_fee" = "Frais"; "lightning__balance" = "Solde"; +"lightning__move_to_spark__amount" = "Montant"; +"lightning__move_to_spark__confirm_text" = "Votre solde est déplacé vers Spark via Lightning, le moyen le moins cher de le garder dans Dépenses. Les frais de routage ci-dessous sont le maximum que vous payez."; +"lightning__move_to_spark__confirm_title" = "Déplacer vers\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Une partie de votre solde est maintenant sur Spark. Déplacez le reste de la même façon, puis fermez la connexion vidée."; +"lightning__move_to_spark__done_text" = "Votre solde est maintenant sur Spark. Fermez la connexion vidée pour renvoyer sa réserve vers l'Épargne."; +"lightning__move_to_spark__done_title" = "Déplacé vers\nSpark"; +"lightning__move_to_spark__failed_nothing" = "Vos connexions Lightning n'ont plus de solde à déplacer."; +"lightning__move_to_spark__failed_spark" = "Spark n'est pas encore prêt à recevoir. Réessayez dans un instant."; +"lightning__move_to_spark__failed_title" = "Déplacement\nimpossible"; +"lightning__move_to_spark__failed_unknown" = "Une erreur s'est produite lors de la préparation du déplacement. Réessayez."; +"lightning__move_to_spark__fee" = "Frais de routage"; +"lightning__move_to_spark__intro_text" = "Blocktank ferme ses connexions Lightning. Déplacez votre solde vers Spark maintenant : c'est l'option la moins chère, et il reste dans Dépenses."; +"lightning__move_to_spark__intro_title" = "Votre connexion\nva être fermée"; +"lightning__move_to_spark__move_half" = "Déplacer la moitié"; +"lightning__move_to_spark__move_now" = "Déplacer maintenant"; +"lightning__move_to_spark__move_rest" = "Déplacer le reste"; +"lightning__move_to_spark__nav_title" = "Déplacement vers Spark"; +"lightning__move_to_spark__quoting" = "Recherche d'une route et de ses frais…"; +"lightning__move_to_spark__swipe" = "Glissez pour déplacer"; +"lightning__move_to_spark__too_large_none" = "Fermez plutôt la connexion pour renvoyer le solde vers l'Épargne."; +"lightning__move_to_spark__too_large_smaller" = "Vous pouvez le déplacer en plusieurs parties plus petites."; +"lightning__move_to_spark__too_large_text" = "{amount} est trop élevé pour être routé vers Spark en un seul paiement."; +"lightning__move_to_spark__too_large_title" = "Montant\ntrop élevé"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Frais de réclamation"; "lightning__spark_confirmations" = "{count}/3 confirmations"; @@ -412,6 +435,9 @@ "lightning__spark_exit__leftover_swept" = "{amount} de frais d'urgence inutilisés ont été envoyés vers l'épargne."; "lightning__spark_exit__leftover_sending" = "Envoi de {amount} de frais d'urgence inutilisés vers l'épargne."; "lightning__spark_exit__leftover_dust" = "{amount} de frais d'urgence inutilisés est trop faible pour être envoyé et reste à {address}, chemin de dérivation {path}."; +"lightning__spark_exit__earlier_addresses" = "Anciennes adresses de sortie"; +"lightning__spark_exit__earlier_addresses_text" = "Les sorties d'urgence précédentes ont utilisé ces adresses de financement. Les pièces restées sur l'une d'elles vous appartiennent toujours : dépensez-les avec votre phrase de récupération et son chemin de dérivation."; +"lightning__spark_exit__earlier_path" = "Chemin de dérivation"; "lightning__spark_exit__lost_leaves" = "{amount} a été réclamé on-chain par un ancien propriétaire de ces fonds et ne peut pas être récupéré."; "lightning__spark_exit__notification_lost" = "{amount} de votre transfert forcé ne peut pas être récupéré. Ouvrez Bitkit pour savoir pourquoi."; "lightning__spark_exit__notification_failed" = "Votre transfert forcé s'est arrêté. Ouvrez Bitkit pour savoir pourquoi."; @@ -434,6 +460,7 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit n'a pas pu lire la progression enregistrée de ce transfert, il la reconstruit donc à partir de la chaîne."; "lightning__spark_exit__leftover_rejected" = "{amount} de frais d'urgence inutilisés n'a pas pu être envoyé et reste à {address}, chemin de dérivation {path}."; "lightning__spark_exit__notification_not_moving" = "Votre transfert forcé n'avance pas. Ouvrez Bitkit pour savoir pourquoi."; +"lightning__spark_exit__note_notifications_button" = "Activer les notifications"; "lightning__spark_exit__waiting_operators" = "{amount} que les opérateurs Spark ont déplacé on-chain attend qu'ils le libèrent. Bitkit redemande pendant une semaine au maximum."; "lightning__spark_exit__fee_rose" = "Les frais de réseau ont dépassé ceux de ce transfert. Il peut ralentir."; "lightning__spark_exit__fee_bump_button" = "Payer des frais plus élevés"; @@ -1420,6 +1447,7 @@ "wallet__swap_route_restored_title" = "Paiement renvoyé vers l'Épargne"; "wallet__send_paykit_no_route__title" = "Impossible de payer ce contact"; "wallet__send_paykit_no_route__description" = "Ce contact n’a actuellement aucun moyen de paiement que Bitkit peut utiliser."; +"wallet__send_paykit_withdrawal_settling__description" = "Un retrait précédent depuis votre solde Dépenses est toujours en cours de règlement. Réessayez une fois qu'il est terminé."; "wallet__recipient_contact" = "Contact"; "wallet__recipient_invoice" = "Coller la facture"; "wallet__recipient_manual" = "Entrer manuellement"; @@ -1510,6 +1538,7 @@ "wallet__payment_recipient_rejected" = "Le destinataire a rejeté ce paiement Lightning. Vérifiez la facture et réessayez."; "wallet__payment_abandoned" = "Le paiement Lightning a été arrêté avant d'être terminé."; "wallet__payment_expired" = "Ce paiement Lightning a expiré. Demandez une nouvelle facture."; +"wallet__payment_restored_invoice" = "Bitkit ne peut pas confirmer que cette facture n'a pas été payée avant la restauration de votre portefeuille. Veuillez demander une nouvelle facture."; "wallet__payment_timeout" = "Le paiement a expiré. Veuillez réessayer."; "wallet__payment_route_not_found" = "Bitkit n'a pas trouvé de route Lightning pour ce paiement."; "wallet__payment_retries_exhausted" = "Bitkit a essayé plusieurs routes Lightning, mais le paiement n'a pas pu être terminé."; @@ -1539,7 +1568,7 @@ "wallet__receive_show_qr" = "Afficher le QR code"; "wallet__receive_text_lnfunds" = "Vous souhaitez recevoir des fonds Lightning?"; "wallet__receive_spending" = "Recevoir sur le compte de dépenses"; -"wallet__receive_spending_text" = "Profitez de paiements en bitcoins instantanés et bon marché sur le Lightning Network."; +"wallet__receive_spending_text" = "Profitez de transactions instantanées et bon marché avec vos amis, votre famille et les commerçants."; "wallet__receive_spending_title" = "Recevoir sur le solde de dépenses"; "wallet__receive_cjit_error" = "Échec de la transaction"; "wallet__receive_cjit_error_msg" = "Échec de l’envoi vers Dépenses."; @@ -1556,6 +1585,7 @@ "wallet__activity_failed" = "Échec"; "wallet__activity_transfer" = "Transfert"; "wallet__activity_transferring" = "Transfert en cours"; +"wallet__activity_move_to_spark" = "Déplacement vers Spark"; "wallet__activity_transfer_savings_pending" = "Depuis le compte Dépenses ({duration})"; "wallet__activity_transfer_savings_done" = "Depuis le compte Dépenses"; "wallet__activity_transfer_spending_pending" = "Depuis l\'Épargne ({duration})"; @@ -2102,3 +2132,5 @@ "subscriptions__allowance_auto_paid" = "Payé automatiquement"; "wallet__balance_updating" = "Mise à jour du solde…"; +"lightning__move_to_spark__in_flight_text" = "Le paiement est en route et apparaîtra dans Spark une fois réglé. En cas d'échec, le montant reste dans votre connexion."; +"lightning__move_to_spark__in_flight_title" = "Déplacement vers\nSpark"; diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings index 11e23d4451..baca29d6c2 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -200,7 +200,7 @@ "lightning__funding__nav_title" = "Conto di Spesa"; "lightning__funding__text" = "Il modo più semplice è usare i tuoi risparmi Bitkit o inviare bitcoin da un portafoglio diverso."; "lightning__funding__title" = "Manda fondi al tuo conto di spesa"; -"lightning__funding__button1" = "Trasferimento da risparmio"; +"lightning__funding__button1" = "Trasferisci dai risparmi"; "lightning__funding__button2" = "Usa un altro portafoglio"; "lightning__funding__button3" = "Configurazione manuale"; "lightning__funding_advanced__button_short" = "Configurazione Avanzata"; @@ -230,6 +230,7 @@ "lightning__transfer_failed__cancel" = "Ispeziona errore"; "lightning__transfer_failed__continue" = "Riprova"; "lightning__spending_amount__quarter" = "25%"; +"lightning__spending_amount__error_min__title" = "Saldo Minimo dei Risparmi"; "lightning__spending_amount__error_max__title" = "Massimo Conto di Spesa"; "lightning__spending_amount__error_max__description" = "L'importo che puoi trasferire al tuo conto di spesa e' attualmente limitato a ₿ {amount}."; "lightning__spending_amount__error_fee" = "Impossibile ottenere la commissione di rete. Tocca per riprovare."; @@ -352,6 +353,29 @@ "lightning__transaction" = "Transazione"; "lightning__order_fee" = "Fee Ordine"; "lightning__balance" = "Saldo"; +"lightning__move_to_spark__amount" = "Importo"; +"lightning__move_to_spark__confirm_text" = "Il tuo saldo si sposta su Spark tramite Lightning, il modo più economico per mantenerlo nella Spesa. La commissione di routing qui sotto è il massimo che paghi."; +"lightning__move_to_spark__confirm_title" = "Sposta su\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Parte del tuo saldo ora è su Spark. Sposta il resto allo stesso modo, poi chiudi la connessione svuotata."; +"lightning__move_to_spark__done_text" = "Il tuo saldo ora è su Spark. Chiudi la connessione svuotata per riportare la sua riserva nei Risparmi."; +"lightning__move_to_spark__done_title" = "Spostato su\nSpark"; +"lightning__move_to_spark__failed_nothing" = "Le tue connessioni Lightning non hanno più saldo da spostare."; +"lightning__move_to_spark__failed_spark" = "Spark non è ancora pronto a ricevere. Riprova tra un momento."; +"lightning__move_to_spark__failed_title" = "Impossibile\nspostare"; +"lightning__move_to_spark__failed_unknown" = "Qualcosa è andato storto durante la preparazione dello spostamento. Riprova."; +"lightning__move_to_spark__fee" = "Commissione di routing"; +"lightning__move_to_spark__intro_text" = "Blocktank sta chiudendo le sue connessioni Lightning. Sposta ora il tuo saldo su Spark: è l'opzione più economica e resta nella Spesa."; +"lightning__move_to_spark__intro_title" = "La tua connessione\nsta per chiudersi"; +"lightning__move_to_spark__move_half" = "Sposta Metà"; +"lightning__move_to_spark__move_now" = "Sposta Ora"; +"lightning__move_to_spark__move_rest" = "Sposta il Resto"; +"lightning__move_to_spark__nav_title" = "Sposta su Spark"; +"lightning__move_to_spark__quoting" = "Ricerca di un percorso e della sua commissione…"; +"lightning__move_to_spark__swipe" = "Scorri Per Spostare"; +"lightning__move_to_spark__too_large_none" = "Chiudi invece la connessione per riportare il saldo nei Risparmi."; +"lightning__move_to_spark__too_large_smaller" = "Puoi spostarlo in parti più piccole."; +"lightning__move_to_spark__too_large_text" = "{amount} è troppo grande per essere instradato su Spark in un unico pagamento."; +"lightning__move_to_spark__too_large_title" = "Importo\ntroppo grande"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Commissione di riscatto"; "lightning__spark_confirmations" = "{count}/3 conferme"; @@ -405,6 +429,9 @@ "lightning__spark_exit__leftover_swept" = "{amount} di commissioni di emergenza non utilizzate è stato inviato ai risparmi."; "lightning__spark_exit__leftover_sending" = "Invio di {amount} di commissioni di emergenza non utilizzate ai risparmi."; "lightning__spark_exit__leftover_dust" = "{amount} di commissioni di emergenza non utilizzate è troppo poco per essere inviato e resta su {address}, percorso di derivazione {path}."; +"lightning__spark_exit__earlier_addresses" = "Indirizzi di uscita precedenti"; +"lightning__spark_exit__earlier_addresses_text" = "Le precedenti uscite di emergenza hanno usato questi indirizzi di finanziamento. Le monete rimaste su uno restano tue: spendile con la tua recovery phrase e il suo percorso di derivazione."; +"lightning__spark_exit__earlier_path" = "Percorso di derivazione"; "lightning__spark_exit__lost_leaves" = "{amount} è stato riscattato on-chain da un precedente proprietario di questi fondi e non può essere recuperato."; "lightning__spark_exit__notification_lost" = "{amount} del tuo trasferimento forzato non può essere recuperato. Apri Bitkit per scoprire perché."; "lightning__spark_exit__notification_failed" = "Il tuo trasferimento forzato si è interrotto. Apri Bitkit per scoprire perché."; @@ -427,6 +454,7 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit non è riuscito a leggere l'avanzamento salvato di questo trasferimento, quindi lo ricostruisce dalla blockchain."; "lightning__spark_exit__leftover_rejected" = "{amount} di commissioni di emergenza non utilizzate non ha potuto essere inviato e resta su {address}, percorso di derivazione {path}."; "lightning__spark_exit__notification_not_moving" = "Il tuo trasferimento forzato non avanza. Apri Bitkit per scoprire perché."; +"lightning__spark_exit__note_notifications_button" = "Attiva le notifiche"; "lightning__spark_exit__waiting_operators" = "{amount} che gli operatori Spark hanno spostato on-chain attende che lo rilascino. Bitkit lo richiede per un massimo di una settimana."; "lightning__spark_exit__fee_rose" = "Le commissioni di rete hanno superato quella di questo trasferimento. Potrebbe rallentare."; "lightning__spark_exit__fee_bump_button" = "Paga una commissione più alta"; @@ -1385,6 +1413,7 @@ "wallet__swap_route_restored_title" = "Pagamento restituito ai Risparmi"; "wallet__send_paykit_no_route__title" = "Impossibile pagare questo contatto"; "wallet__send_paykit_no_route__description" = "Al momento questo contatto non ha un metodo di pagamento che Bitkit possa usare."; +"wallet__send_paykit_withdrawal_settling__description" = "Un prelievo precedente dal tuo saldo di spesa è ancora in fase di regolamento. Riprova quando sarà completato."; "wallet__recipient_contact" = "Contatto"; "wallet__recipient_invoice" = "Incolla fattura"; "wallet__recipient_manual" = "Inserisci Manualmente"; @@ -1474,6 +1503,7 @@ "wallet__payment_recipient_rejected" = "Il destinatario ha rifiutato questo pagamento Lightning. Controlla la fattura e riprova."; "wallet__payment_abandoned" = "Il pagamento Lightning è stato interrotto prima del completamento."; "wallet__payment_expired" = "Questo pagamento Lightning è scaduto. Richiedi una nuova fattura."; +"wallet__payment_restored_invoice" = "Bitkit non può confermare che questa fattura non sia stata pagata prima del ripristino del tuo wallet. Richiedi una nuova fattura."; "wallet__payment_timeout" = "Il pagamento è scaduto. Riprova."; "wallet__payment_route_not_found" = "Bitkit non ha trovato una rotta Lightning per questo pagamento."; "wallet__payment_retries_exhausted" = "Bitkit ha provato diverse rotte Lightning, ma il pagamento non è stato completato."; @@ -1503,7 +1533,7 @@ "wallet__receive_show_qr" = "Visualizza QR Code"; "wallet__receive_text_lnfunds" = "Vuoi ricevere fondi Lightning?"; "wallet__receive_spending" = "Ricevi fondi Lightning"; -"wallet__receive_spending_text" = "Goditi pagamenti bitcoin istantanei ed economici sulla Lightning Network."; +"wallet__receive_spending_text" = "Goditi transazioni istantanee ed economiche con amici, familiari e commercianti."; "wallet__receive_spending_title" = "Ricevi su saldo di spesa"; "wallet__receive_cjit_error" = "Transazione Fallita"; "wallet__receive_cjit_error_msg" = "Impossibile inviare fondi al tuo conto di spesa."; @@ -1519,6 +1549,7 @@ "wallet__activity_failed" = "Fallito"; "wallet__activity_transfer" = "Trasferisci"; "wallet__activity_transferring" = "Trasferimento in corso"; +"wallet__activity_move_to_spark" = "Sposta su Spark"; "wallet__activity_transfer_savings_pending" = "Da Saldo Spendibile ({duration})"; "wallet__activity_transfer_savings_done" = "Da Saldo Spendibile"; "wallet__activity_transfer_spending_pending" = "Dai risparmi ({duration})"; @@ -2061,3 +2092,5 @@ "subscriptions__allowance_auto_paid" = "Pagato automaticamente"; "wallet__balance_updating" = "Aggiornamento del saldo…"; +"lightning__move_to_spark__in_flight_text" = "Il pagamento è in corso e apparirà in Spark una volta regolato. Se non va a buon fine, l'importo resta nella tua connessione."; +"lightning__move_to_spark__in_flight_title" = "Spostamento su\nSpark"; diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings index c0fc50cb1f..22d683ee01 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -356,6 +356,29 @@ "lightning__transaction" = "Transactie"; "lightning__order_fee" = "Order kosten"; "lightning__balance" = "Saldo"; +"lightning__move_to_spark__amount" = "Bedrag"; +"lightning__move_to_spark__confirm_text" = "Je saldo gaat via Lightning naar Spark, de goedkoopste manier om het in je bestedingssaldo te houden. De routeringsvergoeding hieronder is het maximum dat je betaalt."; +"lightning__move_to_spark__confirm_title" = "Verplaatsen naar\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Een deel van je saldo staat nu op Spark. Verplaats de rest op dezelfde manier en sluit daarna de leeggemaakte verbinding."; +"lightning__move_to_spark__done_text" = "Je saldo staat nu op Spark. Sluit de leeggemaakte verbinding om de reserve ervan terug te zetten naar je spaargeld."; +"lightning__move_to_spark__done_title" = "Verplaatst naar\nSpark"; +"lightning__move_to_spark__failed_nothing" = "Je Lightning-verbindingen hebben geen saldo meer om te verplaatsen."; +"lightning__move_to_spark__failed_spark" = "Spark is nog niet klaar om te ontvangen. Probeer het zo opnieuw."; +"lightning__move_to_spark__failed_title" = "Verplaatsen\nmislukt"; +"lightning__move_to_spark__failed_unknown" = "Er ging iets mis bij het voorbereiden van de verplaatsing. Probeer het opnieuw."; +"lightning__move_to_spark__fee" = "Routeringsvergoeding"; +"lightning__move_to_spark__intro_text" = "Blocktank sluit zijn Lightning-verbindingen. Verplaats je saldo nu naar Spark: dat is de goedkoopste optie, en het blijft in je bestedingssaldo."; +"lightning__move_to_spark__intro_title" = "Je verbinding\nwordt gesloten"; +"lightning__move_to_spark__move_half" = "Helft Verplaatsen"; +"lightning__move_to_spark__move_now" = "Nu Verplaatsen"; +"lightning__move_to_spark__move_rest" = "Rest Verplaatsen"; +"lightning__move_to_spark__nav_title" = "Verplaatsen Naar Spark"; +"lightning__move_to_spark__quoting" = "Route en vergoeding zoeken…"; +"lightning__move_to_spark__swipe" = "Veeg Om Te Verplaatsen"; +"lightning__move_to_spark__too_large_none" = "Sluit in plaats daarvan de verbinding om het saldo terug te zetten naar je spaargeld."; +"lightning__move_to_spark__too_large_smaller" = "Je kunt het in kleinere delen verplaatsen."; +"lightning__move_to_spark__too_large_text" = "{amount} is te groot om in één betaling naar Spark te routeren."; +"lightning__move_to_spark__too_large_title" = "Bedrag\nte groot"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Claimkosten"; "lightning__spark_confirmations" = "{count}/3 bevestigingen"; @@ -409,6 +432,9 @@ "lightning__spark_exit__leftover_swept" = "{amount} aan ongebruikte noodkosten is naar spaargeld gestuurd."; "lightning__spark_exit__leftover_sending" = "{amount} aan ongebruikte noodkosten wordt naar spaargeld gestuurd."; "lightning__spark_exit__leftover_dust" = "{amount} aan ongebruikte noodkosten is te klein om te versturen en blijft op {address}, afleidingspad {path}."; +"lightning__spark_exit__earlier_addresses" = "Eerdere exitadressen"; +"lightning__spark_exit__earlier_addresses_text" = "Eerdere noodexits gebruikten deze financieringsadressen. Coins die op een adres zijn achtergebleven, blijven van jou: besteed ze met je herstelwoorden en het afleidingspad."; +"lightning__spark_exit__earlier_path" = "Afleidingspad"; "lightning__spark_exit__lost_leaves" = "{amount} is on-chain geclaimd door een eerdere eigenaar van dit geld en kan niet worden teruggehaald."; "lightning__spark_exit__notification_lost" = "{amount} van uw geforceerde overboeking kan niet worden hersteld. Open Bitkit om te zien waarom."; "lightning__spark_exit__notification_failed" = "Uw geforceerde overboeking is gestopt. Open Bitkit om te zien waarom."; @@ -431,6 +457,7 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit kon de opgeslagen voortgang van deze overboeking niet lezen en bouwt die daarom opnieuw op vanaf de chain."; "lightning__spark_exit__leftover_rejected" = "{amount} aan ongebruikte noodkosten kon niet worden verstuurd en blijft op {address}, afleidingspad {path}."; "lightning__spark_exit__notification_not_moving" = "Uw geforceerde overboeking komt niet verder. Open Bitkit om te zien waarom."; +"lightning__spark_exit__note_notifications_button" = "Meldingen aanzetten"; "lightning__spark_exit__waiting_operators" = "{amount} dat de Spark-operators on-chain hebben gezet, wacht tot zij het vrijgeven. Bitkit vraagt het tot een week lang opnieuw."; "lightning__spark_exit__fee_rose" = "De netwerkkosten zijn hoger geworden dan de kosten van deze overboeking. Het kan vertragen."; "lightning__spark_exit__fee_bump_button" = "Hogere vergoeding betalen"; @@ -1415,6 +1442,7 @@ "wallet__swap_route_restored_title" = "Betaling teruggestort naar Spaargeld"; "wallet__send_paykit_no_route__title" = "Kan dit contact niet betalen"; "wallet__send_paykit_no_route__description" = "Dit contact heeft op dit moment geen betaalmethode die Bitkit kan gebruiken."; +"wallet__send_paykit_withdrawal_settling__description" = "Een eerdere opname van je bestedingssaldo wordt nog verwerkt. Probeer het opnieuw zodra die is voltooid."; "wallet__recipient_contact" = "Contact"; "wallet__recipient_invoice" = "Factuur Plakken"; "wallet__recipient_manual" = "Handmatig Invoeren"; @@ -1505,6 +1533,7 @@ "wallet__payment_recipient_rejected" = "De ontvanger heeft deze Lightning-betaling geweigerd. Controleer de factuur en probeer het opnieuw."; "wallet__payment_abandoned" = "De Lightning-betaling is gestopt voordat deze was voltooid."; "wallet__payment_expired" = "Deze Lightning-betaling is verlopen. Vraag een nieuwe factuur aan."; +"wallet__payment_restored_invoice" = "Bitkit kan niet bevestigen dat deze factuur niet is betaald voordat je je wallet herstelde. Vraag een nieuwe factuur aan."; "wallet__payment_timeout" = "Time-out voor betaling. Probeer het opnieuw."; "wallet__payment_route_not_found" = "Bitkit kon geen Lightning-route voor deze betaling vinden."; "wallet__payment_retries_exhausted" = "Bitkit heeft meerdere Lightning-routes geprobeerd, maar de betaling kon niet worden voltooid."; @@ -1534,7 +1563,7 @@ "wallet__receive_show_qr" = "Toon QR Code"; "wallet__receive_text_lnfunds" = "Wilt u Lightning ₿ ontvangen?"; "wallet__receive_spending" = "Ontvang Lightning-geld"; -"wallet__receive_spending_text" = "Geniet van directe en goedkope bitcoin-betalingen op het Lightning Network."; +"wallet__receive_spending_text" = "Geniet van directe en goedkope transacties met vrienden, familie en winkeliers."; "wallet__receive_spending_title" = "Ontvang op bestedingssaldo"; "wallet__receive_cjit_error" = "Transactie Mislukt"; "wallet__receive_cjit_error_msg" = "Fehler beim Senden der Gelder auf dein Ausgabenkonto."; @@ -1551,6 +1580,7 @@ "wallet__activity_failed" = "Mislukt"; "wallet__activity_transfer" = "Overboeken"; "wallet__activity_transferring" = "Overboeken"; +"wallet__activity_move_to_spark" = "Verplaatsen naar Spark"; "wallet__activity_transfer_savings_pending" = "Van Bestedingssaldo ({duration})"; "wallet__activity_transfer_savings_done" = "Van Bestedingssaldo"; "wallet__activity_transfer_spending_pending" = "Van Spaargeld ({duration})"; @@ -2096,3 +2126,5 @@ "subscriptions__allowance_auto_paid" = "Automatisch betaald"; "wallet__balance_updating" = "Saldo bijwerken…"; +"lightning__move_to_spark__in_flight_text" = "De betaling is onderweg en verschijnt in Spark zodra die is afgerond. Als die mislukt, blijft het bedrag in je verbinding."; +"lightning__move_to_spark__in_flight_title" = "Onderweg naar\nSpark"; diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings index 39ecbfd344..d71bffd76b 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -358,6 +358,29 @@ "lightning__transaction" = "Transakcja"; "lightning__order_fee" = "Opłata za zamówienie"; "lightning__balance" = "Saldo"; +"lightning__move_to_spark__amount" = "Kwota"; +"lightning__move_to_spark__confirm_text" = "Twoje saldo zostanie przeniesione do Spark przez Lightning, najtańszym sposobem na zachowanie go w Wydatkach. Opłata za routing poniżej to maksimum, jakie zapłacisz."; +"lightning__move_to_spark__confirm_title" = "Przenieś do\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Część Twojego salda jest już w Spark. Przenieś resztę w ten sam sposób, a potem zamknij opróżnione połączenie."; +"lightning__move_to_spark__done_text" = "Twoje saldo jest już w Spark. Zamknij opróżnione połączenie, aby zwrócić jego rezerwę do Oszczędności."; +"lightning__move_to_spark__done_title" = "Przeniesiono do\nSpark"; +"lightning__move_to_spark__failed_nothing" = "Na Twoich połączeniach Lightning nie zostało saldo do przeniesienia."; +"lightning__move_to_spark__failed_spark" = "Spark nie jest jeszcze gotowy do odbioru. Spróbuj ponownie za chwilę."; +"lightning__move_to_spark__failed_title" = "Nie udało się\nprzenieść"; +"lightning__move_to_spark__failed_unknown" = "Coś poszło nie tak podczas przygotowywania przeniesienia. Spróbuj ponownie."; +"lightning__move_to_spark__fee" = "Opłata za routing"; +"lightning__move_to_spark__intro_text" = "Blocktank zamyka swoje połączenia Lightning. Przenieś teraz saldo do Spark: to najtańsza opcja, a saldo pozostaje w Wydatkach."; +"lightning__move_to_spark__intro_title" = "Twoje połączenie\nzostanie zamknięte"; +"lightning__move_to_spark__move_half" = "Przenieś połowę"; +"lightning__move_to_spark__move_now" = "Przenieś teraz"; +"lightning__move_to_spark__move_rest" = "Przenieś resztę"; +"lightning__move_to_spark__nav_title" = "Przeniesienie do Spark"; +"lightning__move_to_spark__quoting" = "Szukanie trasy i jej opłaty…"; +"lightning__move_to_spark__swipe" = "Przesuń, aby przenieść"; +"lightning__move_to_spark__too_large_none" = "Zamiast tego zamknij połączenie, aby zwrócić saldo do Oszczędności."; +"lightning__move_to_spark__too_large_smaller" = "Możesz ją przenieść w mniejszych częściach."; +"lightning__move_to_spark__too_large_text" = "Kwota {amount} jest zbyt duża, aby przesłać ją do Spark jedną płatnością."; +"lightning__move_to_spark__too_large_title" = "Kwota\nzbyt duża"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Opłata za odbiór"; "lightning__spark_confirmations" = "{count}/3 potwierdzeń"; @@ -411,6 +434,9 @@ "lightning__spark_exit__leftover_swept" = "{amount} niewykorzystanych opłat awaryjnych zostało wysłane do oszczędności."; "lightning__spark_exit__leftover_sending" = "Wysyłanie {amount} niewykorzystanych opłat awaryjnych do oszczędności."; "lightning__spark_exit__leftover_dust" = "{amount} niewykorzystanych opłat awaryjnych to za mało, by je wysłać, i pozostaje pod adresem {address}, ścieżka derywacji {path}."; +"lightning__spark_exit__earlier_addresses" = "Wcześniejsze adresy wyjścia"; +"lightning__spark_exit__earlier_addresses_text" = "Wcześniejsze wyjścia awaryjne korzystały z tych adresów finansowania. Środki pozostawione na jednym z nich nadal należą do Ciebie: wydaj je za pomocą frazy odzyskiwania i ścieżki derywacji."; +"lightning__spark_exit__earlier_path" = "Ścieżka derywacji"; "lightning__spark_exit__lost_leaves" = "{amount} zostało przejęte on-chain przez poprzedniego właściciela tych środków i nie można go odzyskać."; "lightning__spark_exit__notification_lost" = "{amount} z Twojego wymuszonego transferu nie można odzyskać. Otwórz Bitkit, aby zobaczyć powód."; "lightning__spark_exit__notification_failed" = "Twój wymuszony transfer został zatrzymany. Otwórz Bitkit, aby zobaczyć powód."; @@ -433,6 +459,7 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit nie mógł odczytać zapisanego postępu tego transferu, więc odbudowuje go z łańcucha."; "lightning__spark_exit__leftover_rejected" = "{amount} niewykorzystanych opłat awaryjnych nie udało się wysłać i pozostaje pod adresem {address}, ścieżka derywacji {path}."; "lightning__spark_exit__notification_not_moving" = "Twój wymuszony transfer nie postępuje. Otwórz Bitkit, aby sprawdzić dlaczego."; +"lightning__spark_exit__note_notifications_button" = "Włącz powiadomienia"; "lightning__spark_exit__waiting_operators" = "{amount} przeniesione on-chain przez operatorów Spark czeka, aż je wydadzą. Bitkit będzie pytać ponownie przez maksymalnie tydzień."; "lightning__spark_exit__fee_rose" = "Opłaty sieciowe wzrosły powyżej opłaty tego transferu. Może on zwolnić."; "lightning__spark_exit__fee_bump_button" = "Zapłać wyższą opłatę"; @@ -1419,6 +1446,7 @@ "wallet__swap_route_restored_title" = "Płatność zwrócona do Oszczędności"; "wallet__send_paykit_no_route__title" = "Nie można zapłacić temu kontaktowi"; "wallet__send_paykit_no_route__description" = "Ten kontakt nie ma obecnie żadnej metody płatności, której Bitkit może użyć."; +"wallet__send_paykit_withdrawal_settling__description" = "Wcześniejsza wypłata z Twojego salda wydatków jest wciąż rozliczana. Spróbuj ponownie, gdy się zakończy."; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Wklej fakturę"; "wallet__recipient_manual" = "Wprowadź ręcznie"; @@ -1509,6 +1537,7 @@ "wallet__payment_recipient_rejected" = "Odbiorca odrzucił tę płatność Lightning. Sprawdź fakturę i spróbuj ponownie."; "wallet__payment_abandoned" = "Płatność Lightning została zatrzymana przed zakończeniem."; "wallet__payment_expired" = "Ta płatność Lightning wygasła. Poproś o nową fakturę."; +"wallet__payment_restored_invoice" = "Bitkit nie może potwierdzić, że ta faktura nie została opłacona przed przywróceniem Twojego portfela. Poproś o nową fakturę."; "wallet__payment_timeout" = "Przekroczono limit czasu płatności. Spróbuj ponownie."; "wallet__payment_route_not_found" = "Bitkit nie znalazł trasy Lightning dla tej płatności."; "wallet__payment_retries_exhausted" = "Bitkit wypróbował kilka tras Lightning, ale płatności nie udało się ukończyć."; @@ -1538,7 +1567,7 @@ "wallet__receive_show_qr" = "Skanuj kod QR"; "wallet__receive_text_lnfunds" = "Chcesz otrzymać fundusze Lightning?"; "wallet__receive_spending" = "Odbierz środki Lightning"; -"wallet__receive_spending_text" = "Korzystaj z natychmiastowych i tanich płatności bitcoin w sieci Lightning."; +"wallet__receive_spending_text" = "Korzystaj z natychmiastowych i tanich transakcji ze znajomymi, rodziną i sprzedawcami."; "wallet__receive_spending_title" = "Odbierz na saldo wydatków"; "wallet__receive_cjit_error" = "Transakcja nie powiodła się"; "wallet__receive_cjit_error_msg" = "Nie udało się wysłać środków na Twoje saldo wydatków."; @@ -1555,6 +1584,7 @@ "wallet__activity_failed" = "Niepowodzenie"; "wallet__activity_transfer" = "Transfery"; "wallet__activity_transferring" = "Przesyłanie"; +"wallet__activity_move_to_spark" = "Przeniesienie do Spark"; "wallet__activity_transfer_savings_pending" = "Z salda wydatków ({duration})"; "wallet__activity_transfer_savings_done" = "Z salda wydatków"; "wallet__activity_transfer_spending_pending" = "Z oszczędności ({duration})"; @@ -2101,3 +2131,5 @@ "subscriptions__allowance_auto_paid" = "Opłacono automatycznie"; "wallet__balance_updating" = "Aktualizowanie salda…"; +"lightning__move_to_spark__in_flight_text" = "Płatność jest w drodze i pojawi się w Spark po rozliczeniu. Jeśli się nie powiedzie, kwota pozostanie w Twoim połączeniu."; +"lightning__move_to_spark__in_flight_title" = "Przenoszenie do\nSpark"; diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings index bc0ba75a69..ea9a7c7f02 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -358,6 +358,29 @@ "lightning__transaction" = "Transação"; "lightning__order_fee" = "Taxa de pedido"; "lightning__balance" = "Saldo"; +"lightning__move_to_spark__amount" = "Valor"; +"lightning__move_to_spark__confirm_text" = "Seu saldo vai para a Spark pela Lightning, a forma de menor taxa de mantê-lo em Gastos. A taxa de roteamento abaixo é o máximo que você paga."; +"lightning__move_to_spark__confirm_title" = "Mover para a\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Parte do seu saldo já está na Spark. Mova o restante da mesma forma e depois feche a conexão esvaziada."; +"lightning__move_to_spark__done_text" = "Seu saldo já está na Spark. Feche a conexão esvaziada para devolver a reserva dela à Poupança."; +"lightning__move_to_spark__done_title" = "Movido para a\nSpark"; +"lightning__move_to_spark__failed_nothing" = "Suas conexões Lightning não têm mais saldo para mover."; +"lightning__move_to_spark__failed_spark" = "A Spark ainda não está pronta para receber. Tente novamente em instantes."; +"lightning__move_to_spark__failed_title" = "Não foi possível\nmover"; +"lightning__move_to_spark__failed_unknown" = "Algo deu errado ao preparar a movimentação. Tente novamente."; +"lightning__move_to_spark__fee" = "Taxa de roteamento"; +"lightning__move_to_spark__intro_text" = "A Blocktank está fechando suas conexões Lightning. Mova seu saldo para a Spark agora: é a opção de menor taxa, e ele continua em Gastos."; +"lightning__move_to_spark__intro_title" = "Sua conexão\nvai ser fechada"; +"lightning__move_to_spark__move_half" = "Mover Metade"; +"lightning__move_to_spark__move_now" = "Mover Agora"; +"lightning__move_to_spark__move_rest" = "Mover o Restante"; +"lightning__move_to_spark__nav_title" = "Mover Para a Spark"; +"lightning__move_to_spark__quoting" = "Buscando uma rota e sua taxa…"; +"lightning__move_to_spark__swipe" = "Deslizar Para Mover"; +"lightning__move_to_spark__too_large_none" = "Em vez disso, feche a conexão para devolver o saldo à Poupança."; +"lightning__move_to_spark__too_large_smaller" = "Você pode movê-lo em partes menores."; +"lightning__move_to_spark__too_large_text" = "{amount} é grande demais para ser roteado para a Spark em um único pagamento."; +"lightning__move_to_spark__too_large_title" = "Valor\ngrande demais"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Taxa de resgate"; "lightning__spark_confirmations" = "{count}/3 confirmações"; @@ -411,6 +434,9 @@ "lightning__spark_exit__leftover_swept" = "{amount} de taxas de emergência não utilizadas foi enviado para a poupança."; "lightning__spark_exit__leftover_sending" = "Enviando {amount} de taxas de emergência não utilizadas para a poupança."; "lightning__spark_exit__leftover_dust" = "{amount} de taxas de emergência não utilizadas é pequeno demais para enviar e fica em {address}, caminho de derivação {path}."; +"lightning__spark_exit__earlier_addresses" = "Endereços de saída anteriores"; +"lightning__spark_exit__earlier_addresses_text" = "As saídas de emergência anteriores usaram estes endereços de financiamento. As moedas deixadas em um deles continuam sendo suas: gaste-as com sua frase de recuperação e o caminho de derivação dela."; +"lightning__spark_exit__earlier_path" = "Caminho de derivação"; "lightning__spark_exit__lost_leaves" = "{amount} foi resgatado on-chain por um antigo dono desses fundos e não pode ser recuperado."; "lightning__spark_exit__notification_lost" = "{amount} da sua transferência forçada não pode ser recuperado. Abra a Bitkit para ver o motivo."; "lightning__spark_exit__notification_failed" = "Sua transferência forçada parou. Abra a Bitkit para ver o motivo."; @@ -433,6 +459,7 @@ "lightning__spark_exit__rebuilt_from_chain" = "A Bitkit não conseguiu ler o progresso salvo desta transferência, então o reconstrói a partir da blockchain."; "lightning__spark_exit__leftover_rejected" = "{amount} de taxas de emergência não utilizadas não pôde ser enviado e fica em {address}, caminho de derivação {path}."; "lightning__spark_exit__notification_not_moving" = "Sua transferência forçada não está avançando. Abra a Bitkit para ver o motivo."; +"lightning__spark_exit__note_notifications_button" = "Ativar notificações"; "lightning__spark_exit__waiting_operators" = "{amount} que os operadores da Spark moveram on-chain aguarda que eles o liberem. A Bitkit pede novamente por até uma semana."; "lightning__spark_exit__fee_rose" = "As taxas de rede subiram acima da taxa desta transferência. Ela pode ficar mais lenta."; "lightning__spark_exit__fee_bump_button" = "Pagar uma taxa maior"; @@ -1420,6 +1447,7 @@ "wallet__swap_route_restored_title" = "Pagamento devolvido à Poupança"; "wallet__send_paykit_no_route__title" = "Não é possível pagar este contato"; "wallet__send_paykit_no_route__description" = "Este contato não tem nenhum método de pagamento que o Bitkit possa usar agora."; +"wallet__send_paykit_withdrawal_settling__description" = "Um saque anterior do seu saldo de gastos ainda está sendo liquidado. Tente novamente quando ele for concluído."; "wallet__recipient_contact" = "Contato"; "wallet__recipient_invoice" = "Colar Invoice"; "wallet__recipient_manual" = "Inserir Manualmente"; @@ -1510,6 +1538,7 @@ "wallet__payment_recipient_rejected" = "O destinatário rejeitou este pagamento Lightning. Verifique a fatura e tente novamente."; "wallet__payment_abandoned" = "O pagamento Lightning foi interrompido antes de ser concluído."; "wallet__payment_expired" = "Este pagamento Lightning expirou. Solicite uma nova fatura."; +"wallet__payment_restored_invoice" = "A Bitkit não consegue confirmar que esta fatura não foi paga antes de você restaurar sua carteira. Solicite uma nova fatura."; "wallet__payment_timeout" = "O pagamento expirou. Tente novamente."; "wallet__payment_route_not_found" = "O Bitkit não conseguiu encontrar uma rota Lightning para este pagamento."; "wallet__payment_retries_exhausted" = "O Bitkit tentou várias rotas Lightning, mas o pagamento não pôde ser concluído."; @@ -1539,7 +1568,7 @@ "wallet__receive_show_qr" = "Mostrar código QR"; "wallet__receive_text_lnfunds" = "Deseja receber via Lightning?"; "wallet__receive_spending" = "Receber no Saldo de Gastos"; -"wallet__receive_spending_text" = "Aproveite pagamentos em bitcoin instantâneos e baratos na Lightning Network."; +"wallet__receive_spending_text" = "Aproveite transações instantâneas e baratas com amigos, família e comerciantes."; "wallet__receive_spending_title" = "Receber no saldo de gastos"; "wallet__receive_cjit_error" = "Falha na Transação"; "wallet__receive_cjit_error_msg" = "Falha ao enviar fundos para sua conta de gastos."; @@ -1556,6 +1585,7 @@ "wallet__activity_failed" = "Falha"; "wallet__activity_transfer" = "Transferência"; "wallet__activity_transferring" = "Transferindo"; +"wallet__activity_move_to_spark" = "Mover para a Spark"; "wallet__activity_transfer_savings_pending" = "Do Saldo de Gastos ({duration})"; "wallet__activity_transfer_savings_done" = "Do Saldo de Gastos"; "wallet__activity_transfer_spending_pending" = "Da Poupança ({duration})"; @@ -2102,3 +2132,5 @@ "subscriptions__allowance_auto_paid" = "Pago automaticamente"; "wallet__balance_updating" = "Atualizando saldo…"; +"lightning__move_to_spark__in_flight_text" = "O pagamento está a caminho e aparece na Spark quando for liquidado. Se falhar, o valor continua na sua conexão."; +"lightning__move_to_spark__in_flight_title" = "Movendo para a\nSpark"; diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings index f48c7b66d8..dd0c3e22de 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -5,6 +5,7 @@ "wallet__payment_recipient_rejected" = "O destinatário rejeitou este pagamento Lightning. Verifique a fatura e tente novamente."; "wallet__payment_abandoned" = "O pagamento Lightning foi interrompido antes de ser concluído."; "wallet__payment_expired" = "Este pagamento Lightning expirou. Peça uma nova fatura."; +"wallet__payment_restored_invoice" = "A Bitkit não consegue confirmar que esta fatura não foi paga antes de restaurar a sua carteira. Peça uma nova fatura."; "wallet__payment_timeout" = "O pagamento expirou. Tente novamente."; "wallet__send_error_support" = "Suporte"; "wallet__payment_route_not_found" = "O Bitkit não conseguiu encontrar uma rota Lightning para este pagamento."; @@ -251,6 +252,7 @@ "lightning__spending_intro__text" = "Transfira fundos para seu saldo de gastos para desfrutar de transações instantâneas e baratas com amigos, familiares e comerciantes."; "lightning__spending_intro__button" = "Começar"; "lightning__spending_amount__quarter" = "25%"; +"lightning__spending_amount__error_min__title" = "Mínimo do saldo de poupança"; "lightning__spending_amount__error_max__title" = "Saldo de gastos Máximo"; "lightning__spending_amount__error_max__description" = "O valor que você pode transferir para seu saldo de gastos está atualmente limitado a ₿ {amount}."; "lightning__spending_amount__error_fee" = "Não foi possível obter a taxa de rede. Toque para tentar novamente."; @@ -356,6 +358,29 @@ "lightning__transaction" = "Transação"; "lightning__order_fee" = "Taxa de pedido"; "lightning__balance" = "Saldo"; +"lightning__move_to_spark__amount" = "Montante"; +"lightning__move_to_spark__confirm_text" = "O seu saldo é movido para a Spark através da Lightning, a forma com as taxas mais baixas de o manter em Gastos. A taxa de encaminhamento abaixo é o máximo que paga."; +"lightning__move_to_spark__confirm_title" = "Mover para a\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Parte do seu saldo já está na Spark. Mova o resto da mesma forma e depois feche a conexão esvaziada."; +"lightning__move_to_spark__done_text" = "O seu saldo já está na Spark. Feche a conexão esvaziada para devolver a respetiva reserva à Poupança."; +"lightning__move_to_spark__done_title" = "Movido para a\nSpark"; +"lightning__move_to_spark__failed_nothing" = "As suas conexões Lightning não têm saldo para mover."; +"lightning__move_to_spark__failed_spark" = "A Spark ainda não está pronta para receber. Tente novamente daqui a pouco."; +"lightning__move_to_spark__failed_title" = "Não foi possível\nmover"; +"lightning__move_to_spark__failed_unknown" = "Algo correu mal ao preparar o movimento. Tente novamente."; +"lightning__move_to_spark__fee" = "Taxa de encaminhamento"; +"lightning__move_to_spark__intro_text" = "A Blocktank está a fechar as suas conexões Lightning. Mova agora o seu saldo para a Spark: é a opção com as taxas mais baixas e continua em Gastos."; +"lightning__move_to_spark__intro_title" = "A sua conexão\nvai ser fechada"; +"lightning__move_to_spark__move_half" = "Mover Metade"; +"lightning__move_to_spark__move_now" = "Mover Agora"; +"lightning__move_to_spark__move_rest" = "Mover o Resto"; +"lightning__move_to_spark__nav_title" = "Mover Para a Spark"; +"lightning__move_to_spark__quoting" = "A procurar uma rota e a respetiva taxa…"; +"lightning__move_to_spark__swipe" = "Deslizar Para Mover"; +"lightning__move_to_spark__too_large_none" = "Em vez disso, feche a conexão para devolver o saldo à Poupança."; +"lightning__move_to_spark__too_large_smaller" = "Pode movê-lo em partes mais pequenas."; +"lightning__move_to_spark__too_large_text" = "{amount} é demasiado elevado para encaminhar para a Spark num só pagamento."; +"lightning__move_to_spark__too_large_title" = "Montante\ndemasiado elevado"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Taxa de resgate"; "lightning__spark_confirmations" = "{count}/3 confirmações"; @@ -409,6 +434,9 @@ "lightning__spark_exit__leftover_swept" = "{amount} de taxas de emergência não utilizadas foi enviado para a poupança."; "lightning__spark_exit__leftover_sending" = "A enviar {amount} de taxas de emergência não utilizadas para a poupança."; "lightning__spark_exit__leftover_dust" = "{amount} de taxas de emergência não utilizadas é demasiado pequeno para enviar e fica em {address}, caminho de derivação {path}."; +"lightning__spark_exit__earlier_addresses" = "Endereços de saída anteriores"; +"lightning__spark_exit__earlier_addresses_text" = "As saídas de emergência anteriores usaram estes endereços de financiamento. As moedas deixadas num deles continuam a ser suas: gaste-as com a sua frase de recuperação e o respetivo caminho de derivação."; +"lightning__spark_exit__earlier_path" = "Caminho de derivação"; "lightning__spark_exit__lost_leaves" = "{amount} foi reclamado on-chain por um antigo dono destes fundos e não pode ser recuperado."; "lightning__spark_exit__notification_lost" = "{amount} da sua transferência forçada não pode ser recuperado. Abra a Bitkit para ver porquê."; "lightning__spark_exit__notification_failed" = "A sua transferência forçada parou. Abra a Bitkit para ver porquê."; @@ -431,6 +459,7 @@ "lightning__spark_exit__rebuilt_from_chain" = "A Bitkit não conseguiu ler o progresso guardado desta transferência, por isso reconstrói-o a partir da blockchain."; "lightning__spark_exit__leftover_rejected" = "{amount} de taxas de emergência não utilizadas não pôde ser enviado e fica em {address}, caminho de derivação {path}."; "lightning__spark_exit__notification_not_moving" = "A sua transferência forçada não está a avançar. Abra a Bitkit para ver porquê."; +"lightning__spark_exit__note_notifications_button" = "Ativar notificações"; "lightning__spark_exit__waiting_operators" = "{amount} que os operadores da Spark moveram on-chain aguarda que o libertem. A Bitkit volta a pedir durante até uma semana."; "lightning__spark_exit__fee_rose" = "As taxas de rede subiram acima da taxa desta transferência. Pode ficar mais lenta."; "lightning__spark_exit__fee_bump_button" = "Pagar uma taxa mais alta"; @@ -1174,6 +1203,7 @@ "wallet__swap_route_restored_title" = "Pagamento devolvido às Poupanças"; "wallet__send_paykit_no_route__title" = "Não é possível pagar a este contacto"; "wallet__send_paykit_no_route__description" = "Este contacto não tem neste momento nenhum método de pagamento que a Bitkit possa usar."; +"wallet__send_paykit_withdrawal_settling__description" = "Um saque anterior do seu saldo de gastos ainda está a ser liquidado. Tente novamente quando estiver concluído."; "wallet__recipient_contact" = "Contato"; "wallet__recipient_invoice" = "Colar Invoice"; "wallet__recipient_manual" = "Inserir Manualmente"; @@ -1256,7 +1286,7 @@ "wallet__receive_note_placeholder" = "Comentário opcional para o pagador"; "wallet__receive_show_qr" = "Mostrar código QR"; "wallet__receive_spending" = "Receber fundos Lightning"; -"wallet__receive_spending_text" = "Desfrute de pagamentos em bitcoin instantâneos e baratos na rede Lightning."; +"wallet__receive_spending_text" = "Desfrute de transações instantâneas e baratas com amigos, família e comerciantes."; "wallet__receive_spending_title" = "Receba no saldo de gastos"; "wallet__activity" = "Atividade"; "wallet__activity_no" = "Nenhuma atividade ainda"; @@ -1267,6 +1297,7 @@ "wallet__activity_failed" = "Falha"; "wallet__activity_transfer" = "Transferência"; "wallet__activity_transferring" = "Em transferência"; +"wallet__activity_move_to_spark" = "Mover para a Spark"; "wallet__activity_transfer_savings_pending" = "Do Saldo de Gastos (±{duration})"; "wallet__activity_transfer_savings_done" = "Do Saldo de Gastos"; "wallet__activity_transfer_spending_pending" = "Da Poupança (±{duration})"; @@ -1748,5 +1779,7 @@ "subscriptions__allowance_auto_paid" = "Pago automaticamente"; "wallet__balance_updating" = "A atualizar o saldo…"; +"lightning__move_to_spark__in_flight_text" = "O pagamento está a caminho e aparece na Spark quando for liquidado. Se falhar, o montante fica na sua conexão."; +"lightning__move_to_spark__in_flight_title" = "A mover para a\nSpark"; "other__error_keychain" = "Problema de Ligação de Dados"; "other__error_keychain_msg" = "Não foi possível carregar a chave principal do porta-chaves."; diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings index f339835a0c..f5e2d7af09 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -231,6 +231,7 @@ "lightning__transfer_failed__cancel" = "Проверить Ошибку"; "lightning__transfer_failed__continue" = "Попробовать Снова"; "lightning__spending_amount__quarter" = "25%"; +"lightning__spending_amount__error_min__title" = "Минимум Баланса Сбережений"; "lightning__spending_amount__error_max__title" = "Максимум Баланса Расходов"; "lightning__spending_amount__error_max__description" = "Сумма, которую вы можете перевести на баланс расходов, в настоящее время ограничена ₿ {amount}."; "lightning__spending_amount__error_fee" = "Не удалось получить сетевую комиссию. Нажмите, чтобы повторить."; @@ -353,6 +354,29 @@ "lightning__transaction" = "Транзакция"; "lightning__order_fee" = "Комиссия Ордера"; "lightning__balance" = "Баланс"; +"lightning__move_to_spark__amount" = "Сумма"; +"lightning__move_to_spark__confirm_text" = "Ваш баланс переносится в Spark через Lightning — это самый дешёвый способ сохранить его в Расходах. Комиссия за маршрутизацию ниже — максимум, который вы заплатите."; +"lightning__move_to_spark__confirm_title" = "Перенос в\nSpark"; +"lightning__move_to_spark__done_rest_text" = "Часть вашего баланса уже в Spark. Перенесите остаток так же, а затем закройте опустевшее соединение."; +"lightning__move_to_spark__done_text" = "Ваш баланс уже в Spark. Закройте опустевшее соединение, чтобы вернуть его резерв в Сбережения."; +"lightning__move_to_spark__done_title" = "Перенесено в\nSpark"; +"lightning__move_to_spark__failed_nothing" = "На ваших Lightning соединениях не осталось баланса для переноса."; +"lightning__move_to_spark__failed_spark" = "Spark пока не готов принимать платежи. Попробуйте ещё раз чуть позже."; +"lightning__move_to_spark__failed_title" = "Не удалось\nперенести"; +"lightning__move_to_spark__failed_unknown" = "Что-то пошло не так при подготовке переноса. Попробуйте снова."; +"lightning__move_to_spark__fee" = "Комиссия за маршрутизацию"; +"lightning__move_to_spark__intro_text" = "Blocktank закрывает свои Lightning соединения. Перенесите баланс в Spark сейчас: это самый дешёвый вариант, и баланс останется в Расходах."; +"lightning__move_to_spark__intro_title" = "Ваше соединение\nзакрывается"; +"lightning__move_to_spark__move_half" = "Перенести Половину"; +"lightning__move_to_spark__move_now" = "Перенести Сейчас"; +"lightning__move_to_spark__move_rest" = "Перенести Остаток"; +"lightning__move_to_spark__nav_title" = "Перенос в Spark"; +"lightning__move_to_spark__quoting" = "Поиск маршрута и комиссии…"; +"lightning__move_to_spark__swipe" = "Проведите для Переноса"; +"lightning__move_to_spark__too_large_none" = "Вместо этого закройте соединение, чтобы вернуть баланс в Сбережения."; +"lightning__move_to_spark__too_large_smaller" = "Вы можете перенести её несколькими частями поменьше."; +"lightning__move_to_spark__too_large_text" = "Сумма {amount} слишком велика, чтобы направить её в Spark одним платежом."; +"lightning__move_to_spark__too_large_title" = "Сумма\nслишком велика"; "lightning__spark" = "Spark"; "lightning__spark_claim_fee" = "Комиссия за зачисление"; "lightning__spark_confirmations" = "{count}/3 подтверждений"; @@ -406,6 +430,9 @@ "lightning__spark_exit__leftover_swept" = "Неиспользованные экстренные комиссии ({amount}) отправлены в сбережения."; "lightning__spark_exit__leftover_sending" = "Отправка неиспользованных экстренных комиссий ({amount}) в сбережения."; "lightning__spark_exit__leftover_dust" = "Неиспользованные экстренные комиссии в размере {amount} слишком малы для отправки и остаются на {address}, путь деривации {path}."; +"lightning__spark_exit__earlier_addresses" = "Прежние адреса выхода"; +"lightning__spark_exit__earlier_addresses_text" = "Прежние экстренные выходы использовали эти адреса пополнения. Монеты, оставшиеся на одном из них, по-прежнему ваши: потратьте их с помощью фразы восстановления и её пути деривации."; +"lightning__spark_exit__earlier_path" = "Путь деривации"; "lightning__spark_exit__lost_leaves" = "{amount} забрал ончейн один из прежних владельцев этих средств, их нельзя вернуть."; "lightning__spark_exit__notification_lost" = "{amount} из вашего принудительного перевода нельзя вернуть. Откройте Bitkit, чтобы узнать причину."; "lightning__spark_exit__notification_failed" = "Ваш принудительный перевод остановлен. Откройте Bitkit, чтобы узнать причину."; @@ -428,6 +455,7 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit не смог прочитать сохранённый прогресс этого перевода, поэтому восстанавливает его по блокчейну."; "lightning__spark_exit__leftover_rejected" = "Неиспользованные экстренные комиссии в размере {amount} не удалось отправить, они остаются на {address}, путь деривации {path}."; "lightning__spark_exit__notification_not_moving" = "Ваш принудительный перевод не продвигается. Откройте Bitkit, чтобы узнать причину."; +"lightning__spark_exit__note_notifications_button" = "Включить уведомления"; "lightning__spark_exit__waiting_operators" = "{amount}, которые операторы Spark перевели ончейн, ждут, пока операторы их выдадут. Bitkit будет запрашивать снова в течение недели."; "lightning__spark_exit__fee_rose" = "Сетевые комиссии превысили комиссию этого перевода. Он может замедлиться."; "lightning__spark_exit__fee_bump_button" = "Заплатить больше"; @@ -1404,6 +1432,7 @@ "wallet__swap_route_restored_title" = "Платёж возвращён в Сбережения"; "wallet__send_paykit_no_route__title" = "Не удаётся оплатить этому контакту"; "wallet__send_paykit_no_route__description" = "У этого контакта сейчас нет способа оплаты, который может использовать Bitkit."; +"wallet__send_paykit_withdrawal_settling__description" = "Предыдущий вывод с баланса расходов ещё не завершён. Попробуйте снова, когда он завершится."; "wallet__recipient_contact" = "Контакт"; "wallet__recipient_invoice" = "Вставить Инвойс"; "wallet__recipient_manual" = "Ввести Вручную"; @@ -1493,6 +1522,7 @@ "wallet__payment_recipient_rejected" = "Получатель отклонил этот платеж Lightning. Проверьте счет и попробуйте снова."; "wallet__payment_abandoned" = "Платеж Lightning был остановлен до завершения."; "wallet__payment_expired" = "Срок действия этого платежа Lightning истек. Запросите новый счет."; +"wallet__payment_restored_invoice" = "Bitkit не может подтвердить, что этот счёт не был оплачен до восстановления вашего кошелька. Запросите новый счёт."; "wallet__payment_timeout" = "Время ожидания платежа истекло. Попробуйте еще раз."; "wallet__payment_route_not_found" = "Bitkit не смог найти маршрут Lightning для этого платежа."; "wallet__payment_retries_exhausted" = "Bitkit попробовал несколько маршрутов Lightning, но платеж не удалось завершить."; @@ -1522,7 +1552,7 @@ "wallet__receive_show_qr" = "Показать QR-код"; "wallet__receive_text_lnfunds" = "Хотите получить Лайтнинг средства?"; "wallet__receive_spending" = "Получить Lightning средства"; -"wallet__receive_spending_text" = "Наслаждайтесь мгновенными и дешёвыми биткоин-платежами в сети Lightning."; +"wallet__receive_spending_text" = "Наслаждайтесь мгновенными и дешёвыми транзакциями с друзьями, семьёй и продавцами."; "wallet__receive_spending_title" = "Получить на баланс расходов"; "wallet__receive_cjit_error" = "Транзакция не удалась"; "wallet__receive_cjit_error_msg" = "Не удалось отправить средства на ваш Баланс Расходов."; @@ -1539,6 +1569,7 @@ "wallet__activity_failed" = "Не удалось"; "wallet__activity_transfer" = "Перенос"; "wallet__activity_transferring" = "Перевод"; +"wallet__activity_move_to_spark" = "Перенос в Spark"; "wallet__activity_transfer_savings_pending" = "От Расходов ({duration}м)"; "wallet__activity_transfer_savings_done" = "От Расходов"; "wallet__activity_transfer_spending_pending" = "От Сбережений ({duration}м)"; @@ -2082,3 +2113,5 @@ "subscriptions__allowance_auto_paid" = "Оплачено автоматически"; "wallet__balance_updating" = "Обновление баланса…"; +"lightning__move_to_spark__in_flight_text" = "Платёж в пути и появится в Spark после завершения. Если он не пройдёт, сумма останется в вашем соединении."; +"lightning__move_to_spark__in_flight_title" = "Идёт перенос\nв Spark"; diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index e5b898b4a3..8cc37fbcf3 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -819,6 +819,7 @@ class BackupService { SparkExitEarlierAddressBackup.restore(payload.sparkExitEarlierAddresses, network: "\(Env.network)") { SparkExitEarlierAddressStore(walletIndex: $0) } + await MoveToSparkPayments.restore(payload.moveToSparkPaymentHashes) // Force address rotation by clearing onchain address UserDefaults.standard.set("", forKey: "onchainAddress") @@ -992,6 +993,15 @@ class BackupService { } .store(in: cancellables) + // METADATA (moves to Spark) + MoveToSparkPayments.savedPublisher + .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) + .sink { @Sendable [weak self] _ in + guard let self, !self.shouldSkipBackup() else { return } + markBackupRequired(category: .metadata) + } + .store(in: cancellables) + // APP STATE (UserDefaults changes, etc.) SettingsViewModel.shared.appStatePublisher .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) @@ -1421,6 +1431,7 @@ class BackupService { // case to guard against. Nil rather than an empty map when nothing is named, so an // envelope this app writes stays byte-comparable with one bitkit-android writes. let hwWalletNames = HwKnownDeviceStorage.backupSnapshot() + let moveToSparkPaymentHashes = await MoveToSparkPayments.backupSnapshot() let payload = MetadataBackupV1( version: 1, @@ -1433,7 +1444,8 @@ class BackupService { sparkExitEarlierAddresses: SparkExitEarlierAddressBackup.backup( SparkExitEarlierAddressStore(walletIndex: LightningService.shared.currentWalletIndex), walletKey: SparkExitFundingIndexes.walletKey(network: "\(Env.network)", walletIndex: LightningService.shared.currentWalletIndex) - ) + ), + moveToSparkPaymentHashes: moveToSparkPaymentHashes.isEmpty ? nil : moveToSparkPaymentHashes ) return try JSONEncoder().encode(payload) @@ -1495,7 +1507,7 @@ class BackupService { let backup: SparkExitBackupV1 do { backup = try JSONDecoder().decode(SparkExitBackupV1.self, from: data) - } catch let error as DecodingError { + } catch let error as Swift.DecodingError { // A layout this app can't read never becomes readable here, so it is kept apart for an app that can. Logger.warn("Unreadable '\(BackupCategory.sparkExit.rawValue)' backup: \(error)", context: "BackupService") try await setAsideRejectedSparkExit(data) @@ -1513,8 +1525,8 @@ class BackupService { } } - /// Keeps remote exit data Spark can never import under its own key, so a fresh export doesn't replace it and an app that - /// can import it still finds it. The first such copy stays; a later one doesn't overwrite it. + /// Keeps remote exit data Spark can never import under its own key, so a fresh export doesn't replace it and it stays + /// recoverable. The first such copy stays; a later one doesn't overwrite it. Nothing reads the key back yet. private func setAsideRejectedSparkExit(_ data: Data?) async throws { guard let data else { return } guard try await fetchBackup(Self.sparkExitRejectedKey) == nil else { diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 595383b893..7caf1213c0 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1004,6 +1004,11 @@ class ActivityService { existing: existing.status, update: state, isStaleRailFailure: LightningService.shared.isStaleFailure(paymentHash: payment.id, from: rail) + // Spark's failure of an attempt it created before a retry still in doubt went out. + || (rail == .channelFree && LightningService.shared.isEarlierThanUncertainRailSend( + paymentHash: payment.id, + createdAt: paymentTimestamp + )) ) { return diff --git a/Bitkit/ViewModels/AppViewModel.swift b/Bitkit/ViewModels/AppViewModel.swift index 07b0c75ebc..cb54b9135c 100644 --- a/Bitkit/ViewModels/AppViewModel.swift +++ b/Bitkit/ViewModels/AppViewModel.swift @@ -1981,7 +1981,6 @@ extension AppViewModel { ) } case let .paymentFailed(paymentId, paymentHash, reason): - MoveToSparkPayments.remove(paymentHash) let outcome = QuickPayPaymentCoordinator.shared.complete( paymentId: paymentId, paymentHash: paymentHash, diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 14eb476235..35681d1ec7 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -823,7 +823,9 @@ extension ChannelFreeRailTests { rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil)] rail.balanceSats = 0 - // Spark reports the failure of a payment it created before this send went out. + // Spark reports the failure of a payment it created before this send went out; its activity keeps its status too. + XCTAssertTrue(Bitkit.LightningService.shared.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900)) + XCTAssertFalse(Bitkit.LightningService.shared.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 1000)) Bitkit.LightningService.shared.emitChannelFreeRailEvent( .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), paymentCreatedAt: 900 diff --git a/BitkitTests/MoveToSparkQuoteTests.swift b/BitkitTests/MoveToSparkQuoteTests.swift index 5b59b50137..80dfaef554 100644 --- a/BitkitTests/MoveToSparkQuoteTests.swift +++ b/BitkitTests/MoveToSparkQuoteTests.swift @@ -1,4 +1,5 @@ @testable import Bitkit +import BitkitCore import LDKNode import XCTest @@ -135,19 +136,36 @@ final class MoveToSparkPaymentsTests: XCTestCase { XCTAssertFalse(MoveToSparkPayments.contains(nil)) } - func testFailedMoveIsForgotten() { + func testAnOldMoveIsStillKnown() { + MoveToSparkPayments.insert("abcd", now: Date(timeIntervalSince1970: 1_000_000)) + XCTAssertTrue(MoveToSparkPayments.contains("abcd")) + } + + func testOnlyAMovesSendIsAMoveToSpark() { MoveToSparkPayments.insert("abcd") - MoveToSparkPayments.insert("ef01") - MoveToSparkPayments.remove("ABCD") - XCTAssertFalse(MoveToSparkPayments.contains("abcd")) - XCTAssertTrue(MoveToSparkPayments.contains("ef01")) + XCTAssertTrue(activity(id: "abcd", type: .sent, message: "").isMoveToSpark) + XCTAssertFalse(activity(id: "ef01", type: .sent, message: MoveToSparkMath.invoiceDescription).isMoveToSpark) + XCTAssertFalse(activity(id: "abcd", type: .received, message: "").isMoveToSpark) } - func testHashIsKeptUntilItsRetentionEnds() { - let start = Date(timeIntervalSince1970: 1_000_000) - MoveToSparkPayments.insert("abcd", now: start) - XCTAssertTrue(MoveToSparkPayments.contains("abcd", now: start.addingTimeInterval(MoveToSparkPayments.retention - 1))) - XCTAssertFalse(MoveToSparkPayments.contains("abcd", now: start.addingTimeInterval(MoveToSparkPayments.retention))) + private func activity(id: String, type: BitkitCore.PaymentType, message: String) -> LightningActivity { + LightningActivity( + walletId: WalletScope.default, id: id, txType: type, status: .succeeded, value: 1000, fee: 1, + invoice: "lnbcrt1", message: message, timestamp: 1, preimage: nil, contact: nil, + createdAt: 1, updatedAt: 1, seenAt: nil + ) + } + + func testRestoredHashesAreKnownAndBackedUpSorted() throws { + MoveToSparkPayments.insert("ef01") + MoveToSparkPayments.restore(["ABCD", "ef01"]) + XCTAssertTrue(MoveToSparkPayments.contains("abcd")) + XCTAssertEqual(MoveToSparkPayments.backupSnapshot(), ["abcd", "ef01"]) + + let json = #"{"version":1,"createdAt":1,"tagMetadata":[],"cache":{"hasSeenContactsIntro":true},"moveToSparkPaymentHashes":["abcd"]}"# + XCTAssertEqual(try JSONDecoder().decode(MetadataBackupV1.self, from: Data(json.utf8)).moveToSparkPaymentHashes, ["abcd"]) + let older = #"{"version":1,"createdAt":1,"tagMetadata":[],"cache":{"hasSeenContactsIntro":true}}"# + XCTAssertNil(try JSONDecoder().decode(MetadataBackupV1.self, from: Data(older.utf8)).moveToSparkPaymentHashes) } func testWipeForgetsEveryHash() { diff --git a/Docs/RELEASE.md b/Docs/RELEASE.md index 1ac48dc6a7..7dd01855e8 100644 --- a/Docs/RELEASE.md +++ b/Docs/RELEASE.md @@ -127,7 +127,7 @@ Apply the shared [store release-note checks](https://github.com/synonymdev/bitki ## 2. Build and Upload to TestFlight -Before archiving, make sure the Breez API key is available (ask the team for the key). Either store it in the macOS keychain item `BREEZ_API_KEY` (copy the key, then run `printf 'add-generic-password -U -a %s -s BREEZ_API_KEY -w %s\n' "$USER" "$(pbpaste)" | security -i && pbcopy Tap "Move To Spark" and verify the screen shows an amount (testTag "MoveToSparkAmount") and a routing fee (testTag "MoveToSparkFee") Swipe to move (testTag "MoveToSparkSwipe") and verify "Moved to Spark" shows the moved amount (testTag "MoveToSparkMoved") and "Close" (testTag "MoveToSparkClose") Tap "Close" (testTag "MoveToSparkClose"), then "Close" on the close confirmation, and verify Lightning Connections shows no channel under OPEN CONNECTIONS, only Spark via Breez, whose balance grew by the moved amount - Go back to Home, open Spending and verify the "Move To Spark" button is gone + Go back to Home, verify Activity lists a "Move to Spark" transfer row with the moved amount plus the routing fee, and that its detail screen is titled "Move to Spark" + Open Spending and verify the "Move To Spark" button is gone From 0f7b28ce0c27448399f116894033aa5cf2f72274 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 15:25:20 +0100 Subject: [PATCH 04/64] fix: spark exit data kept on every rejection, retry hold safe from clock skew Keep each different rejected exit copy and keep the staged data when the remote copy is gone; count a Spark failure as an earlier attempt only past a 10 s clock margin; cache the move hashes Activity reads per row. Verified: swiftformat --lint on changed files; unit tests pending on m1a --- Bitkit/Managers/MoveToSparkManager.swift | 26 ++++++++++++++++---- Bitkit/Services/BackupService.swift | 30 +++++++++++++++--------- Bitkit/Services/LightningService.swift | 7 ++++-- BitkitTests/ChannelFreeRailTests.swift | 4 ++++ BitkitTests/SparkExitBackupTests.swift | 27 +++++++++++++++++++-- 5 files changed, 74 insertions(+), 20 deletions(-) diff --git a/Bitkit/Managers/MoveToSparkManager.swift b/Bitkit/Managers/MoveToSparkManager.swift index 7c33d2bc94..f255038bcc 100644 --- a/Bitkit/Managers/MoveToSparkManager.swift +++ b/Bitkit/Managers/MoveToSparkManager.swift @@ -5,7 +5,7 @@ import LDKNode /// The amounts behind moving the channels' balance to Spark, kept apart so they can be tested without a node. enum MoveToSparkMath { - /// The move invoice's description, which is also how Activity tells a move's send from other payments. + /// The move invoice's description. static let invoiceDescription = "Move to Spark" /// Below this a move is not offered: what is left is about the routing fee. static let minMoveSats: UInt64 = 1000 @@ -98,7 +98,12 @@ enum MoveToSparkError: Error { @MainActor enum MoveToSparkPayments { private static let storageKey = "moveToSparkPaymentHashes" - static var defaults: UserDefaults = .standard + static var defaults: UserDefaults = .standard { + didSet { cached = nil } + } + + /// Read once, as Activity asks for every row it draws. + private static var cached: [String: Double]? /// Outside the main actor, so the backup observers can subscribe from anywhere. nonisolated static var savedPublisher: AnyPublisher { MoveToSparkPaymentsSaved.subject.eraseToAnyPublisher() @@ -107,7 +112,7 @@ enum MoveToSparkPayments { static func insert(_ paymentHash: String, now: Date = Date()) { var hashes = stored hashes[paymentHash.lowercased()] = now.timeIntervalSince1970 - defaults.set(hashes, forKey: storageKey) + save(hashes) MoveToSparkPaymentsSaved.subject.send() } @@ -123,19 +128,30 @@ enum MoveToSparkPayments { for hash in paymentHashes where hashes[hash.lowercased()] == nil { hashes[hash.lowercased()] = now.timeIntervalSince1970 } - defaults.set(hashes, forKey: storageKey) + save(hashes) } static func contains(_ paymentHash: String?) -> Bool { paymentHash.map { stored[$0.lowercased()] != nil } ?? false } + private static func save(_ hashes: [String: Double]) { + defaults.set(hashes, forKey: storageKey) + cached = hashes + } + static func removeAll() { defaults.removeObject(forKey: storageKey) + cached = nil } private static var stored: [String: Double] { - defaults.dictionary(forKey: storageKey) as? [String: Double] ?? [:] + if let cached { + return cached + } + let hashes = defaults.dictionary(forKey: storageKey) as? [String: Double] ?? [:] + cached = hashes + return hashes } } diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 8cc37fbcf3..e8a93fe908 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -1,5 +1,6 @@ import BitkitCore import Combine +import CryptoKit import Foundation import Paykit import VssRustClientFfi @@ -134,7 +135,8 @@ class BackupService { /// Set while the Spark exit data restore hasn't succeeded or found no older backup, kept across launches, so a fresh /// export never replaces the remote backup it couldn't read yet. private static let sparkExitRestorePendingKey = "sparkExitRestorePending" - /// The remote key of exit data Spark rejected for good, read and written alike by bitkit-android. + /// The remote key of exit data Spark rejected for good. A later, different rejected copy goes under this key plus + /// `_` and the first 16 hex digits of its SHA-256. static let sparkExitRejectedKey = "SPARK_EXIT_REJECTED" private let backupData: ((BackupCategory) async throws -> Data)? private let importStagedSparkExit: () async -> SparkStagedExitImport @@ -457,7 +459,11 @@ class BackupService { case .pending: throw SparkExitBackupError.restorePending case .rejected: - try await setAsideRejectedSparkExit(fetchBackup(BackupCategory.sparkExit.rawValue)) + // The staged data came from this remote copy; without it, the staged data stays for a later try. + guard let rejected = try await fetchBackup(BackupCategory.sparkExit.rawValue) else { + throw SparkExitBackupError.restorePending + } + try await setAsideRejectedSparkExit(rejected) await discardStagedSparkExit() case .nothingStaged, .imported: break @@ -1526,15 +1532,17 @@ class BackupService { } /// Keeps remote exit data Spark can never import under its own key, so a fresh export doesn't replace it and it stays - /// recoverable. The first such copy stays; a later one doesn't overwrite it. Nothing reads the key back yet. - private func setAsideRejectedSparkExit(_ data: Data?) async throws { - guard let data else { return } - guard try await fetchBackup(Self.sparkExitRejectedKey) == nil else { - Logger.info("Kept the earlier '\(Self.sparkExitRejectedKey)' backup", context: "BackupService") - return - } - try await uploadBackup(Self.sparkExitRejectedKey, data) - Logger.warn("Set Spark exit data Spark can't import aside as '\(Self.sparkExitRejectedKey)'", context: "BackupService") + /// recoverable. Each different rejected copy is kept; nothing reads them back yet. + private func setAsideRejectedSparkExit(_ data: Data) async throws { + var key = Self.sparkExitRejectedKey + if let kept = try await fetchBackup(key) { + guard kept != data else { return } + let digest = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + key += "_" + digest.prefix(16) + guard try await fetchBackup(key) == nil else { return } + } + try await uploadBackup(key, data) + Logger.warn("Set Spark exit data Spark can't import aside as '\(key)'", context: "BackupService") } /// Nothing while an exit runs: the operators may stop reporting a leaf once it is being exited, so a fresh export diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index b5f1d90757..9f3c22052f 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1675,15 +1675,18 @@ class LightningService: NodeLifecycleService { } /// Whether Spark created the payment of a failure at `createdAt` before the send of `paymentHash` still in doubt went - /// out: the failure ended an earlier attempt, and Spark may still finish the later one. + /// out: the failure ended an earlier attempt, and Spark may still finish the later one. Spark's clock and this + /// phone's may differ, so a payment created within `railClockSkewSeconds` of the send counts as the send's own. func isEarlierThanUncertainRailSend(paymentHash: String, createdAt: UInt64) -> Bool { eventCallbackLock.withLock { let hash = paymentHash.lowercased() guard uncertainRailSendFailedAt()[hash] != nil, let startedAt = uncertainRailSendStartedAt()[hash] else { return false } - return createdAt < UInt64(max(0, startedAt)) + return createdAt.addingReportingOverflow(Self.railClockSkewSeconds).partialValue < UInt64(max(0, startedAt)) } } + static let railClockSkewSeconds: UInt64 = 10 + /// Rail sends whose outcome stayed unknown, listed as pending until a sync after them reaches the rail: Spark may /// still finish one, while its own list shows only an earlier attempt, or nothing. private func unsettledUncertainRailSends() async -> [ChannelFreeRailPayment] { diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 35681d1ec7..c5c62b5f24 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -826,6 +826,10 @@ extension ChannelFreeRailTests { // Spark reports the failure of a payment it created before this send went out; its activity keeps its status too. XCTAssertTrue(Bitkit.LightningService.shared.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900)) XCTAssertFalse(Bitkit.LightningService.shared.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 1000)) + XCTAssertFalse( + Bitkit.LightningService.shared.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 995), + "A Spark clock a few seconds behind made the retry's own failure look earlier" + ) Bitkit.LightningService.shared.emitChannelFreeRailEvent( .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), paymentCreatedAt: 900 diff --git a/BitkitTests/SparkExitBackupTests.swift b/BitkitTests/SparkExitBackupTests.swift index df0b90ad06..bfd000ec1d 100644 --- a/BitkitTests/SparkExitBackupTests.swift +++ b/BitkitTests/SparkExitBackupTests.swift @@ -165,7 +165,8 @@ final class SparkExitBackupTests: XCTestCase { defaults: defaults, backupData: { _ in export }, uploadBackup: { remote[$0] = $1 }, - fetchBackup: { remote[$0] } + fetchBackup: { remote[$0] }, + importStagedSparkExit: { .nothingStaged } ) await service.restoreSparkExit() @@ -209,7 +210,7 @@ final class SparkExitBackupTests: XCTestCase { XCTAssertEqual(remote["SPARK_EXIT"], export) } - func testAnEarlierRejectedCopyIsNotOverwritten() async throws { + func testAnEarlierRejectedCopyIsKeptBesideALaterOne() async throws { let suite = "SparkExitBackupTests.\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) defer { defaults.removePersistentDomain(forName: suite) } @@ -229,9 +230,31 @@ final class SparkExitBackupTests: XCTestCase { _ = await service.triggerBackup(category: .sparkExit) XCTAssertEqual(remote["SPARK_EXIT_REJECTED"], earlier) + XCTAssertEqual(remote["SPARK_EXIT_REJECTED_1d9283d848ea941a"], Data("later".utf8)) XCTAssertEqual(remote["SPARK_EXIT"], export) } + func testRejectedDataMissingRemotelyStaysStaged() async throws { + let suite = "SparkExitBackupTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + var remote: [String: Data] = [:] + var staged: SparkStagedExitImport = .rejected + let service = BackupService( + defaults: defaults, + backupData: { _ in Data("fresh".utf8) }, + uploadBackup: { remote[$0] = $1 }, + fetchBackup: { remote[$0] }, + importStagedSparkExit: { staged }, + discardStagedSparkExit: { staged = .nothingStaged } + ) + + _ = await service.triggerBackup(category: .sparkExit) + + XCTAssertEqual(staged, .rejected, "The staged exit data was dropped with no copy kept") + XCTAssertNil(remote["SPARK_EXIT"]) + } + func testOnlyInvalidInputMarksExitDataAsRejected() { XCTAssertEqual(SparkStagedExitImport(importError: SdkError.InvalidInput("unsupported exit state version")), .rejected) XCTAssertEqual(SparkStagedExitImport(importError: URLError(.notConnectedToInternet)), .pending) From c291ee9645ca315c242089de5f584c0ac17803f9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 15:53:09 +0100 Subject: [PATCH 05/64] fix: rejected spark exit data kept when another device replaced the backup Set aside the staged exit data itself when the remote backup no longer holds it, instead of a fresh download that may be another device's. Verified: swiftformat --lint on changed files; unit tests pending on m1a --- Bitkit/Managers/SparkManager.swift | 7 ++++++- Bitkit/Services/BackupService.swift | 29 +++++++++++++++++++++----- BitkitTests/SparkExitBackupTests.swift | 29 ++++++++++++++++++-------- 3 files changed, 50 insertions(+), 15 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 7f54300e04..eac2066822 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -1488,7 +1488,12 @@ final class SparkManager: ChannelFreeLightningRail { await importRestoredExitState(walletIndex: walletIndex) } - /// Drops restored exit data Spark rejected, once the backup set its remote copy aside. + /// The restored exit data waiting for Spark to import it, if any. + func stagedExitState(walletIndex: Int) -> String? { + FileManager.default.contents(atPath: Env.sparkExitRestore(walletIndex: walletIndex).path).map { String(decoding: $0, as: UTF8.self) } + } + + /// Drops restored exit data Spark rejected, once the backup set a copy of it aside. func discardStagedExitState(walletIndex: Int) { try? FileManager.default.removeItem(at: Env.sparkExitRestore(walletIndex: walletIndex)) } diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index e8a93fe908..e688fca258 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -141,6 +141,7 @@ class BackupService { private let backupData: ((BackupCategory) async throws -> Data)? private let importStagedSparkExit: () async -> SparkStagedExitImport private let discardStagedSparkExit: () async -> Void + private let stagedSparkExitState: () async -> String? private let restoreExitBackup: (SparkExitBackupV1) async throws -> Void private let isSparkExitActive: () async -> Bool private let uploadBackup: (String, Data) async throws -> Void @@ -196,6 +197,9 @@ class BackupService { discardStagedSparkExit: @escaping () async -> Void = { @MainActor in SparkManager.shared.discardStagedExitState(walletIndex: LightningService.shared.currentWalletIndex) }, + stagedSparkExitState: @escaping () async -> String? = { @MainActor in + SparkManager.shared.stagedExitState(walletIndex: LightningService.shared.currentWalletIndex) + }, restoreExitBackup: @escaping (SparkExitBackupV1) async throws -> Void = { @MainActor backup in try await SparkManager.shared.restoreExitBackup(backup, walletIndex: LightningService.shared.currentWalletIndex) } @@ -203,6 +207,7 @@ class BackupService { self.defaults = defaults self.importStagedSparkExit = importStagedSparkExit self.discardStagedSparkExit = discardStagedSparkExit + self.stagedSparkExitState = stagedSparkExitState self.restoreExitBackup = restoreExitBackup self.isSparkExitActive = isSparkExitActive self.fetchBackup = fetchBackup @@ -454,16 +459,14 @@ class BackupService { } guard !defaults.bool(forKey: Self.sparkExitRestorePendingKey) else { throw SparkExitBackupError.restorePending } // Restored exit data Spark couldn't import yet lives only in the remote backup, so nothing replaces it, unless - // Spark can never import it: then the remote copy is set aside and fresh exports go up again. + // Spark can never import it: then a copy of it is set aside and fresh exports go up again. switch await importStagedSparkExit() { case .pending: throw SparkExitBackupError.restorePending case .rejected: - // The staged data came from this remote copy; without it, the staged data stays for a later try. - guard let rejected = try await fetchBackup(BackupCategory.sparkExit.rawValue) else { - throw SparkExitBackupError.restorePending + if let staged = await stagedSparkExitState() { + try await setAsideRejectedSparkExit(rejectedSparkExitCopy(staged: staged)) } - try await setAsideRejectedSparkExit(rejected) await discardStagedSparkExit() case .nothingStaged, .imported: break @@ -1531,6 +1534,22 @@ class BackupService { } } + /// The remote exit backup when it still holds the staged data, byte for byte as it came; otherwise, as another device + /// may have replaced it since, the staged data in a backup of its own. + private func rejectedSparkExitCopy(staged: String) async throws -> Data { + let remote = try await fetchBackup(BackupCategory.sparkExit.rawValue) + let remoteBackup = remote.flatMap { try? JSONDecoder().decode(SparkExitBackupV1.self, from: $0) } + if let remote, remoteBackup?.exitState == staged { + return remote + } + return try JSONEncoder().encode(SparkExitBackupV1( + version: 1, + createdAt: UInt64(Date().timeIntervalSince1970 * 1000), + network: remoteBackup?.network ?? "\(Env.network)", + exitState: staged + )) + } + /// Keeps remote exit data Spark can never import under its own key, so a fresh export doesn't replace it and it stays /// recoverable. Each different rejected copy is kept; nothing reads them back yet. private func setAsideRejectedSparkExit(_ data: Data) async throws { diff --git a/BitkitTests/SparkExitBackupTests.swift b/BitkitTests/SparkExitBackupTests.swift index bfd000ec1d..0349b47932 100644 --- a/BitkitTests/SparkExitBackupTests.swift +++ b/BitkitTests/SparkExitBackupTests.swift @@ -1,5 +1,6 @@ @testable import Bitkit import BreezSdkSpark +import CryptoKit import XCTest @MainActor @@ -193,6 +194,7 @@ final class SparkExitBackupTests: XCTestCase { fetchBackup: { remote[$0] }, importStagedSparkExit: { staged }, discardStagedSparkExit: { staged = .nothingStaged }, + stagedSparkExitState: { "newer" }, restoreExitBackup: { _ in } ) @@ -216,7 +218,8 @@ final class SparkExitBackupTests: XCTestCase { defer { defaults.removePersistentDomain(forName: suite) } let export = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 1000, network: "regtest", exitState: "fresh")) let earlier = Data("earlier".utf8) - var remote = ["SPARK_EXIT": Data("later".utf8), "SPARK_EXIT_REJECTED": earlier] + let later = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 900, network: "regtest", exitState: "later")) + var remote = ["SPARK_EXIT": later, "SPARK_EXIT_REJECTED": earlier] var staged: SparkStagedExitImport = .rejected let service = BackupService( defaults: defaults, @@ -224,35 +227,43 @@ final class SparkExitBackupTests: XCTestCase { uploadBackup: { remote[$0] = $1 }, fetchBackup: { remote[$0] }, importStagedSparkExit: { staged }, - discardStagedSparkExit: { staged = .nothingStaged } + discardStagedSparkExit: { staged = .nothingStaged }, + stagedSparkExitState: { "later" } ) _ = await service.triggerBackup(category: .sparkExit) + let digest = SHA256.hash(data: later).map { String(format: "%02x", $0) }.joined() XCTAssertEqual(remote["SPARK_EXIT_REJECTED"], earlier) - XCTAssertEqual(remote["SPARK_EXIT_REJECTED_1d9283d848ea941a"], Data("later".utf8)) + XCTAssertEqual(remote["SPARK_EXIT_REJECTED_" + digest.prefix(16)], later) XCTAssertEqual(remote["SPARK_EXIT"], export) } - func testRejectedDataMissingRemotelyStaysStaged() async throws { + func testRejectedDataAnotherDeviceReplacedRemotelyIsSetAsideFromTheStagedCopy() async throws { let suite = "SparkExitBackupTests.\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) defer { defaults.removePersistentDomain(forName: suite) } - var remote: [String: Data] = [:] + let export = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 1000, network: "regtest", exitState: "fresh")) + let otherDevice = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 950, network: "regtest", exitState: "other")) + var remote = ["SPARK_EXIT": otherDevice] var staged: SparkStagedExitImport = .rejected let service = BackupService( defaults: defaults, - backupData: { _ in Data("fresh".utf8) }, + backupData: { _ in export }, uploadBackup: { remote[$0] = $1 }, fetchBackup: { remote[$0] }, importStagedSparkExit: { staged }, - discardStagedSparkExit: { staged = .nothingStaged } + discardStagedSparkExit: { staged = .nothingStaged }, + stagedSparkExitState: { "mine" } ) _ = await service.triggerBackup(category: .sparkExit) - XCTAssertEqual(staged, .rejected, "The staged exit data was dropped with no copy kept") - XCTAssertNil(remote["SPARK_EXIT"]) + let kept = try JSONDecoder().decode(SparkExitBackupV1.self, from: XCTUnwrap(remote["SPARK_EXIT_REJECTED"])) + XCTAssertEqual(kept.exitState, "mine", "The rejected exit data was lost for another device's backup") + XCTAssertEqual(kept.network, "regtest") + XCTAssertEqual(staged, .nothingStaged) + XCTAssertEqual(remote["SPARK_EXIT"], export) } func testOnlyInvalidInputMarksExitDataAsRejected() { From abc9d3cc2230ca93dc4fda89320a28f24b438fc0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 16:14:11 +0100 Subject: [PATCH 06/64] fix: rejected spark exit copies never overwrite each other Every rejected exit copy goes under SPARK_EXIT_REJECTED_ plus the first 16 hex digits of its SHA-256, so two devices setting different copies aside at once can't overwrite each other. Verified: swiftformat --lint on changed files; unit tests pending on m1a --- Bitkit/Services/BackupService.swift | 23 ++++++++++++----------- BitkitTests/SparkExitBackupTests.swift | 17 +++++++++-------- 2 files changed, 21 insertions(+), 19 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index e688fca258..ddd1d8d291 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -135,8 +135,8 @@ class BackupService { /// Set while the Spark exit data restore hasn't succeeded or found no older backup, kept across launches, so a fresh /// export never replaces the remote backup it couldn't read yet. private static let sparkExitRestorePendingKey = "sparkExitRestorePending" - /// The remote key of exit data Spark rejected for good. A later, different rejected copy goes under this key plus - /// `_` and the first 16 hex digits of its SHA-256. + /// The prefix of the remote keys of exit data Spark rejected for good: each copy goes under this plus `_` and the first + /// 16 hex digits of its SHA-256. static let sparkExitRejectedKey = "SPARK_EXIT_REJECTED" private let backupData: ((BackupCategory) async throws -> Data)? private let importStagedSparkExit: () async -> SparkStagedExitImport @@ -1550,20 +1550,21 @@ class BackupService { )) } - /// Keeps remote exit data Spark can never import under its own key, so a fresh export doesn't replace it and it stays - /// recoverable. Each different rejected copy is kept; nothing reads them back yet. + /// Keeps exit data Spark can never import under a key of its own, so a fresh export doesn't replace it and it stays + /// recoverable. The key is derived from the data, so devices setting different copies aside at once never overwrite + /// each other's. Nothing reads them back yet. private func setAsideRejectedSparkExit(_ data: Data) async throws { - var key = Self.sparkExitRejectedKey - if let kept = try await fetchBackup(key) { - guard kept != data else { return } - let digest = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() - key += "_" + digest.prefix(16) - guard try await fetchBackup(key) == nil else { return } - } + let key = Self.rejectedSparkExitKey(for: data) + guard try await fetchBackup(key) == nil else { return } try await uploadBackup(key, data) Logger.warn("Set Spark exit data Spark can't import aside as '\(key)'", context: "BackupService") } + static func rejectedSparkExitKey(for data: Data) -> String { + let digest = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + return sparkExitRejectedKey + "_" + digest.prefix(16) + } + /// Nothing while an exit runs: the operators may stop reporting a leaf once it is being exited, so a fresh export /// could drop the very leaf a restored wallet needs. The backup from before the exit stays. private func sparkExitBackupData() async throws -> Data? { diff --git a/BitkitTests/SparkExitBackupTests.swift b/BitkitTests/SparkExitBackupTests.swift index 0349b47932..0f557e705e 100644 --- a/BitkitTests/SparkExitBackupTests.swift +++ b/BitkitTests/SparkExitBackupTests.swift @@ -174,7 +174,7 @@ final class SparkExitBackupTests: XCTestCase { let outcome = await service.triggerBackup(category: .sparkExit) XCTAssertEqual(outcome, .completed) - XCTAssertEqual(remote["SPARK_EXIT_REJECTED"], unreadable, "The exit data this app can't read was lost") + XCTAssertEqual(remote[BackupService.rejectedSparkExitKey(for: unreadable)], unreadable, "The exit data this app can't read was lost") XCTAssertEqual(remote["SPARK_EXIT"], export) } @@ -201,25 +201,25 @@ final class SparkExitBackupTests: XCTestCase { await service.restoreSparkExit() _ = await service.triggerBackup(category: .sparkExit) XCTAssertEqual(remote["SPARK_EXIT"], restored, "A transient import failure let a fresh export replace the remote copy") - XCTAssertNil(remote["SPARK_EXIT_REJECTED"]) + XCTAssertFalse(remote.keys.contains { $0.hasPrefix("SPARK_EXIT_REJECTED") }) staged = .rejected let outcome = await service.triggerBackup(category: .sparkExit) XCTAssertEqual(outcome, .completed) XCTAssertEqual(staged, .nothingStaged) - XCTAssertEqual(remote["SPARK_EXIT_REJECTED"], restored) + XCTAssertEqual(remote[BackupService.rejectedSparkExitKey(for: restored)], restored) XCTAssertEqual(remote["SPARK_EXIT"], export) } - func testAnEarlierRejectedCopyIsKeptBesideALaterOne() async throws { + func testDifferentRejectedCopiesNeverOverwriteEachOther() async throws { let suite = "SparkExitBackupTests.\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) defer { defaults.removePersistentDomain(forName: suite) } let export = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 1000, network: "regtest", exitState: "fresh")) let earlier = Data("earlier".utf8) let later = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 900, network: "regtest", exitState: "later")) - var remote = ["SPARK_EXIT": later, "SPARK_EXIT_REJECTED": earlier] + var remote = ["SPARK_EXIT": later, BackupService.rejectedSparkExitKey(for: earlier): earlier] var staged: SparkStagedExitImport = .rejected let service = BackupService( defaults: defaults, @@ -233,9 +233,10 @@ final class SparkExitBackupTests: XCTestCase { _ = await service.triggerBackup(category: .sparkExit) + XCTAssertEqual(remote[BackupService.rejectedSparkExitKey(for: earlier)], earlier) + XCTAssertEqual(remote[BackupService.rejectedSparkExitKey(for: later)], later) let digest = SHA256.hash(data: later).map { String(format: "%02x", $0) }.joined() - XCTAssertEqual(remote["SPARK_EXIT_REJECTED"], earlier) - XCTAssertEqual(remote["SPARK_EXIT_REJECTED_" + digest.prefix(16)], later) + XCTAssertEqual(BackupService.rejectedSparkExitKey(for: later), "SPARK_EXIT_REJECTED_" + digest.prefix(16)) XCTAssertEqual(remote["SPARK_EXIT"], export) } @@ -259,7 +260,7 @@ final class SparkExitBackupTests: XCTestCase { _ = await service.triggerBackup(category: .sparkExit) - let kept = try JSONDecoder().decode(SparkExitBackupV1.self, from: XCTUnwrap(remote["SPARK_EXIT_REJECTED"])) + let kept = try JSONDecoder().decode(SparkExitBackupV1.self, from: XCTUnwrap(remote.first { $0.key.hasPrefix("SPARK_EXIT_REJECTED_") }?.value)) XCTAssertEqual(kept.exitState, "mine", "The rejected exit data was lost for another device's backup") XCTAssertEqual(kept.network, "regtest") XCTAssertEqual(staged, .nothingStaged) From 655046911c900bc38aeb4c823715ccf28c6e80d0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 18:18:33 +0100 Subject: [PATCH 07/64] fix: retry hold kept when a spark failure races the retry Check whether a Spark failure belongs to an earlier attempt and end the hold under one lock, so a retry recorded in between keeps its hold. Verified: swiftformat --lint on the changed file; unit tests pending on m1a --- Bitkit/Services/LightningService.swift | 59 ++++++++++++++++---------- 1 file changed, 37 insertions(+), 22 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 9f3c22052f..5ea0a76e4e 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1678,11 +1678,13 @@ class LightningService: NodeLifecycleService { /// out: the failure ended an earlier attempt, and Spark may still finish the later one. Spark's clock and this /// phone's may differ, so a payment created within `railClockSkewSeconds` of the send counts as the send's own. func isEarlierThanUncertainRailSend(paymentHash: String, createdAt: UInt64) -> Bool { - eventCallbackLock.withLock { - let hash = paymentHash.lowercased() - guard uncertainRailSendFailedAt()[hash] != nil, let startedAt = uncertainRailSendStartedAt()[hash] else { return false } - return createdAt.addingReportingOverflow(Self.railClockSkewSeconds).partialValue < UInt64(max(0, startedAt)) - } + eventCallbackLock.withLock { isEarlierThanUncertainRailSendLocked(hash: paymentHash.lowercased(), createdAt: createdAt) } + } + + /// Callers hold `eventCallbackLock`. + private func isEarlierThanUncertainRailSendLocked(hash: String, createdAt: UInt64) -> Bool { + guard uncertainRailSendFailedAt()[hash] != nil, let startedAt = uncertainRailSendStartedAt()[hash] else { return false } + return createdAt.addingReportingOverflow(Self.railClockSkewSeconds).partialValue < UInt64(max(0, startedAt)) } static let railClockSkewSeconds: UInt64 = 10 @@ -1712,14 +1714,31 @@ class LightningService: NodeLifecycleService { } private func endRailSendUncertainty(paymentHash: String) { - eventCallbackLock.withLock { - var started = uncertainRailSendStartedAt() - if started.removeValue(forKey: paymentHash.lowercased()) != nil { - railAttemptsStore.set(started, forKey: Self.uncertainRailSendsStartedKey) + eventCallbackLock.withLock { clearRailSendUncertainty(hash: paymentHash.lowercased()) } + } + + /// Callers hold `eventCallbackLock`. + private func clearRailSendUncertainty(hash: String) { + var started = uncertainRailSendStartedAt() + if started.removeValue(forKey: hash) != nil { + railAttemptsStore.set(started, forKey: Self.uncertainRailSendsStartedKey) + } + var uncertain = uncertainRailSendFailedAt() + guard uncertain.removeValue(forKey: hash) != nil else { return } + railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) + } + + /// Ends the hold a Spark failure settles, unless it ended an attempt before the send still in doubt; checked and + /// ended under one lock, so a retry recorded in between keeps its hold. False when the failure is ignored. + private func settleRailFailure(paymentHash: String, createdAt: UInt64?) -> Bool { + let hash = paymentHash.lowercased() + return eventCallbackLock.withLock { + if let createdAt, isEarlierThanUncertainRailSendLocked(hash: hash, createdAt: createdAt) { + return false } - var uncertain = uncertainRailSendFailedAt() - guard uncertain.removeValue(forKey: paymentHash.lowercased()) != nil else { return } - railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) + clearRailSendUncertainty(hash: hash) + removeAttempt(paymentHash: hash, key: Self.railAttemptsKey) + return true } } @@ -2364,18 +2383,14 @@ extension LightningService { /// Spark runs before the node starts, so its events wait until the node's event callback is set rather than being lost. /// `paymentCreatedAt` is when Spark created the payment the event is about, in seconds since 1970. func emitChannelFreeRailEvent(_ event: Event, paymentCreatedAt: UInt64? = nil) { - if case let .paymentFailed(_, paymentHash?, _) = event, let paymentCreatedAt, - isEarlierThanUncertainRailSend(paymentHash: paymentHash, createdAt: paymentCreatedAt) - { - Logger.info("Ignored a Spark failure of an attempt before the send still in doubt: \(event)", context: "LightningService") - return - } switch event { case let .paymentFailed(_, paymentHash?, _): - // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. - endRailSendUncertainty(paymentHash: paymentHash) - // The failure of the send itself, which may arrive while its send call is still returning. - releaseRailAttempt(paymentHash: paymentHash, unlessInFlight: false) + // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held; the + // failure of the send itself may arrive while its send call is still returning. + guard settleRailFailure(paymentHash: paymentHash, createdAt: paymentCreatedAt) else { + Logger.info("Ignored a Spark failure of an attempt before the send still in doubt: \(event)", context: "LightningService") + return + } case let .paymentSuccessful(_, paymentHash, _, _): endRailSendUncertainty(paymentHash: paymentHash) default: From 83ff4b289b5ea9e762a8e9b744e725d7c4bfb52d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 18:56:35 +0100 Subject: [PATCH 08/64] fix: spark failure ends a retry's hold only by its own payment id Before a retried Spark send goes out, record Spark's ids of the invoice's earlier attempts from the listing the send already reads. A late failure ends the hold only when its payment id is not one of them. Without ids, a failure created before the send or within the clock margin after it keeps the hold, so an earlier attempt's failure can't free a duplicate payment. Verified: ChannelFreeRailTests, MoveToSparkQuoteTests and SparkExitBackupTests pass on an iPhone 17 Pro simulator; swiftformat lint clean. --- Bitkit/Managers/SparkManager.swift | 7 +-- Bitkit/Services/CoreService.swift | 10 ++-- Bitkit/Services/LightningService.swift | 73 +++++++++++++++++++------- BitkitTests/ChannelFreeRailTests.swift | 72 +++++++++++++++++++------ 4 files changed, 121 insertions(+), 41 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index eac2066822..54865eebc7 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -774,7 +774,8 @@ final class SparkManager: ChannelFreeLightningRail { status: Self.ldkStatus(payment.status), preimage: htlcDetails.preimage, timestamp: payment.timestamp, - feeSats: Self.sats(payment.fees) + feeSats: Self.sats(payment.fees), + id: payment.id ) } } @@ -1921,7 +1922,7 @@ final class SparkManager: ChannelFreeLightningRail { await Self.handleSettledPayment( payment, record: { await self.recordActivity($0) }, - emit: { LightningService.shared.emitChannelFreeRailEvent($0, paymentCreatedAt: payment.timestamp) }, + emit: { LightningService.shared.emitChannelFreeRailEvent($0, paymentCreatedAt: payment.timestamp, railPaymentId: payment.id) }, refresh: { try await self.refresh() } ) case let .paymentPending(payment): @@ -1979,7 +1980,7 @@ final class SparkManager: ChannelFreeLightningRail { sendsRecordedWithoutFee.remove(payment.id) } do { - try await CoreService.shared.activity.recordChannelFreeRailPayment(details) + try await CoreService.shared.activity.recordChannelFreeRailPayment(details, railPaymentId: payment.id) unsavedPayments.remove(payment.id) return true } catch { diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 7caf1213c0..a94fb843af 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -951,9 +951,9 @@ class ActivityService { /// Records a Lightning payment the channel-free rail sent or received the way an LDK payment is recorded, so it keeps /// its Paykit contact and seen state across syncs. - func recordChannelFreeRailPayment(_ payment: PaymentDetails) async throws { + func recordChannelFreeRailPayment(_ payment: PaymentDetails, railPaymentId: String? = nil) async throws { try await ServiceQueue.background(.core) { - try await self.processLightningPayment(payment, rail: .channelFree) + try await self.processLightningPayment(payment, rail: .channelFree, railPaymentId: railPaymentId) } } @@ -970,7 +970,8 @@ class ActivityService { return update == .failed && existing != .failed && isStaleRailFailure } - private func processLightningPayment(_ payment: PaymentDetails, rail: LightningPaymentRail = .ldk) async throws { + /// `railPaymentId` is the channel-free rail's id of the attempt, which a retried invoice lists once per attempt. + private func processLightningPayment(_ payment: PaymentDetails, rail: LightningPaymentRail = .ldk, railPaymentId: String? = nil) async throws { guard case let .bolt11(_, preimage, _, description, bolt11) = payment.kind else { return } // Skip pending inbound payments - just means they created an invoice @@ -1007,7 +1008,8 @@ class ActivityService { // Spark's failure of an attempt it created before a retry still in doubt went out. || (rail == .channelFree && LightningService.shared.isEarlierThanUncertainRailSend( paymentHash: payment.id, - createdAt: paymentTimestamp + createdAt: paymentTimestamp, + paymentId: railPaymentId )) ) { diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 5ea0a76e4e..1c47a25ccd 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -77,6 +77,8 @@ struct ChannelFreeRailPayment: Equatable { let preimage: String? var timestamp: UInt64 = 0 var feeSats: UInt64 = 0 + /// The rail's id of this attempt; a retried invoice lists one per attempt. + var id: String? /// The attempt that decides an outbound payment of `paymentHash`: a retried invoice is listed once per attempt, /// so a pending or settled one wins over failed ones, then the newest. @@ -1090,13 +1092,15 @@ class LightningService: NodeLifecycleService { let mark = attemptMark if !channelsOnly, let rail = channelFreeRail, await shouldPayWithRail(rail, bolt11: bolt11, sats: sats) { // LDK refuses its own repeats; Spark doesn't, so a Spark send checks both rails. + var earlierAttemptIds: [String]? if let paid = try await settledEarlierAttempt( paymentHash: paymentHash, on: [.ldk, .channelFree], bolt11: bolt11, sats: sats, invoiceCreatedAt: invoice?.secondsSinceEpoch(), - invoiceExpiresAt: expiresAt + invoiceExpiresAt: expiresAt, + readRailPayments: { earlierAttemptIds = Self.railAttemptIds($0, paymentHash: paymentHash) } ) { return paid } @@ -1144,7 +1148,7 @@ class LightningService: NodeLifecycleService { self?.recordRailAttempt(paymentHash: paymentHash, expiresAt: expiresAt) // Kept until the call returns, so a send cut off by process death stays held after a relaunch. if let paymentHash { - self?.markRailSendUncertain(paymentHash: paymentHash, since: mark) + self?.markRailSendUncertain(paymentHash: paymentHash, since: mark, earlierAttemptIds: earlierAttemptIds) } } ) @@ -1172,7 +1176,7 @@ class LightningService: NodeLifecycleService { } catch { // A send that failed once submitted may still go out, so its outcome waits for a later sync. if let paymentHash { - markRailSendUncertain(paymentHash: paymentHash, since: mark) + markRailSendUncertain(paymentHash: paymentHash, since: mark, earlierAttemptIds: earlierAttemptIds) } throw error } @@ -1238,6 +1242,8 @@ class LightningService: NodeLifecycleService { /// When each of those sends was submitted, in seconds since 1970, so a failure Spark reports for a payment it created /// before then is known to belong to an earlier attempt. private static let uncertainRailSendsStartedKey = "channelFreeRailUncertainSendStartedAt" + /// The rail's ids of the attempts each of those sends followed, so a failure of one is told from the send's own. + private static let uncertainRailSendsEarlierAttemptsKey = "channelFreeRailUncertainSendEarlierAttempts" /// A listing drops the hashes it shows failed only, or paid once the invoice has expired, so the other rail can't /// pay it again, and ones it doesn't show once the invoice expired `unlistedAttemptSettleSeconds` ago. Paid or /// unlisted hashes with no known expiry (kept before expiries were, or whose invoice can't be parsed) are dropped @@ -1430,6 +1436,7 @@ class LightningService: NodeLifecycleService { eventCallbackLock.withLock { railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsKey) railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsStartedKey) + railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsEarlierAttemptsKey) railAttemptsStore.removeObject(forKey: Self.railAttemptsKey) railAttemptsStore.removeObject(forKey: Self.expiriesKey(Self.railAttemptsKey)) attemptRecordedAt[Self.railAttemptsKey] = nil @@ -1514,7 +1521,8 @@ class LightningService: NodeLifecycleService { bolt11: String, sats: UInt64?, invoiceCreatedAt: UInt64?, - invoiceExpiresAt: Int? + invoiceExpiresAt: Int?, + readRailPayments: ([ChannelFreeRailPayment]) -> Void = { _ in } ) async throws -> PaymentHash? { guard let paymentHash else { return nil } var statuses: [PaymentStatus] = rails.contains(.channelFree) && isRailSendInFlight(paymentHash: paymentHash) ? [.pending] : [] @@ -1547,6 +1555,7 @@ class LightningService: NodeLifecycleService { if rails.contains(.channelFree) { let mark = attemptMark if let payments = await readableRailPayments() { + readRailPayments(payments) let live = keepRailAttempts(from: payments, since: mark) let payment = ChannelFreeRailPayment.latestOutboundAttempt(payments, paymentHash: paymentHash) if let payment { @@ -1653,7 +1662,7 @@ class LightningService: NodeLifecycleService { /// A rail send about to be submitted, or that failed after it was, until a sync after it and its invoice's expiry /// settle it. The expiry is the one kept beside the hash. - private func markRailSendUncertain(paymentHash: String, since mark: AttemptMark) { + private func markRailSendUncertain(paymentHash: String, since mark: AttemptMark, earlierAttemptIds: [String]?) { let hash = paymentHash.lowercased() let failedAt = Int(max(0, now().timeIntervalSince1970)) eventCallbackLock.withLock { @@ -1663,6 +1672,9 @@ class LightningService: NodeLifecycleService { var started = uncertainRailSendStartedAt() started[hash] = failedAt railAttemptsStore.set(started, forKey: Self.uncertainRailSendsStartedKey) + var earlier = uncertainRailSendEarlierAttempts() + earlier[hash] = earlierAttemptIds + railAttemptsStore.set(earlier, forKey: Self.uncertainRailSendsEarlierAttemptsKey) } uncertain[hash] = failedAt railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) @@ -1674,17 +1686,37 @@ class LightningService: NodeLifecycleService { railAttemptsStore.dictionary(forKey: Self.uncertainRailSendsStartedKey) as? [String: Int] ?? [:] } - /// Whether Spark created the payment of a failure at `createdAt` before the send of `paymentHash` still in doubt went - /// out: the failure ended an earlier attempt, and Spark may still finish the later one. Spark's clock and this - /// phone's may differ, so a payment created within `railClockSkewSeconds` of the send counts as the send's own. - func isEarlierThanUncertainRailSend(paymentHash: String, createdAt: UInt64) -> Bool { - eventCallbackLock.withLock { isEarlierThanUncertainRailSendLocked(hash: paymentHash.lowercased(), createdAt: createdAt) } + /// Callers hold `eventCallbackLock`. + private func uncertainRailSendEarlierAttempts() -> [String: [String]] { + railAttemptsStore.dictionary(forKey: Self.uncertainRailSendsEarlierAttemptsKey) as? [String: [String]] ?? [:] + } + + /// The rail's ids of its attempts to pay `paymentHash`, nil when one has none. + private static func railAttemptIds(_ payments: [ChannelFreeRailPayment], paymentHash: String?) -> [String]? { + guard let paymentHash else { return nil } + let attempts = payments.filter { $0.direction == .outbound && $0.paymentHash.caseInsensitiveCompare(paymentHash) == .orderedSame } + let ids = attempts.compactMap(\.id) + return ids.count == attempts.count ? ids : nil + } + + /// Whether a failure of `paymentHash` may have ended an attempt before the send still in doubt, which Spark may still + /// finish: the rail's attempt `paymentId` is one listed before the send went out. Without both ids, a payment Spark + /// created before the send or within `railClockSkewSeconds` after it (Spark's clock and this phone's may differ) + /// may be earlier, so it keeps the hold too. + func isEarlierThanUncertainRailSend(paymentHash: String, createdAt: UInt64, paymentId: String? = nil) -> Bool { + eventCallbackLock.withLock { + isEarlierThanUncertainRailSendLocked(hash: paymentHash.lowercased(), createdAt: createdAt, paymentId: paymentId) + } } /// Callers hold `eventCallbackLock`. - private func isEarlierThanUncertainRailSendLocked(hash: String, createdAt: UInt64) -> Bool { - guard uncertainRailSendFailedAt()[hash] != nil, let startedAt = uncertainRailSendStartedAt()[hash] else { return false } - return createdAt.addingReportingOverflow(Self.railClockSkewSeconds).partialValue < UInt64(max(0, startedAt)) + private func isEarlierThanUncertainRailSendLocked(hash: String, createdAt: UInt64, paymentId: String?) -> Bool { + guard uncertainRailSendFailedAt()[hash] != nil else { return false } + if let paymentId, let earlier = uncertainRailSendEarlierAttempts()[hash] { + return earlier.contains(paymentId) + } + guard let startedAt = uncertainRailSendStartedAt()[hash] else { return false } + return createdAt < UInt64(max(0, startedAt)).addingReportingOverflow(Self.railClockSkewSeconds).partialValue } static let railClockSkewSeconds: UInt64 = 10 @@ -1723,6 +1755,10 @@ class LightningService: NodeLifecycleService { if started.removeValue(forKey: hash) != nil { railAttemptsStore.set(started, forKey: Self.uncertainRailSendsStartedKey) } + var earlier = uncertainRailSendEarlierAttempts() + if earlier.removeValue(forKey: hash) != nil { + railAttemptsStore.set(earlier, forKey: Self.uncertainRailSendsEarlierAttemptsKey) + } var uncertain = uncertainRailSendFailedAt() guard uncertain.removeValue(forKey: hash) != nil else { return } railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) @@ -1730,10 +1766,10 @@ class LightningService: NodeLifecycleService { /// Ends the hold a Spark failure settles, unless it ended an attempt before the send still in doubt; checked and /// ended under one lock, so a retry recorded in between keeps its hold. False when the failure is ignored. - private func settleRailFailure(paymentHash: String, createdAt: UInt64?) -> Bool { + private func settleRailFailure(paymentHash: String, createdAt: UInt64?, paymentId: String?) -> Bool { let hash = paymentHash.lowercased() return eventCallbackLock.withLock { - if let createdAt, isEarlierThanUncertainRailSendLocked(hash: hash, createdAt: createdAt) { + if let createdAt, isEarlierThanUncertainRailSendLocked(hash: hash, createdAt: createdAt, paymentId: paymentId) { return false } clearRailSendUncertainty(hash: hash) @@ -2381,13 +2417,14 @@ extension LightningService { } /// Spark runs before the node starts, so its events wait until the node's event callback is set rather than being lost. - /// `paymentCreatedAt` is when Spark created the payment the event is about, in seconds since 1970. - func emitChannelFreeRailEvent(_ event: Event, paymentCreatedAt: UInt64? = nil) { + /// `paymentCreatedAt` is when Spark created the payment the event is about, in seconds since 1970, and `railPaymentId` + /// Spark's id of it. + func emitChannelFreeRailEvent(_ event: Event, paymentCreatedAt: UInt64? = nil, railPaymentId: String? = nil) { switch event { case let .paymentFailed(_, paymentHash?, _): // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held; the // failure of the send itself may arrive while its send call is still returning. - guard settleRailFailure(paymentHash: paymentHash, createdAt: paymentCreatedAt) else { + guard settleRailFailure(paymentHash: paymentHash, createdAt: paymentCreatedAt, paymentId: railPaymentId) else { Logger.info("Ignored a Spark failure of an attempt before the send still in doubt: \(event)", context: "LightningService") return } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index c5c62b5f24..55d215da18 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -814,32 +814,72 @@ extension ChannelFreeRailTests { func testALateFailureOfAnEarlierAttemptKeepsARetryInDoubtHeld() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: 1000) } + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + // Spark lists an earlier attempt of the invoice when the retry goes out. + rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier")] rail.balanceSats = 100_000 rail.errorAfterSubmission = NSError(domain: "spark", code: 2) - _ = try? await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + _ = try? await service.send(bolt11: Self.invoice) rail.errorAfterSubmission = nil rail.syncedAfter = { ($0 ?? 0) < 1000 } - rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil)] rail.balanceSats = 0 - // Spark reports the failure of a payment it created before this send went out; its activity keeps its status too. - XCTAssertTrue(Bitkit.LightningService.shared.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900)) - XCTAssertFalse(Bitkit.LightningService.shared.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 1000)) - XCTAssertFalse( - Bitkit.LightningService.shared.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 995), - "A Spark clock a few seconds behind made the retry's own failure look earlier" + // The earlier attempt's failure keeps the hold, whatever Spark's clock stamped on it; the retry's own ends it. + for createdAt: UInt64 in [900, 995, 1000, 1005] { + XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: createdAt, paymentId: "earlier")) + XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: createdAt, paymentId: "retry")) + } + // Without Spark's id, a failure stamped before the send or within the clock margin after it keeps the hold. + XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 995)) + XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 1005)) + XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 1010)) + + // The earlier attempt's failure arrives stamped five seconds before the retry. + service.emitChannelFreeRailEvent( + .paymentFailed(paymentId: "earlier", paymentHash: hash, reason: nil), + paymentCreatedAt: 995, + railPaymentId: "earlier" ) - Bitkit.LightningService.shared.emitChannelFreeRailEvent( - .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), - paymentCreatedAt: 900 + await assertRefusedAsDuplicate() + // An ambiguous failure without Spark's id, stamped at the retry's start, keeps the hold too. + service.emitChannelFreeRailEvent(.paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), paymentCreatedAt: 1000) + await assertRefusedAsDuplicate() + + // The failure of the retry itself ends the hold, even stamped before it by a clock behind. + service.emitChannelFreeRailEvent( + .paymentFailed(paymentId: "retry", paymentHash: hash, reason: nil), + paymentCreatedAt: 995, + railPaymentId: "retry" + ) + await assertReachesTheNode() + } + + func testAFailureWithoutSparkIdsKeepsTheHoldUntilPastTheClockMargin() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + // Spark's earlier attempt carries no id, so attempts can't be told apart by id. + rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil)] + rail.balanceSats = 100_000 + rail.errorAfterSubmission = NSError(domain: "spark", code: 2) + _ = try? await service.send(bolt11: Self.invoice) + rail.errorAfterSubmission = nil + rail.syncedAfter = { ($0 ?? 0) < 1000 } + rail.balanceSats = 0 + + XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 1005, paymentId: "retry")) + service.emitChannelFreeRailEvent( + .paymentFailed(paymentId: "retry", paymentHash: hash, reason: nil), + paymentCreatedAt: 1005, + railPaymentId: "retry" ) await assertRefusedAsDuplicate() - // The failure of the send itself ends the hold. - Bitkit.LightningService.shared.emitChannelFreeRailEvent( - .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), - paymentCreatedAt: 1000 + service.emitChannelFreeRailEvent( + .paymentFailed(paymentId: "retry", paymentHash: hash, reason: nil), + paymentCreatedAt: 1010, + railPaymentId: "retry" ) await assertReachesTheNode() } From 874e4715b09de642abba3a3aadf78b661f7b3fc5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 21:40:05 +0100 Subject: [PATCH 09/64] fix: spark send activity settles when its hold expires A failure of an earlier attempt that arrives while a retry is in doubt leaves the send's activity pending. When the hold then ends at the invoice's expiry, write Spark's latest send of the invoice, or mark the stored pending send failed when Spark lists none. Spark syncs now also end holds whose invoice expired, so this no longer waits for a new send. Verified: ChannelFreeRail, MoveToSpark activity, late outcome and quote, SparkExitBackup, SparkLightningSend, SparkPaymentSafety, SparkRelaunchActivity and SparkTransferActivity tests pass on an iPhone 17 Pro simulator; swiftformat lint clean. --- Bitkit/Managers/SparkManager.swift | 32 +++++++++++++++ Bitkit/Services/CoreService.swift | 8 ++++ Bitkit/Services/LightningService.swift | 12 ++++++ BitkitTests/ChannelFreeRailTests.swift | 56 ++++++++++++++++++++++++-- 4 files changed, 105 insertions(+), 3 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 54865eebc7..a2a9fda6be 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -415,6 +415,7 @@ final class SparkManager: ChannelFreeLightningRail { // Registered before the first refresh marks Spark ready, so Lightning calls never see it ready while they // still go to LDK, even when that refresh or the activity sync fails. An emergency exit keeps it out. LightningService.shared.channelFreePaymentHistory = self + LightningService.shared.railSendHoldExpired = { [weak self] hash in await self?.recordExpiredHold(paymentHash: hash) } if !isExiting { LightningService.shared.channelFreeRail = self } @@ -1842,6 +1843,35 @@ final class SparkManager: ChannelFreeLightningRail { return result } + /// Writes the activity of a send whose hold ended at its invoice's expiry: Spark's latest send of it, or a failure + /// of the stored pending send when Spark lists none. + private func recordExpiredHold(paymentHash: String) async { + guard let payments = try? await requireSdk().listPayments(request: ListPaymentsRequest()).payments else { return } + await Self.recordExpiredHold( + paymentHash: paymentHash, + payments: payments, + record: { await self.recordActivity($0) }, + failStoredSend: { try? await CoreService.shared.activity.failPendingLightningSend(id: $0) } + ) + } + + static func recordExpiredHold( + paymentHash: String, + payments: [Payment], + record: (Payment) async -> Bool, + failStoredSend: (String) async -> Void + ) async { + let sends = payments.filter { payment in + guard payment.paymentType == .send, case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details else { return false } + return htlcDetails.paymentHash.caseInsensitiveCompare(paymentHash) == .orderedSame + } + if let latest = sends.max(by: { $0.timestamp < $1.timestamp }) { + _ = await record(latest) + } else { + await failStoredSend(paymentHash) + } + } + /// Payment hashes whose every Lightning send failed, so a hold on a channel retry can be released. nonisolated static func failedSendHashes(_ payments: [Payment]) -> [String] { var failed: [String] = [] @@ -1867,6 +1897,7 @@ final class SparkManager: ChannelFreeLightningRail { } // A send that failed while the app was closed released no hold on a channel retry. await Self.releaseFailedSendHolds { try await self.requireSdk().listPayments(request: ListPaymentsRequest()).payments } + await LightningService.shared.endExpiredRailSendUncertainties() if let recordError { throw recordError } @@ -1909,6 +1940,7 @@ final class SparkManager: ChannelFreeLightningRail { syncedThisRun = true await LightningService.shared.listRailSendsIfUnseeded() await refreshState() + await LightningService.shared.endExpiredRailSendUncertainties() await Self.settleAfterSync( since: Self.pendingContactWithdrawal?.startedAt ?? 0, hasSynced: { await self.hasSynced(after: $0) }, diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index a94fb843af..819e57a06e 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1407,6 +1407,14 @@ class ActivityService { return !onchain.doesExist && onchain.txType == .sent && txIdsInBoostTxIds.contains(onchain.txId) } + /// Marks the stored Lightning send `id` failed while it is still pending. + func failPendingLightningSend(id: String) async throws { + guard case var .lightning(activity) = try await getActivity(id: id), activity.txType == .sent, activity.status == .pending + else { return } + activity.status = .failed + try await update(id: id, activity: .lightning(activity)) + } + func update(id: String, activity: Activity) async throws { try await ServiceQueue.background(.core) { try updateActivity(activityId: id, activity: activity) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 1c47a25ccd..96a95a9e2e 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -177,6 +177,9 @@ class LightningService: NodeLifecycleService { /// The rail whose payments the duplicate-payment check reads, kept while an emergency exit takes Spark off /// Lightning: an invoice Spark paid or is paying is never paid again over a channel. weak var channelFreePaymentHistory: ChannelFreeLightningRail? + /// Writes the activity of a rail send in doubt once its hold ends at its invoice's expiry, as the failure of an + /// earlier attempt that came meanwhile left the row pending. + var railSendHoldExpired: ((String) async -> Void)? var onchainTransactionConfirmed: (@Sendable (String) async -> Void)? var onchainTransactionReceived: (@Sendable (String) async -> Void)? typealias OnchainActivityCompletion = @MainActor () async -> Void @@ -1791,9 +1794,18 @@ 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 } endRailSendUncertainty(paymentHash: hash) + await railSendHoldExpired?(hash) return true } + /// Ends the holds of rail sends in doubt whose invoice expired since a sync reached the rail. + func endExpiredRailSendUncertainties() async { + let hashes = eventCallbackLock.withLock { Array(uncertainRailSendFailedAt().keys) } + for hash in hashes { + _ = await railSyncedSinceUncertainSend(paymentHash: hash) + } + } + private static func pendingDuplicate(paymentHash: String?) -> NodeError { .DuplicatePayment(message: "An earlier attempt to pay '\(paymentHash ?? "")' is still pending") } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 55d215da18..ba61158dba 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -884,6 +884,56 @@ extension ChannelFreeRailTests { await assertReachesTheNode() } + func testAHoldThatEndsAtTheInvoicesExpiryWritesTheSendsActivity() async throws { + let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) + let hash = String(invoice.paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + rail.balanceSats = 100_000 + rail.errorAfterSubmission = NSError(domain: "spark", code: 2) + _ = try? await service.send(bolt11: Self.invoice) + rail.errorAfterSubmission = nil + rail.syncedAfter = { _ in true } + var expired: [String] = [] + let previousHook = service.railSendHoldExpired + defer { service.railSendHoldExpired = previousHook } + service.railSendHoldExpired = { expired.append($0) } + + await service.endExpiredRailSendUncertainties() + XCTAssertEqual(expired, [], "a hold ended before the invoice expired") + XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900)) + + let expiresAt = invoice.secondsSinceEpoch() + invoice.expiryTimeSeconds() + service.now = { Date(timeIntervalSince1970: TimeInterval(expiresAt)) } + await service.endExpiredRailSendUncertainties() + XCTAssertEqual(expired, [hash], "the send's activity wasn't written when its hold ended") + XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900)) + } + + func testAnExpiredHoldWritesSparksLatestSendOrFailsTheStoredOne() async { + let hash = "ab" + var recorded: [String] = [] + var failed: [String] = [] + let payments = [ + Self.sparkPayment(hash: hash, status: .failed, id: "earlier", timestamp: 1), + Self.sparkPayment(hash: hash, status: .failed, id: "retry", timestamp: 5), + Self.sparkPayment(hash: "cd", status: .completed, id: "other", timestamp: 9), + ] + await SparkManager.recordExpiredHold( + paymentHash: hash, payments: payments, + record: { recorded.append($0.id); return true }, failStoredSend: { failed.append($0) } + ) + XCTAssertEqual(recorded, ["retry"]) + XCTAssertEqual(failed, []) + + await SparkManager.recordExpiredHold( + paymentHash: "ef", payments: payments, + record: { recorded.append($0.id); return true }, failStoredSend: { failed.append($0) } + ) + XCTAssertEqual(recorded, ["retry"]) + XCTAssertEqual(failed, ["ef"], "a send Spark lists none of stayed pending") + } + func testAnUnknownSparkSendStaysHeldAfterARelaunchWhenSparkListsOnlyAnOlderFailedAttempt() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared @@ -927,14 +977,14 @@ extension ChannelFreeRailTests { kept.forEach { service.railAttemptsStore.set($0.value, forKey: $0.key) } } - private static func sparkPayment(hash: String, status: BreezSdkSpark.PaymentStatus) -> Payment { + private static func sparkPayment(hash: String, status: BreezSdkSpark.PaymentStatus, id: String? = nil, timestamp: UInt64 = 1) -> Payment { Payment( - id: hash, + id: id ?? hash, paymentType: .send, status: status, amount: 20000, fees: 0, - timestamp: 1, + timestamp: timestamp, method: .lightning, details: .lightning( description: nil, From 2d84e2d7983a1f5dabee723530486015d968b07c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 22:37:49 +0100 Subject: [PATCH 10/64] fix: expired spark hold retries its activity write until saved A hold that ends at the invoice's expiry keeps its hash in a persisted list until its activity is saved, so a failed Spark listing or write is retried on the next Spark sync. Failing a stored pending send now reads, checks and writes the row in one core-queue operation, so a change saved in between isn't overwritten. Verified: ChannelFreeRail, MoveToSpark activity, late outcome and quote, SparkExitBackup, SparkLightningSend, SparkPaymentSafety, SparkRelaunchActivity and SparkTransferActivity tests pass on an iPhone 17 Pro simulator; swiftformat lint clean. --- Bitkit/Managers/SparkManager.swift | 21 +++++++++-------- Bitkit/Services/CoreService.swift | 13 +++++++---- Bitkit/Services/LightningService.swift | 31 +++++++++++++++++++++----- BitkitTests/ChannelFreeRailTests.swift | 18 ++++++++++----- 4 files changed, 58 insertions(+), 25 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index a2a9fda6be..735246a8ee 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -415,7 +415,7 @@ final class SparkManager: ChannelFreeLightningRail { // Registered before the first refresh marks Spark ready, so Lightning calls never see it ready while they // still go to LDK, even when that refresh or the activity sync fails. An emergency exit keeps it out. LightningService.shared.channelFreePaymentHistory = self - LightningService.shared.railSendHoldExpired = { [weak self] hash in await self?.recordExpiredHold(paymentHash: hash) } + LightningService.shared.railSendHoldExpired = { [weak self] hash in await self?.recordExpiredHold(paymentHash: hash) ?? false } if !isExiting { LightningService.shared.channelFreeRail = self } @@ -1844,14 +1844,14 @@ final class SparkManager: ChannelFreeLightningRail { } /// Writes the activity of a send whose hold ended at its invoice's expiry: Spark's latest send of it, or a failure - /// of the stored pending send when Spark lists none. - private func recordExpiredHold(paymentHash: String) async { - guard let payments = try? await requireSdk().listPayments(request: ListPaymentsRequest()).payments else { return } - await Self.recordExpiredHold( + /// of the stored pending send when Spark lists none. Returns whether it was saved. + private func recordExpiredHold(paymentHash: String) async -> Bool { + guard let payments = try? await requireSdk().listPayments(request: ListPaymentsRequest()).payments else { return false } + return await Self.recordExpiredHold( paymentHash: paymentHash, payments: payments, record: { await self.recordActivity($0) }, - failStoredSend: { try? await CoreService.shared.activity.failPendingLightningSend(id: $0) } + failStoredSend: { await (try? CoreService.shared.activity.failPendingLightningSend(id: $0)) != nil } ) } @@ -1859,17 +1859,16 @@ final class SparkManager: ChannelFreeLightningRail { paymentHash: String, payments: [Payment], record: (Payment) async -> Bool, - failStoredSend: (String) async -> Void - ) async { + failStoredSend: (String) async -> Bool + ) async -> Bool { let sends = payments.filter { payment in guard payment.paymentType == .send, case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details else { return false } return htlcDetails.paymentHash.caseInsensitiveCompare(paymentHash) == .orderedSame } if let latest = sends.max(by: { $0.timestamp < $1.timestamp }) { - _ = await record(latest) - } else { - await failStoredSend(paymentHash) + return await record(latest) } + return await failStoredSend(paymentHash) } /// Payment hashes whose every Lightning send failed, so a hold on a channel retry can be released. diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 819e57a06e..1a63374ded 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1408,11 +1408,16 @@ class ActivityService { } /// Marks the stored Lightning send `id` failed while it is still pending. + /// Read, checked and written in one core-queue operation, so a change saved meanwhile isn't overwritten. func failPendingLightningSend(id: String) async throws { - guard case var .lightning(activity) = try await getActivity(id: id), activity.txType == .sent, activity.status == .pending - else { return } - activity.status = .failed - try await update(id: id, activity: .lightning(activity)) + try await ServiceQueue.background(.core) { + guard case var .lightning(activity) = try getActivityById(walletId: WalletScope.default, activityId: id), + activity.txType == .sent, activity.status == .pending + else { return } + activity.status = .failed + try updateActivity(activityId: id, activity: .lightning(activity)) + self.activitiesChangedSubject.send() + } } func update(id: String, activity: Activity) async throws { diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 96a95a9e2e..98fa69e212 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -178,8 +178,8 @@ class LightningService: NodeLifecycleService { /// Lightning: an invoice Spark paid or is paying is never paid again over a channel. weak var channelFreePaymentHistory: ChannelFreeLightningRail? /// Writes the activity of a rail send in doubt once its hold ends at its invoice's expiry, as the failure of an - /// earlier attempt that came meanwhile left the row pending. - var railSendHoldExpired: ((String) async -> Void)? + /// earlier attempt that came meanwhile left the row pending. Returns whether the activity was saved. + var railSendHoldExpired: ((String) async -> Bool)? var onchainTransactionConfirmed: (@Sendable (String) async -> Void)? var onchainTransactionReceived: (@Sendable (String) async -> Void)? typealias OnchainActivityCompletion = @MainActor () async -> Void @@ -1247,6 +1247,8 @@ class LightningService: NodeLifecycleService { private static let uncertainRailSendsStartedKey = "channelFreeRailUncertainSendStartedAt" /// The rail's ids of the attempts each of those sends followed, so a failure of one is told from the send's own. private static let uncertainRailSendsEarlierAttemptsKey = "channelFreeRailUncertainSendEarlierAttempts" + /// Hashes whose hold ended at their invoice's expiry before their activity was saved, retried on each rail sync. + private static let expiredRailHoldsUnrecordedKey = "channelFreeRailExpiredHoldsUnrecorded" /// A listing drops the hashes it shows failed only, or paid once the invoice has expired, so the other rail can't /// pay it again, and ones it doesn't show once the invoice expired `unlistedAttemptSettleSeconds` ago. Paid or /// unlisted hashes with no known expiry (kept before expiries were, or whose invoice can't be parsed) are dropped @@ -1440,6 +1442,7 @@ class LightningService: NodeLifecycleService { railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsKey) railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsStartedKey) railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsEarlierAttemptsKey) + railAttemptsStore.removeObject(forKey: Self.expiredRailHoldsUnrecordedKey) railAttemptsStore.removeObject(forKey: Self.railAttemptsKey) railAttemptsStore.removeObject(forKey: Self.expiriesKey(Self.railAttemptsKey)) attemptRecordedAt[Self.railAttemptsKey] = nil @@ -1793,19 +1796,37 @@ class LightningService: NodeLifecycleService { // Spark keeps a send it committed but didn't finish in a cache no call exposes, and a sync that reached Spark // 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 } - endRailSendUncertainty(paymentHash: hash) - await railSendHoldExpired?(hash) + eventCallbackLock.withLock { + clearRailSendUncertainty(hash: hash) + var unrecorded = Set(railAttemptsStore.stringArray(forKey: Self.expiredRailHoldsUnrecordedKey) ?? []) + unrecorded.insert(hash) + railAttemptsStore.set(Array(unrecorded), forKey: Self.expiredRailHoldsUnrecordedKey) + } + await recordExpiredRailHold(hash) return true } - /// Ends the holds of rail sends in doubt whose invoice expired since a sync reached the rail. + /// Writes the activity of each send whose hold ended earlier but wasn't saved, then ends the holds of rail sends in + /// doubt whose invoice expired since a sync reached the rail. func endExpiredRailSendUncertainties() async { + let unrecorded = eventCallbackLock.withLock { railAttemptsStore.stringArray(forKey: Self.expiredRailHoldsUnrecordedKey) ?? [] } + for hash in unrecorded { + await recordExpiredRailHold(hash) + } let hashes = eventCallbackLock.withLock { Array(uncertainRailSendFailedAt().keys) } for hash in hashes { _ = await railSyncedSinceUncertainSend(paymentHash: hash) } } + private func recordExpiredRailHold(_ hash: String) async { + guard let record = railSendHoldExpired, await record(hash) else { return } + eventCallbackLock.withLock { + let unrecorded = railAttemptsStore.stringArray(forKey: Self.expiredRailHoldsUnrecordedKey) ?? [] + railAttemptsStore.set(unrecorded.filter { $0 != hash }, forKey: Self.expiredRailHoldsUnrecordedKey) + } + } + private static func pendingDuplicate(paymentHash: String?) -> NodeError { .DuplicatePayment(message: "An earlier attempt to pay '\(paymentHash ?? "")' is still pending") } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index ba61158dba..949d433e65 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -897,7 +897,8 @@ extension ChannelFreeRailTests { var expired: [String] = [] let previousHook = service.railSendHoldExpired defer { service.railSendHoldExpired = previousHook } - service.railSendHoldExpired = { expired.append($0) } + var saves = false + service.railSendHoldExpired = { expired.append($0); return saves } await service.endExpiredRailSendUncertainties() XCTAssertEqual(expired, [], "a hold ended before the invoice expired") @@ -908,6 +909,13 @@ extension ChannelFreeRailTests { await service.endExpiredRailSendUncertainties() XCTAssertEqual(expired, [hash], "the send's activity wasn't written when its hold ended") XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900)) + + // The write failed, so the next sync tries it again, until it is saved. + saves = true + await service.endExpiredRailSendUncertainties() + XCTAssertEqual(expired, [hash, hash], "an activity that failed to save wasn't retried") + await service.endExpiredRailSendUncertainties() + XCTAssertEqual(expired, [hash, hash], "a saved activity was written again") } func testAnExpiredHoldWritesSparksLatestSendOrFailsTheStoredOne() async { @@ -919,16 +927,16 @@ extension ChannelFreeRailTests { Self.sparkPayment(hash: hash, status: .failed, id: "retry", timestamp: 5), Self.sparkPayment(hash: "cd", status: .completed, id: "other", timestamp: 9), ] - await SparkManager.recordExpiredHold( + _ = await SparkManager.recordExpiredHold( paymentHash: hash, payments: payments, - record: { recorded.append($0.id); return true }, failStoredSend: { failed.append($0) } + record: { recorded.append($0.id); return true }, failStoredSend: { failed.append($0); return true } ) XCTAssertEqual(recorded, ["retry"]) XCTAssertEqual(failed, []) - await SparkManager.recordExpiredHold( + _ = await SparkManager.recordExpiredHold( paymentHash: "ef", payments: payments, - record: { recorded.append($0.id); return true }, failStoredSend: { failed.append($0) } + record: { recorded.append($0.id); return true }, failStoredSend: { failed.append($0); return true } ) XCTAssertEqual(recorded, ["retry"]) XCTAssertEqual(failed, ["ef"], "a send Spark lists none of stayed pending") From d7cefc6c526a9990c299b9d4bd5af415acf09b17 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 22:58:11 +0100 Subject: [PATCH 11/64] fix: spark early claim capped at the approved fee A waiting early claim left the first quote's fee as the deposit's cap, so Spark would not claim a later offer the user's approved fee still covers. The claim now caps at the approved fee. After a waiting claim the poll still sends no new quote; an offer above the approved fee ends as Unavailable and is claimed at maturity. Verified: SparkTransferFlow, SparkClaimOffer, SparkClaimFee, SparkFundingRecovery and ChannelFreeRail tests pass on an iPhone 17 Pro simulator; swiftformat lint clean. --- Bitkit/Managers/SparkManager.swift | 8 ++++---- Bitkit/ViewModels/SparkTransferFlow.swift | 7 ++++--- BitkitTests/SparkTransferFlowTests.swift | 21 ++++++++++++++++----- 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 735246a8ee..f0d762c9d3 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -851,14 +851,14 @@ final class SparkManager: ChannelFreeLightningRail { } } - /// Accepts the early claim of `offer` at its quoted fee. The fee ceiling stays on the deposit, so an early claim - /// not offered at this depth is still made once the provider offers it. - func claimEarly(_ offer: SparkClaimOffer) async throws -> SparkEarlyClaim { + /// Accepts the early claim of `offer`, capped at `ceilingSats`, the fee the user approved. The cap stays on the + /// deposit, so an early claim not offered at this depth is still made once the provider offers it within the cap. + func claimEarly(_ offer: SparkClaimOffer, ceilingSats: UInt64) async throws -> SparkEarlyClaim { guard case let .choice(earlyFeeSats, _, _, _) = offer.kind else { return .claimed } let request = ClaimDepositRequest( txid: offer.txid, vout: offer.vout, - maxFee: MaxFee(onchain: .fixed(amount: earlyFeeSats), proportionalPpm: nil) + maxFee: MaxFee(onchain: .fixed(amount: max(earlyFeeSats, ceilingSats)), proportionalPpm: nil) ) let claim: SparkEarlyClaim do { diff --git a/Bitkit/ViewModels/SparkTransferFlow.swift b/Bitkit/ViewModels/SparkTransferFlow.swift index b2c25acb5b..285fbaec93 100644 --- a/Bitkit/ViewModels/SparkTransferFlow.swift +++ b/Bitkit/ViewModels/SparkTransferFlow.swift @@ -132,7 +132,8 @@ enum SparkClaimDecision { /// The Spark calls the deposit claim makes, injectable so the polling can be tested without the SDK. struct SparkClaimOperations { var offer: (String) async throws -> SparkClaimOffer? - var claimEarly: (SparkClaimOffer) async throws -> SparkEarlyClaim + /// Accepts the early claim of an offer, capped at the fee the user approved. + var claimEarly: (SparkClaimOffer, _ ceilingSats: UInt64) async throws -> SparkEarlyClaim /// Whether Spark still lists the deposit as unclaimed, without asking the provider for a quote. var isUnclaimed: (String) async throws -> Bool var refresh: () async -> Void @@ -144,7 +145,7 @@ struct SparkClaimOperations { static var live: SparkClaimOperations { SparkClaimOperations( offer: { try await SparkManager.shared.depositClaimOffer(txid: $0) }, - claimEarly: { try await SparkManager.shared.claimEarly($0) }, + claimEarly: { try await SparkManager.shared.claimEarly($0, ceilingSats: $1) }, isUnclaimed: { try await SparkManager.shared.isDepositUnclaimed(txid: $0) }, refresh: { await SparkManager.shared.refreshState() }, sleep: { try? await Task.sleep(for: $0) }, @@ -524,7 +525,7 @@ final class SparkTransferFlow { } setClaimState(.claiming, for: txid) claimedOffers[txid] = found - let claim = try await operations.claimEarly(found) + let claim = try await operations.claimEarly(found, ceilings[txid] ?? 0) guard !Task.isCancelled else { return } if let state = SparkClaimDecision.onClaim(claim) { setClaimState(state, for: txid) diff --git a/BitkitTests/SparkTransferFlowTests.swift b/BitkitTests/SparkTransferFlowTests.swift index 3967b49dc5..35ca186866 100644 --- a/BitkitTests/SparkTransferFlowTests.swift +++ b/BitkitTests/SparkTransferFlowTests.swift @@ -74,7 +74,7 @@ final class SparkTransferFlowTests: XCTestCase { offer: { txid in SparkClaimOffer(txid: txid, vout: 0, kind: .choice( earlyFeeSats: 900, earlyConfirmations: 0, standardFeeSats: 198, standardConfirmations: 3 )) }, - claimEarly: { _ in .repriced(requiredFeeSats: 1500) }, + claimEarly: { _, _ in .repriced(requiredFeeSats: 1500) }, isUnclaimed: { _ in true }, refresh: {}, sleep: { _ in }, @@ -103,7 +103,7 @@ final class SparkTransferFlowTests: XCTestCase { offer: { txid in SparkClaimOffer(txid: txid, vout: 0, kind: .choice( earlyFeeSats: 900, earlyConfirmations: 0, standardFeeSats: 198, standardConfirmations: 3 )) }, - claimEarly: { _ in .repriced(requiredFeeSats: 1500) }, + claimEarly: { _, _ in .repriced(requiredFeeSats: 1500) }, isUnclaimed: { _ in true }, refresh: {}, sleep: { _ in }, @@ -133,7 +133,7 @@ final class SparkTransferFlowTests: XCTestCase { offer: { txid in SparkClaimOffer(txid: txid, vout: 0, kind: .choice( earlyFeeSats: 1500, earlyConfirmations: 0, standardFeeSats: 198, standardConfirmations: 3 )) }, - claimEarly: { _ in .claimed }, + claimEarly: { _, _ in .claimed }, isUnclaimed: { _ in true }, refresh: {}, sleep: { _ in }, @@ -172,6 +172,15 @@ final class SparkTransferFlowTests: XCTestCase { XCTAssertEqual(calls.unclaimedChecks, 2) } + @MainActor + func testAWaitingEarlyClaimIsCappedAtTheApprovedFeeNotTheFirstQuote() async { + let calls = PollCalls() + let flow = pollingFlow(offers: [choice(earlyFee: 300)], claims: [.waiting], pollAttempts: 2, calls: calls) + flow.onBroadcast(txid: "txid", ceilingSats: 500) + await flow.waitForClaim() + XCTAssertEqual(calls.ceilings, [500], "Spark would leave a later offer under the approved fee unclaimed") + } + @MainActor func testDepositListedThenGoneWasAdded() async { let flow = pollingFlow(offers: [choice(earlyFee: 900)], claims: [.waiting], unclaimed: [false]) @@ -222,7 +231,7 @@ final class SparkTransferFlowTests: XCTestCase { offer: { txid in SparkClaimOffer(txid: txid, vout: 0, kind: .choice( earlyFeeSats: 900, earlyConfirmations: 0, standardFeeSats: 198, standardConfirmations: 3 )) }, - claimEarly: { offer in + claimEarly: { offer, _ in await withCheckedContinuation { release = $0 } claimed.append(offer.txid) return .claimed @@ -487,6 +496,7 @@ final class SparkTransferFlowTests: XCTestCase { var offers = 0 var claims = 0 var unclaimedChecks = 0 + var ceilings: [UInt64] = [] } /// A flow whose poll answers with `offers` in turn (nil once they run out), whose claims answer with `claims`, and @@ -508,8 +518,9 @@ final class SparkTransferFlowTests: XCTestCase { guard !offers.isEmpty, let kind = offers.removeFirst() else { return nil } return SparkClaimOffer(txid: txid, vout: 0, kind: kind) }, - claimEarly: { _ in + claimEarly: { _, ceilingSats in calls.claims += 1 + calls.ceilings.append(ceilingSats) return claims.isEmpty ? .waiting : claims.removeFirst() }, isUnclaimed: { _ in From 72fe952bde7c1320dd36448a1e460e9c7c34d93f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 17 Nov 2026 23:35:21 +0100 Subject: [PATCH 12/64] fix: spark exit backup from another device restored before replaced When Spark rejects staged exit data and the remote backup now holds another device's exit data, set the staged copy aside and restore the remote one instead of uploading over it. After setting an unreadable backup aside, read the remote again and keep the restore pending if it changed meanwhile. A Spark send in doubt saved before this version, with no start time or attempt ids, stays held against any failure until its invoice expires. Verified: ChannelFreeRail, SparkExitBackup, SparkExit, SparkRelaunchActivity, SparkPaymentSafety, SparkLightningSend and MoveToSparkQuote tests pass on an iPhone 17 Pro simulator; swiftformat lint clean. --- Bitkit/Services/BackupService.swift | 23 +++++++++++---- Bitkit/Services/LightningService.swift | 4 ++- BitkitTests/ChannelFreeRailTests.swift | 23 +++++++++++++++ BitkitTests/SparkExitBackupTests.swift | 41 ++++++++++++++++++++++++-- 4 files changed, 82 insertions(+), 9 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index ddd1d8d291..b5863fe9bb 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -464,10 +464,20 @@ class BackupService { case .pending: throw SparkExitBackupError.restorePending case .rejected: + var isReplacedRemotely = false if let staged = await stagedSparkExitState() { - try await setAsideRejectedSparkExit(rejectedSparkExitCopy(staged: staged)) + let copy = try await rejectedSparkExitCopy(staged: staged) + try await setAsideRejectedSparkExit(copy.data) + isReplacedRemotely = copy.isReplacedRemotely } await discardStagedSparkExit() + // Another device replaced the backup with exit data this one never read, so it is restored before + // anything replaces it. + if isReplacedRemotely { + defaults.set(true, forKey: Self.sparkExitRestorePendingKey) + await restoreSparkExit() + throw SparkExitBackupError.restorePending + } case .nothingStaged, .imported: break } @@ -1520,6 +1530,8 @@ class BackupService { // A layout this app can't read never becomes readable here, so it is kept apart for an app that can. Logger.warn("Unreadable '\(BackupCategory.sparkExit.rawValue)' backup: \(error)", context: "BackupService") try await setAsideRejectedSparkExit(data) + // Another device may have written a backup meanwhile; it is read before anything replaces it. + guard try await fetchBackup(BackupCategory.sparkExit.rawValue) == data else { return } defaults.removeObject(forKey: Self.sparkExitRestorePendingKey) return } @@ -1535,19 +1547,20 @@ class BackupService { } /// The remote exit backup when it still holds the staged data, byte for byte as it came; otherwise, as another device - /// may have replaced it since, the staged data in a backup of its own. - private func rejectedSparkExitCopy(staged: String) async throws -> Data { + /// may have replaced it since, the staged data in a backup of its own, and whether the remote holds other data. + private func rejectedSparkExitCopy(staged: String) async throws -> (data: Data, isReplacedRemotely: Bool) { let remote = try await fetchBackup(BackupCategory.sparkExit.rawValue) let remoteBackup = remote.flatMap { try? JSONDecoder().decode(SparkExitBackupV1.self, from: $0) } if let remote, remoteBackup?.exitState == staged { - return remote + return (remote, false) } - return try JSONEncoder().encode(SparkExitBackupV1( + let copy = try JSONEncoder().encode(SparkExitBackupV1( version: 1, createdAt: UInt64(Date().timeIntervalSince1970 * 1000), network: remoteBackup?.network ?? "\(Env.network)", exitState: staged )) + return (copy, remote != nil) } /// Keeps exit data Spark can never import under a key of its own, so a fresh export doesn't replace it and it stays diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 98fa69e212..9f30f86e37 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1721,7 +1721,9 @@ class LightningService: NodeLifecycleService { if let paymentId, let earlier = uncertainRailSendEarlierAttempts()[hash] { return earlier.contains(paymentId) } - guard let startedAt = uncertainRailSendStartedAt()[hash] else { return false } + // A send in doubt saved before its start was recorded can't be told from an earlier attempt, so it stays held + // until its invoice expires. + guard let startedAt = uncertainRailSendStartedAt()[hash] else { return true } return createdAt < UInt64(max(0, startedAt)).addingReportingOverflow(Self.railClockSkewSeconds).partialValue } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 949d433e65..a66a44cdc3 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -855,6 +855,29 @@ extension ChannelFreeRailTests { await assertReachesTheNode() } + func testASendInDoubtSavedBeforeTheUpgradeStaysHeldAgainstAnyFailure() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + rail.balanceSats = 100_000 + rail.errorAfterSubmission = NSError(domain: "spark", code: 2) + _ = try? await service.send(bolt11: Self.invoice) + rail.errorAfterSubmission = nil + // An earlier app version recorded neither the send's start nor its earlier attempts. + service.railAttemptsStore.removeObject(forKey: "channelFreeRailUncertainSendStartedAt") + service.railAttemptsStore.removeObject(forKey: "channelFreeRailUncertainSendEarlierAttempts") + rail.syncedAfter = { ($0 ?? 0) < 1000 } + rail.balanceSats = 0 + + XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 2000, paymentId: "any")) + service.emitChannelFreeRailEvent( + .paymentFailed(paymentId: "any", paymentHash: hash, reason: nil), + paymentCreatedAt: 2000, + railPaymentId: "any" + ) + await assertRefusedAsDuplicate() + } + func testAFailureWithoutSparkIdsKeepsTheHoldUntilPastTheClockMargin() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared diff --git a/BitkitTests/SparkExitBackupTests.swift b/BitkitTests/SparkExitBackupTests.swift index 0f557e705e..be112e9dcd 100644 --- a/BitkitTests/SparkExitBackupTests.swift +++ b/BitkitTests/SparkExitBackupTests.swift @@ -248,14 +248,17 @@ final class SparkExitBackupTests: XCTestCase { let otherDevice = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 950, network: "regtest", exitState: "other")) var remote = ["SPARK_EXIT": otherDevice] var staged: SparkStagedExitImport = .rejected + var restored: [String] = [] let service = BackupService( defaults: defaults, backupData: { _ in export }, uploadBackup: { remote[$0] = $1 }, + waitForTemporaryFailureDelay: { _ in }, fetchBackup: { remote[$0] }, importStagedSparkExit: { staged }, discardStagedSparkExit: { staged = .nothingStaged }, - stagedSparkExitState: { "mine" } + stagedSparkExitState: { "mine" }, + restoreExitBackup: { restored.append($0.exitState); staged = .pending } ) _ = await service.triggerBackup(category: .sparkExit) @@ -263,8 +266,40 @@ final class SparkExitBackupTests: XCTestCase { let kept = try JSONDecoder().decode(SparkExitBackupV1.self, from: XCTUnwrap(remote.first { $0.key.hasPrefix("SPARK_EXIT_REJECTED_") }?.value)) XCTAssertEqual(kept.exitState, "mine", "The rejected exit data was lost for another device's backup") XCTAssertEqual(kept.network, "regtest") - XCTAssertEqual(staged, .nothingStaged) - XCTAssertEqual(remote["SPARK_EXIT"], export) + XCTAssertEqual(remote["SPARK_EXIT"], otherDevice, "A fresh export replaced exit data another device backed up") + XCTAssertEqual(restored, ["other"], "The other device's exit data was never restored") + } + + func testABackupAnotherDeviceWritesWhileAnUnreadableOneIsSetAsideIsRestoredFirst() async throws { + let suite = "SparkExitBackupTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let unreadable = Data("unreadable".utf8) + let otherDevice = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 950, network: "regtest", exitState: "other")) + let export = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 1000, network: "regtest", exitState: "fresh")) + var remote = ["SPARK_EXIT": unreadable] + var restored: [String] = [] + let service = BackupService( + defaults: defaults, + backupData: { _ in export }, + uploadBackup: { key, data in + remote[key] = data + // Another device backs up its exit data while this one sets the unreadable copy aside. + if key.hasPrefix("SPARK_EXIT_REJECTED_") { + remote["SPARK_EXIT"] = otherDevice + } + }, + waitForTemporaryFailureDelay: { _ in }, + fetchBackup: { remote[$0] }, + importStagedSparkExit: { .nothingStaged }, + restoreExitBackup: { restored.append($0.exitState) } + ) + + await service.restoreSparkExit() + _ = await service.triggerBackup(category: .sparkExit) + + XCTAssertEqual(remote[BackupService.rejectedSparkExitKey(for: unreadable)], unreadable) + XCTAssertEqual(restored, ["other"], "A backup written during the set-aside was replaced unread") } func testOnlyInvalidInputMarksExitDataAsRejected() { From cb55e2930a8beb0586999968ce84f95fc047f8fb Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 00:10:15 +0100 Subject: [PATCH 13/64] fix: spark retry and exit backup keep what they must recover Keep Spark's ids of a retry's earlier attempts after Spark takes the retry, until it settles, so an earlier attempt's late failure neither ends its hold nor fails its pending Activity row. Note the restore of another device's exit backup before the staged copy is dropped, so a stop in between still restores it, and count a staged exit file that can't be read as pending rather than absent. Verified: ChannelFreeRail, SparkExitBackup, SparkExit, SparkRelaunchActivity, SparkPaymentSafety, SparkLightningSend, MoveToSparkQuote and SparkTransferFlow tests pass on an iPhone 17 Pro simulator; swiftformat lint clean. --- Bitkit/Managers/SparkManager.swift | 13 +++--- Bitkit/Services/BackupService.swift | 14 ++++--- Bitkit/Services/LightningService.swift | 11 ++++-- BitkitTests/ChannelFreeRailTests.swift | 37 +++++++++++++++++ BitkitTests/SparkExitBackupTests.swift | 55 ++++++++++++++++++++++++++ 5 files changed, 115 insertions(+), 15 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index f0d762c9d3..7dda9a45ec 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -1490,9 +1490,11 @@ final class SparkManager: ChannelFreeLightningRail { await importRestoredExitState(walletIndex: walletIndex) } - /// The restored exit data waiting for Spark to import it, if any. - func stagedExitState(walletIndex: Int) -> String? { - FileManager.default.contents(atPath: Env.sparkExitRestore(walletIndex: walletIndex).path).map { String(decoding: $0, as: UTF8.self) } + /// The restored exit data waiting for Spark to import it, if any. Throws when a staged file can't be read. + func stagedExitState(walletIndex: Int) throws -> String? { + let file = Env.sparkExitRestore(walletIndex: walletIndex) + guard FileManager.default.fileExists(atPath: file.path) else { return nil } + return try String(decoding: Data(contentsOf: file), as: UTF8.self) } /// Drops restored exit data Spark rejected, once the backup set a copy of it aside. @@ -1503,8 +1505,9 @@ final class SparkManager: ChannelFreeLightningRail { @discardableResult private func importRestoredExitState(walletIndex: Int) async -> SparkStagedExitImport { let file = Env.sparkExitRestore(walletIndex: walletIndex) - guard let data = FileManager.default.contents(atPath: file.path) else { return .nothingStaged } - guard let sdk else { return .pending } + guard FileManager.default.fileExists(atPath: file.path) else { return .nothingStaged } + // A staged file that can't be read now isn't absent: nothing may replace the remote copy until it is imported. + guard let data = FileManager.default.contents(atPath: file.path), let sdk else { return .pending } do { let imported = try await sdk.importUnilateralExitState( request: ImportUnilateralExitStateRequest(exitState: String(decoding: data, as: UTF8.self)) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index b5863fe9bb..8f5612cde7 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -141,7 +141,7 @@ class BackupService { private let backupData: ((BackupCategory) async throws -> Data)? private let importStagedSparkExit: () async -> SparkStagedExitImport private let discardStagedSparkExit: () async -> Void - private let stagedSparkExitState: () async -> String? + private let stagedSparkExitState: () async throws -> String? private let restoreExitBackup: (SparkExitBackupV1) async throws -> Void private let isSparkExitActive: () async -> Bool private let uploadBackup: (String, Data) async throws -> Void @@ -197,8 +197,8 @@ class BackupService { discardStagedSparkExit: @escaping () async -> Void = { @MainActor in SparkManager.shared.discardStagedExitState(walletIndex: LightningService.shared.currentWalletIndex) }, - stagedSparkExitState: @escaping () async -> String? = { @MainActor in - SparkManager.shared.stagedExitState(walletIndex: LightningService.shared.currentWalletIndex) + stagedSparkExitState: @escaping () async throws -> String? = { @MainActor in + try SparkManager.shared.stagedExitState(walletIndex: LightningService.shared.currentWalletIndex) }, restoreExitBackup: @escaping (SparkExitBackupV1) async throws -> Void = { @MainActor backup in try await SparkManager.shared.restoreExitBackup(backup, walletIndex: LightningService.shared.currentWalletIndex) @@ -465,16 +465,18 @@ class BackupService { throw SparkExitBackupError.restorePending case .rejected: var isReplacedRemotely = false - if let staged = await stagedSparkExitState() { + if let staged = try await stagedSparkExitState() { let copy = try await rejectedSparkExitCopy(staged: staged) try await setAsideRejectedSparkExit(copy.data) isReplacedRemotely = copy.isReplacedRemotely } - await discardStagedSparkExit() // Another device replaced the backup with exit data this one never read, so it is restored before - // anything replaces it. + // anything replaces it; noted before the staged copy goes, so a stop in between still restores it. if isReplacedRemotely { defaults.set(true, forKey: Self.sparkExitRestorePendingKey) + } + await discardStagedSparkExit() + if isReplacedRemotely { await restoreSparkExit() throw SparkExitBackupError.restorePending } diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 9f30f86e37..ef4ef6d574 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1156,7 +1156,9 @@ class LightningService: NodeLifecycleService { } ) if let paymentHash { - endRailSendUncertainty(paymentHash: paymentHash) + // Spark took the send, which may still be pending: its earlier attempts stay known until it settles, + // so their failures don't end its hold. + eventCallbackLock.withLock { clearRailSendUncertainty(hash: paymentHash.lowercased(), keepingEarlierAttempts: true) } } return sent } catch let refusal as ChannelFreeRailSendRefused { @@ -1717,10 +1719,11 @@ class LightningService: NodeLifecycleService { /// Callers hold `eventCallbackLock`. private func isEarlierThanUncertainRailSendLocked(hash: String, createdAt: UInt64, paymentId: String?) -> Bool { - guard uncertainRailSendFailedAt()[hash] != nil else { return false } + // Known until the latest send settles, also once Spark took it, so its earlier attempts are told apart by id. if let paymentId, let earlier = uncertainRailSendEarlierAttempts()[hash] { return earlier.contains(paymentId) } + guard uncertainRailSendFailedAt()[hash] != nil else { return false } // A send in doubt saved before its start was recorded can't be told from an earlier attempt, so it stays held // until its invoice expires. guard let startedAt = uncertainRailSendStartedAt()[hash] else { return true } @@ -1758,13 +1761,13 @@ class LightningService: NodeLifecycleService { } /// Callers hold `eventCallbackLock`. - private func clearRailSendUncertainty(hash: String) { + private func clearRailSendUncertainty(hash: String, keepingEarlierAttempts: Bool = false) { var started = uncertainRailSendStartedAt() if started.removeValue(forKey: hash) != nil { railAttemptsStore.set(started, forKey: Self.uncertainRailSendsStartedKey) } var earlier = uncertainRailSendEarlierAttempts() - if earlier.removeValue(forKey: hash) != nil { + if !keepingEarlierAttempts, earlier.removeValue(forKey: hash) != nil { railAttemptsStore.set(earlier, forKey: Self.uncertainRailSendsEarlierAttemptsKey) } var uncertain = uncertainRailSendFailedAt() diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index a66a44cdc3..a5aeaf22f1 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -878,6 +878,43 @@ extension ChannelFreeRailTests { await assertRefusedAsDuplicate() } + func testAnEarlierAttemptsFailureAfterSparkTookTheRetryKeepsItsHold() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier")] + rail.balanceSats = 100_000 + // Spark takes the retry, which stays pending. + _ = try await service.send(bolt11: Self.invoice) + rail.sentBolt11 = nil + rail.payments = [ + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier"), + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .pending, preimage: nil, id: "retry"), + ] + rail.balanceSats = 0 + + XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 2000, paymentId: "earlier")) + XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 2000, paymentId: "retry")) + service.emitChannelFreeRailEvent( + .paymentFailed(paymentId: "earlier", paymentHash: hash, reason: nil), + paymentCreatedAt: 900, + railPaymentId: "earlier" + ) + await assertRefusedAsDuplicate() + + // The retry's own failure ends it. + rail.payments = [ + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier"), + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "retry"), + ] + service.emitChannelFreeRailEvent( + .paymentFailed(paymentId: "retry", paymentHash: hash, reason: nil), + paymentCreatedAt: 1000, + railPaymentId: "retry" + ) + await assertReachesTheNode() + } + func testAFailureWithoutSparkIdsKeepsTheHoldUntilPastTheClockMargin() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared diff --git a/BitkitTests/SparkExitBackupTests.swift b/BitkitTests/SparkExitBackupTests.swift index be112e9dcd..83835b1d0f 100644 --- a/BitkitTests/SparkExitBackupTests.swift +++ b/BitkitTests/SparkExitBackupTests.swift @@ -302,6 +302,61 @@ final class SparkExitBackupTests: XCTestCase { XCTAssertEqual(restored, ["other"], "A backup written during the set-aside was replaced unread") } + func testARestoreOfAnotherDevicesBackupIsNotedBeforeTheStagedCopyGoes() async throws { + let suite = "SparkExitBackupTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let export = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 1000, network: "regtest", exitState: "fresh")) + let otherDevice = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 950, network: "regtest", exitState: "other")) + var remote = ["SPARK_EXIT": otherDevice] + var staged: SparkStagedExitImport = .rejected + var isRestorePendingWhenDiscarded: Bool? + let service = BackupService( + defaults: defaults, + backupData: { _ in export }, + uploadBackup: { remote[$0] = $1 }, + waitForTemporaryFailureDelay: { _ in }, + fetchBackup: { remote[$0] }, + importStagedSparkExit: { staged }, + discardStagedSparkExit: { + // A stop here relaunches with whatever was saved before the staged copy went. + isRestorePendingWhenDiscarded = defaults.bool(forKey: "sparkExitRestorePending") + staged = .nothingStaged + }, + stagedSparkExitState: { "mine" }, + restoreExitBackup: { _ in staged = .pending } + ) + + _ = await service.triggerBackup(category: .sparkExit) + + XCTAssertEqual(isRestorePendingWhenDiscarded, true, "A stop after the staged copy went would replace the other device's backup unread") + XCTAssertEqual(remote["SPARK_EXIT"], otherDevice) + } + + func testAStagedFileThatCantBeReadKeepsTheRemoteCopy() async throws { + let suite = "SparkExitBackupTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let export = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 1000, network: "regtest", exitState: "fresh")) + let restored = try JSONEncoder().encode(SparkExitBackupV1(version: 1, createdAt: 950, network: "regtest", exitState: "restored")) + var remote = ["SPARK_EXIT": restored] + struct Unreadable: Error {} + let service = BackupService( + defaults: defaults, + backupData: { _ in export }, + uploadBackup: { remote[$0] = $1 }, + waitForTemporaryFailureDelay: { _ in }, + fetchBackup: { remote[$0] }, + importStagedSparkExit: { .rejected }, + discardStagedSparkExit: {}, + stagedSparkExitState: { throw Unreadable() } + ) + + _ = await service.triggerBackup(category: .sparkExit) + + XCTAssertEqual(remote["SPARK_EXIT"], restored, "A staged file that couldn't be read let a fresh export replace the remote copy") + } + func testOnlyInvalidInputMarksExitDataAsRejected() { XCTAssertEqual(SparkStagedExitImport(importError: SdkError.InvalidInput("unsupported exit state version")), .rejected) XCTAssertEqual(SparkStagedExitImport(importError: URLError(.notConnectedToInternet)), .pending) From f9fa2c280e8f51aaeda274879afae4e93bf39b56 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 00:29:58 +0100 Subject: [PATCH 14/64] fix: move to spark stays offered while a move awaits its result Spending and Lightning Connections offered Move to Spark only while the channels had something to move, so a move in flight that used up their balance hid its own screen. They now also offer it while a move is kept for its result. Verified: MoveToSparkLateOutcome, MoveToSparkQuote, MoveToSparkActivity and MoveToSparkMath tests pass on an iPhone 17 Pro simulator; swiftformat lint clean. --- Bitkit/Managers/MoveToSparkManager.swift | 5 +++++ .../Advanced/LightningConnectionsView.swift | 2 +- Bitkit/Views/Wallets/SpendingWalletScreen.swift | 3 ++- BitkitTests/MoveToSparkLateOutcomeTests.swift | 14 ++++++++++++++ 4 files changed, 22 insertions(+), 2 deletions(-) diff --git a/Bitkit/Managers/MoveToSparkManager.swift b/Bitkit/Managers/MoveToSparkManager.swift index f255038bcc..f99199ca75 100644 --- a/Bitkit/Managers/MoveToSparkManager.swift +++ b/Bitkit/Managers/MoveToSparkManager.swift @@ -230,6 +230,11 @@ final class MoveToSparkManager { /// A swiped payment that has not settled yet; leaving the screen keeps it, so it is never quoted over. private var isMoveInFlight = false + /// A move is kept for its result, so its screen stays reachable while the channels have nothing left to move. + var keepsMoveForItsResult: Bool { + keepsOutcome || isMoveInFlight + } + private let services: any MoveToSparkServices init(services: any MoveToSparkServices = LiveMoveToSparkServices()) { diff --git a/Bitkit/Views/Settings/Advanced/LightningConnectionsView.swift b/Bitkit/Views/Settings/Advanced/LightningConnectionsView.swift index eb0efa83ae..3ccd657da4 100644 --- a/Bitkit/Views/Settings/Advanced/LightningConnectionsView.swift +++ b/Bitkit/Views/Settings/Advanced/LightningConnectionsView.swift @@ -156,7 +156,7 @@ struct LightningConnectionsView: View { } } - if MoveToSparkMath.canMove( + if MoveToSparkManager.shared.keepsMoveForItsResult || MoveToSparkMath.canMove( channels: wallet.channels, isSparkUsable: MoveToSparkMath.isSparkUsable(SparkManager.shared) ) { diff --git a/Bitkit/Views/Wallets/SpendingWalletScreen.swift b/Bitkit/Views/Wallets/SpendingWalletScreen.swift index 7228112b6b..229ece9a0c 100644 --- a/Bitkit/Views/Wallets/SpendingWalletScreen.swift +++ b/Bitkit/Views/Wallets/SpendingWalletScreen.swift @@ -9,7 +9,8 @@ struct SpendingWalletScreen: View { @EnvironmentObject var wallet: WalletViewModel private var canMoveToSpark: Bool { - MoveToSparkMath.canMove(channels: wallet.channels, isSparkUsable: MoveToSparkMath.isSparkUsable(SparkManager.shared)) + MoveToSparkManager.shared.keepsMoveForItsResult + || MoveToSparkMath.canMove(channels: wallet.channels, isSparkUsable: MoveToSparkMath.isSparkUsable(SparkManager.shared)) } private var shouldShowOnboarding: Bool { diff --git a/BitkitTests/MoveToSparkLateOutcomeTests.swift b/BitkitTests/MoveToSparkLateOutcomeTests.swift index d63fab83dd..611ab5694c 100644 --- a/BitkitTests/MoveToSparkLateOutcomeTests.swift +++ b/BitkitTests/MoveToSparkLateOutcomeTests.swift @@ -3,6 +3,20 @@ import LDKNode import XCTest final class MoveToSparkLateOutcomeTests: XCTestCase { + @MainActor + func testAMoveKeptForItsResultKeepsItsScreenReachableUntilTheWalletIsWiped() { + let manager = MoveToSparkManager() + XCTAssertFalse(manager.keepsMoveForItsResult) + + _ = manager.beginMove() + XCTAssertTrue(manager.keepsMoveForItsResult, "A move in flight hid its screen once the channels had nothing left to move") + manager.reset() + XCTAssertTrue(manager.keepsMoveForItsResult, "Leaving the screen of a move in flight forgot it") + + manager.resetForWipe() + XCTAssertFalse(manager.keepsMoveForItsResult) + } + func testLateSuccessOfTheInFlightMoveShowsItMovedWithItsFee() { let state = MoveToSparkState.inFlight(amountSats: 40000) XCTAssertTrue(MoveToSparkManager.showsInFlightMove(state, generation: 3, moveGeneration: 3)) From dffd284c891d54272a9dc52613219141ec01d4bc Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 20:43:15 +0100 Subject: [PATCH 15/64] fix: spark retry spark took holds the node until spark lists it Once Spark took a retry, its listing can still show only the earlier attempts' failures. Those failures now read pending while the invoice is unexpired and no other attempt is listed, so the node never pays an invoice the retry may still pay. Verified: ChannelFreeRailTests, SparkTransferFlowTests, SparkExitBackupTests and MoveToSparkLateOutcomeTests pass on an iPhone 17 Pro simulator --- Bitkit/Services/LightningService.swift | 24 +++++++++++++++++++++++- BitkitTests/ChannelFreeRailTests.swift | 22 ++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index ef4ef6d574..8dee204b4f 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1694,6 +1694,28 @@ class LightningService: NodeLifecycleService { railAttemptsStore.dictionary(forKey: Self.uncertainRailSendsStartedKey) as? [String: Int] ?? [:] } + /// Spark took a retry of an unexpired invoice but lists only the attempts before it: their failures read pending, so + /// the node never pays the invoice the retry may still pay. + private func takenRetriesPending(_ payments: [ChannelFreeRailPayment], unexpired: Set) -> [ChannelFreeRailPayment] { + let earlier = eventCallbackLock.withLock { uncertainRailSendEarlierAttempts() } + guard !earlier.isEmpty else { return payments } + let isEarlier = { (payment: ChannelFreeRailPayment) in + payment.id.map { earlier[payment.paymentHash.lowercased()]?.contains($0) ?? false } ?? false + } + let retryListed = Set(payments.filter { $0.direction == .outbound && !isEarlier($0) }.map { $0.paymentHash.lowercased() }) + return payments.map { payment in + let hash = payment.paymentHash.lowercased() + guard payment.direction == .outbound, payment.status == .failed, isEarlier(payment), unexpired.contains(hash), + !retryListed.contains(hash) else { return payment } + var pending = ChannelFreeRailPayment( + paymentHash: payment.paymentHash, direction: payment.direction, status: .pending, preimage: payment.preimage, + timestamp: payment.timestamp, feeSats: payment.feeSats + ) + pending.id = payment.id + return pending + } + } + /// Callers hold `eventCallbackLock`. private func uncertainRailSendEarlierAttempts() -> [String: [String]] { railAttemptsStore.dictionary(forKey: Self.uncertainRailSendsEarlierAttemptsKey) as? [String: [String]] ?? [:] @@ -2522,7 +2544,7 @@ extension LightningService { // Read before the listing, so a sync that ends while it is read can't settle a send the listing predates. let unsettled = await unsettledUncertainRailSends() let kept = unexpiredRailAttempts() - let payments = try await rail.lightningPayments() + let payments = try await takenRetriesPending(rail.lightningPayments(), unexpired: kept) 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() } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index a5aeaf22f1..4aa475201f 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -915,6 +915,28 @@ extension ChannelFreeRailTests { await assertReachesTheNode() } + func testARetrySparkTookButDoesntListYetKeepsTheNodeFromPaying() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + let earlier = Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier") + rail.payments = [earlier] + rail.balanceSats = 100_000 + _ = try await service.send(bolt11: Self.invoice) + rail.sentBolt11 = nil + rail.balanceSats = 0 + + // Spark took the retry but still lists only the earlier failure. + await assertRefusedAsDuplicate() + + // Once it lists the retry failed, the invoice can be paid again. + rail.payments = [ + earlier, + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "retry"), + ] + await assertReachesTheNode() + } + func testAFailureWithoutSparkIdsKeepsTheHoldUntilPastTheClockMargin() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared From 4d5f4eb248699e3879fd7b1dc904859bfa940519 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 18 Nov 2026 20:43:16 +0100 Subject: [PATCH 16/64] fix: spark exit restore logs the data staged, not restored The restore only stages the exit data; Spark imports it once connected and may still reject it, so the log no longer calls it a success. Verified: log wording only; SparkExitBackupTests pass on an iPhone 17 Pro simulator --- Bitkit/Services/BackupService.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 8f5612cde7..c163640520 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -1538,7 +1538,8 @@ class BackupService { return } try await restoreExitBackup(backup) - Logger.info("Restore success for: '\(BackupCategory.sparkExit.rawValue)'", context: "BackupService") + // Spark imports it only once connected, and may still reject it then. + Logger.info("Staged '\(BackupCategory.sparkExit.rawValue)' for Spark's import", context: "BackupService") } else { Logger.warn("Restore null for: '\(BackupCategory.sparkExit.rawValue)'", context: "BackupService") } From 336484308817d3b07eba2c96e1341d293c537015 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 13:36:58 +0100 Subject: [PATCH 17/64] fix: startup sync keeps the hold on a retry spark took Once Spark took a retry, the launch's activity sync released its hold when Spark's list still showed only the earlier failed attempt. That dropped the stored expiry the duplicate check reads, so the node could pay the unexpired invoice while the retry may still settle. The startup release now skips failures of the attempts listed before the send Spark took, and releases the hold once Spark lists the retry itself failed. Verified: ChannelFreeRailTests, SparkPaymentSafetyTests, MoveToSparkQuoteTests and SparkExitBackupTests on an iOS simulator --- Bitkit/Managers/SparkManager.swift | 9 +++++--- Bitkit/Services/LightningService.swift | 5 +++++ BitkitTests/ChannelFreeRailTests.swift | 29 ++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 7dda9a45ec..623cce7f5b 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -1874,13 +1874,15 @@ final class SparkManager: ChannelFreeLightningRail { return await failStoredSend(paymentHash) } - /// Payment hashes whose every Lightning send failed, so a hold on a channel retry can be released. - nonisolated static func failedSendHashes(_ payments: [Payment]) -> [String] { + /// Payment hashes whose every Lightning send failed, so a hold on a channel retry can be released. A failure of an + /// attempt listed before a send Spark took doesn't count: that send may still pay the invoice. + nonisolated static func failedSendHashes(_ payments: [Payment], earlierAttemptIds: [String: [String]] = [:]) -> [String] { var failed: [String] = [] var live: Set = [] for payment in payments where payment.paymentType == .send { guard case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details else { continue } if payment.status == .failed { + guard earlierAttemptIds[htlcDetails.paymentHash.lowercased()]?.contains(payment.id) != true else { continue } failed.append(htlcDetails.paymentHash) } else { live.insert(htlcDetails.paymentHash) @@ -1909,8 +1911,9 @@ final class SparkManager: ChannelFreeLightningRail { /// so a retry the user started meanwhile keeps its hold, as does one recorded or ending while the list is read. static func releaseFailedSendHolds(listPayments: () async throws -> [Payment]) async { let mark = LightningService.shared.attemptMark + let earlier = LightningService.shared.railSendEarlierAttemptIds guard let latest = try? await listPayments() else { return } - for paymentHash in failedSendHashes(latest) { + for paymentHash in failedSendHashes(latest, earlierAttemptIds: earlier) { LightningService.shared.releaseRailAttempt(paymentHash: paymentHash, since: mark) } } diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 8dee204b4f..902148e42c 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1716,6 +1716,11 @@ class LightningService: NodeLifecycleService { } } + /// The rail's ids of the attempts before each send in doubt or that Spark took, by hash. + var railSendEarlierAttemptIds: [String: [String]] { + eventCallbackLock.withLock { uncertainRailSendEarlierAttempts() } + } + /// Callers hold `eventCallbackLock`. private func uncertainRailSendEarlierAttempts() -> [String: [String]] { railAttemptsStore.dictionary(forKey: Self.uncertainRailSendsEarlierAttemptsKey) as? [String: [String]] ?? [:] diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 4aa475201f..de260d139c 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -937,6 +937,35 @@ extension ChannelFreeRailTests { await assertReachesTheNode() } + func testARetrySparkTookStaysHeldAfterARelaunchWhileSparkListsOnlyTheEarlierFailure() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + let earlier = Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier") + rail.payments = [earlier] + rail.balanceSats = 100_000 + _ = try await service.send(bolt11: Self.invoice) + rail.sentBolt11 = nil + rail.balanceSats = 0 + try simulateRelaunch() + + // The launch's sync reads Spark's list, which still shows only the earlier failed attempt. + await SparkManager.releaseFailedSendHolds { [Self.sparkPayment(hash: hash, status: .failed, id: "earlier")] } + let kept = service.railAttemptsStore.stringArray(forKey: Self.railAttemptsKey) ?? [] + XCTAssertTrue(kept.contains(hash), "an earlier attempt's failure released a retry Spark took") + await assertRefusedAsDuplicate() + + // Once it lists the retry failed, the invoice can be paid again. + await SparkManager.releaseFailedSendHolds { + [Self.sparkPayment(hash: hash, status: .failed, id: "earlier"), Self.sparkPayment(hash: hash, status: .failed, id: "retry")] + } + rail.payments = [ + earlier, + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "retry"), + ] + await assertReachesTheNode() + } + func testAFailureWithoutSparkIdsKeepsTheHoldUntilPastTheClockMargin() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared From ee309f1b88fd555b9db263517fcc88c7ab5f5311 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 14:08:25 +0100 Subject: [PATCH 18/64] fix: app status opens spark's detail offline App Status's Spark row opened the Spark connection detail only while its status read ready, so offline, with Spark's state already read, the detail could only be reached from Lightning Connections. The row now opens it once Spark has read its state, as on Android. Verified: AppStatusHelperTests and AppStatusExitTests on an iOS simulator --- Bitkit/Utilities/AppStatusHelper.swift | 5 +++++ Bitkit/Views/Settings/AppStatusView.swift | 4 ++-- BitkitTests/AppStatusHelperTests.swift | 9 +++++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/Bitkit/Utilities/AppStatusHelper.swift b/Bitkit/Utilities/AppStatusHelper.swift index 4e8c35a7ed..e9ce2aefb5 100644 --- a/Bitkit/Utilities/AppStatusHelper.swift +++ b/Bitkit/Utilities/AppStatusHelper.swift @@ -117,6 +117,11 @@ struct AppStatusHelper { ) } + /// Spark's detail shows a zero balance until Spark has read its state; once it has, the detail opens offline too. + nonisolated static func opensSparkDetail(status: HealthStatus, isReady: Bool) -> Bool { + status == .ready || isReady + } + /// Spark carries Lightning when no channel can, so the connection is ready through it; red only when neither can pay. nonisolated static func channelsStatus( isOnline: Bool, diff --git a/Bitkit/Views/Settings/AppStatusView.swift b/Bitkit/Views/Settings/AppStatusView.swift index 3c70e5108d..e73063b594 100644 --- a/Bitkit/Views/Settings/AppStatusView.swift +++ b/Bitkit/Views/Settings/AppStatusView.swift @@ -173,8 +173,8 @@ struct AppStatusView: View { title: t("settings__status__spark__title"), description: t("settings__status__spark__\(status.rawValue)"), status: status, - // Spark's detail shows a zero balance until Spark has read its state. - onTap: status == .ready ? { navigation.navigate(.sparkConnectionDetail) } : nil + onTap: AppStatusHelper.opensSparkDetail(status: status, isReady: SparkManager.shared.isReady) + ? { navigation.navigate(.sparkConnectionDetail) } : nil ) .accessibilityElement(children: .contain) .accessibilityIdentifier("Status-spark") diff --git a/BitkitTests/AppStatusHelperTests.swift b/BitkitTests/AppStatusHelperTests.swift index dcd0a874cc..2749f1bab6 100644 --- a/BitkitTests/AppStatusHelperTests.swift +++ b/BitkitTests/AppStatusHelperTests.swift @@ -16,6 +16,15 @@ final class AppStatusHelperTests: XCTestCase { XCTAssertEqual(AppStatusHelper.sparkStatus(isOnline: true, isSupported: true, isReady: false, hasStartFailed: true), .error) } + func testSparkDetailOpensOfflineOnceSparkHasReadItsState() { + let offline = AppStatusHelper.sparkStatus(isOnline: false, isSupported: true, isReady: true, hasStartFailed: false) + XCTAssertEqual(offline, .error) + XCTAssertTrue(AppStatusHelper.opensSparkDetail(status: .error, isReady: true)) + XCTAssertTrue(AppStatusHelper.opensSparkDetail(status: .ready, isReady: true)) + XCTAssertFalse(AppStatusHelper.opensSparkDetail(status: .pending, isReady: false)) + XCTAssertFalse(AppStatusHelper.opensSparkDetail(status: .error, isReady: false)) + } + func testChannelsStatusIsReadyThroughSparkWhenNoChannelIsUsable() { let status = AppStatusHelper.channelsStatus(isOnline: true, hasUsableChannels: false, hasChannels: true, isSparkUsable: true) XCTAssertEqual(status, .ready) From 6c1c0addcdd808e3f6503a6459a208419e76afe8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 15:28:40 +0100 Subject: [PATCH 19/64] fix: an expired hold writes a live retry over a tied failure When a hold ended at the invoice's expiry, the send's Activity row was written from Spark's newest send by timestamp alone, so an earlier failure listed in the same second as a pending retry could mark the live retry failed. A live send now wins over failed ones, then the newest, as the duplicate-payment selector does. Verified: ChannelFreeRailTests and SparkPaymentSafetyTests on an iOS simulator --- Bitkit/Managers/SparkManager.swift | 3 ++- BitkitTests/ChannelFreeRailTests.swift | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 623cce7f5b..022a3d9bdb 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -1868,7 +1868,8 @@ final class SparkManager: ChannelFreeLightningRail { guard payment.paymentType == .send, case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details else { return false } return htlcDetails.paymentHash.caseInsensitiveCompare(paymentHash) == .orderedSame } - if let latest = sends.max(by: { $0.timestamp < $1.timestamp }) { + // A live send wins over failed ones, then the newest, as a retry can share its earlier attempt's timestamp. + if let latest = sends.max(by: { ($0.status == .failed ? 0 : 1, $0.timestamp) < ($1.status == .failed ? 0 : 1, $1.timestamp) }) { return await record(latest) } return await failStoredSend(paymentHash) diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index de260d139c..5cd7321bf2 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1053,6 +1053,20 @@ extension ChannelFreeRailTests { XCTAssertEqual(failed, ["ef"], "a send Spark lists none of stayed pending") } + func testAnExpiredHoldWritesALiveRetryOverAFailureWithTheSameTimestamp() async { + let hash = "ab" + let failed = Self.sparkPayment(hash: hash, status: .failed, id: "earlier", timestamp: 5) + let pending = Self.sparkPayment(hash: hash, status: .pending, id: "retry", timestamp: 5) + for payments in [[failed, pending], [pending, failed]] { + var recorded: [String] = [] + _ = await SparkManager.recordExpiredHold( + paymentHash: hash, payments: payments, + record: { recorded.append($0.id); return true }, failStoredSend: { _ in true } + ) + XCTAssertEqual(recorded, ["retry"], "a failure tied with the live retry replaced its row") + } + } + func testAnUnknownSparkSendStaysHeldAfterARelaunchWhenSparkListsOnlyAnOlderFailedAttempt() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared From 50e7c1c911e8c08b8cf4616a4a013ef5b76af10a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 17:13:11 +0100 Subject: [PATCH 20/64] fix: exit data network, move backup mark and exit expiry - Set-aside exit data rebuilt without a readable remote entry carries Spark's network name (mainnet), as Spark's restore reads it, not the app's (bitcoin). - A move to Spark marks the metadata backup required as its hash is saved, not half a second later, so a stop in between can't leave an Activity backup holding the move without the metadata naming it one. - During an exit, the hold on a Spark send in doubt ends at its invoice's expiry through Spark's history rail, so its row no longer stays pending through the exit. Verified: ChannelFreeRailTests, SparkPaymentSafetyTests, SparkExitBackupTests and MoveToSparkQuoteTests on an iOS simulator --- Bitkit/Managers/SparkManager.swift | 5 +++++ Bitkit/Services/BackupService.swift | 6 +++--- Bitkit/Services/LightningService.swift | 5 ++++- BitkitTests/ChannelFreeRailTests.swift | 28 ++++++++++++++++++++++++++ BitkitTests/SparkExitBackupTests.swift | 5 +++++ 5 files changed, 45 insertions(+), 4 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 022a3d9bdb..e7964fa065 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -383,6 +383,11 @@ final class SparkManager: ChannelFreeLightningRail { .bolt11Invoice(preferSpark: prefersSpark, completionTimeoutSecs: nil) } + /// The network name an exit backup carries: Spark's, which names Bitcoin's main network `mainnet`. + nonisolated static func exitBackupNetworkName(_ network: LDKNode.Network) -> String { + network == .bitcoin ? "\(BreezSdkSpark.Network.mainnet)" : "\(network)" + } + private static var sparkNetwork: BreezSdkSpark.Network? { switch Env.network { case .bitcoin: Env.breezApiKey == nil ? nil : .mainnet diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index c163640520..a3c156c1f0 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -1014,9 +1014,9 @@ class BackupService { } .store(in: cancellables) - // METADATA (moves to Spark) + // METADATA (moves to Spark). Marked as the hash is saved, so a stop right after can't leave a later Activity backup + // holding the move without the metadata that names it one. MoveToSparkPayments.savedPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) .sink { @Sendable [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } markBackupRequired(category: .metadata) @@ -1560,7 +1560,7 @@ class BackupService { let copy = try JSONEncoder().encode(SparkExitBackupV1( version: 1, createdAt: UInt64(Date().timeIntervalSince1970 * 1000), - network: remoteBackup?.network ?? "\(Env.network)", + network: remoteBackup?.network ?? SparkManager.exitBackupNetworkName(Env.network), exitState: staged )) return (copy, remote != nil) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 902148e42c..9806445f2e 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1824,7 +1824,10 @@ class LightningService: NodeLifecycleService { uncertainRailSendFailedAt()[hash].map { (failedAt: UInt64($0), expiresAt: attemptExpiries(key: Self.railAttemptsKey)[hash]) } } guard let uncertain else { return true } - guard let rail = channelFreeRail, await rail.hasSynced(after: uncertain.failedAt) 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: uncertain.failedAt) else { + return false + } // Spark keeps a send it committed but didn't finish in a cache no call exposes, and a sync that reached Spark // 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 } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 5cd7321bf2..51507c9a09 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1029,6 +1029,34 @@ extension ChannelFreeRailTests { XCTAssertEqual(expired, [hash, hash], "a saved activity was written again") } + func testAHoldEndsAtTheInvoicesExpiryDuringAnExit() async throws { + let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) + let hash = String(invoice.paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + rail.balanceSats = 100_000 + rail.errorAfterSubmission = NSError(domain: "spark", code: 2) + _ = try? await service.send(bolt11: Self.invoice) + rail.errorAfterSubmission = nil + rail.syncedAfter = { _ in true } + var expired: [String] = [] + let previousHook = service.railSendHoldExpired + let previousHistory = service.channelFreePaymentHistory + defer { + service.railSendHoldExpired = previousHook + service.channelFreePaymentHistory = previousHistory + } + service.railSendHoldExpired = { expired.append($0); return true } + // The exit takes Spark off sending and keeps its history. + service.channelFreePaymentHistory = rail + service.channelFreeRail = nil + + let expiresAt = invoice.secondsSinceEpoch() + invoice.expiryTimeSeconds() + service.now = { Date(timeIntervalSince1970: TimeInterval(expiresAt)) } + await service.endExpiredRailSendUncertainties() + XCTAssertEqual(expired, [hash], "the send stayed pending through the exit") + } + func testAnExpiredHoldWritesSparksLatestSendOrFailsTheStoredOne() async { let hash = "ab" var recorded: [String] = [] diff --git a/BitkitTests/SparkExitBackupTests.swift b/BitkitTests/SparkExitBackupTests.swift index 83835b1d0f..991cab069b 100644 --- a/BitkitTests/SparkExitBackupTests.swift +++ b/BitkitTests/SparkExitBackupTests.swift @@ -5,6 +5,11 @@ import XCTest @MainActor final class SparkExitBackupTests: XCTestCase { + func testAnExitBackupNamesTheNetworkAsSparkDoes() { + XCTAssertEqual(SparkManager.exitBackupNetworkName(.bitcoin), "mainnet") + XCTAssertEqual(SparkManager.exitBackupNetworkName(.regtest), "\(BreezSdkSpark.Network.regtest)") + } + private let walletIndex = 99 override func tearDown() { From da75b3cadc169a4df0f87a7b8164e91e4539f9c8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 19:03:04 +0100 Subject: [PATCH 21/64] fix: release the early claim cap when the claim poll gives up When the deposit poll gave up on a waiting early claim and showed the normal speed, the approved fee stayed on the deposit as its cap, so Spark could still claim it early. The cap is now cleared then, as Wait already does. Verified: SparkTransferFlowTests on an iOS simulator, then the unit suite (the selection in unit-tests.yml) --- Bitkit/ViewModels/SparkTransferFlow.swift | 38 +++++++++++++---------- BitkitTests/SparkTransferFlowTests.swift | 20 +++++++++++- 2 files changed, 41 insertions(+), 17 deletions(-) diff --git a/Bitkit/ViewModels/SparkTransferFlow.swift b/Bitkit/ViewModels/SparkTransferFlow.swift index 285fbaec93..f22c886037 100644 --- a/Bitkit/ViewModels/SparkTransferFlow.swift +++ b/Bitkit/ViewModels/SparkTransferFlow.swift @@ -439,25 +439,29 @@ final class SparkTransferFlow { if let txid { watchTasks[txid]?.cancel() watchTasks[txid] = nil - if let offer = claimedOffers.removeValue(forKey: txid) { - let operations = operations - let attempts = max(pollAttempts, 1) - // Not awaited: the SDK call ignores cancellation and can take a while. Tried again while another claim of - // the deposit, such as Spark's own sync, leaves the cap in place. - Task { - for attempt in 1 ... attempts { - if await operations.releaseEarlyClaim(offer) { - return - } - if attempt < attempts { - await operations.sleep(Self.pollInterval) - } - } - Logger.warn("Gave up clearing the early claim cap of Spark deposit \(offer.txid)", context: "SparkTransferFlow") + releaseEarlyClaimCap(txid: txid) + } + claimState = .later + } + + /// Clears the fee cap an early claim attempt left on the deposit, so Spark no longer claims it early. + private func releaseEarlyClaimCap(txid: String) { + guard let offer = claimedOffers.removeValue(forKey: txid) else { return } + let operations = operations + let attempts = max(pollAttempts, 1) + // Not awaited: the SDK call ignores cancellation and can take a while. Tried again while another claim of the + // deposit, such as Spark's own sync, leaves the cap in place. + Task { + for attempt in 1 ... attempts { + if await operations.releaseEarlyClaim(offer) { + return + } + if attempt < attempts { + await operations.sleep(Self.pollInterval) } } + Logger.warn("Gave up clearing the early claim cap of Spark deposit \(offer.txid)", context: "SparkTransferFlow") } - claimState = .later } /// Waits for the current transfer's claim to settle; for tests. @@ -543,6 +547,8 @@ final class SparkTransferFlow { // A deposit Spark listed whose early claim never came is waiting for its confirmations, not unseen. guard offers[txid] == nil else { Logger.info("No early claim for Spark deposit \(txid) within the polling window", context: "SparkTransferFlow") + // Shown at the normal speed, so Spark no longer claims it early at the approved fee. + releaseEarlyClaimCap(txid: txid) setClaimState(.unavailable, for: txid) return } diff --git a/BitkitTests/SparkTransferFlowTests.swift b/BitkitTests/SparkTransferFlowTests.swift index 35ca186866..2016d73b0a 100644 --- a/BitkitTests/SparkTransferFlowTests.swift +++ b/BitkitTests/SparkTransferFlowTests.swift @@ -172,6 +172,19 @@ final class SparkTransferFlowTests: XCTestCase { XCTAssertEqual(calls.unclaimedChecks, 2) } + @MainActor + func testAWaitingEarlyClaimThePollGivesUpOnClearsItsFeeCap() async throws { + let calls = PollCalls() + let flow = pollingFlow(offers: [choice(earlyFee: 900)], claims: [.waiting], pollAttempts: 3, calls: calls) + flow.onBroadcast(txid: "txid") + await flow.waitForClaim() + for _ in 0 ..< 100 where calls.released.isEmpty { + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertEqual(flow.claimState, .unavailable) + XCTAssertEqual(calls.released, ["txid"], "Spark may still claim early while the transfer shows the normal speed") + } + @MainActor func testAWaitingEarlyClaimIsCappedAtTheApprovedFeeNotTheFirstQuote() async { let calls = PollCalls() @@ -497,6 +510,7 @@ final class SparkTransferFlowTests: XCTestCase { var claims = 0 var unclaimedChecks = 0 var ceilings: [UInt64] = [] + var released: [String] = [] } /// A flow whose poll answers with `offers` in turn (nil once they run out), whose claims answer with `claims`, and @@ -528,7 +542,11 @@ final class SparkTransferFlowTests: XCTestCase { return unclaimed.isEmpty ? true : unclaimed.removeFirst() }, refresh: {}, - sleep: { _ in } + sleep: { _ in }, + releaseEarlyClaim: { offer in + calls.released.append(offer.txid) + return true + } ) return SparkTransferFlow(amountSats: 100_000, quote: quote, operations: operations, pollAttempts: pollAttempts ?? offers.count + 1) } From b24d06c261ca754e3da8d6ebbc969e8a32af58e2 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 19:03:05 +0100 Subject: [PATCH 22/64] fix: hold a taken spark retry by its own id Spark's send now returns the retry's own payment id, kept while the attempt holds the invoice. Once Spark took a retry, a failure under any other id is an earlier attempt's, also one Spark listed only after the retry went out, so it no longer ends the hold, marks the Activity row failed, or releases the hold at launch. A taken retry Spark lists no outcome of, only an earlier failure or nothing, ends 10 minutes past its invoice's expiry, the grace Android uses: its hold ends and its Activity row is written from Spark's list. A send in doubt now waits the same grace past expiry. Closes #1378 Verified: ChannelFreeRailTests, SparkPaymentSafetyTests, SparkTransferFlowTests, SparkExitBackupTests and MoveToSparkQuoteTests on an iOS simulator, then the unit suite (the selection in unit-tests.yml) --- Bitkit/Managers/SparkManager.swift | 19 ++-- Bitkit/Services/LightningService.swift | 122 +++++++++++++++++++++---- BitkitTests/ChannelFreeRailTests.swift | 107 +++++++++++++++++++++- 3 files changed, 224 insertions(+), 24 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index e7964fa065..0e34af820e 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -656,7 +656,7 @@ final class SparkManager: ChannelFreeLightningRail { sats: UInt64?, maxFeeSats: UInt64?, beforeSubmission: @escaping () throws -> Void - ) async throws -> PaymentHash { + ) async throws -> (paymentHash: PaymentHash, paymentId: String?) { let prepared: PrepareSendPaymentResponse let sdk: BreezSdk do { @@ -696,7 +696,7 @@ final class SparkManager: ChannelFreeLightningRail { } } Logger.info("Sent Spark payment '\(response.payment.id)' with status '\(response.payment.status)'", context: "SparkManager") - return invoiceDetails.paymentHash + return (invoiceDetails.paymentHash, response.payment.id) } nonisolated static func checkSendFee(_ feeSats: UInt64, maxFeeSats: UInt64?) throws { @@ -1881,14 +1881,20 @@ final class SparkManager: ChannelFreeLightningRail { } /// Payment hashes whose every Lightning send failed, so a hold on a channel retry can be released. A failure of an - /// attempt listed before a send Spark took doesn't count: that send may still pay the invoice. - nonisolated static func failedSendHashes(_ payments: [Payment], earlierAttemptIds: [String: [String]] = [:]) -> [String] { + /// attempt before a send Spark took doesn't count: that send may still pay the invoice. + nonisolated static func failedSendHashes( + _ payments: [Payment], + earlierAttemptIds: [String: [String]] = [:], + takenIds: [String: String] = [:] + ) -> [String] { var failed: [String] = [] var live: Set = [] for payment in payments where payment.paymentType == .send { guard case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details else { continue } if payment.status == .failed { - guard earlierAttemptIds[htlcDetails.paymentHash.lowercased()]?.contains(payment.id) != true else { continue } + guard !LightningService.isEarlierRailAttempt( + id: payment.id, hash: htlcDetails.paymentHash.lowercased(), taken: takenIds, earlier: earlierAttemptIds + ) else { continue } failed.append(htlcDetails.paymentHash) } else { live.insert(htlcDetails.paymentHash) @@ -1918,8 +1924,9 @@ final class SparkManager: ChannelFreeLightningRail { static func releaseFailedSendHolds(listPayments: () async throws -> [Payment]) async { let mark = LightningService.shared.attemptMark let earlier = LightningService.shared.railSendEarlierAttemptIds + let taken = LightningService.shared.railSendTakenIds guard let latest = try? await listPayments() else { return } - for paymentHash in failedSendHashes(latest, earlierAttemptIds: earlier) { + for paymentHash in failedSendHashes(latest, earlierAttemptIds: earlier, takenIds: taken) { LightningService.shared.releaseRailAttempt(paymentHash: paymentHash, since: mark) } } diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 9806445f2e..357026eb60 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -12,8 +12,9 @@ protocol ChannelFreeLightningRail: AnyObject { @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 + /// payment goes out, as the node path does. Returns the payment's hash and the rail's id of this attempt. + func send(bolt11: String, sats: UInt64?, maxFeeSats: UInt64?, beforeSubmission: @escaping () throws -> Void) async throws + -> (paymentHash: PaymentHash, paymentId: String?) 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] @@ -1156,11 +1157,11 @@ class LightningService: NodeLifecycleService { } ) if let paymentHash { - // Spark took the send, which may still be pending: its earlier attempts stay known until it settles, - // so their failures don't end its hold. - eventCallbackLock.withLock { clearRailSendUncertainty(hash: paymentHash.lowercased(), keepingEarlierAttempts: true) } + // Spark took the send, which may still be pending: its own id and its earlier attempts stay known until + // it settles, so their failures don't end its hold. + takeRailSend(hash: paymentHash.lowercased(), paymentId: sent.paymentId, since: mark) } - return sent + return sent.paymentHash } catch let refusal as ChannelFreeRailSendRefused { // Nothing left the wallet, and the checks above leave no earlier live attempt under this hash. if let paymentHash { @@ -1249,6 +1250,8 @@ class LightningService: NodeLifecycleService { private static let uncertainRailSendsStartedKey = "channelFreeRailUncertainSendStartedAt" /// The rail's ids of the attempts each of those sends followed, so a failure of one is told from the send's own. private static let uncertainRailSendsEarlierAttemptsKey = "channelFreeRailUncertainSendEarlierAttempts" + /// The rail's id of each send Spark took, by hash, until it settles: any other attempt's failure is an earlier one's. + private static let takenRailSendsKey = "channelFreeRailTakenSendIds" /// Hashes whose hold ended at their invoice's expiry before their activity was saved, retried on each rail sync. private static let expiredRailHoldsUnrecordedKey = "channelFreeRailExpiredHoldsUnrecorded" /// A listing drops the hashes it shows failed only, or paid once the invoice has expired, so the other rail can't @@ -1444,6 +1447,7 @@ class LightningService: NodeLifecycleService { railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsKey) railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsStartedKey) railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsEarlierAttemptsKey) + railAttemptsStore.removeObject(forKey: Self.takenRailSendsKey) railAttemptsStore.removeObject(forKey: Self.expiredRailHoldsUnrecordedKey) railAttemptsStore.removeObject(forKey: Self.railAttemptsKey) railAttemptsStore.removeObject(forKey: Self.expiriesKey(Self.railAttemptsKey)) @@ -1680,8 +1684,12 @@ class LightningService: NodeLifecycleService { var started = uncertainRailSendStartedAt() started[hash] = failedAt railAttemptsStore.set(started, forKey: Self.uncertainRailSendsStartedKey) + // A send Spark took before this one is now an earlier attempt too, listed or not. + var taken = takenRailSendIds() + let takenBefore = taken.removeValue(forKey: hash) + railAttemptsStore.set(taken, forKey: Self.takenRailSendsKey) var earlier = uncertainRailSendEarlierAttempts() - earlier[hash] = earlierAttemptIds + earlier[hash] = earlierAttemptIds.map { ids in takenBefore.map { ids.contains($0) ? ids : ids + [$0] } ?? ids } railAttemptsStore.set(earlier, forKey: Self.uncertainRailSendsEarlierAttemptsKey) } uncertain[hash] = failedAt @@ -1697,10 +1705,11 @@ class LightningService: NodeLifecycleService { /// Spark took a retry of an unexpired invoice but lists only the attempts before it: their failures read pending, so /// the node never pays the invoice the retry may still pay. private func takenRetriesPending(_ payments: [ChannelFreeRailPayment], unexpired: Set) -> [ChannelFreeRailPayment] { - let earlier = eventCallbackLock.withLock { uncertainRailSendEarlierAttempts() } - guard !earlier.isEmpty else { return payments } + let (earlier, taken) = eventCallbackLock.withLock { (uncertainRailSendEarlierAttempts(), takenRailSendIds()) } + guard !earlier.isEmpty || !taken.isEmpty else { return payments } let isEarlier = { (payment: ChannelFreeRailPayment) in - payment.id.map { earlier[payment.paymentHash.lowercased()]?.contains($0) ?? false } ?? false + payment.id.map { Self.isEarlierRailAttempt(id: $0, hash: payment.paymentHash.lowercased(), taken: taken, earlier: earlier) } + ?? false } let retryListed = Set(payments.filter { $0.direction == .outbound && !isEarlier($0) }.map { $0.paymentHash.lowercased() }) return payments.map { payment in @@ -1721,6 +1730,38 @@ class LightningService: NodeLifecycleService { eventCallbackLock.withLock { uncertainRailSendEarlierAttempts() } } + /// The rail's id of each send Spark took, by hash. + var railSendTakenIds: [String: String] { + eventCallbackLock.withLock { takenRailSendIds() } + } + + /// Whether the rail's attempt `id` of `hash` came before the send still held: once Spark took that send under an id + /// of its own, any other id, as Spark may list an older attempt only after the send went out; before, one listed + /// before the send went out. + nonisolated static func isEarlierRailAttempt(id: String, hash: String, taken: [String: String], earlier: [String: [String]]) -> Bool { + if let takenId = taken[hash] { + return id != takenId + } + return earlier[hash]?.contains(id) ?? false + } + + /// Callers hold `eventCallbackLock`. + private func takenRailSendIds() -> [String: String] { + railAttemptsStore.dictionary(forKey: Self.takenRailSendsKey) as? [String: String] ?? [:] + } + + /// Spark took the send of `hash`: it is no longer in doubt, and its own id is kept while the attempt it made still + /// holds the invoice, so a failure that ended it meanwhile leaves no id behind. + private func takeRailSend(hash: String, paymentId: String?, since mark: AttemptMark) { + eventCallbackLock.withLock { + clearRailSendUncertainty(hash: hash, keepingEarlierAttempts: true) + guard let paymentId, attemptsRecorded(since: mark.records, key: Self.railAttemptsKey).contains(hash) else { return } + var taken = takenRailSendIds() + taken[hash] = paymentId + railAttemptsStore.set(taken, forKey: Self.takenRailSendsKey) + } + } + /// Callers hold `eventCallbackLock`. private func uncertainRailSendEarlierAttempts() -> [String: [String]] { railAttemptsStore.dictionary(forKey: Self.uncertainRailSendsEarlierAttemptsKey) as? [String: [String]] ?? [:] @@ -1747,8 +1788,10 @@ class LightningService: NodeLifecycleService { /// Callers hold `eventCallbackLock`. private func isEarlierThanUncertainRailSendLocked(hash: String, createdAt: UInt64, paymentId: String?) -> Bool { // Known until the latest send settles, also once Spark took it, so its earlier attempts are told apart by id. - if let paymentId, let earlier = uncertainRailSendEarlierAttempts()[hash] { - return earlier.contains(paymentId) + let taken = takenRailSendIds() + let earlier = uncertainRailSendEarlierAttempts() + if let paymentId, taken[hash] != nil || earlier[hash] != nil { + return Self.isEarlierRailAttempt(id: paymentId, hash: hash, taken: taken, earlier: earlier) } guard uncertainRailSendFailedAt()[hash] != nil else { return false } // A send in doubt saved before its start was recorded can't be told from an earlier attempt, so it stays held @@ -1772,14 +1815,15 @@ class LightningService: NodeLifecycleService { return pending } - /// Spark's kept sends whose invoice is unexpired. A sync can still resume one Spark committed but lists no row for, - /// also after a relaunch, so it is pending until its invoice expires, the rule `railSyncedSinceUncertainSend` holds. + /// Spark's kept sends whose invoice is unexpired, or expired less than `unlistedRailSendGraceSeconds` ago. A sync can + /// still resume one Spark committed but lists no row for, also after a relaunch, so it is pending until then, the rule + /// `railSyncedSinceUncertainSend` holds. private func unexpiredRailAttempts() -> Set { let seconds = Int(now().timeIntervalSince1970) return eventCallbackLock.withLock { let expiries = attemptExpiries(key: Self.railAttemptsKey) let hashes = railAttemptsStore.stringArray(forKey: Self.railAttemptsKey) ?? [] - return Set(hashes.filter { hash in expiries[hash].map { $0 > seconds } ?? false }) + return Set(hashes.filter { hash in expiries[hash].map { $0 > seconds - Self.unlistedRailSendGraceSeconds } ?? false }) } } @@ -1797,6 +1841,10 @@ class LightningService: NodeLifecycleService { if !keepingEarlierAttempts, earlier.removeValue(forKey: hash) != nil { railAttemptsStore.set(earlier, forKey: Self.uncertainRailSendsEarlierAttemptsKey) } + var taken = takenRailSendIds() + if !keepingEarlierAttempts, taken.removeValue(forKey: hash) != nil { + railAttemptsStore.set(taken, forKey: Self.takenRailSendsKey) + } var uncertain = uncertainRailSendFailedAt() guard uncertain.removeValue(forKey: hash) != nil else { return } railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) @@ -1830,7 +1878,8 @@ class LightningService: NodeLifecycleService { } // Spark keeps a send it committed but didn't finish in a cache no call exposes, and a sync that reached Spark // 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 } + guard let expiresAt = uncertain.expiresAt, Int(now().timeIntervalSince1970) - Self.unlistedRailSendGraceSeconds >= expiresAt + else { return false } eventCallbackLock.withLock { clearRailSendUncertainty(hash: hash) var unrecorded = Set(railAttemptsStore.stringArray(forKey: Self.expiredRailHoldsUnrecordedKey) ?? []) @@ -1852,6 +1901,47 @@ class LightningService: NodeLifecycleService { for hash in hashes { _ = await railSyncedSinceUncertainSend(paymentHash: hash) } + await endExpiredUnlistedTakenRailSends() + } + + /// How long past its invoice's expiry a rail send Spark lists no outcome of still counts as live: an HTLC under way + /// at the expiry can still settle a little after it. + static let unlistedRailSendGraceSeconds = 10 * 60 + + /// Ends the holds of sends Spark took whose own outcome it still doesn't list, only an earlier attempt's failure or + /// nothing, once their invoice expired `unlistedRailSendGraceSeconds` ago, and writes their Activity row from that. + /// A send Spark lists is left to its own outcome. + private func endExpiredUnlistedTakenRailSends() async { + let nowSeconds = Int(now().timeIntervalSince1970) + let (expired, taken, earlier) = eventCallbackLock.withLock { + let uncertain = uncertainRailSendFailedAt() + let taken = takenRailSendIds() + let earlier = uncertainRailSendEarlierAttempts() + let expiries = attemptExpiries(key: Self.railAttemptsKey) + let held = Set(taken.keys).union(earlier.keys).subtracting(uncertain.keys) + let expired = held.filter { hash in expiries[hash].map { nowSeconds - Self.unlistedRailSendGraceSeconds >= $0 } ?? false } + return (expired, taken, earlier) + } + guard !expired.isEmpty, let rail = channelFreeRail ?? channelFreePaymentHistory, + let payments = try? await rail.lightningPayments() else { return } + for hash in expired { + let isListed = payments.contains { payment in + payment.direction == .outbound && payment.paymentHash.lowercased() == hash + && !(payment.id.map { Self.isEarlierRailAttempt(id: $0, hash: hash, taken: taken, earlier: earlier) } ?? false) + } + guard !isListed else { continue } + eventCallbackLock.withLock { + // Left alone if a new send of the invoice started meanwhile. + guard takenRailSendIds()[hash] == taken[hash], uncertainRailSendEarlierAttempts()[hash] == earlier[hash], + uncertainRailSendFailedAt()[hash] == nil else { return } + clearRailSendUncertainty(hash: hash) + removeAttempt(paymentHash: hash, key: Self.railAttemptsKey) + var unrecorded = Set(railAttemptsStore.stringArray(forKey: Self.expiredRailHoldsUnrecordedKey) ?? []) + unrecorded.insert(hash) + railAttemptsStore.set(Array(unrecorded), forKey: Self.expiredRailHoldsUnrecordedKey) + } + await recordExpiredRailHold(hash) + } } private func recordExpiredRailHold(_ hash: String) async { diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 51507c9a09..ede2cd6332 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -669,6 +669,10 @@ extension ChannelFreeRailTests { rail.syncedAfter = { _ in true } let expiresAt = try Self.invoiceExpiresAt() Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: expiresAt) } + // An HTLC under way at the expiry can still settle a little after it. + await assertRefusedAsDuplicate() + Bitkit.LightningService.shared + .now = { Date(timeIntervalSince1970: expiresAt + TimeInterval(Bitkit.LightningService.unlistedRailSendGraceSeconds)) } await assertReachesTheNode() } @@ -686,6 +690,10 @@ extension ChannelFreeRailTests { await assertRefusedAsDuplicate() Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: expiresAt) } + // An HTLC under way at the expiry can still settle a little after it. + await assertRefusedAsDuplicate() + Bitkit.LightningService.shared + .now = { Date(timeIntervalSince1970: expiresAt + TimeInterval(Bitkit.LightningService.unlistedRailSendGraceSeconds)) } await assertReachesTheNode() } @@ -724,6 +732,8 @@ extension ChannelFreeRailTests { XCTAssertEqual(status, .pending, "a send Spark can still resume was read as never made") await assertRefusedAsDuplicate() service.now = { Date(timeIntervalSince1970: TimeInterval(expiresAt)) } + await assertRefusedAsDuplicate() + service.now = { Date(timeIntervalSince1970: TimeInterval(expiresAt + Bitkit.LightningService.unlistedRailSendGraceSeconds)) } await assertReachesTheNode() } @@ -966,6 +976,87 @@ extension ChannelFreeRailTests { await assertReachesTheNode() } + func testAnOlderAttemptSparkListsOnlyAfterATakenRetryKeepsItsHold() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + // Spark lists no earlier attempt before the retry goes out, and takes the retry under its own id. + rail.balanceSats = 100_000 + rail.sentPaymentId = "retry" + _ = try await service.send(bolt11: Self.invoice) + rail.sentBolt11 = nil + rail.balanceSats = 0 + + // An older attempt shows up afterwards, failed, while the retry is still unlisted. + let older = Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "older") + XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 2000, paymentId: "older")) + XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 2000, paymentId: "retry")) + service.emitChannelFreeRailEvent( + .paymentFailed(paymentId: "older", paymentHash: hash, reason: nil), + paymentCreatedAt: 2000, + railPaymentId: "older" + ) + rail.payments = [older] + await assertRefusedAsDuplicate() + try simulateRelaunch() + await SparkManager.releaseFailedSendHolds { [Self.sparkPayment(hash: hash, status: .failed, id: "older")] } + let kept = service.railAttemptsStore.stringArray(forKey: Self.railAttemptsKey) ?? [] + XCTAssertTrue(kept.contains(hash), "an older attempt's failure released the retry Spark took") + await assertRefusedAsDuplicate() + + // Once Spark lists the retry itself failed, the invoice can be paid again. + await SparkManager.releaseFailedSendHolds { + [Self.sparkPayment(hash: hash, status: .failed, id: "older"), Self.sparkPayment(hash: hash, status: .failed, id: "retry")] + } + rail.payments = [ + older, + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "retry"), + ] + await assertReachesTheNode() + } + + func testATakenRetrySparkNeverListsEndsPastTheInvoicesExpiry() async throws { + let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) + let hash = String(invoice.paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + let earlier = Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier") + rail.payments = [earlier] + rail.balanceSats = 100_000 + rail.sentPaymentId = "retry" + _ = try await service.send(bolt11: Self.invoice) + rail.sentBolt11 = nil + rail.balanceSats = 0 + var expired: [String] = [] + let previousHook = service.railSendHoldExpired + defer { service.railSendHoldExpired = previousHook } + service.railSendHoldExpired = { expired.append($0); return true } + + let expiresAt = invoice.secondsSinceEpoch() + invoice.expiryTimeSeconds() + service.now = { Date(timeIntervalSince1970: TimeInterval(expiresAt)) } + await service.endExpiredRailSendUncertainties() + XCTAssertEqual(expired, [], "a retry Spark took ended at the invoice's expiry") + XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900, paymentId: "earlier")) + + // Spark listing the retry leaves it to its own outcome. + let graceEnds = expiresAt + UInt64(Bitkit.LightningService.unlistedRailSendGraceSeconds) + service.now = { Date(timeIntervalSince1970: TimeInterval(graceEnds)) } + rail.payments = [ + earlier, + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .pending, preimage: nil, id: "retry"), + ] + await service.endExpiredRailSendUncertainties() + XCTAssertEqual(expired, []) + + // Listing only the earlier failure past the grace ends it, and its row is written from that failure. + rail.payments = [earlier] + await service.endExpiredRailSendUncertainties() + XCTAssertEqual(expired, [hash], "a retry Spark never lists stayed pending past its invoice's expiry") + XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900, paymentId: "earlier")) + await service.endExpiredRailSendUncertainties() + XCTAssertEqual(expired, [hash], "an ended hold was written again") + } + func testAFailureWithoutSparkIdsKeepsTheHoldUntilPastTheClockMargin() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared @@ -1016,8 +1107,12 @@ extension ChannelFreeRailTests { XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900)) let expiresAt = invoice.secondsSinceEpoch() + invoice.expiryTimeSeconds() + let graceEnds = expiresAt + UInt64(Bitkit.LightningService.unlistedRailSendGraceSeconds) service.now = { Date(timeIntervalSince1970: TimeInterval(expiresAt)) } await service.endExpiredRailSendUncertainties() + XCTAssertEqual(expired, [], "a hold Spark may still settle ended at the invoice's expiry") + service.now = { Date(timeIntervalSince1970: TimeInterval(graceEnds)) } + await service.endExpiredRailSendUncertainties() XCTAssertEqual(expired, [hash], "the send's activity wasn't written when its hold ended") XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900)) @@ -1052,8 +1147,12 @@ extension ChannelFreeRailTests { service.channelFreeRail = nil let expiresAt = invoice.secondsSinceEpoch() + invoice.expiryTimeSeconds() + let graceEnds = expiresAt + UInt64(Bitkit.LightningService.unlistedRailSendGraceSeconds) service.now = { Date(timeIntervalSince1970: TimeInterval(expiresAt)) } await service.endExpiredRailSendUncertainties() + XCTAssertEqual(expired, [], "a hold Spark may still settle ended at the invoice's expiry") + service.now = { Date(timeIntervalSince1970: TimeInterval(graceEnds)) } + await service.endExpiredRailSendUncertainties() XCTAssertEqual(expired, [hash], "the send stayed pending through the exit") } @@ -2163,6 +2262,8 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { var estimateError: Error? var listError: Error? var sentBolt11: String? + /// The rail's id of the attempt a send returns. + var sentPaymentId: String? var sends = 0 var sentFeeLimitSats: UInt64? var sendGate: (() async -> Void)? @@ -2189,7 +2290,9 @@ 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?, beforeSubmission: @escaping () throws -> Void) async throws + -> (paymentHash: PaymentHash, paymentId: String?) + { if let refusal { throw refusal } @@ -2205,7 +2308,7 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { sentFeeLimitSats = maxFeeSats sentBolt11 = bolt11 sends += 1 - return "ee" + return ("ee", sentPaymentId) } func estimateRoutingFees(bolt11: String, amountSats: UInt64?) async throws -> UInt64 { From ba074c95c2abac4d22bf1beb8b74df3113c788e4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 19:30:49 +0100 Subject: [PATCH 23/64] fix: hold a send in doubt against a failure its list didn't name A send whose call threw is kept in doubt with the list read before it went out as its earlier attempts. A failure that list didn't name was read as the send's own, so an older attempt Spark listed only later could end the hold and mark Activity failed while Spark may still finish the send. Such a failure is now told apart by when Spark created it, as one without an id is: within the clock margin after the send went out it keeps the hold. Verified: the unit suite (the selection in unit-tests.yml) on an iOS simulator --- Bitkit/Services/LightningService.swift | 4 ++- BitkitTests/ChannelFreeRailTests.swift | 45 ++++++++++++++++++++++++-- 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 357026eb60..9ed1dcddbe 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1790,9 +1790,11 @@ class LightningService: NodeLifecycleService { // Known until the latest send settles, also once Spark took it, so its earlier attempts are told apart by id. let taken = takenRailSendIds() let earlier = uncertainRailSendEarlierAttempts() - if let paymentId, taken[hash] != nil || earlier[hash] != nil { + if let paymentId, taken[hash] != nil || earlier[hash]?.contains(paymentId) == true { return Self.isEarlierRailAttempt(id: paymentId, hash: hash, taken: taken, earlier: earlier) } + // A send still in doubt has no id of its own yet, and the list read before it went out can lack an older attempt, + // so a failure that list doesn't name is told apart by when Spark created it. guard uncertainRailSendFailedAt()[hash] != nil else { return false } // A send in doubt saved before its start was recorded can't be told from an earlier attempt, so it stays held // until its invoice expires. diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index ede2cd6332..82a39c87be 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -835,11 +835,13 @@ extension ChannelFreeRailTests { rail.syncedAfter = { ($0 ?? 0) < 1000 } rail.balanceSats = 0 - // The earlier attempt's failure keeps the hold, whatever Spark's clock stamped on it; the retry's own ends it. + // The earlier attempt's failure keeps the hold, whatever Spark's clock stamped on it. A failure the list read before + // the retry doesn't name may be an older attempt it lacked, so it ends the hold only stamped past the clock margin. for createdAt: UInt64 in [900, 995, 1000, 1005] { XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: createdAt, paymentId: "earlier")) - XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: createdAt, paymentId: "retry")) + XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: createdAt, paymentId: "retry")) } + XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 1010, paymentId: "retry")) // Without Spark's id, a failure stamped before the send or within the clock margin after it keeps the hold. XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 995)) XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 1005)) @@ -856,12 +858,18 @@ extension ChannelFreeRailTests { service.emitChannelFreeRailEvent(.paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), paymentCreatedAt: 1000) await assertRefusedAsDuplicate() - // The failure of the retry itself ends the hold, even stamped before it by a clock behind. + // The failure of the retry itself ends the hold, stamped past the clock margin. service.emitChannelFreeRailEvent( .paymentFailed(paymentId: "retry", paymentHash: hash, reason: nil), paymentCreatedAt: 995, railPaymentId: "retry" ) + await assertRefusedAsDuplicate() + service.emitChannelFreeRailEvent( + .paymentFailed(paymentId: "retry", paymentHash: hash, reason: nil), + paymentCreatedAt: 1010, + railPaymentId: "retry" + ) await assertReachesTheNode() } @@ -1057,6 +1065,37 @@ extension ChannelFreeRailTests { XCTAssertEqual(expired, [hash], "an ended hold was written again") } + func testAnOlderAttemptMissingFromTheListBeforeASendInDoubtKeepsItsHold() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + // Spark lists no earlier attempt before the retry goes out, and the send's call throws after submission. + rail.balanceSats = 100_000 + rail.errorAfterSubmission = NSError(domain: "spark", code: 2) + _ = try? await service.send(bolt11: Self.invoice) + rail.errorAfterSubmission = nil + rail.syncedAfter = { ($0 ?? 0) < 1000 } + rail.balanceSats = 0 + + // An older attempt Spark created before the retry shows up failed: the retry stays held. + XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900, paymentId: "older")) + service.emitChannelFreeRailEvent( + .paymentFailed(paymentId: "older", paymentHash: hash, reason: nil), + paymentCreatedAt: 900, + railPaymentId: "older" + ) + await assertRefusedAsDuplicate() + + // The retry's own failure, created after it went out, ends the hold. + XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 1010, paymentId: "retry")) + service.emitChannelFreeRailEvent( + .paymentFailed(paymentId: "retry", paymentHash: hash, reason: nil), + paymentCreatedAt: 1010, + railPaymentId: "retry" + ) + await assertReachesTheNode() + } + func testAFailureWithoutSparkIdsKeepsTheHoldUntilPastTheClockMargin() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared From 3ced5ab95e245e80b0c2241cd7fcd0d0c7cdaec1 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 20:04:53 +0100 Subject: [PATCH 24/64] fix: a send in doubt's own failure ends its hold again Spark dates a payment at its start, so with the clock margin applied to every failure the pre-send list didn't name, a send in doubt's own failure read as an earlier attempt's, and every send whose call threw, a first send included, stayed held until its invoice expired. Such a failure now counts as an earlier attempt's only when Spark created it at least the clock margin before the send went out. Verified: the unit suite (the selection in unit-tests.yml) on an iOS simulator --- Bitkit/Services/LightningService.swift | 9 ++++++-- BitkitTests/ChannelFreeRailTests.swift | 32 ++++++++++---------------- 2 files changed, 19 insertions(+), 22 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 9ed1dcddbe..37700bf218 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1793,9 +1793,14 @@ class LightningService: NodeLifecycleService { if let paymentId, taken[hash] != nil || earlier[hash]?.contains(paymentId) == true { return Self.isEarlierRailAttempt(id: paymentId, hash: hash, taken: taken, earlier: earlier) } - // A send still in doubt has no id of its own yet, and the list read before it went out can lack an older attempt, - // so a failure that list doesn't name is told apart by when Spark created it. guard uncertainRailSendFailedAt()[hash] != nil else { return false } + // A send still in doubt has no id of its own yet, and the list read before it went out can lack an older attempt. + // Spark dates a payment at its start, so a failure that list doesn't name is an earlier attempt's only when created + // clearly before the send; one dated around it is the send's own. + if paymentId != nil, earlier[hash] != nil { + guard let startedAt = uncertainRailSendStartedAt()[hash] else { return true } + return Int64(clamping: createdAt) + Int64(Self.railClockSkewSeconds) <= Int64(startedAt) + } // A send in doubt saved before its start was recorded can't be told from an earlier attempt, so it stays held // until its invoice expires. guard let startedAt = uncertainRailSendStartedAt()[hash] else { return true } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 82a39c87be..9a9dbd54ea 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -835,13 +835,13 @@ extension ChannelFreeRailTests { rail.syncedAfter = { ($0 ?? 0) < 1000 } rail.balanceSats = 0 - // The earlier attempt's failure keeps the hold, whatever Spark's clock stamped on it. A failure the list read before - // the retry doesn't name may be an older attempt it lacked, so it ends the hold only stamped past the clock margin. - for createdAt: UInt64 in [900, 995, 1000, 1005] { + // The earlier attempt's failure keeps the hold, whatever Spark's clock stamped on it; the retry's own ends it. A + // failure the list doesn't name keeps it only when dated clearly before the retry, as an older attempt the list lacked. + for createdAt: UInt64 in [995, 1000, 1005] { XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: createdAt, paymentId: "earlier")) - XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: createdAt, paymentId: "retry")) + XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: createdAt, paymentId: "retry")) } - XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 1010, paymentId: "retry")) + XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 990, paymentId: "older")) // Without Spark's id, a failure stamped before the send or within the clock margin after it keeps the hold. XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 995)) XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 1005)) @@ -858,18 +858,12 @@ extension ChannelFreeRailTests { service.emitChannelFreeRailEvent(.paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), paymentCreatedAt: 1000) await assertRefusedAsDuplicate() - // The failure of the retry itself ends the hold, stamped past the clock margin. + // The failure of the retry itself ends the hold, even stamped before it by a clock behind. service.emitChannelFreeRailEvent( .paymentFailed(paymentId: "retry", paymentHash: hash, reason: nil), paymentCreatedAt: 995, railPaymentId: "retry" ) - await assertRefusedAsDuplicate() - service.emitChannelFreeRailEvent( - .paymentFailed(paymentId: "retry", paymentHash: hash, reason: nil), - paymentCreatedAt: 1010, - railPaymentId: "retry" - ) await assertReachesTheNode() } @@ -1069,7 +1063,7 @@ extension ChannelFreeRailTests { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared service.now = { Date(timeIntervalSince1970: 1000) } - // Spark lists no earlier attempt before the retry goes out, and the send's call throws after submission. + // Spark lists no earlier attempt before the send goes out, and the send's call throws after submission. rail.balanceSats = 100_000 rail.errorAfterSubmission = NSError(domain: "spark", code: 2) _ = try? await service.send(bolt11: Self.invoice) @@ -1077,8 +1071,7 @@ extension ChannelFreeRailTests { rail.syncedAfter = { ($0 ?? 0) < 1000 } rail.balanceSats = 0 - // An older attempt Spark created before the retry shows up failed: the retry stays held. - XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900, paymentId: "older")) + // An older attempt Spark created well before the send shows up failed: the send stays held. service.emitChannelFreeRailEvent( .paymentFailed(paymentId: "older", paymentHash: hash, reason: nil), paymentCreatedAt: 900, @@ -1086,12 +1079,11 @@ extension ChannelFreeRailTests { ) await assertRefusedAsDuplicate() - // The retry's own failure, created after it went out, ends the hold. - XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 1010, paymentId: "retry")) + // The send's own failure, dated at its start, ends the hold. service.emitChannelFreeRailEvent( - .paymentFailed(paymentId: "retry", paymentHash: hash, reason: nil), - paymentCreatedAt: 1010, - railPaymentId: "retry" + .paymentFailed(paymentId: "own", paymentHash: hash, reason: nil), + paymentCreatedAt: 1000, + railPaymentId: "own" ) await assertReachesTheNode() } From 767c9cb98a43cfa2603c425d2b9b4c655950d1ac Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 20:24:31 +0100 Subject: [PATCH 25/64] fix: end an unlisted taken retry only after a full sync - Spark's list proves a taken retry missing only once a sync that started past the grace reached Spark, so a partial sync's list no longer ends a send Spark accepted. - The retry's own stored Activity row is failed, keeping its amount, fee and time, instead of being written from an earlier attempt's failure; a write that fails is retried on the next sync. Verified: the unit suite (the selection in unit-tests.yml) on an iOS simulator --- Bitkit/Managers/SparkManager.swift | 3 ++ Bitkit/Services/LightningService.swift | 51 +++++++++++++++++++++----- BitkitTests/ChannelFreeRailTests.swift | 39 +++++++++++++++----- 3 files changed, 73 insertions(+), 20 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 0e34af820e..b5400812f5 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -421,6 +421,9 @@ final class SparkManager: ChannelFreeLightningRail { // still go to LDK, even when that refresh or the activity sync fails. An emergency exit keeps it out. LightningService.shared.channelFreePaymentHistory = self LightningService.shared.railSendHoldExpired = { [weak self] hash in await self?.recordExpiredHold(paymentHash: hash) ?? false } + LightningService.shared.railTakenSendUnlisted = { hash in + await (try? CoreService.shared.activity.failPendingLightningSend(id: hash)) != nil + } if !isExiting { LightningService.shared.channelFreeRail = self } diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 37700bf218..97197171c9 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -181,6 +181,9 @@ class LightningService: NodeLifecycleService { /// Writes the activity of a rail send in doubt once its hold ends at its invoice's expiry, as the failure of an /// earlier attempt that came meanwhile left the row pending. Returns whether the activity was saved. var railSendHoldExpired: ((String) async -> Bool)? + /// Fails the stored Activity row of a send Spark took but never listed, once its hold ends past its invoice's expiry, + /// keeping the row's own amount and fee. Returns whether the row was saved. + var railTakenSendUnlisted: ((String) async -> Bool)? var onchainTransactionConfirmed: (@Sendable (String) async -> Void)? var onchainTransactionReceived: (@Sendable (String) async -> Void)? typealias OnchainActivityCompletion = @MainActor () async -> Void @@ -1252,6 +1255,8 @@ class LightningService: NodeLifecycleService { private static let uncertainRailSendsEarlierAttemptsKey = "channelFreeRailUncertainSendEarlierAttempts" /// The rail's id of each send Spark took, by hash, until it settles: any other attempt's failure is an earlier one's. private static let takenRailSendsKey = "channelFreeRailTakenSendIds" + /// Hashes of taken sends Spark never listed whose hold ended before their row was failed, retried on each rail sync. + private static let unlistedTakenRailSendsUnfailedKey = "channelFreeRailUnlistedTakenSendsUnfailed" /// Hashes whose hold ended at their invoice's expiry before their activity was saved, retried on each rail sync. private static let expiredRailHoldsUnrecordedKey = "channelFreeRailExpiredHoldsUnrecorded" /// A listing drops the hashes it shows failed only, or paid once the invoice has expired, so the other rail can't @@ -1448,6 +1453,7 @@ class LightningService: NodeLifecycleService { railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsStartedKey) railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsEarlierAttemptsKey) railAttemptsStore.removeObject(forKey: Self.takenRailSendsKey) + railAttemptsStore.removeObject(forKey: Self.unlistedTakenRailSendsUnfailedKey) railAttemptsStore.removeObject(forKey: Self.expiredRailHoldsUnrecordedKey) railAttemptsStore.removeObject(forKey: Self.railAttemptsKey) railAttemptsStore.removeObject(forKey: Self.expiriesKey(Self.railAttemptsKey)) @@ -1916,9 +1922,14 @@ class LightningService: NodeLifecycleService { static let unlistedRailSendGraceSeconds = 10 * 60 /// Ends the holds of sends Spark took whose own outcome it still doesn't list, only an earlier attempt's failure or - /// nothing, once their invoice expired `unlistedRailSendGraceSeconds` ago, and writes their Activity row from that. - /// A send Spark lists is left to its own outcome. + /// nothing, once their invoice expired `unlistedRailSendGraceSeconds` ago and a sync since reached Spark, and fails + /// their stored Activity row, as an earlier attempt's row would bring its own amount and fee. A send Spark lists is + /// left to its own outcome. private func endExpiredUnlistedTakenRailSends() async { + let unfailed = eventCallbackLock.withLock { railAttemptsStore.stringArray(forKey: Self.unlistedTakenRailSendsUnfailedKey) ?? [] } + for hash in unfailed { + await failUnlistedTakenRailSend(hash) + } let nowSeconds = Int(now().timeIntervalSince1970) let (expired, taken, earlier) = eventCallbackLock.withLock { let uncertain = uncertainRailSendFailedAt() @@ -1926,12 +1937,24 @@ class LightningService: NodeLifecycleService { let earlier = uncertainRailSendEarlierAttempts() let expiries = attemptExpiries(key: Self.railAttemptsKey) let held = Set(taken.keys).union(earlier.keys).subtracting(uncertain.keys) - let expired = held.filter { hash in expiries[hash].map { nowSeconds - Self.unlistedRailSendGraceSeconds >= $0 } ?? false } + var expired: [String: Int] = [:] + for hash in held { + if let expiresAt = expiries[hash], nowSeconds - Self.unlistedRailSendGraceSeconds >= expiresAt { + expired[hash] = expiresAt + } + } return (expired, taken, earlier) } - guard !expired.isEmpty, let rail = channelFreeRail ?? channelFreePaymentHistory, - let payments = try? await rail.lightningPayments() else { return } - for hash in expired { + guard !expired.isEmpty, let rail = channelFreeRail ?? channelFreePaymentHistory else { return } + // Absence proves nothing until a sync that started past the grace reached Spark. + var synced: [String] = [] + for (hash, expiresAt) in expired { + if await rail.hasSynced(after: UInt64(max(0, expiresAt + Self.unlistedRailSendGraceSeconds))) { + synced.append(hash) + } + } + guard !synced.isEmpty, let payments = try? await rail.lightningPayments() else { return } + for hash in synced { let isListed = payments.contains { payment in payment.direction == .outbound && payment.paymentHash.lowercased() == hash && !(payment.id.map { Self.isEarlierRailAttempt(id: $0, hash: hash, taken: taken, earlier: earlier) } ?? false) @@ -1943,11 +1966,19 @@ class LightningService: NodeLifecycleService { uncertainRailSendFailedAt()[hash] == nil else { return } clearRailSendUncertainty(hash: hash) removeAttempt(paymentHash: hash, key: Self.railAttemptsKey) - var unrecorded = Set(railAttemptsStore.stringArray(forKey: Self.expiredRailHoldsUnrecordedKey) ?? []) - unrecorded.insert(hash) - railAttemptsStore.set(Array(unrecorded), forKey: Self.expiredRailHoldsUnrecordedKey) + var unfailed = Set(railAttemptsStore.stringArray(forKey: Self.unlistedTakenRailSendsUnfailedKey) ?? []) + unfailed.insert(hash) + railAttemptsStore.set(Array(unfailed), forKey: Self.unlistedTakenRailSendsUnfailedKey) } - await recordExpiredRailHold(hash) + await failUnlistedTakenRailSend(hash) + } + } + + private func failUnlistedTakenRailSend(_ hash: String) async { + guard let fail = railTakenSendUnlisted, await fail(hash) else { return } + eventCallbackLock.withLock { + let unfailed = railAttemptsStore.stringArray(forKey: Self.unlistedTakenRailSendsUnfailedKey) ?? [] + railAttemptsStore.set(unfailed.filter { $0 != hash }, forKey: Self.unlistedTakenRailSendsUnfailedKey) } } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 9a9dbd54ea..8235ff9edb 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1029,34 +1029,53 @@ extension ChannelFreeRailTests { _ = try await service.send(bolt11: Self.invoice) rail.sentBolt11 = nil rail.balanceSats = 0 - var expired: [String] = [] + var replayed: [String] = [] + var failed: [String] = [] + var saves = false let previousHook = service.railSendHoldExpired - defer { service.railSendHoldExpired = previousHook } - service.railSendHoldExpired = { expired.append($0); return true } + let previousUnlisted = service.railTakenSendUnlisted + defer { + service.railSendHoldExpired = previousHook + service.railTakenSendUnlisted = previousUnlisted + } + service.railSendHoldExpired = { replayed.append($0); return true } + service.railTakenSendUnlisted = { failed.append($0); return saves } let expiresAt = invoice.secondsSinceEpoch() + invoice.expiryTimeSeconds() + let graceEnds = expiresAt + UInt64(Bitkit.LightningService.unlistedRailSendGraceSeconds) service.now = { Date(timeIntervalSince1970: TimeInterval(expiresAt)) } await service.endExpiredRailSendUncertainties() - XCTAssertEqual(expired, [], "a retry Spark took ended at the invoice's expiry") + XCTAssertEqual(failed, [], "a retry Spark took ended at the invoice's expiry") XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900, paymentId: "earlier")) - // Spark listing the retry leaves it to its own outcome. - let graceEnds = expiresAt + UInt64(Bitkit.LightningService.unlistedRailSendGraceSeconds) + // Past the grace, absence proves nothing until a sync that started since reached Spark. service.now = { Date(timeIntervalSince1970: TimeInterval(graceEnds)) } + rail.syncedAfter = { ($0 ?? 0) < graceEnds } + await service.endExpiredRailSendUncertainties() + XCTAssertEqual(failed, [], "a partial sync's list ended a retry Spark took") + + // Spark listing the retry leaves it to its own outcome. + rail.syncedAfter = { _ in true } rail.payments = [ earlier, Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .pending, preimage: nil, id: "retry"), ] await service.endExpiredRailSendUncertainties() - XCTAssertEqual(expired, []) + XCTAssertEqual(failed, []) - // Listing only the earlier failure past the grace ends it, and its row is written from that failure. + // Listing only the earlier failure ends it and fails the retry's own row, never replaying the earlier attempt. rail.payments = [earlier] await service.endExpiredRailSendUncertainties() - XCTAssertEqual(expired, [hash], "a retry Spark never lists stayed pending past its invoice's expiry") + XCTAssertEqual(failed, [hash], "a retry Spark never lists stayed pending past its invoice's expiry") XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900, paymentId: "earlier")) + + // The write failed, so the next sync tries it again, until it is saved. + saves = true + await service.endExpiredRailSendUncertainties() + XCTAssertEqual(failed, [hash, hash], "a row that failed to save wasn't retried") await service.endExpiredRailSendUncertainties() - XCTAssertEqual(expired, [hash], "an ended hold was written again") + XCTAssertEqual(failed, [hash, hash], "a saved row was failed again") + XCTAssertEqual(replayed, [], "the earlier attempt's row replaced the retry's") } func testAnOlderAttemptMissingFromTheListBeforeASendInDoubtKeepsItsHold() async throws { From 2500d3119659a19c51f2525eb8c195c37d8824bf Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 21:16:47 +0100 Subject: [PATCH 26/64] fix: keep a held spark send's row and hold until reconciled - A send Spark took stays held, with its expiry, until the expiry sweep ends it, so a listing for another invoice's send past the grace no longer drops it before the sweep has the sync it needs. - At expiry a held send's row is written only from a live Spark send; with failures alone listed, one may be an earlier attempt's, so the stored row is failed in place. - A failed Spark send's row keeps its details against another attempt's failure, so a retry at another amount never shows the first attempt's amount, fee and time. Verified: the unit suite (the selection in unit-tests.yml) on an iOS simulator --- Bitkit/Managers/SparkManager.swift | 8 +++++--- Bitkit/Services/CoreService.swift | 18 ++++++++++++++---- Bitkit/Services/LightningService.swift | 8 ++++++-- BitkitTests/ChannelFreeRailTests.swift | 26 ++++++++++++++++++++++---- 4 files changed, 47 insertions(+), 13 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index b5400812f5..94d5b42844 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -1876,9 +1876,11 @@ final class SparkManager: ChannelFreeLightningRail { guard payment.paymentType == .send, case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details else { return false } return htlcDetails.paymentHash.caseInsensitiveCompare(paymentHash) == .orderedSame } - // A live send wins over failed ones, then the newest, as a retry can share its earlier attempt's timestamp. - if let latest = sends.max(by: { ($0.status == .failed ? 0 : 1, $0.timestamp) < ($1.status == .failed ? 0 : 1, $1.timestamp) }) { - return await record(latest) + // A live send is the one that pays the invoice, the newest when a retry shares its earlier attempt's timestamp. A + // listed failure may be an earlier attempt's, whose amount and fee aren't the held send's, so without a live send + // the stored row is failed in place. + if let live = sends.filter({ $0.status != .failed }).max(by: { $0.timestamp < $1.timestamp }) { + return await record(live) } return await failStoredSend(paymentHash) } diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 1a63374ded..3964fa31ca 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -961,12 +961,21 @@ class ActivityService { /// so a send recorded after the app was killed mid-payment still names its contact. nonisolated(unsafe) static var sentPaymentContacts = SentPaymentContacts(defaults: .standard) - /// Whether a Lightning activity keeps its status against an update: a settled payment stays settled, and a failure - /// from the rail that didn't carry the latest attempt is stale. - static func keepsLightningStatus(existing: BitkitCore.PaymentState, update: BitkitCore.PaymentState, isStaleRailFailure: Bool) -> Bool { + /// Whether a Lightning activity keeps its status against an update: a settled payment stays settled, a failure from + /// the rail that didn't carry the latest attempt is stale, and a failed Spark send keeps its row, as Spark lists one + /// failure per attempt and an earlier one's carries that attempt's amount and fee. + static func keepsLightningStatus( + existing: BitkitCore.PaymentState, + update: BitkitCore.PaymentState, + isStaleRailFailure: Bool, + isChannelFreeSend: Bool = false + ) -> Bool { if existing == .succeeded, update != .succeeded { return true } + if isChannelFreeSend, existing == .failed, update == .failed { + return true + } return update == .failed && existing != .failed && isStaleRailFailure } @@ -1010,7 +1019,8 @@ class ActivityService { paymentHash: payment.id, createdAt: paymentTimestamp, paymentId: railPaymentId - )) + )), + isChannelFreeSend: rail == .channelFree && payment.direction == .outbound ) { return diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 97197171c9..cf0c4cfc20 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1830,13 +1830,17 @@ class LightningService: NodeLifecycleService { /// Spark's kept sends whose invoice is unexpired, or expired less than `unlistedRailSendGraceSeconds` ago. A sync can /// still resume one Spark committed but lists no row for, also after a relaunch, so it is pending until then, the rule - /// `railSyncedSinceUncertainSend` holds. + /// `railSyncedSinceUncertainSend` holds. A send Spark took stays in until the expiry sweep ends it, so no listing + /// drops its hash and expiry before the sweep has the sync it needs. private func unexpiredRailAttempts() -> Set { let seconds = Int(now().timeIntervalSince1970) return eventCallbackLock.withLock { let expiries = attemptExpiries(key: Self.railAttemptsKey) let hashes = railAttemptsStore.stringArray(forKey: Self.railAttemptsKey) ?? [] - return Set(hashes.filter { hash in expiries[hash].map { $0 > seconds - Self.unlistedRailSendGraceSeconds } ?? false }) + let awaitingSweep = Set(takenRailSendIds().keys).union(uncertainRailSendEarlierAttempts().keys) + return Set(hashes.filter { hash in + expiries[hash].map { $0 > seconds - Self.unlistedRailSendGraceSeconds || awaitingSweep.contains(hash) } ?? false + }) } } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 8235ff9edb..f3bc0d3a80 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -229,6 +229,8 @@ extension ChannelFreeRailTests { service.nodePayments = { [] } _ = try await service.send(bolt11: Self.invoice) rail.sentBolt11 = nil + // Spark's next sync ends the expired send it took but never listed. + await service.endExpiredRailSendUncertainties() service.nodePayments = { nil } _ = try await service.send(bolt11: Self.invoice) @@ -276,6 +278,8 @@ extension ChannelFreeRailTests { service.nodePayments = { [failed] } _ = try await service.send(bolt11: Self.invoice) rail.sentBolt11 = nil + // Spark's next sync ends the expired send it took but never listed. + await service.endExpiredRailSendUncertainties() service.nodePayments = { nil } _ = try await service.send(bolt11: Self.invoice) @@ -1048,11 +1052,14 @@ extension ChannelFreeRailTests { XCTAssertEqual(failed, [], "a retry Spark took ended at the invoice's expiry") XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900, paymentId: "earlier")) - // Past the grace, absence proves nothing until a sync that started since reached Spark. + // Past the grace, absence proves nothing until a sync that started since reached Spark, and a listing meanwhile, for + // another invoice's send, keeps the retry held, so the sweep still finds it. service.now = { Date(timeIntervalSince1970: TimeInterval(graceEnds)) } rail.syncedAfter = { ($0 ?? 0) < graceEnds } await service.endExpiredRailSendUncertainties() XCTAssertEqual(failed, [], "a partial sync's list ended a retry Spark took") + _ = try? await service.send(bolt11: "lnbcrt1rail", sats: 1000) + await assertRefusedAsDuplicate() // Spark listing the retry leaves it to its own outcome. rail.syncedAfter = { _ in true } @@ -1206,13 +1213,13 @@ extension ChannelFreeRailTests { XCTAssertEqual(expired, [hash], "the send stayed pending through the exit") } - func testAnExpiredHoldWritesSparksLatestSendOrFailsTheStoredOne() async { + func testAnExpiredHoldWritesSparksLiveSendOrFailsTheStoredOne() async { let hash = "ab" var recorded: [String] = [] var failed: [String] = [] let payments = [ Self.sparkPayment(hash: hash, status: .failed, id: "earlier", timestamp: 1), - Self.sparkPayment(hash: hash, status: .failed, id: "retry", timestamp: 5), + Self.sparkPayment(hash: hash, status: .completed, id: "retry", timestamp: 5), Self.sparkPayment(hash: "cd", status: .completed, id: "other", timestamp: 9), ] _ = await SparkManager.recordExpiredHold( @@ -1222,12 +1229,20 @@ extension ChannelFreeRailTests { XCTAssertEqual(recorded, ["retry"]) XCTAssertEqual(failed, []) + // Only failures listed: one may be an earlier attempt's, with its own amount and fee, so the stored row fails. + _ = await SparkManager.recordExpiredHold( + paymentHash: hash, payments: [Self.sparkPayment(hash: hash, status: .failed, id: "earlier", timestamp: 1)], + record: { recorded.append($0.id); return true }, failStoredSend: { failed.append($0); return true } + ) + XCTAssertEqual(recorded, ["retry"], "an earlier attempt's failure replaced the held send's row") + XCTAssertEqual(failed, [hash]) + _ = await SparkManager.recordExpiredHold( paymentHash: "ef", payments: payments, record: { recorded.append($0.id); return true }, failStoredSend: { failed.append($0); return true } ) XCTAssertEqual(recorded, ["retry"]) - XCTAssertEqual(failed, ["ef"], "a send Spark lists none of stayed pending") + XCTAssertEqual(failed, [hash, "ef"], "a send Spark lists none of stayed pending") } func testAnExpiredHoldWritesALiveRetryOverAFailureWithTheSameTimestamp() async { @@ -2228,6 +2243,9 @@ extension ChannelFreeRailTests { XCTAssertTrue(ActivityService.keepsLightningStatus(existing: .succeeded, update: .failed, isStaleRailFailure: false)) XCTAssertTrue(ActivityService.keepsLightningStatus(existing: .pending, update: .failed, isStaleRailFailure: true)) XCTAssertFalse(ActivityService.keepsLightningStatus(existing: .pending, update: .failed, isStaleRailFailure: false)) + // A failed Spark send keeps its row against another attempt's failure, which carries that attempt's amount. + XCTAssertTrue(ActivityService.keepsLightningStatus(existing: .failed, update: .failed, isStaleRailFailure: false, isChannelFreeSend: true)) + XCTAssertFalse(ActivityService.keepsLightningStatus(existing: .failed, update: .failed, isStaleRailFailure: false)) XCTAssertFalse(ActivityService.keepsLightningStatus(existing: .failed, update: .succeeded, isStaleRailFailure: false)) XCTAssertFalse(ActivityService.keepsLightningStatus(existing: .pending, update: .succeeded, isStaleRailFailure: true)) } From 5b35eb69129844a7f940077b7a873ddb18e31bba Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 22:01:03 +0100 Subject: [PATCH 27/64] fix: a failed spark row takes its own attempt's updates The failed-row guard now keeps a failed Spark row only against a failure dated before the row's attempt, so the row still takes its own attempt's fee and amount corrections and a later attempt's failure. Verified: full unit suite on the iOS simulator --- Bitkit/Services/CoreService.swift | 12 +++++--- BitkitTests/ChannelFreeRailTests.swift | 7 +++-- BitkitTests/SparkRelaunchActivityTests.swift | 32 ++++++++++++++++++++ 3 files changed, 44 insertions(+), 7 deletions(-) diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 3964fa31ca..44f800ebb0 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -962,18 +962,19 @@ class ActivityService { nonisolated(unsafe) static var sentPaymentContacts = SentPaymentContacts(defaults: .standard) /// Whether a Lightning activity keeps its status against an update: a settled payment stays settled, a failure from - /// the rail that didn't carry the latest attempt is stale, and a failed Spark send keeps its row, as Spark lists one - /// failure per attempt and an earlier one's carries that attempt's amount and fee. + /// the rail that didn't carry the latest attempt is stale, and a failed Spark send keeps its row against the failure + /// of an older attempt, as Spark lists one failure per attempt, each with its own amount and fee. The row's own + /// attempt and later ones still update it. static func keepsLightningStatus( existing: BitkitCore.PaymentState, update: BitkitCore.PaymentState, isStaleRailFailure: Bool, - isChannelFreeSend: Bool = false + isOlderChannelFreeAttempt: Bool = false ) -> Bool { if existing == .succeeded, update != .succeeded { return true } - if isChannelFreeSend, existing == .failed, update == .failed { + if isOlderChannelFreeAttempt, existing == .failed, update == .failed { return true } return update == .failed && existing != .failed && isStaleRailFailure @@ -1020,7 +1021,8 @@ class ActivityService { createdAt: paymentTimestamp, paymentId: railPaymentId )), - isChannelFreeSend: rail == .channelFree && payment.direction == .outbound + // Spark dates an attempt at its start, so an older one's failure is dated before the row's attempt. + isOlderChannelFreeAttempt: rail == .channelFree && payment.direction == .outbound && paymentTimestamp < existing.timestamp ) { return diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index f3bc0d3a80..aa8e31df61 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -2243,8 +2243,11 @@ extension ChannelFreeRailTests { XCTAssertTrue(ActivityService.keepsLightningStatus(existing: .succeeded, update: .failed, isStaleRailFailure: false)) XCTAssertTrue(ActivityService.keepsLightningStatus(existing: .pending, update: .failed, isStaleRailFailure: true)) XCTAssertFalse(ActivityService.keepsLightningStatus(existing: .pending, update: .failed, isStaleRailFailure: false)) - // A failed Spark send keeps its row against another attempt's failure, which carries that attempt's amount. - XCTAssertTrue(ActivityService.keepsLightningStatus(existing: .failed, update: .failed, isStaleRailFailure: false, isChannelFreeSend: true)) + // A failed Spark send keeps its row against an older attempt's failure, which carries that attempt's amount, and + // takes its own attempt's or a later one's. + XCTAssertTrue(ActivityService.keepsLightningStatus( + existing: .failed, update: .failed, isStaleRailFailure: false, isOlderChannelFreeAttempt: true + )) XCTAssertFalse(ActivityService.keepsLightningStatus(existing: .failed, update: .failed, isStaleRailFailure: false)) XCTAssertFalse(ActivityService.keepsLightningStatus(existing: .failed, update: .succeeded, isStaleRailFailure: false)) XCTAssertFalse(ActivityService.keepsLightningStatus(existing: .pending, update: .succeeded, isStaleRailFailure: true)) diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index 15bab32b61..1068bd8b1b 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -97,4 +97,36 @@ final class SparkRelaunchActivityTests: XCTestCase { guard case let .lightning(lightning)? = activity else { return XCTFail("The send wasn't recorded") } XCTAssertEqual(lightning.contact, "pk:contact") } + + func testAFailedSparkRowKeepsItsDetailsAgainstAnOlderAttemptButTakesItsOwnAndLaterOnes() async throws { + let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "e7", count: 16) + func failed(sats: UInt64, feeSats: UInt64, at timestamp: UInt64) -> PaymentDetails { + PaymentDetails( + id: hash, + kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), + amountMsat: sats * 1000, feePaidMsat: feeSats * 1000, direction: .outbound, status: .failed, latestUpdateTimestamp: timestamp + ) + } + func row() async throws -> LightningActivity? { + guard case let .lightning(lightning)? = try await CoreService.shared.activity.getActivity(id: hash) else { return nil } + return lightning + } + // An amountless invoice's retry, at another amount, failed and was recorded. + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 0, at: 200)) + + // A replay of the first attempt's failure leaves the retry's details. + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 300, feeSats: 0, at: 100)) + var current = try await row() + XCTAssertEqual(current?.value, 500, "an older attempt's failure replaced the retry's amount") + + // The retry's own fee correction still lands. + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 3, at: 200)) + current = try await row() + XCTAssertEqual(current?.fee, 3) + + // A later attempt's failure takes the row. + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 700, feeSats: 0, at: 300)) + current = try await row() + XCTAssertEqual(current?.value, 700) + } } From 4b79febdde505053694338a22a429d7585441c0e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 22:38:47 +0100 Subject: [PATCH 28/64] fix: a failed spark row keeps its attempt in a same-second tie Each channel-free send row remembers the Spark id of the attempt that last wrote it. Another attempt's failure dated the same second no longer replaces the row's amount and fee, while the row's own fee correction and a later attempt still update it. Verified: full unit suite on the iOS simulator --- Bitkit/Services/CoreService.swift | 39 +++++++++++++++++++- BitkitTests/SparkRelaunchActivityTests.swift | 34 +++++++++++++++++ 2 files changed, 71 insertions(+), 2 deletions(-) diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 44f800ebb0..e4c341a004 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -961,6 +961,9 @@ class ActivityService { /// so a send recorded after the app was killed mid-payment still names its contact. nonisolated(unsafe) static var sentPaymentContacts = SentPaymentContacts(defaults: .standard) + /// The Spark id of the attempt each channel-free send row was last written from, by payment hash. + nonisolated(unsafe) static var channelFreeRowAttempts = ChannelFreeRowAttempts(defaults: .standard) + /// Whether a Lightning activity keeps its status against an update: a settled payment stays settled, a failure from /// the rail that didn't carry the latest attempt is stale, and a failed Spark send keeps its row against the failure /// of an older attempt, as Spark lists one failure per attempt, each with its own amount and fee. The row's own @@ -1021,8 +1024,13 @@ class ActivityService { createdAt: paymentTimestamp, paymentId: railPaymentId )), - // Spark dates an attempt at its start, so an older one's failure is dated before the row's attempt. - isOlderChannelFreeAttempt: rail == .channelFree && payment.direction == .outbound && paymentTimestamp < existing.timestamp + // Spark dates an attempt at its start, so an older one's failure is dated before the row's attempt, or + // in the same second when the retry started at once; then the row's own Spark id tells them apart. + isOlderChannelFreeAttempt: rail == .channelFree && payment.direction == .outbound + && (paymentTimestamp < existing.timestamp || paymentTimestamp == existing.timestamp && Self.isOtherRowAttempt( + railPaymentId, + rowAttemptId: Self.channelFreeRowAttempts.attemptId(forPaymentHash: payment.id) + )) ) { return @@ -1095,6 +1103,14 @@ class ActivityService { if payment.direction == .outbound, ln.contact != nil, payment.status != .pending { Self.sentPaymentContacts.forget(paymentHash: payment.id) } + if rail == .channelFree, payment.direction == .outbound, let railPaymentId { + Self.channelFreeRowAttempts.remember(railPaymentId, forPaymentHash: payment.id) + } + } + + static func isOtherRowAttempt(_ railPaymentId: String?, rowAttemptId: String?) -> Bool { + guard let railPaymentId, let rowAttemptId else { return false } + return railPaymentId != rowAttemptId } /// A succeeded Spark receive proves the move's LDK send settled, so the send's row becomes succeeded and keeps its amount and fee. @@ -2855,3 +2871,22 @@ struct SentPaymentContacts: @unchecked Sendable { } } } + +struct ChannelFreeRowAttempts: @unchecked Sendable { + private static let key = "channelFreeRowAttemptIds" + private static let lock = NSLock() + let defaults: UserDefaults + + func remember(_ attemptId: String, forPaymentHash paymentHash: String) { + Self.lock.withLock { + var attempts = defaults.dictionary(forKey: Self.key) as? [String: String] ?? [:] + guard attempts[paymentHash.lowercased()] != attemptId else { return } + attempts[paymentHash.lowercased()] = attemptId + defaults.set(attempts, forKey: Self.key) + } + } + + func attemptId(forPaymentHash paymentHash: String) -> String? { + (defaults.dictionary(forKey: Self.key) as? [String: String])?[paymentHash.lowercased()] + } +} diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index 1068bd8b1b..1bcd1cf838 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -129,4 +129,38 @@ final class SparkRelaunchActivityTests: XCTestCase { current = try await row() XCTAssertEqual(current?.value, 700) } + + func testAFailedSparkRowKeepsItsAttemptAgainstAnotherAttemptOfTheSameSecond() async throws { + let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "e8", count: 16) + func failed(sats: UInt64, feeSats: UInt64, at timestamp: UInt64) -> PaymentDetails { + PaymentDetails( + id: hash, + kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), + amountMsat: sats * 1000, feePaidMsat: feeSats * 1000, direction: .outbound, status: .failed, latestUpdateTimestamp: timestamp + ) + } + func row() async throws -> LightningActivity? { + guard case let .lightning(lightning)? = try await CoreService.shared.activity.getActivity(id: hash) else { return nil } + return lightning + } + // A retry started in the same second as the first attempt, at another amount, failed and was recorded. + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 0, at: 200), railPaymentId: "retry") + + // A replay of the first attempt's failure, dated the same second, leaves the retry's details. + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 300, feeSats: 1, at: 200), railPaymentId: "first") + var current = try await row() + XCTAssertEqual(current?.value, 500, "another attempt of the same second replaced the retry's amount") + XCTAssertEqual(current?.fee, 0, "another attempt of the same second replaced the retry's fee") + + // The retry's own fee correction still lands. + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 3, at: 200), railPaymentId: "retry") + current = try await row() + XCTAssertEqual(current?.fee, 3) + + // A later attempt's failure takes the row, and then owns it. + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 700, feeSats: 0, at: 300), railPaymentId: "third") + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 3, at: 300), railPaymentId: "retry") + current = try await row() + XCTAssertEqual(current?.value, 700) + } } From a19bd85b1bdc8cc7ea62e5d58fc3a9e6ef7c3f57 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 22:49:52 +0100 Subject: [PATCH 29/64] fix: a held spark retry's own failure always takes its row The same-second tie rule no longer keeps a failed row against the failure of the taken retry that still holds the invoice, and the row writers are kept for the latest 100 invoices, as on Android. Verified: full unit suite on the iOS simulator --- Bitkit/Services/CoreService.swift | 19 +++++++++++++------ Bitkit/Services/LightningService.swift | 5 +++++ BitkitTests/SparkRelaunchActivityTests.swift | 15 +++++++++++++++ 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index e4c341a004..3f77c33ffb 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1025,8 +1025,10 @@ class ActivityService { paymentId: railPaymentId )), // Spark dates an attempt at its start, so an older one's failure is dated before the row's attempt, or - // in the same second when the retry started at once; then the row's own Spark id tells them apart. + // in the same second when the retry started at once; then the row's own Spark id tells them apart. The + // held attempt's own failure always writes. isOlderChannelFreeAttempt: rail == .channelFree && payment.direction == .outbound + && (railPaymentId == nil || railPaymentId != LightningService.shared.heldRailSendId(paymentHash: payment.id)) && (paymentTimestamp < existing.timestamp || paymentTimestamp == existing.timestamp && Self.isOtherRowAttempt( railPaymentId, rowAttemptId: Self.channelFreeRowAttempts.attemptId(forPaymentHash: payment.id) @@ -2872,21 +2874,26 @@ struct SentPaymentContacts: @unchecked Sendable { } } +/// Kept as `[hash, id]` pairs, oldest first, for the latest `limit` hashes. struct ChannelFreeRowAttempts: @unchecked Sendable { private static let key = "channelFreeRowAttemptIds" private static let lock = NSLock() + static let limit = 100 let defaults: UserDefaults func remember(_ attemptId: String, forPaymentHash paymentHash: String) { + let hash = paymentHash.lowercased() Self.lock.withLock { - var attempts = defaults.dictionary(forKey: Self.key) as? [String: String] ?? [:] - guard attempts[paymentHash.lowercased()] != attemptId else { return } - attempts[paymentHash.lowercased()] = attemptId - defaults.set(attempts, forKey: Self.key) + var pairs = defaults.array(forKey: Self.key) as? [[String]] ?? [] + guard pairs.last(where: { $0.first == hash })?.last != attemptId else { return } + pairs.removeAll { $0.first == hash } + pairs.append([hash, attemptId]) + defaults.set(Array(pairs.suffix(Self.limit)), forKey: Self.key) } } func attemptId(forPaymentHash paymentHash: String) -> String? { - (defaults.dictionary(forKey: Self.key) as? [String: String])?[paymentHash.lowercased()] + let hash = paymentHash.lowercased() + return (defaults.array(forKey: Self.key) as? [[String]])?.last { $0.count == 2 && $0[0] == hash }?[1] } } diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index cf0c4cfc20..9ba3392185 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1785,6 +1785,11 @@ class LightningService: NodeLifecycleService { /// finish: the rail's attempt `paymentId` is one listed before the send went out. Without both ids, a payment Spark /// created before the send or within `railClockSkewSeconds` after it (Spark's clock and this phone's may differ) /// may be earlier, so it keeps the hold too. + /// Spark's id of the taken send that still holds the invoice of `paymentHash`, if any. + func heldRailSendId(paymentHash: String) -> String? { + eventCallbackLock.withLock { takenRailSendIds()[paymentHash.lowercased()] } + } + func isEarlierThanUncertainRailSend(paymentHash: String, createdAt: UInt64, paymentId: String? = nil) -> Bool { eventCallbackLock.withLock { isEarlierThanUncertainRailSendLocked(hash: paymentHash.lowercased(), createdAt: createdAt, paymentId: paymentId) diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index 1bcd1cf838..79ce8c52aa 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -163,4 +163,19 @@ final class SparkRelaunchActivityTests: XCTestCase { current = try await row() XCTAssertEqual(current?.value, 700) } + + func testChannelFreeRowAttemptsKeepTheLatestRowWritersUpToTheLimit() throws { + let suite = "ChannelFreeRowAttemptsTests-\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let attempts = ChannelFreeRowAttempts(defaults: defaults) + for index in 0 ... ChannelFreeRowAttempts.limit { + attempts.remember("id\(index)", forPaymentHash: "hash\(index)") + } + attempts.remember("newer", forPaymentHash: "HASH1") + + XCTAssertNil(attempts.attemptId(forPaymentHash: "hash0")) + XCTAssertEqual(attempts.attemptId(forPaymentHash: "hash1"), "newer") + XCTAssertEqual(attempts.attemptId(forPaymentHash: "hash\(ChannelFreeRowAttempts.limit)"), "id\(ChannelFreeRowAttempts.limit)") + } } From 059c82f3cfddaa2c76d3666a178d19acb9ccf3d7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 19 Nov 2026 23:38:07 +0100 Subject: [PATCH 30/64] fix: settle a spark send in doubt only after a post-grace sync A send in doubt is failed for its absence only once a sync that started past its invoice's expiry and grace reached Spark. A retry's failure in the same second as the attempt that wrote its failed row now takes the row when the retry lists that attempt as earlier. Verified: full unit suite on the iOS simulator --- Bitkit/Services/CoreService.swift | 12 ++++++++---- Bitkit/Services/LightningService.swift | 18 ++++++++++-------- BitkitTests/ChannelFreeRailTests.swift | 16 ++++++++++++---- BitkitTests/SparkRelaunchActivityTests.swift | 14 ++++++++++++++ 4 files changed, 44 insertions(+), 16 deletions(-) diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 3f77c33ffb..edae6a1366 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1031,7 +1031,8 @@ class ActivityService { && (railPaymentId == nil || railPaymentId != LightningService.shared.heldRailSendId(paymentHash: payment.id)) && (paymentTimestamp < existing.timestamp || paymentTimestamp == existing.timestamp && Self.isOtherRowAttempt( railPaymentId, - rowAttemptId: Self.channelFreeRowAttempts.attemptId(forPaymentHash: payment.id) + rowAttemptId: Self.channelFreeRowAttempts.attemptId(forPaymentHash: payment.id), + earlierAttemptIds: LightningService.shared.railSendEarlierAttemptIds[payment.id.lowercased()] )) ) { @@ -1110,9 +1111,12 @@ class ActivityService { } } - static func isOtherRowAttempt(_ railPaymentId: String?, rowAttemptId: String?) -> Bool { - guard let railPaymentId, let rowAttemptId else { return false } - return railPaymentId != rowAttemptId + /// Whether `railPaymentId` is another attempt than the row's, and not the send that went out after it: the send in + /// flight lists the attempts before it, and its failure is recorded before that list goes. + static func isOtherRowAttempt(_ railPaymentId: String?, rowAttemptId: String?, earlierAttemptIds: [String]? = nil) -> Bool { + guard let railPaymentId, let rowAttemptId, railPaymentId != rowAttemptId else { return false } + let isLaterSend = earlierAttemptIds.map { $0.contains(rowAttemptId) && !$0.contains(railPaymentId) } ?? false + return !isLaterSend } /// A succeeded Spark receive proves the move's LDK send settled, so the send's row becomes succeeded and keeps its amount and fee. diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 9ba3392185..8669d62685 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1781,15 +1781,15 @@ class LightningService: NodeLifecycleService { return ids.count == attempts.count ? ids : nil } - /// Whether a failure of `paymentHash` may have ended an attempt before the send still in doubt, which Spark may still - /// finish: the rail's attempt `paymentId` is one listed before the send went out. Without both ids, a payment Spark - /// created before the send or within `railClockSkewSeconds` after it (Spark's clock and this phone's may differ) - /// may be earlier, so it keeps the hold too. /// Spark's id of the taken send that still holds the invoice of `paymentHash`, if any. func heldRailSendId(paymentHash: String) -> String? { eventCallbackLock.withLock { takenRailSendIds()[paymentHash.lowercased()] } } + /// Whether a failure of `paymentHash` may have ended an attempt before the send still in doubt, which Spark may still + /// finish: the rail's attempt `paymentId` is one listed before the send went out. Without both ids, a payment Spark + /// created before the send or within `railClockSkewSeconds` after it (Spark's clock and this phone's may differ) + /// may be earlier, so it keeps the hold too. func isEarlierThanUncertainRailSend(paymentHash: String, createdAt: UInt64, paymentId: String? = nil) -> Bool { eventCallbackLock.withLock { isEarlierThanUncertainRailSendLocked(hash: paymentHash.lowercased(), createdAt: createdAt, paymentId: paymentId) @@ -1894,14 +1894,16 @@ class LightningService: NodeLifecycleService { uncertainRailSendFailedAt()[hash].map { (failedAt: UInt64($0), expiresAt: attemptExpiries(key: Self.railAttemptsKey)[hash]) } } guard let uncertain else { return true } - // 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: uncertain.failedAt) else { - return false - } // Spark keeps a send it committed but didn't finish in a cache no call exposes, and a sync that reached Spark // 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) - Self.unlistedRailSendGraceSeconds >= expiresAt else { return false } + // Absence proves nothing until a sync that started past the grace reached Spark. During an exit Spark no longer + // sends but still syncs its history, which settles the send the same way. + let settledAfter = max(uncertain.failedAt, UInt64(max(0, expiresAt + Self.unlistedRailSendGraceSeconds))) + guard let rail = channelFreeRail ?? channelFreePaymentHistory, await rail.hasSynced(after: settledAfter) else { + return false + } eventCallbackLock.withLock { clearRailSendUncertainty(hash: hash) var unrecorded = Set(railAttemptsStore.stringArray(forKey: Self.expiredRailHoldsUnrecordedKey) ?? []) diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index aa8e31df61..5cb5b36bb9 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -675,8 +675,12 @@ extension ChannelFreeRailTests { Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: expiresAt) } // An HTLC under way at the expiry can still settle a little after it. await assertRefusedAsDuplicate() - Bitkit.LightningService.shared - .now = { Date(timeIntervalSince1970: expiresAt + TimeInterval(Bitkit.LightningService.unlistedRailSendGraceSeconds)) } + let graceEnds = expiresAt + TimeInterval(Bitkit.LightningService.unlistedRailSendGraceSeconds) + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: graceEnds) } + // Absence proves nothing until a sync that started past the grace reached Spark. + rail.syncedAfter = { ($0 ?? 0) < UInt64(graceEnds) } + await assertRefusedAsDuplicate() + rail.syncedAfter = { _ in true } await assertReachesTheNode() } @@ -696,8 +700,12 @@ extension ChannelFreeRailTests { Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: expiresAt) } // An HTLC under way at the expiry can still settle a little after it. await assertRefusedAsDuplicate() - Bitkit.LightningService.shared - .now = { Date(timeIntervalSince1970: expiresAt + TimeInterval(Bitkit.LightningService.unlistedRailSendGraceSeconds)) } + let graceEnds = expiresAt + TimeInterval(Bitkit.LightningService.unlistedRailSendGraceSeconds) + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: graceEnds) } + // Absence proves nothing until a sync that started past the grace reached Spark. + rail.syncedAfter = { ($0 ?? 0) < UInt64(graceEnds) } + await assertRefusedAsDuplicate() + rail.syncedAfter = { _ in true } await assertReachesTheNode() } diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index 79ce8c52aa..81b7a5d242 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -178,4 +178,18 @@ final class SparkRelaunchActivityTests: XCTestCase { XCTAssertEqual(attempts.attemptId(forPaymentHash: "hash1"), "newer") XCTAssertEqual(attempts.attemptId(forPaymentHash: "hash\(ChannelFreeRowAttempts.limit)"), "id\(ChannelFreeRowAttempts.limit)") } + + func testASameSecondFailureTakesTheRowOnlyAsTheSendAfterTheRowsAttempt() { + // The row's own attempt, and a row or failure without an id, write it. + XCTAssertFalse(ActivityService.isOtherRowAttempt("first", rowAttemptId: "first")) + XCTAssertFalse(ActivityService.isOtherRowAttempt(nil, rowAttemptId: "first")) + XCTAssertFalse(ActivityService.isOtherRowAttempt("retry", rowAttemptId: nil)) + // Another attempt of the same second keeps the row when nothing orders the two. + XCTAssertTrue(ActivityService.isOtherRowAttempt("first", rowAttemptId: "retry")) + XCTAssertTrue(ActivityService.isOtherRowAttempt("first", rowAttemptId: "retry", earlierAttemptIds: ["older"])) + // The retry in flight lists the row's attempt before it, so its failure takes the row. + XCTAssertFalse(ActivityService.isOtherRowAttempt("retry", rowAttemptId: "first", earlierAttemptIds: ["first"])) + // While it is in flight, an attempt it lists as earlier still keeps the row. + XCTAssertTrue(ActivityService.isOtherRowAttempt("older", rowAttemptId: "first", earlierAttemptIds: ["first", "older"])) + } } From 713a882d56a6d7bd456b2c001ce7a172c6e26229 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 00:04:24 +0100 Subject: [PATCH 31/64] fix: keep exit data staged while a rejected copy is set aside Discarding restored exit data Spark rejected now deletes the staged file only while it still holds that data, so exit data a restore staged meanwhile stays for import. Verified: full unit suite on the iOS simulator --- Bitkit/Managers/SparkManager.swift | 6 ++++-- Bitkit/Services/BackupService.swift | 13 ++++++++----- BitkitTests/SparkExitBackupTests.swift | 25 ++++++++++++++++++++----- 3 files changed, 32 insertions(+), 12 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 94d5b42844..3e5dc47036 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -1505,8 +1505,10 @@ final class SparkManager: ChannelFreeLightningRail { return try String(decoding: Data(contentsOf: file), as: UTF8.self) } - /// Drops restored exit data Spark rejected, once the backup set a copy of it aside. - func discardStagedExitState(walletIndex: Int) { + /// Drops restored exit data Spark rejected, once the backup set a copy of it aside, unless newer data was staged + /// meanwhile. Read and delete run on the main actor with no suspension between them, as staging does. + func discardStagedExitState(_ exitState: String, walletIndex: Int) { + guard (try? stagedExitState(walletIndex: walletIndex)) == exitState else { return } try? FileManager.default.removeItem(at: Env.sparkExitRestore(walletIndex: walletIndex)) } diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index a3c156c1f0..d200a87a02 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -140,7 +140,7 @@ class BackupService { static let sparkExitRejectedKey = "SPARK_EXIT_REJECTED" private let backupData: ((BackupCategory) async throws -> Data)? private let importStagedSparkExit: () async -> SparkStagedExitImport - private let discardStagedSparkExit: () async -> Void + private let discardStagedSparkExit: (String) async -> Void private let stagedSparkExitState: () async throws -> String? private let restoreExitBackup: (SparkExitBackupV1) async throws -> Void private let isSparkExitActive: () async -> Bool @@ -194,8 +194,8 @@ class BackupService { importStagedSparkExit: @escaping () async -> SparkStagedExitImport = { @MainActor in await SparkManager.shared.importStagedExitState(walletIndex: LightningService.shared.currentWalletIndex) }, - discardStagedSparkExit: @escaping () async -> Void = { @MainActor in - SparkManager.shared.discardStagedExitState(walletIndex: LightningService.shared.currentWalletIndex) + discardStagedSparkExit: @escaping (String) async -> Void = { @MainActor exitState in + SparkManager.shared.discardStagedExitState(exitState, walletIndex: LightningService.shared.currentWalletIndex) }, stagedSparkExitState: @escaping () async throws -> String? = { @MainActor in try SparkManager.shared.stagedExitState(walletIndex: LightningService.shared.currentWalletIndex) @@ -465,7 +465,8 @@ class BackupService { throw SparkExitBackupError.restorePending case .rejected: var isReplacedRemotely = false - if let staged = try await stagedSparkExitState() { + let staged = try await stagedSparkExitState() + if let staged { let copy = try await rejectedSparkExitCopy(staged: staged) try await setAsideRejectedSparkExit(copy.data) isReplacedRemotely = copy.isReplacedRemotely @@ -475,7 +476,9 @@ class BackupService { if isReplacedRemotely { defaults.set(true, forKey: Self.sparkExitRestorePendingKey) } - await discardStagedSparkExit() + if let staged { + await discardStagedSparkExit(staged) + } if isReplacedRemotely { await restoreSparkExit() throw SparkExitBackupError.restorePending diff --git a/BitkitTests/SparkExitBackupTests.swift b/BitkitTests/SparkExitBackupTests.swift index 991cab069b..a0ba98cc06 100644 --- a/BitkitTests/SparkExitBackupTests.swift +++ b/BitkitTests/SparkExitBackupTests.swift @@ -198,7 +198,7 @@ final class SparkExitBackupTests: XCTestCase { waitForTemporaryFailureDelay: { _ in }, fetchBackup: { remote[$0] }, importStagedSparkExit: { staged }, - discardStagedSparkExit: { staged = .nothingStaged }, + discardStagedSparkExit: { _ in staged = .nothingStaged }, stagedSparkExitState: { "newer" }, restoreExitBackup: { _ in } ) @@ -232,7 +232,7 @@ final class SparkExitBackupTests: XCTestCase { uploadBackup: { remote[$0] = $1 }, fetchBackup: { remote[$0] }, importStagedSparkExit: { staged }, - discardStagedSparkExit: { staged = .nothingStaged }, + discardStagedSparkExit: { _ in staged = .nothingStaged }, stagedSparkExitState: { "later" } ) @@ -261,7 +261,7 @@ final class SparkExitBackupTests: XCTestCase { waitForTemporaryFailureDelay: { _ in }, fetchBackup: { remote[$0] }, importStagedSparkExit: { staged }, - discardStagedSparkExit: { staged = .nothingStaged }, + discardStagedSparkExit: { _ in staged = .nothingStaged }, stagedSparkExitState: { "mine" }, restoreExitBackup: { restored.append($0.exitState); staged = .pending } ) @@ -323,7 +323,7 @@ final class SparkExitBackupTests: XCTestCase { waitForTemporaryFailureDelay: { _ in }, fetchBackup: { remote[$0] }, importStagedSparkExit: { staged }, - discardStagedSparkExit: { + discardStagedSparkExit: { _ in // A stop here relaunches with whatever was saved before the staged copy went. isRestorePendingWhenDiscarded = defaults.bool(forKey: "sparkExitRestorePending") staged = .nothingStaged @@ -353,7 +353,7 @@ final class SparkExitBackupTests: XCTestCase { waitForTemporaryFailureDelay: { _ in }, fetchBackup: { remote[$0] }, importStagedSparkExit: { .rejected }, - discardStagedSparkExit: {}, + discardStagedSparkExit: { _ in }, stagedSparkExitState: { throw Unreadable() } ) @@ -408,4 +408,19 @@ final class SparkExitBackupTests: XCTestCase { XCTAssertTrue(mark.claim(version: SparkManager.exitStateGeneration), "The restart kept the stale exit data backup") } + + @MainActor + func testDiscardingRejectedExitDataKeepsNewerDataStagedMeanwhile() throws { + let walletIndex = 9901 + let file = Env.sparkExitRestore(walletIndex: walletIndex) + defer { try? FileManager.default.removeItem(at: file) } + try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("newer".utf8).write(to: file) + + SparkManager.shared.discardStagedExitState("rejected", walletIndex: walletIndex) + XCTAssertEqual(try SparkManager.shared.stagedExitState(walletIndex: walletIndex), "newer") + + SparkManager.shared.discardStagedExitState("newer", walletIndex: walletIndex) + XCTAssertNil(try SparkManager.shared.stagedExitState(walletIndex: walletIndex)) + } } From eacd614c19f612d01fed074df837872dc49bcf44 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 01:08:27 +0100 Subject: [PATCH 32/64] fix: keep a spark send's earlier attempts past its hold Each Spark send's earlier attempt ids are kept after its hold for the latest 100 invoices, so after a restart a known earlier attempt's failure never writes over the send's failed row, whatever Spark's dates. At expiry the live send recorded is one the held send didn't follow. Verified: full unit suite on the iOS simulator --- Bitkit/Managers/SparkManager.swift | 12 ++++++--- Bitkit/Services/CoreService.swift | 10 ++++++++ Bitkit/Services/LightningService.swift | 32 ++++++++++++++++++++++++ BitkitTests/ChannelFreeRailTests.swift | 34 ++++++++++++++++++++++++++ 4 files changed, 84 insertions(+), 4 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 3e5dc47036..d537223882 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -1863,6 +1863,7 @@ final class SparkManager: ChannelFreeLightningRail { return await Self.recordExpiredHold( paymentHash: paymentHash, payments: payments, + earlierAttemptIds: LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: paymentHash), record: { await self.recordActivity($0) }, failStoredSend: { await (try? CoreService.shared.activity.failPendingLightningSend(id: $0)) != nil } ) @@ -1871,6 +1872,7 @@ final class SparkManager: ChannelFreeLightningRail { static func recordExpiredHold( paymentHash: String, payments: [Payment], + earlierAttemptIds: Set = [], record: (Payment) async -> Bool, failStoredSend: (String) async -> Bool ) async -> Bool { @@ -1878,10 +1880,12 @@ final class SparkManager: ChannelFreeLightningRail { guard payment.paymentType == .send, case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details else { return false } return htlcDetails.paymentHash.caseInsensitiveCompare(paymentHash) == .orderedSame } - // A live send is the one that pays the invoice, the newest when a retry shares its earlier attempt's timestamp. A - // listed failure may be an earlier attempt's, whose amount and fee aren't the held send's, so without a live send - // the stored row is failed in place. - if let live = sends.filter({ $0.status != .failed }).max(by: { $0.timestamp < $1.timestamp }) { + // A live send is the one that pays the invoice: not one the held send followed, then the newest. A listed failure + // may be an earlier attempt's, whose amount and fee aren't the held send's, so without a live send the stored row + // is failed in place. + if let live = sends.filter({ $0.status != .failed }) + .max(by: { (earlierAttemptIds.contains($0.id) ? 0 : 1, $0.timestamp) < (earlierAttemptIds.contains($1.id) ? 0 : 1, $1.timestamp) }) + { return await record(live) } return await failStoredSend(paymentHash) diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index edae6a1366..2e2199f2e2 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1033,6 +1033,10 @@ class ActivityService { railPaymentId, rowAttemptId: Self.channelFreeRowAttempts.attemptId(forPaymentHash: payment.id), earlierAttemptIds: LightningService.shared.railSendEarlierAttemptIds[payment.id.lowercased()] + ) || Self.isKnownEarlierAttempt( + railPaymentId, + rowAttemptId: Self.channelFreeRowAttempts.attemptId(forPaymentHash: payment.id), + keptEarlierAttemptIds: LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: payment.id) )) ) { @@ -1111,6 +1115,12 @@ class ActivityService { } } + /// Whether `railPaymentId` is an attempt a send of the invoice followed, other than the row's, whatever Spark's dates. + static func isKnownEarlierAttempt(_ railPaymentId: String?, rowAttemptId: String?, keptEarlierAttemptIds: Set) -> Bool { + guard let railPaymentId, railPaymentId != rowAttemptId else { return false } + return keptEarlierAttemptIds.contains(railPaymentId) + } + /// Whether `railPaymentId` is another attempt than the row's, and not the send that went out after it: the send in /// flight lists the attempts before it, and its failure is recorded before that list goes. static func isOtherRowAttempt(_ railPaymentId: String?, rowAttemptId: String?, earlierAttemptIds: [String]? = nil) -> Bool { diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 8669d62685..74784d12f2 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1253,6 +1253,10 @@ class LightningService: NodeLifecycleService { private static let uncertainRailSendsStartedKey = "channelFreeRailUncertainSendStartedAt" /// The rail's ids of the attempts each of those sends followed, so a failure of one is told from the send's own. private static let uncertainRailSendsEarlierAttemptsKey = "channelFreeRailUncertainSendEarlierAttempts" + /// The rail's ids of the attempts each send followed, kept past its hold as `[hash, ids…]` for the latest + /// `keptEarlierAttemptsLimit` hashes, so a failure of one never writes over the send's own row after a restart. + private static let keptRailSendEarlierAttemptsKey = "channelFreeRailKeptSendEarlierAttempts" + static let keptEarlierAttemptsLimit = 100 /// The rail's id of each send Spark took, by hash, until it settles: any other attempt's failure is an earlier one's. private static let takenRailSendsKey = "channelFreeRailTakenSendIds" /// Hashes of taken sends Spark never listed whose hold ended before their row was failed, retried on each rail sync. @@ -1452,6 +1456,7 @@ class LightningService: NodeLifecycleService { railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsKey) railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsStartedKey) railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsEarlierAttemptsKey) + railAttemptsStore.removeObject(forKey: Self.keptRailSendEarlierAttemptsKey) railAttemptsStore.removeObject(forKey: Self.takenRailSendsKey) railAttemptsStore.removeObject(forKey: Self.unlistedTakenRailSendsUnfailedKey) railAttemptsStore.removeObject(forKey: Self.expiredRailHoldsUnrecordedKey) @@ -1697,12 +1702,39 @@ class LightningService: NodeLifecycleService { var earlier = uncertainRailSendEarlierAttempts() earlier[hash] = earlierAttemptIds.map { ids in takenBefore.map { ids.contains($0) ? ids : ids + [$0] } ?? ids } railAttemptsStore.set(earlier, forKey: Self.uncertainRailSendsEarlierAttemptsKey) + keepEarlierAttempts(hash: hash, ids: (earlierAttemptIds ?? []) + (takenBefore.map { [$0] } ?? [])) } uncertain[hash] = failedAt railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) } } + /// Callers hold `eventCallbackLock`. + private func keepEarlierAttempts(hash: String, ids: [String]) { + var entries = railAttemptsStore.array(forKey: Self.keptRailSendEarlierAttemptsKey) as? [[String]] ?? [] + let kept = entries.last { $0.first == hash }.map { Array($0.dropFirst()) } ?? [] + let merged = kept + ids.filter { !kept.contains($0) } + guard !merged.isEmpty, merged != kept else { return } + entries.removeAll { $0.first == hash } + entries.append([hash] + merged) + railAttemptsStore.set(Array(entries.suffix(Self.keptEarlierAttemptsLimit)), forKey: Self.keptRailSendEarlierAttemptsKey) + } + + #if DEBUG + func keepEarlierAttemptsForTesting(hash: String, ids: [String]) { + eventCallbackLock.withLock { keepEarlierAttempts(hash: hash.lowercased(), ids: ids) } + } + #endif + + /// Spark's ids of every attempt a send of `paymentHash` followed, kept past its hold. + func keptRailSendEarlierAttemptIds(paymentHash: String) -> Set { + let hash = paymentHash.lowercased() + return eventCallbackLock.withLock { + let entries = railAttemptsStore.array(forKey: Self.keptRailSendEarlierAttemptsKey) as? [[String]] ?? [] + return Set(entries.last { $0.first == hash }?.dropFirst() ?? []) + } + } + /// Callers hold `eventCallbackLock`. private func uncertainRailSendStartedAt() -> [String: Int] { railAttemptsStore.dictionary(forKey: Self.uncertainRailSendsStartedKey) as? [String: Int] ?? [:] diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 5cb5b36bb9..7eea0ffd27 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1253,6 +1253,40 @@ extension ChannelFreeRailTests { XCTAssertEqual(failed, [hash, "ef"], "a send Spark lists none of stayed pending") } + func testAnExpiredHoldWritesTheHeldSendOverALiveAttemptItFollowed() async { + let hash = "ab" + let earlier = Self.sparkPayment(hash: hash, status: .pending, id: "earlier", timestamp: 5) + let retry = Self.sparkPayment(hash: hash, status: .pending, id: "retry", timestamp: 5) + for payments in [[earlier, retry], [retry, earlier]] { + var recorded: [String] = [] + _ = await SparkManager.recordExpiredHold( + paymentHash: hash, payments: payments, earlierAttemptIds: ["earlier"], + record: { recorded.append($0.id); return true }, failStoredSend: { _ in true } + ) + XCTAssertEqual(recorded, ["retry"]) + } + } + + func testASendsEarlierAttemptsAreKeptPastItsHoldForTheLatestInvoices() throws { + let service = Bitkit.LightningService.shared + let defaults = try XCTUnwrap(UserDefaults(suiteName: "KeptEarlierAttempts-\(UUID().uuidString)")) + let previousStore = service.railAttemptsStore + defer { service.railAttemptsStore = previousStore } + service.railAttemptsStore = defaults + for index in 0 ... Bitkit.LightningService.keptEarlierAttemptsLimit { + service.keepEarlierAttemptsForTesting(hash: "hash\(index)", ids: ["a\(index)"]) + } + service.keepEarlierAttemptsForTesting(hash: "hash1", ids: ["b1"]) + + XCTAssertEqual(service.keptRailSendEarlierAttemptIds(paymentHash: "hash0"), []) + XCTAssertEqual(service.keptRailSendEarlierAttemptIds(paymentHash: "HASH1"), ["a1", "b1"]) + // A known earlier attempt's failure keeps the row whatever its date; the row's own attempt still writes it. + XCTAssertTrue(ActivityService.isKnownEarlierAttempt("a1", rowAttemptId: "retry", keptEarlierAttemptIds: ["a1"])) + XCTAssertFalse(ActivityService.isKnownEarlierAttempt("a1", rowAttemptId: "a1", keptEarlierAttemptIds: ["a1"])) + XCTAssertFalse(ActivityService.isKnownEarlierAttempt("later", rowAttemptId: "retry", keptEarlierAttemptIds: ["a1"])) + XCTAssertFalse(ActivityService.isKnownEarlierAttempt(nil, rowAttemptId: "retry", keptEarlierAttemptIds: ["a1"])) + } + func testAnExpiredHoldWritesALiveRetryOverAFailureWithTheSameTimestamp() async { let hash = "ab" let failed = Self.sparkPayment(hash: hash, status: .failed, id: "earlier", timestamp: 5) From 3c7158875a8d53fc5c4eebd0643e0f5caa64817a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 01:44:24 +0100 Subject: [PATCH 33/64] fix: a spark row failed in place drops its attempt id Failing a held send's row in place forgets which attempt last wrote it, so that attempt's failure, known as an earlier one, no longer reads as the row's own. Verified: full unit suite on the iOS simulator --- Bitkit/Services/CoreService.swift | 11 +++++++++++ BitkitTests/SparkRelaunchActivityTests.swift | 15 +++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 2e2199f2e2..d6ad65cb55 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1460,6 +1460,8 @@ class ActivityService { else { return } activity.status = .failed try updateActivity(activityId: id, activity: .lightning(activity)) + // The held send failed in place, so whichever attempt last wrote the row no longer owns it. + Self.channelFreeRowAttempts.forget(paymentHash: id) self.activitiesChangedSubject.send() } } @@ -2906,6 +2908,15 @@ struct ChannelFreeRowAttempts: @unchecked Sendable { } } + func forget(paymentHash: String) { + let hash = paymentHash.lowercased() + Self.lock.withLock { + guard var pairs = defaults.array(forKey: Self.key) as? [[String]], pairs.contains(where: { $0.first == hash }) else { return } + pairs.removeAll { $0.first == hash } + defaults.set(pairs, forKey: Self.key) + } + } + func attemptId(forPaymentHash paymentHash: String) -> String? { let hash = paymentHash.lowercased() return (defaults.array(forKey: Self.key) as? [[String]])?.last { $0.count == 2 && $0[0] == hash }?[1] diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index 81b7a5d242..e9f8246ece 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -192,4 +192,19 @@ final class SparkRelaunchActivityTests: XCTestCase { // While it is in flight, an attempt it lists as earlier still keeps the row. XCTAssertTrue(ActivityService.isOtherRowAttempt("older", rowAttemptId: "first", earlierAttemptIds: ["first", "older"])) } + + func testFailingAHeldSparkRowInPlaceDropsTheAttemptThatWroteIt() async throws { + let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "e9", count: 16) + let pending = PaymentDetails( + id: hash, + kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), + amountMsat: 500_000, feePaidMsat: 0, direction: .outbound, status: .pending, latestUpdateTimestamp: 200 + ) + try await CoreService.shared.activity.recordChannelFreeRailPayment(pending, railPaymentId: "earlier") + XCTAssertEqual(ActivityService.channelFreeRowAttempts.attemptId(forPaymentHash: hash), "earlier") + + try await CoreService.shared.activity.failPendingLightningSend(id: hash) + // The row is the held send's now, so the attempt that wrote it before no longer counts as its own. + XCTAssertNil(ActivityService.channelFreeRowAttempts.attemptId(forPaymentHash: hash)) + } } From 843a182accdc5c281ecea1926c56aa524f81f807 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 02:10:42 +0100 Subject: [PATCH 34/64] fix: a held spark row failed in place takes its own attempt id Failing a held send's row in place now records the held attempt's own Spark id as the row's writer when known, and otherwise drops the writer only when it is an attempt the send followed, so the retry's id still protects its row against an older same-second failure. The writer is saved before the row fails. Verified: full unit suite on the iOS simulator --- Bitkit/Managers/SparkManager.swift | 14 +++++++-- Bitkit/Services/CoreService.swift | 15 +++++++--- Bitkit/Services/LightningService.swift | 8 +++--- BitkitTests/ChannelFreeRailTests.swift | 2 +- BitkitTests/SparkRelaunchActivityTests.swift | 30 +++++++++++++++++--- 5 files changed, 53 insertions(+), 16 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index d537223882..8d97d37077 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -421,8 +421,8 @@ final class SparkManager: ChannelFreeLightningRail { // still go to LDK, even when that refresh or the activity sync fails. An emergency exit keeps it out. LightningService.shared.channelFreePaymentHistory = self LightningService.shared.railSendHoldExpired = { [weak self] hash in await self?.recordExpiredHold(paymentHash: hash) ?? false } - LightningService.shared.railTakenSendUnlisted = { hash in - await (try? CoreService.shared.activity.failPendingLightningSend(id: hash)) != nil + LightningService.shared.railTakenSendUnlisted = { hash, ownAttemptId in + await Self.failHeldSendRow(paymentHash: hash, ownAttemptId: ownAttemptId) } if !isExiting { LightningService.shared.channelFreeRail = self @@ -1865,10 +1865,18 @@ final class SparkManager: ChannelFreeLightningRail { payments: payments, earlierAttemptIds: LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: paymentHash), record: { await self.recordActivity($0) }, - failStoredSend: { await (try? CoreService.shared.activity.failPendingLightningSend(id: $0)) != nil } + failStoredSend: { await Self.failHeldSendRow(paymentHash: $0, ownAttemptId: nil) } ) } + private static func failHeldSendRow(paymentHash: String, ownAttemptId: String?) async -> Bool { + await (try? CoreService.shared.activity.failPendingLightningSend( + id: paymentHash, + ownAttemptId: ownAttemptId, + earlierAttemptIds: LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: paymentHash) + )) != nil + } + static func recordExpiredHold( paymentHash: String, payments: [Payment], diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index d6ad65cb55..d4f8da3db0 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1452,16 +1452,23 @@ class ActivityService { } /// Marks the stored Lightning send `id` failed while it is still pending. - /// Read, checked and written in one core-queue operation, so a change saved meanwhile isn't overwritten. - func failPendingLightningSend(id: String) async throws { + /// Read, checked and written in one core-queue operation, so a change saved meanwhile isn't overwritten. The row is + /// the held send's now: it takes `ownAttemptId` as the attempt that wrote it when known, and otherwise drops one of + /// `earlierAttemptIds`. Saved before the row fails, so a stop in between finds the row pending and redoes both. + func failPendingLightningSend(id: String, ownAttemptId: String? = nil, earlierAttemptIds: Set = []) async throws { try await ServiceQueue.background(.core) { guard case var .lightning(activity) = try getActivityById(walletId: WalletScope.default, activityId: id), activity.txType == .sent, activity.status == .pending else { return } + if let ownAttemptId { + Self.channelFreeRowAttempts.remember(ownAttemptId, forPaymentHash: id) + } else if let rowAttemptId = Self.channelFreeRowAttempts.attemptId(forPaymentHash: id), + earlierAttemptIds.contains(rowAttemptId) + { + Self.channelFreeRowAttempts.forget(paymentHash: id) + } activity.status = .failed try updateActivity(activityId: id, activity: .lightning(activity)) - // The held send failed in place, so whichever attempt last wrote the row no longer owns it. - Self.channelFreeRowAttempts.forget(paymentHash: id) self.activitiesChangedSubject.send() } } diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 74784d12f2..200210404f 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -183,7 +183,7 @@ class LightningService: NodeLifecycleService { var railSendHoldExpired: ((String) async -> Bool)? /// Fails the stored Activity row of a send Spark took but never listed, once its hold ends past its invoice's expiry, /// keeping the row's own amount and fee. Returns whether the row was saved. - var railTakenSendUnlisted: ((String) async -> Bool)? + var railTakenSendUnlisted: ((_ paymentHash: String, _ ownAttemptId: String?) async -> Bool)? var onchainTransactionConfirmed: (@Sendable (String) async -> Void)? var onchainTransactionReceived: (@Sendable (String) async -> Void)? typealias OnchainActivityCompletion = @MainActor () async -> Void @@ -2013,12 +2013,12 @@ class LightningService: NodeLifecycleService { unfailed.insert(hash) railAttemptsStore.set(Array(unfailed), forKey: Self.unlistedTakenRailSendsUnfailedKey) } - await failUnlistedTakenRailSend(hash) + await failUnlistedTakenRailSend(hash, ownAttemptId: taken[hash]) } } - private func failUnlistedTakenRailSend(_ hash: String) async { - guard let fail = railTakenSendUnlisted, await fail(hash) else { return } + private func failUnlistedTakenRailSend(_ hash: String, ownAttemptId: String? = nil) async { + guard let fail = railTakenSendUnlisted, await fail(hash, ownAttemptId) else { return } eventCallbackLock.withLock { let unfailed = railAttemptsStore.stringArray(forKey: Self.unlistedTakenRailSendsUnfailedKey) ?? [] railAttemptsStore.set(unfailed.filter { $0 != hash }, forKey: Self.unlistedTakenRailSendsUnfailedKey) diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 7eea0ffd27..5a1834b1c7 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1051,7 +1051,7 @@ extension ChannelFreeRailTests { service.railTakenSendUnlisted = previousUnlisted } service.railSendHoldExpired = { replayed.append($0); return true } - service.railTakenSendUnlisted = { failed.append($0); return saves } + service.railTakenSendUnlisted = { hash, _ in failed.append(hash); return saves } let expiresAt = invoice.secondsSinceEpoch() + invoice.expiryTimeSeconds() let graceEnds = expiresAt + UInt64(Bitkit.LightningService.unlistedRailSendGraceSeconds) diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index e9f8246ece..4b6601cd3b 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -193,7 +193,7 @@ final class SparkRelaunchActivityTests: XCTestCase { XCTAssertTrue(ActivityService.isOtherRowAttempt("older", rowAttemptId: "first", earlierAttemptIds: ["first", "older"])) } - func testFailingAHeldSparkRowInPlaceDropsTheAttemptThatWroteIt() async throws { + func testFailingAHeldSparkRowInPlaceKeepsAWriterItDidntFollow() async throws { let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "e9", count: 16) let pending = PaymentDetails( id: hash, @@ -203,8 +203,30 @@ final class SparkRelaunchActivityTests: XCTestCase { try await CoreService.shared.activity.recordChannelFreeRailPayment(pending, railPaymentId: "earlier") XCTAssertEqual(ActivityService.channelFreeRowAttempts.attemptId(forPaymentHash: hash), "earlier") - try await CoreService.shared.activity.failPendingLightningSend(id: hash) - // The row is the held send's now, so the attempt that wrote it before no longer counts as its own. - XCTAssertNil(ActivityService.channelFreeRowAttempts.attemptId(forPaymentHash: hash)) + // An attempt that isn't one the held send followed stays the row's writer. + try await CoreService.shared.activity.failPendingLightningSend(id: hash, earlierAttemptIds: ["older"]) + XCTAssertEqual(ActivityService.channelFreeRowAttempts.attemptId(forPaymentHash: hash), "earlier") + } + + func testFailingAHeldSparkRowInPlaceMakesItTheHeldAttemptsOwn() async throws { + func pendingRow(_ hash: String) async throws { + let pending = PaymentDetails( + id: hash, + kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), + amountMsat: 500_000, feePaidMsat: 0, direction: .outbound, status: .pending, latestUpdateTimestamp: 200 + ) + try await CoreService.shared.activity.recordChannelFreeRailPayment(pending, railPaymentId: "earlier") + } + let taken = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "ea", count: 16) + try await pendingRow(taken) + // The held send's own id becomes the writer, so it keeps the row against an older failure of the same second. + try await CoreService.shared.activity.failPendingLightningSend(id: taken, ownAttemptId: "retry", earlierAttemptIds: ["earlier"]) + XCTAssertEqual(ActivityService.channelFreeRowAttempts.attemptId(forPaymentHash: taken), "retry") + + let inDoubt = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "eb", count: 16) + try await pendingRow(inDoubt) + // Without its own id, an earlier attempt that wrote the row no longer counts as the row's own. + try await CoreService.shared.activity.failPendingLightningSend(id: inDoubt, earlierAttemptIds: ["earlier"]) + XCTAssertNil(ActivityService.channelFreeRowAttempts.attemptId(forPaymentHash: inDoubt)) } } From 352b311eadf11d24fe5647d7188299a60a813c69 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 04:20:47 +0100 Subject: [PATCH 35/64] fix: a spark row its earlier payment still owns keeps its writer The writer of each Spark send row is kept with a stamp of the row it wrote (timestamp, amount, fee). Failing a held row in place drops a writer known as an earlier attempt only when a retry has since written over the row, so a pending row the earlier payment still owns keeps its writer and that payment's final fee still lands. Verified: full unit suite on the iOS simulator --- Bitkit/Services/CoreService.swift | 36 ++++++++++++++------ BitkitTests/SparkRelaunchActivityTests.swift | 25 ++++++++++---- 2 files changed, 44 insertions(+), 17 deletions(-) diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index d4f8da3db0..2b8afa6e2e 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1111,7 +1111,7 @@ class ActivityService { Self.sentPaymentContacts.forget(paymentHash: payment.id) } if rail == .channelFree, payment.direction == .outbound, let railPaymentId { - Self.channelFreeRowAttempts.remember(railPaymentId, forPaymentHash: payment.id) + Self.channelFreeRowAttempts.remember(railPaymentId, forPaymentHash: payment.id, stamp: ChannelFreeRowAttempts.stamp(ln)) } } @@ -1461,10 +1461,13 @@ class ActivityService { activity.txType == .sent, activity.status == .pending else { return } if let ownAttemptId { - Self.channelFreeRowAttempts.remember(ownAttemptId, forPaymentHash: id) + Self.channelFreeRowAttempts.remember(ownAttemptId, forPaymentHash: id, stamp: ChannelFreeRowAttempts.stamp(activity)) } else if let rowAttemptId = Self.channelFreeRowAttempts.attemptId(forPaymentHash: id), - earlierAttemptIds.contains(rowAttemptId) + earlierAttemptIds.contains(rowAttemptId), + !Self.channelFreeRowAttempts.isUnchanged(activity, forPaymentHash: id) { + // A retry wrote over the earlier attempt's row. One the earlier attempt still owns keeps its writer, so + // that attempt's final fee still lands. Self.channelFreeRowAttempts.forget(paymentHash: id) } activity.status = .failed @@ -2904,17 +2907,30 @@ struct ChannelFreeRowAttempts: @unchecked Sendable { static let limit = 100 let defaults: UserDefaults - func remember(_ attemptId: String, forPaymentHash paymentHash: String) { + /// The row as its writer left it, so a later write by another payment shows. + static func stamp(_ row: LightningActivity) -> String { + "\(row.timestamp):\(row.value):\(row.fee ?? 0)" + } + + func remember(_ attemptId: String, forPaymentHash paymentHash: String, stamp: String) { let hash = paymentHash.lowercased() + let entry = [hash, attemptId, stamp] Self.lock.withLock { - var pairs = defaults.array(forKey: Self.key) as? [[String]] ?? [] - guard pairs.last(where: { $0.first == hash })?.last != attemptId else { return } - pairs.removeAll { $0.first == hash } - pairs.append([hash, attemptId]) - defaults.set(Array(pairs.suffix(Self.limit)), forKey: Self.key) + var entries = defaults.array(forKey: Self.key) as? [[String]] ?? [] + guard entries.last(where: { $0.first == hash }) != entry else { return } + entries.removeAll { $0.first == hash } + entries.append(entry) + defaults.set(Array(entries.suffix(Self.limit)), forKey: Self.key) } } + /// Whether `row` is as its writer left it. + func isUnchanged(_ row: LightningActivity, forPaymentHash paymentHash: String) -> Bool { + let hash = paymentHash.lowercased() + let entry = (defaults.array(forKey: Self.key) as? [[String]])?.last { $0.first == hash } + return entry?.count == 3 && entry?[2] == Self.stamp(row) + } + func forget(paymentHash: String) { let hash = paymentHash.lowercased() Self.lock.withLock { @@ -2926,6 +2942,6 @@ struct ChannelFreeRowAttempts: @unchecked Sendable { func attemptId(forPaymentHash paymentHash: String) -> String? { let hash = paymentHash.lowercased() - return (defaults.array(forKey: Self.key) as? [[String]])?.last { $0.count == 2 && $0[0] == hash }?[1] + return (defaults.array(forKey: Self.key) as? [[String]])?.last { $0.count >= 2 && $0[0] == hash }?[1] } } diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index 4b6601cd3b..41274e946a 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -170,9 +170,9 @@ final class SparkRelaunchActivityTests: XCTestCase { defer { defaults.removePersistentDomain(forName: suite) } let attempts = ChannelFreeRowAttempts(defaults: defaults) for index in 0 ... ChannelFreeRowAttempts.limit { - attempts.remember("id\(index)", forPaymentHash: "hash\(index)") + attempts.remember("id\(index)", forPaymentHash: "hash\(index)", stamp: "1:2:3") } - attempts.remember("newer", forPaymentHash: "HASH1") + attempts.remember("newer", forPaymentHash: "HASH1", stamp: "1:2:3") XCTAssertNil(attempts.attemptId(forPaymentHash: "hash0")) XCTAssertEqual(attempts.attemptId(forPaymentHash: "hash1"), "newer") @@ -223,10 +223,21 @@ final class SparkRelaunchActivityTests: XCTestCase { try await CoreService.shared.activity.failPendingLightningSend(id: taken, ownAttemptId: "retry", earlierAttemptIds: ["earlier"]) XCTAssertEqual(ActivityService.channelFreeRowAttempts.attemptId(forPaymentHash: taken), "retry") - let inDoubt = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "eb", count: 16) - try await pendingRow(inDoubt) - // Without its own id, an earlier attempt that wrote the row no longer counts as the row's own. - try await CoreService.shared.activity.failPendingLightningSend(id: inDoubt, earlierAttemptIds: ["earlier"]) - XCTAssertNil(ActivityService.channelFreeRowAttempts.attemptId(forPaymentHash: inDoubt)) + let owned = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "eb", count: 16) + try await pendingRow(owned) + // Without its own id, a row the earlier attempt still owns keeps its writer, so that attempt's final fee lands. + try await CoreService.shared.activity.failPendingLightningSend(id: owned, earlierAttemptIds: ["earlier"]) + XCTAssertEqual(ActivityService.channelFreeRowAttempts.attemptId(forPaymentHash: owned), "earlier") + + let overwritten = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "ec", count: 16) + try await pendingRow(overwritten) + // The retry's send wrote over the earlier attempt's row without a Spark id, so that attempt no longer owns it. + guard case var .lightning(row)? = try await CoreService.shared.activity.getActivity(id: overwritten) else { + return XCTFail("the earlier attempt's row is missing") + } + row.value = 700 + try await CoreService.shared.activity.update(id: overwritten, activity: .lightning(row)) + try await CoreService.shared.activity.failPendingLightningSend(id: overwritten, earlierAttemptIds: ["earlier"]) + XCTAssertNil(ActivityService.channelFreeRowAttempts.attemptId(forPaymentHash: overwritten)) } } From 8569ffd1513b80299800ebb2129b03078d4fe1e7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 04:31:18 +0100 Subject: [PATCH 36/64] fix: keep a spark row's writer before writing the row A Spark send row's writer id and stamp are kept before the row is written, in the same core-queue step, and put back when the write fails, so a stop between the two never leaves a retry's row to an earlier writer. Verified: full unit suite on the iOS simulator --- Bitkit/Services/CoreService.swift | 66 +++++++++++++++----- BitkitTests/SparkRelaunchActivityTests.swift | 7 +++ 2 files changed, 56 insertions(+), 17 deletions(-) diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 2b8afa6e2e..cc4d8bc6fa 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1091,28 +1091,36 @@ class ActivityService { try self.settleMove(latest, receiveState: state) return } - guard let latestActivity else { - try upsertActivity(activity: .lightning(ln)) - self.updateBoostTxIdsCache(for: .lightning(ln)) - self.activitiesChangedSubject.send() - return + // The writer is kept before the row is written, so a stop between the two never leaves the row to an earlier + // writer, and put back when the write fails. + let previousWriter = Self.channelFreeRowAttempts.entry(forPaymentHash: payment.id) + if rail == .channelFree, payment.direction == .outbound, let railPaymentId { + Self.channelFreeRowAttempts.remember(railPaymentId, forPaymentHash: payment.id, stamp: ChannelFreeRowAttempts.stamp(ln)) } - var updated = ln - if case let .lightning(latest) = latestActivity, latest.contact != existingLightning?.contact { - updated.contact = latest.contact - } - if self.isContactDetached(activityId: payment.id, walletId: ln.walletId) { - updated.contact = nil + do { + guard let latestActivity else { + try upsertActivity(activity: .lightning(ln)) + self.updateBoostTxIdsCache(for: .lightning(ln)) + self.activitiesChangedSubject.send() + return + } + var updated = ln + if case let .lightning(latest) = latestActivity, latest.contact != existingLightning?.contact { + updated.contact = latest.contact + } + if self.isContactDetached(activityId: payment.id, walletId: ln.walletId) { + updated.contact = nil + } + try updateActivity(activityId: payment.id, activity: .lightning(updated)) + self.activitiesChangedSubject.send() + } catch { + Self.channelFreeRowAttempts.restore(previousWriter, forPaymentHash: payment.id) + throw error } - try updateActivity(activityId: payment.id, activity: .lightning(updated)) - self.activitiesChangedSubject.send() } if payment.direction == .outbound, ln.contact != nil, payment.status != .pending { Self.sentPaymentContacts.forget(paymentHash: payment.id) } - if rail == .channelFree, payment.direction == .outbound, let railPaymentId { - Self.channelFreeRowAttempts.remember(railPaymentId, forPaymentHash: payment.id, stamp: ChannelFreeRowAttempts.stamp(ln)) - } } /// Whether `railPaymentId` is an attempt a send of the invoice followed, other than the row's, whatever Spark's dates. @@ -1460,6 +1468,7 @@ class ActivityService { guard case var .lightning(activity) = try getActivityById(walletId: WalletScope.default, activityId: id), activity.txType == .sent, activity.status == .pending else { return } + let previousWriter = Self.channelFreeRowAttempts.entry(forPaymentHash: id) if let ownAttemptId { Self.channelFreeRowAttempts.remember(ownAttemptId, forPaymentHash: id, stamp: ChannelFreeRowAttempts.stamp(activity)) } else if let rowAttemptId = Self.channelFreeRowAttempts.attemptId(forPaymentHash: id), @@ -1471,7 +1480,12 @@ class ActivityService { Self.channelFreeRowAttempts.forget(paymentHash: id) } activity.status = .failed - try updateActivity(activityId: id, activity: .lightning(activity)) + do { + try updateActivity(activityId: id, activity: .lightning(activity)) + } catch { + Self.channelFreeRowAttempts.restore(previousWriter, forPaymentHash: id) + throw error + } self.activitiesChangedSubject.send() } } @@ -2924,6 +2938,24 @@ struct ChannelFreeRowAttempts: @unchecked Sendable { } } + /// The kept `[hash, id, stamp]` of the row of `paymentHash`, to put back with `restore`. + func entry(forPaymentHash paymentHash: String) -> [String]? { + let hash = paymentHash.lowercased() + return (defaults.array(forKey: Self.key) as? [[String]])?.last { $0.first == hash } + } + + func restore(_ entry: [String]?, forPaymentHash paymentHash: String) { + let hash = paymentHash.lowercased() + Self.lock.withLock { + var entries = defaults.array(forKey: Self.key) as? [[String]] ?? [] + entries.removeAll { $0.first == hash } + if let entry { + entries.append(entry) + } + defaults.set(Array(entries.suffix(Self.limit)), forKey: Self.key) + } + } + /// Whether `row` is as its writer left it. func isUnchanged(_ row: LightningActivity, forPaymentHash paymentHash: String) -> Bool { let hash = paymentHash.lowercased() diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index 41274e946a..3b74a823d0 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -173,6 +173,13 @@ final class SparkRelaunchActivityTests: XCTestCase { attempts.remember("id\(index)", forPaymentHash: "hash\(index)", stamp: "1:2:3") } attempts.remember("newer", forPaymentHash: "HASH1", stamp: "1:2:3") + // A failed row write puts the writer before it back, or removes the one it added. + let before = attempts.entry(forPaymentHash: "hash1") + attempts.remember("failed-write", forPaymentHash: "hash1", stamp: "4:5:6") + attempts.restore(before, forPaymentHash: "hash1") + attempts.remember("unwritten", forPaymentHash: "fresh", stamp: "1:2:3") + attempts.restore(nil, forPaymentHash: "fresh") + XCTAssertNil(attempts.attemptId(forPaymentHash: "fresh")) XCTAssertNil(attempts.attemptId(forPaymentHash: "hash0")) XCTAssertEqual(attempts.attemptId(forPaymentHash: "hash1"), "newer") From bc928fe841ae28b423e52726a91d79613dfeacd0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 05:28:08 +0100 Subject: [PATCH 37/64] fix: a spark row resolves to its writer after a stop A writer kept ahead of its row now keeps the previous writer and its stamp beside it until the row is saved. A row that still matches the previous stamp and not the kept one resolves to the previous writer, so after a stop between the two the earlier payment's final fee still lands. Verified: full unit suite on the iOS simulator --- Bitkit/Services/CoreService.swift | 76 +++++++++++++++----- BitkitTests/SparkRelaunchActivityTests.swift | 23 ++++++ 2 files changed, 83 insertions(+), 16 deletions(-) diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index cc4d8bc6fa..343abfde33 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1031,11 +1031,11 @@ class ActivityService { && (railPaymentId == nil || railPaymentId != LightningService.shared.heldRailSendId(paymentHash: payment.id)) && (paymentTimestamp < existing.timestamp || paymentTimestamp == existing.timestamp && Self.isOtherRowAttempt( railPaymentId, - rowAttemptId: Self.channelFreeRowAttempts.attemptId(forPaymentHash: payment.id), + rowAttemptId: Self.channelFreeRowAttempts.attemptId(forPaymentHash: payment.id, row: existing), earlierAttemptIds: LightningService.shared.railSendEarlierAttemptIds[payment.id.lowercased()] ) || Self.isKnownEarlierAttempt( railPaymentId, - rowAttemptId: Self.channelFreeRowAttempts.attemptId(forPaymentHash: payment.id), + rowAttemptId: Self.channelFreeRowAttempts.attemptId(forPaymentHash: payment.id, row: existing), keptEarlierAttemptIds: LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: payment.id) )) ) @@ -1094,12 +1094,26 @@ class ActivityService { // The writer is kept before the row is written, so a stop between the two never leaves the row to an earlier // writer, and put back when the write fails. let previousWriter = Self.channelFreeRowAttempts.entry(forPaymentHash: payment.id) - if rail == .channelFree, payment.direction == .outbound, let railPaymentId { - Self.channelFreeRowAttempts.remember(railPaymentId, forPaymentHash: payment.id, stamp: ChannelFreeRowAttempts.stamp(ln)) + let isWriterKept = rail == .channelFree && payment.direction == .outbound && railPaymentId != nil + if isWriterKept, let railPaymentId { + let previousRow: LightningActivity? = if case let .lightning(latest)? = latestActivity { + latest + } else { + nil + } + Self.channelFreeRowAttempts.remember( + railPaymentId, + forPaymentHash: payment.id, + stamp: ChannelFreeRowAttempts.stamp(ln), + previousRowStamp: previousRow.map(ChannelFreeRowAttempts.stamp) + ) } do { guard let latestActivity else { try upsertActivity(activity: .lightning(ln)) + if isWriterKept { + Self.channelFreeRowAttempts.commit(forPaymentHash: payment.id) + } self.updateBoostTxIdsCache(for: .lightning(ln)) self.activitiesChangedSubject.send() return @@ -1112,6 +1126,9 @@ class ActivityService { updated.contact = nil } try updateActivity(activityId: payment.id, activity: .lightning(updated)) + if isWriterKept { + Self.channelFreeRowAttempts.commit(forPaymentHash: payment.id) + } self.activitiesChangedSubject.send() } catch { Self.channelFreeRowAttempts.restore(previousWriter, forPaymentHash: payment.id) @@ -1470,8 +1487,9 @@ class ActivityService { else { return } let previousWriter = Self.channelFreeRowAttempts.entry(forPaymentHash: id) if let ownAttemptId { - Self.channelFreeRowAttempts.remember(ownAttemptId, forPaymentHash: id, stamp: ChannelFreeRowAttempts.stamp(activity)) - } else if let rowAttemptId = Self.channelFreeRowAttempts.attemptId(forPaymentHash: id), + let stamp = ChannelFreeRowAttempts.stamp(activity) + Self.channelFreeRowAttempts.remember(ownAttemptId, forPaymentHash: id, stamp: stamp, previousRowStamp: stamp) + } else if let rowAttemptId = Self.channelFreeRowAttempts.attemptId(forPaymentHash: id, row: activity), earlierAttemptIds.contains(rowAttemptId), !Self.channelFreeRowAttempts.isUnchanged(activity, forPaymentHash: id) { @@ -1482,6 +1500,7 @@ class ActivityService { activity.status = .failed do { try updateActivity(activityId: id, activity: .lightning(activity)) + Self.channelFreeRowAttempts.commit(forPaymentHash: id) } catch { Self.channelFreeRowAttempts.restore(previousWriter, forPaymentHash: id) throw error @@ -2926,19 +2945,47 @@ struct ChannelFreeRowAttempts: @unchecked Sendable { "\(row.timestamp):\(row.value):\(row.fee ?? 0)" } - func remember(_ attemptId: String, forPaymentHash paymentHash: String, stamp: String) { + /// Kept ahead of the row it writes, beside the previous writer and its stamp (none: an empty id and the row's stamp + /// then), until `commit` once the row is saved, so a stop in between still finds the row's real writer. + func remember(_ attemptId: String, forPaymentHash paymentHash: String, stamp: String, previousRowStamp: String? = nil) { let hash = paymentHash.lowercased() - let entry = [hash, attemptId, stamp] Self.lock.withLock { var entries = defaults.array(forKey: Self.key) as? [[String]] ?? [] - guard entries.last(where: { $0.first == hash }) != entry else { return } + let previous = entries.last { $0.first == hash } + let entry = if let previous, previous.count >= 3 { + [hash, attemptId, stamp, previous[1], previous[2]] + } else { + [hash, attemptId, stamp, "", previousRowStamp ?? ""] + } + guard previous != entry, previous.map({ Array($0.prefix(3)) }) != [hash, attemptId, stamp] else { return } entries.removeAll { $0.first == hash } entries.append(entry) defaults.set(Array(entries.suffix(Self.limit)), forKey: Self.key) } } - /// The kept `[hash, id, stamp]` of the row of `paymentHash`, to put back with `restore`. + /// The row is saved: its writer no longer needs the previous one beside it. + func commit(forPaymentHash paymentHash: String) { + let hash = paymentHash.lowercased() + Self.lock.withLock { + guard var entries = defaults.array(forKey: Self.key) as? [[String]], + let index = entries.lastIndex(where: { $0.first == hash }), entries[index].count > 3 + else { return } + entries[index] = Array(entries[index].prefix(3)) + defaults.set(entries, forKey: Self.key) + } + } + + /// The writer of `row`: the kept one, unless `row` still matches the previous writer's stamp and not the kept one's. + private func writer(forPaymentHash paymentHash: String, row: LightningActivity?) -> (id: String, stamp: String)? { + guard let entry = entry(forPaymentHash: paymentHash), entry.count >= 3 else { return nil } + if entry.count == 5, let row, Self.stamp(row) != entry[2], Self.stamp(row) == entry[4] { + return entry[3].isEmpty ? nil : (entry[3], entry[4]) + } + return (entry[1], entry[2]) + } + + /// The kept entry of the row of `paymentHash`, to put back with `restore`. func entry(forPaymentHash paymentHash: String) -> [String]? { let hash = paymentHash.lowercased() return (defaults.array(forKey: Self.key) as? [[String]])?.last { $0.first == hash } @@ -2958,9 +3005,7 @@ struct ChannelFreeRowAttempts: @unchecked Sendable { /// Whether `row` is as its writer left it. func isUnchanged(_ row: LightningActivity, forPaymentHash paymentHash: String) -> Bool { - let hash = paymentHash.lowercased() - let entry = (defaults.array(forKey: Self.key) as? [[String]])?.last { $0.first == hash } - return entry?.count == 3 && entry?[2] == Self.stamp(row) + writer(forPaymentHash: paymentHash, row: row)?.stamp == Self.stamp(row) } func forget(paymentHash: String) { @@ -2972,8 +3017,7 @@ struct ChannelFreeRowAttempts: @unchecked Sendable { } } - func attemptId(forPaymentHash paymentHash: String) -> String? { - let hash = paymentHash.lowercased() - return (defaults.array(forKey: Self.key) as? [[String]])?.last { $0.count >= 2 && $0[0] == hash }?[1] + func attemptId(forPaymentHash paymentHash: String, row: LightningActivity? = nil) -> String? { + writer(forPaymentHash: paymentHash, row: row)?.id } } diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index 3b74a823d0..cfcec0598b 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -247,4 +247,27 @@ final class SparkRelaunchActivityTests: XCTestCase { try await CoreService.shared.activity.failPendingLightningSend(id: overwritten, earlierAttemptIds: ["earlier"]) XCTAssertNil(ActivityService.channelFreeRowAttempts.attemptId(forPaymentHash: overwritten)) } + + func testAStopBetweenKeepingAWriterAndSavingItsRowLeavesTheRowToItsRealWriter() async throws { + let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "ed", count: 16) + let pending = PaymentDetails( + id: hash, + kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), + amountMsat: 500_000, feePaidMsat: 0, direction: .outbound, status: .pending, latestUpdateTimestamp: 200 + ) + try await CoreService.shared.activity.recordChannelFreeRailPayment(pending, railPaymentId: "earlier") + guard case let .lightning(row)? = try await CoreService.shared.activity.getActivity(id: hash) else { + return XCTFail("the earlier payment's row is missing") + } + let attempts = ActivityService.channelFreeRowAttempts + // The retry's writer was kept, then the app stopped before its row was saved. + attempts.remember("retry", forPaymentHash: hash, stamp: "300:700:0", previousRowStamp: ChannelFreeRowAttempts.stamp(row)) + XCTAssertEqual(attempts.attemptId(forPaymentHash: hash, row: row), "earlier") + XCTAssertTrue(attempts.isUnchanged(row, forPaymentHash: hash)) + + // Once the retry's row is saved, it is the retry's. + attempts.commit(forPaymentHash: hash) + XCTAssertEqual(attempts.attemptId(forPaymentHash: hash, row: row), "retry") + XCTAssertFalse(attempts.isUnchanged(row, forPaymentHash: hash)) + } } From c67bb228150d230aa60e6280ed25bb84e7e82ab3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 11:51:29 +0100 Subject: [PATCH 38/64] fix: spark keeps a retried send's row writer The row-writer cap drops writers of sends with no kept earlier attempts first, so a retried send keeps its writer while its earlier attempt ids are kept. Verified: BitkitTests pass, including the new retried-send writer test. --- Bitkit/Services/CoreService.swift | 16 +++++++++++++--- Bitkit/Services/LightningService.swift | 2 +- BitkitTests/SparkRelaunchActivityTests.swift | 18 ++++++++++++++++++ 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 343abfde33..efbb40d869 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -2933,7 +2933,7 @@ struct SentPaymentContacts: @unchecked Sendable { } } -/// Kept as `[hash, id]` pairs, oldest first, for the latest `limit` hashes. +/// Kept as `[hash, id]` pairs, oldest first, for the latest `limit` hashes and those of sends with kept earlier attempts. struct ChannelFreeRowAttempts: @unchecked Sendable { private static let key = "channelFreeRowAttemptIds" private static let lock = NSLock() @@ -2960,7 +2960,7 @@ struct ChannelFreeRowAttempts: @unchecked Sendable { guard previous != entry, previous.map({ Array($0.prefix(3)) }) != [hash, attemptId, stamp] else { return } entries.removeAll { $0.first == hash } entries.append(entry) - defaults.set(Array(entries.suffix(Self.limit)), forKey: Self.key) + defaults.set(capped(entries), forKey: Self.key) } } @@ -2999,10 +2999,20 @@ struct ChannelFreeRowAttempts: @unchecked Sendable { if let entry { entries.append(entry) } - defaults.set(Array(entries.suffix(Self.limit)), forKey: Self.key) + defaults.set(capped(entries), forKey: Self.key) } } + /// Drops the oldest writers past `limit`, keeping those of retried sends while their earlier attempts are kept. + private func capped(_ entries: [[String]]) -> [[String]] { + let excess = entries.count - Self.limit + guard excess > 0 else { return entries } + let kept = defaults.array(forKey: LightningService.keptRailSendEarlierAttemptsKey) as? [[String]] ?? [] + let retried = Set(kept.compactMap(\.first)) + let dropped = Set(entries.compactMap(\.first).filter { !retried.contains($0) }.prefix(excess)) + return entries.filter { !dropped.contains($0.first ?? "") } + } + /// Whether `row` is as its writer left it. func isUnchanged(_ row: LightningActivity, forPaymentHash paymentHash: String) -> Bool { writer(forPaymentHash: paymentHash, row: row)?.stamp == Self.stamp(row) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 200210404f..3e6fa0aca6 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1255,7 +1255,7 @@ class LightningService: NodeLifecycleService { private static let uncertainRailSendsEarlierAttemptsKey = "channelFreeRailUncertainSendEarlierAttempts" /// The rail's ids of the attempts each send followed, kept past its hold as `[hash, ids…]` for the latest /// `keptEarlierAttemptsLimit` hashes, so a failure of one never writes over the send's own row after a restart. - private static let keptRailSendEarlierAttemptsKey = "channelFreeRailKeptSendEarlierAttempts" + static let keptRailSendEarlierAttemptsKey = "channelFreeRailKeptSendEarlierAttempts" static let keptEarlierAttemptsLimit = 100 /// The rail's id of each send Spark took, by hash, until it settles: any other attempt's failure is an earlier one's. private static let takenRailSendsKey = "channelFreeRailTakenSendIds" diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index cfcec0598b..76be45aafe 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -186,6 +186,24 @@ final class SparkRelaunchActivityTests: XCTestCase { XCTAssertEqual(attempts.attemptId(forPaymentHash: "hash\(ChannelFreeRowAttempts.limit)"), "id\(ChannelFreeRowAttempts.limit)") } + func testChannelFreeRowAttemptsKeepARetriedSendsWriterPastTheLatestSends() throws { + let suite = "ChannelFreeRowAttemptsTests-\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + defaults.set([["retried", "earlier"]], forKey: LightningService.keptRailSendEarlierAttemptsKey) + let attempts = ChannelFreeRowAttempts(defaults: defaults) + attempts.remember("original", forPaymentHash: "retried", stamp: "1:2:3") + attempts.remember("id", forPaymentHash: "plain", stamp: "1:2:3") + for index in 0 ..< ChannelFreeRowAttempts.limit { + attempts.remember("id\(index)", forPaymentHash: "later\(index)", stamp: "1:2:3") + } + + XCTAssertEqual(attempts.entry(forPaymentHash: "retried"), ["retried", "original", "1:2:3", "", ""]) + XCTAssertNil(attempts.entry(forPaymentHash: "plain")) + XCTAssertNil(attempts.entry(forPaymentHash: "later0")) + XCTAssertEqual((defaults.array(forKey: "channelFreeRowAttemptIds") as? [[String]])?.count, ChannelFreeRowAttempts.limit) + } + func testASameSecondFailureTakesTheRowOnlyAsTheSendAfterTheRowsAttempt() { // The row's own attempt, and a row or failure without an id, write it. XCTAssertFalse(ActivityService.isOtherRowAttempt("first", rowAttemptId: "first")) From 48d866213253181345ef40f9c650db4ce65b9723 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 12:22:17 +0100 Subject: [PATCH 39/64] fix: spark caps row writers of plain sends only The row-writer cap keeps the latest 100 writers of sends without kept earlier attempts, so a new send's writer is never dropped at once when retried sends fill the store; retried sends stay bounded by their earlier attempts' own cap. Verified: BitkitTests pass, including the new full-store writer test. --- Bitkit/Services/CoreService.swift | 8 ++++---- BitkitTests/SparkRelaunchActivityTests.swift | 20 ++++++++++++++++++-- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index efbb40d869..53414403e4 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -3003,13 +3003,13 @@ struct ChannelFreeRowAttempts: @unchecked Sendable { } } - /// Drops the oldest writers past `limit`, keeping those of retried sends while their earlier attempts are kept. + /// Keeps the latest `limit` writers of sends without kept earlier attempts, and those of retried sends, which the + /// earlier attempts' own cap bounds. private func capped(_ entries: [[String]]) -> [[String]] { - let excess = entries.count - Self.limit - guard excess > 0 else { return entries } + guard entries.count > Self.limit else { return entries } let kept = defaults.array(forKey: LightningService.keptRailSendEarlierAttemptsKey) as? [[String]] ?? [] let retried = Set(kept.compactMap(\.first)) - let dropped = Set(entries.compactMap(\.first).filter { !retried.contains($0) }.prefix(excess)) + let dropped = Set(entries.compactMap(\.first).filter { !retried.contains($0) }.dropLast(Self.limit)) return entries.filter { !dropped.contains($0.first ?? "") } } diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index 76be45aafe..f4702fda2a 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -200,8 +200,24 @@ final class SparkRelaunchActivityTests: XCTestCase { XCTAssertEqual(attempts.entry(forPaymentHash: "retried"), ["retried", "original", "1:2:3", "", ""]) XCTAssertNil(attempts.entry(forPaymentHash: "plain")) - XCTAssertNil(attempts.entry(forPaymentHash: "later0")) - XCTAssertEqual((defaults.array(forKey: "channelFreeRowAttemptIds") as? [[String]])?.count, ChannelFreeRowAttempts.limit) + XCTAssertEqual(attempts.attemptId(forPaymentHash: "later0"), "id0") + XCTAssertEqual((defaults.array(forKey: "channelFreeRowAttemptIds") as? [[String]])?.count, ChannelFreeRowAttempts.limit + 1) + } + + func testChannelFreeRowAttemptsKeepANewSendsWriterBesideAFullSetOfRetriedSends() throws { + let suite = "ChannelFreeRowAttemptsTests-\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let retried = (0 ..< ChannelFreeRowAttempts.limit).map { "retried\($0)" } + defaults.set(retried.map { [$0, "earlier"] }, forKey: LightningService.keptRailSendEarlierAttemptsKey) + let attempts = ChannelFreeRowAttempts(defaults: defaults) + for hash in retried { + attempts.remember("id", forPaymentHash: hash, stamp: "1:2:3") + } + attempts.remember("new", forPaymentHash: "plain", stamp: "1:2:3") + + XCTAssertEqual(attempts.attemptId(forPaymentHash: "plain"), "new") + XCTAssertEqual(attempts.attemptId(forPaymentHash: "retried0"), "id") } func testASameSecondFailureTakesTheRowOnlyAsTheSendAfterTheRowsAttempt() { From 254d8ce36c600f759d09ae809671755abb77b708 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 14:52:33 +0100 Subject: [PATCH 40/64] fix: spark expiry sweeps queue the row update first Both expiry sweeps now queue the Activity update before clearing the hold, so a stop in between can't strand the send in Pending. The queued failed-row retry of an unlisted taken send keeps the taken attempt's id, and the taken-send sweep fails the row only when its identity check ends the hold. Verified: BitkitTests pass; the taken-retry expiry test checks the retried write keeps the attempt id. --- Bitkit/Services/LightningService.swift | 36 ++++++++++++++++---------- BitkitTests/ChannelFreeRailTests.swift | 8 +++++- 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 3e6fa0aca6..00d55b136a 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1259,8 +1259,9 @@ class LightningService: NodeLifecycleService { static let keptEarlierAttemptsLimit = 100 /// The rail's id of each send Spark took, by hash, until it settles: any other attempt's failure is an earlier one's. private static let takenRailSendsKey = "channelFreeRailTakenSendIds" - /// Hashes of taken sends Spark never listed whose hold ended before their row was failed, retried on each rail sync. - private static let unlistedTakenRailSendsUnfailedKey = "channelFreeRailUnlistedTakenSendsUnfailed" + /// Taken sends Spark never listed whose hold ended before their row was failed, with the attempt each took, by hash, + /// retried on each rail sync. + private static let unlistedTakenRailSendsUnfailedKey = "channelFreeRailUnlistedTakenSendsUnfailedIds" /// Hashes whose hold ended at their invoice's expiry before their activity was saved, retried on each rail sync. private static let expiredRailHoldsUnrecordedKey = "channelFreeRailExpiredHoldsUnrecorded" /// A listing drops the hashes it shows failed only, or paid once the invoice has expired, so the other rail can't @@ -1937,10 +1938,10 @@ class LightningService: NodeLifecycleService { return false } eventCallbackLock.withLock { - clearRailSendUncertainty(hash: hash) var unrecorded = Set(railAttemptsStore.stringArray(forKey: Self.expiredRailHoldsUnrecordedKey) ?? []) unrecorded.insert(hash) railAttemptsStore.set(Array(unrecorded), forKey: Self.expiredRailHoldsUnrecordedKey) + clearRailSendUncertainty(hash: hash) } await recordExpiredRailHold(hash) return true @@ -1969,9 +1970,9 @@ class LightningService: NodeLifecycleService { /// their stored Activity row, as an earlier attempt's row would bring its own amount and fee. A send Spark lists is /// left to its own outcome. private func endExpiredUnlistedTakenRailSends() async { - let unfailed = eventCallbackLock.withLock { railAttemptsStore.stringArray(forKey: Self.unlistedTakenRailSendsUnfailedKey) ?? [] } - for hash in unfailed { - await failUnlistedTakenRailSend(hash) + let unfailed = eventCallbackLock.withLock { unlistedTakenRailSendsUnfailed() } + for (hash, ownAttemptId) in unfailed { + await failUnlistedTakenRailSend(hash, ownAttemptId: ownAttemptId.isEmpty ? nil : ownAttemptId) } let nowSeconds = Int(now().timeIntervalSince1970) let (expired, taken, earlier) = eventCallbackLock.withLock { @@ -2003,16 +2004,18 @@ class LightningService: NodeLifecycleService { && !(payment.id.map { Self.isEarlierRailAttempt(id: $0, hash: hash, taken: taken, earlier: earlier) } ?? false) } guard !isListed else { continue } - eventCallbackLock.withLock { + let isEnded = eventCallbackLock.withLock { // Left alone if a new send of the invoice started meanwhile. guard takenRailSendIds()[hash] == taken[hash], uncertainRailSendEarlierAttempts()[hash] == earlier[hash], - uncertainRailSendFailedAt()[hash] == nil else { return } + uncertainRailSendFailedAt()[hash] == nil else { return false } + var unfailed = unlistedTakenRailSendsUnfailed() + unfailed[hash] = taken[hash] ?? "" + railAttemptsStore.set(unfailed, forKey: Self.unlistedTakenRailSendsUnfailedKey) clearRailSendUncertainty(hash: hash) removeAttempt(paymentHash: hash, key: Self.railAttemptsKey) - var unfailed = Set(railAttemptsStore.stringArray(forKey: Self.unlistedTakenRailSendsUnfailedKey) ?? []) - unfailed.insert(hash) - railAttemptsStore.set(Array(unfailed), forKey: Self.unlistedTakenRailSendsUnfailedKey) + return true } + guard isEnded else { continue } await failUnlistedTakenRailSend(hash, ownAttemptId: taken[hash]) } } @@ -2020,11 +2023,18 @@ class LightningService: NodeLifecycleService { private func failUnlistedTakenRailSend(_ hash: String, ownAttemptId: String? = nil) async { guard let fail = railTakenSendUnlisted, await fail(hash, ownAttemptId) else { return } eventCallbackLock.withLock { - let unfailed = railAttemptsStore.stringArray(forKey: Self.unlistedTakenRailSendsUnfailedKey) ?? [] - railAttemptsStore.set(unfailed.filter { $0 != hash }, forKey: Self.unlistedTakenRailSendsUnfailedKey) + var unfailed = unlistedTakenRailSendsUnfailed() + unfailed.removeValue(forKey: hash) + railAttemptsStore.set(unfailed, forKey: Self.unlistedTakenRailSendsUnfailedKey) } } + /// Sends whose hold ended but whose Activity row isn't failed yet, each with Spark's id of the attempt it took (empty + /// when none). Callers hold `eventCallbackLock`. + private func unlistedTakenRailSendsUnfailed() -> [String: String] { + railAttemptsStore.dictionary(forKey: Self.unlistedTakenRailSendsUnfailedKey) as? [String: String] ?? [:] + } + private func recordExpiredRailHold(_ hash: String) async { guard let record = railSendHoldExpired, await record(hash) else { return } eventCallbackLock.withLock { diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 5a1834b1c7..5b83789bab 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1043,6 +1043,7 @@ extension ChannelFreeRailTests { rail.balanceSats = 0 var replayed: [String] = [] var failed: [String] = [] + var failedAttemptIds: [String?] = [] var saves = false let previousHook = service.railSendHoldExpired let previousUnlisted = service.railTakenSendUnlisted @@ -1051,7 +1052,11 @@ extension ChannelFreeRailTests { service.railTakenSendUnlisted = previousUnlisted } service.railSendHoldExpired = { replayed.append($0); return true } - service.railTakenSendUnlisted = { hash, _ in failed.append(hash); return saves } + service.railTakenSendUnlisted = { hash, ownAttemptId in + failed.append(hash) + failedAttemptIds.append(ownAttemptId) + return saves + } let expiresAt = invoice.secondsSinceEpoch() + invoice.expiryTimeSeconds() let graceEnds = expiresAt + UInt64(Bitkit.LightningService.unlistedRailSendGraceSeconds) @@ -1088,6 +1093,7 @@ extension ChannelFreeRailTests { saves = true await service.endExpiredRailSendUncertainties() XCTAssertEqual(failed, [hash, hash], "a row that failed to save wasn't retried") + XCTAssertEqual(failedAttemptIds, ["retry", "retry"], "the retried write lost the taken attempt's id") await service.endExpiredRailSendUncertainties() XCTAssertEqual(failed, [hash, hash], "a saved row was failed again") XCTAssertEqual(replayed, [], "the earlier attempt's row replaced the retry's") From c877bfbbc395d0b1e39fa6586c41578ec934a873 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 15:05:33 +0100 Subject: [PATCH 41/64] fix: spark reads a held send as pending Paykit's proof lookup, QuickPay reconcile and the send watcher read a held Spark send as pending while Spark lists only its earlier failed attempts or nothing, until its hold ends past the invoice's expiry. A row's writer stamp now carries its status, so a failed row and a pending retry alike in time, amount and fee are told apart. Verified: BitkitTests pass, including the new held-send status test. --- Bitkit/Services/CoreService.swift | 19 ++++++++----- Bitkit/Services/LightningService.swift | 26 ++++++++++++++++++ .../Services/PaykitPaymentProofService.swift | 6 ++--- .../QuickPayPaymentCoordinator.swift | 2 +- Bitkit/ViewModels/WalletViewModel.swift | 2 +- BitkitTests/ChannelFreeRailTests.swift | 27 +++++++++++++++++++ 6 files changed, 70 insertions(+), 12 deletions(-) diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 53414403e4..9b2e9941da 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1482,13 +1482,19 @@ class ActivityService { /// `earlierAttemptIds`. Saved before the row fails, so a stop in between finds the row pending and redoes both. func failPendingLightningSend(id: String, ownAttemptId: String? = nil, earlierAttemptIds: Set = []) async throws { try await ServiceQueue.background(.core) { - guard case var .lightning(activity) = try getActivityById(walletId: WalletScope.default, activityId: id), + guard case let .lightning(activity) = try getActivityById(walletId: WalletScope.default, activityId: id), activity.txType == .sent, activity.status == .pending else { return } let previousWriter = Self.channelFreeRowAttempts.entry(forPaymentHash: id) + var failed = activity + failed.status = .failed if let ownAttemptId { - let stamp = ChannelFreeRowAttempts.stamp(activity) - Self.channelFreeRowAttempts.remember(ownAttemptId, forPaymentHash: id, stamp: stamp, previousRowStamp: stamp) + Self.channelFreeRowAttempts.remember( + ownAttemptId, + forPaymentHash: id, + stamp: ChannelFreeRowAttempts.stamp(failed), + previousRowStamp: ChannelFreeRowAttempts.stamp(activity) + ) } else if let rowAttemptId = Self.channelFreeRowAttempts.attemptId(forPaymentHash: id, row: activity), earlierAttemptIds.contains(rowAttemptId), !Self.channelFreeRowAttempts.isUnchanged(activity, forPaymentHash: id) @@ -1497,9 +1503,8 @@ class ActivityService { // that attempt's final fee still lands. Self.channelFreeRowAttempts.forget(paymentHash: id) } - activity.status = .failed do { - try updateActivity(activityId: id, activity: .lightning(activity)) + try updateActivity(activityId: id, activity: .lightning(failed)) Self.channelFreeRowAttempts.commit(forPaymentHash: id) } catch { Self.channelFreeRowAttempts.restore(previousWriter, forPaymentHash: id) @@ -2940,9 +2945,9 @@ struct ChannelFreeRowAttempts: @unchecked Sendable { static let limit = 100 let defaults: UserDefaults - /// The row as its writer left it, so a later write by another payment shows. + /// The row as its writer left it, so a later write by another payment shows, even one alike but for its status. static func stamp(_ row: LightningActivity) -> String { - "\(row.timestamp):\(row.value):\(row.fee ?? 0)" + "\(row.timestamp):\(row.value):\(row.fee ?? 0):\(row.status)" } /// Kept ahead of the row it writes, beside the previous writer and its stamp (none: an empty id and the row's stamp diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 00d55b136a..c68f6482ac 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1815,6 +1815,32 @@ class LightningService: NodeLifecycleService { } /// Spark's id of the taken send that still holds the invoice of `paymentHash`, if any. + /// Spark's payments as the app's status lookups read them: a send still held reads as pending while Spark lists none + /// of its own attempts, only earlier failed ones or nothing, until its hold ends past the invoice's expiry. + func channelFreeRailSendStatuses() async throws -> [ChannelFreeRailPayment] { + try await withHeldRailSends(channelFreeRailPayments()) + } + + func withHeldRailSends(_ payments: [ChannelFreeRailPayment]) -> [ChannelFreeRailPayment] { + eventCallbackLock.withLock { + let held = Set(takenRailSendIds().keys).union(uncertainRailSendEarlierAttempts().keys).union(uncertainRailSendFailedAt().keys) + guard !held.isEmpty else { return payments } + var statuses = payments.filter { payment in + let hash = payment.paymentHash.lowercased() + return !(payment.direction == .outbound && payment.status == .failed && held.contains(hash) + && isEarlierThanUncertainRailSendLocked(hash: hash, createdAt: payment.timestamp, paymentId: payment.id)) + } + let listed = Set(statuses.filter { $0.direction == .outbound }.map { $0.paymentHash.lowercased() }) + for hash in held.subtracting(listed).sorted() { + statuses.append(ChannelFreeRailPayment( + paymentHash: hash, direction: .outbound, status: .pending, preimage: nil, + timestamp: UInt64(max(0, now().timeIntervalSince1970)), id: takenRailSendIds()[hash] + )) + } + return statuses + } + } + func heldRailSendId(paymentHash: String) -> String? { eventCallbackLock.withLock { takenRailSendIds()[paymentHash.lowercased()] } } diff --git a/Bitkit/Services/PaykitPaymentProofService.swift b/Bitkit/Services/PaykitPaymentProofService.swift index 2065c5c3f9..0922ec2975 100644 --- a/Bitkit/Services/PaykitPaymentProofService.swift +++ b/Bitkit/Services/PaykitPaymentProofService.swift @@ -308,10 +308,10 @@ struct PaykitLightningPaymentProofLookup: PaykitLightningPaymentProofLookingUp { } } - /// Spark payments are not in LDK's list, so a proof whose completion event was missed settles from Spark's own record. - /// Unavailable while Spark can't list its payments. + /// Spark payments are not in LDK's list, so a proof whose completion event was missed settles from Spark's own record, + /// with a send still held read as pending. Unavailable while Spark can't list its payments. static func railStatus(paymentHash: String) async -> PaykitLightningPaymentProofStatus { - guard let payments = try? await LightningService.shared.channelFreeRailPayments() else { + guard let payments = try? await LightningService.shared.channelFreeRailSendStatuses() else { return .unavailable } guard let payment = ChannelFreeRailPayment.latestOutboundAttempt(payments, paymentHash: paymentHash) else { diff --git a/Bitkit/Utilities/QuickPayPaymentCoordinator.swift b/Bitkit/Utilities/QuickPayPaymentCoordinator.swift index 5a4351d7dc..da5fd5bad4 100644 --- a/Bitkit/Utilities/QuickPayPaymentCoordinator.swift +++ b/Bitkit/Utilities/QuickPayPaymentCoordinator.swift @@ -70,7 +70,7 @@ final class QuickPayPaymentCoordinator { } self.listRows = listRows ?? { try await Self.reconcileRows( - railPayments: { try await LightningService.shared.channelFreeRailPayments() }, + railPayments: { try await LightningService.shared.channelFreeRailSendStatuses() }, nodePayments: { await LightningService.shared.listPayments() } ) } diff --git a/Bitkit/ViewModels/WalletViewModel.swift b/Bitkit/ViewModels/WalletViewModel.swift index 8cc8b4c539..755c9039b7 100644 --- a/Bitkit/ViewModels/WalletViewModel.swift +++ b/Bitkit/ViewModels/WalletViewModel.swift @@ -1373,7 +1373,7 @@ class WalletViewModel: ObservableObject { } // A retry over a channel settles from LDK; an earlier Spark attempt's outcome doesn't decide it. guard lightningService.attemptRail(paymentHash: hash) != .ldk else { return } - let payments = await (try? lightningService.channelFreeRailPayments()) ?? [] + let payments = await (try? lightningService.channelFreeRailSendStatuses()) ?? [] let payment = ChannelFreeRailPayment.latestOutboundAttempt(payments, paymentHash: hash) switch payment?.status { case .succeeded: diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 5b83789bab..07e7a23928 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1099,6 +1099,33 @@ extension ChannelFreeRailTests { XCTAssertEqual(replayed, [], "the earlier attempt's row replaced the retry's") } + func testAHeldTakenRetryReadsPendingWhileSparkListsOnlyAnEarlierFailure() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + let earlier = Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier") + let other = Bitkit.ChannelFreeRailPayment(paymentHash: "other", direction: .outbound, status: .failed, preimage: nil, id: "o") + rail.payments = [earlier] + rail.balanceSats = 100_000 + rail.sentPaymentId = "retry" + _ = try await service.send(bolt11: Self.invoice) + + // Spark lists only the earlier failure, or nothing: the retry it took reads as pending, and other sends as they are. + for listed in [[earlier, other], [other]] { + let statuses = service.withHeldRailSends(listed) + let send = Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(statuses, paymentHash: hash) + XCTAssertEqual(send?.status, .pending) + XCTAssertEqual(send?.id, "retry") + XCTAssertFalse(statuses.contains(earlier)) + XCTAssertTrue(statuses.contains(other)) + } + + // Spark listing the retry's own outcome decides it. + let failedRetry = Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "retry") + let statuses = service.withHeldRailSends([earlier, failedRetry]) + XCTAssertEqual(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(statuses, paymentHash: hash), failedRetry) + } + func testAnOlderAttemptMissingFromTheListBeforeASendInDoubtKeepsItsHold() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared From 5d2569e980167202aea7410b403a98aa5cdccc0e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 16:07:33 +0100 Subject: [PATCH 42/64] fix: spark ends a hold with its attempt record A listing that shows a held send's own outcome ends its hold together with its attempt record and expiry, and an earlier attempt's failure no longer settles it. An outcome delivered before the send returns leaves no hold behind. Verified: BitkitTests pass, including new hold-ending and early-outcome tests. --- Bitkit/Services/LightningService.swift | 27 +++++++++++-- BitkitTests/ChannelFreeRailTests.swift | 56 ++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 3 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index c68f6482ac..4c37a38646 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1401,7 +1401,9 @@ class LightningService: NodeLifecycleService { if let mark, attemptsLive(since: mark, key: Self.railAttemptsKey).contains(hash) { return } + // The send's own outcome is known: its hold ends with the expiry the sweep would have ended it by. removeAttempt(paymentHash: hash, key: Self.railAttemptsKey) + clearRailSendUncertainty(hash: hash) } } @@ -1519,12 +1521,29 @@ class LightningService: NodeLifecycleService { let outbound = payments.filter { $0.direction == .outbound } let hashes = { (status: PaymentStatus) in Set(outbound.filter { $0.status == status }.map { $0.paymentHash.lowercased() }) } return eventCallbackLock.withLock { + // A held send's earlier attempts settle nothing: only its own failure, or any payment of the invoice, does. + let taken = takenRailSendIds() + let earlier = uncertainRailSendEarlierAttempts() + let held = Set(taken.keys).union(earlier.keys) + let ownFailed = Set(outbound.filter { payment in + let hash = payment.paymentHash.lowercased() + guard payment.status == .failed else { return false } + guard let id = payment.id else { return true } + return !Self.isEarlierRailAttempt(id: id, hash: hash, taken: taken, earlier: earlier) + }.map { $0.paymentHash.lowercased() }) let live = hashes(.pending).union(attemptsLive(since: mark, key: Self.railAttemptsKey)) + .union(held.subtracting(ownFailed).subtracting(hashes(.succeeded))) let paid = hashes(.succeeded).subtracting(live) let listed = Set(outbound.map { $0.paymentHash.lowercased() }) + let before = Set(railAttemptsStore.stringArray(forKey: Self.railAttemptsKey) ?? []) trimSettledAttempts( - paid: paid, failed: hashes(.failed).subtracting(paid).subtracting(live), listed: listed, live: live, key: Self.railAttemptsKey + paid: paid, failed: ownFailed.subtracting(paid).subtracting(live), listed: listed, live: live, key: Self.railAttemptsKey ) + // A hold ends with the record and expiry its sweep needs. + let after = Set(railAttemptsStore.stringArray(forKey: Self.railAttemptsKey) ?? []) + for hash in held.intersection(before.subtracting(after)) { + clearRailSendUncertainty(hash: hash) + } return live } } @@ -1793,8 +1812,10 @@ class LightningService: NodeLifecycleService { /// holds the invoice, so a failure that ended it meanwhile leaves no id behind. private func takeRailSend(hash: String, paymentId: String?, since mark: AttemptMark) { eventCallbackLock.withLock { + // An outcome delivered before the send returned already ended its doubt and hold. + let isUnsettled = uncertainRailSendFailedAt()[hash] != nil clearRailSendUncertainty(hash: hash, keepingEarlierAttempts: true) - guard let paymentId, attemptsRecorded(since: mark.records, key: Self.railAttemptsKey).contains(hash) else { return } + guard isUnsettled, let paymentId, attemptsRecorded(since: mark.records, key: Self.railAttemptsKey).contains(hash) else { return } var taken = takenRailSendIds() taken[hash] = paymentId railAttemptsStore.set(taken, forKey: Self.takenRailSendsKey) @@ -1814,7 +1835,6 @@ class LightningService: NodeLifecycleService { return ids.count == attempts.count ? ids : nil } - /// Spark's id of the taken send that still holds the invoice of `paymentHash`, if any. /// Spark's payments as the app's status lookups read them: a send still held reads as pending while Spark lists none /// of its own attempts, only earlier failed ones or nothing, until its hold ends past the invoice's expiry. func channelFreeRailSendStatuses() async throws -> [ChannelFreeRailPayment] { @@ -1841,6 +1861,7 @@ class LightningService: NodeLifecycleService { } } + /// Spark's id of the taken send that still holds the invoice of `paymentHash`, if any. func heldRailSendId(paymentHash: String) -> String? { eventCallbackLock.withLock { takenRailSendIds()[paymentHash.lowercased()] } } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 07e7a23928..93534947db 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1126,6 +1126,62 @@ extension ChannelFreeRailTests { XCTAssertEqual(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(statuses, paymentHash: hash), failedRetry) } + func testOnlyAHeldSendsOwnListedFailureEndsItsHold() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + let earlier = Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier") + rail.payments = [earlier] + rail.balanceSats = 100_000 + rail.sentPaymentId = "retry" + _ = try await service.send(bolt11: Self.invoice) + rail.sentPaymentId = "other" + + // A listing that shows only the earlier failure keeps the retry held. + do { + _ = try await service.send(bolt11: Self.invoice) + XCTFail("a retry Spark took was paid again while held") + } catch {} + XCTAssertEqual(service.heldRailSendId(paymentHash: hash), "retry") + + // One that shows the retry's own failure ends its hold, so the invoice can be paid again. + let failedRetry = Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "retry") + rail.payments = [earlier, failedRetry] + _ = try await service.send(bolt11: Self.invoice) + XCTAssertEqual(service.heldRailSendId(paymentHash: hash), "other") + } + + func testAHeldSendReleasedOnItsOwnFailureEndsItsHold() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + rail.balanceSats = 100_000 + rail.sentPaymentId = "retry" + _ = try await service.send(bolt11: Self.invoice) + XCTAssertEqual(service.heldRailSendId(paymentHash: hash), "retry") + + service.releaseRailAttempt(paymentHash: hash) + XCTAssertNil(service.heldRailSendId(paymentHash: hash)) + XCTAssertNil(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(service.withHeldRailSends([]), paymentHash: hash)) + } + + func testASuccessBeforeTheSendReturnsLeavesNoHold() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + rail.balanceSats = 100_000 + rail.sentPaymentId = "retry" + rail.sendGate = { + service.emitChannelFreeRailEvent( + .paymentSuccessful(paymentId: hash, paymentHash: hash, paymentPreimage: "pp", feePaidMsat: 1000), railPaymentId: "retry" + ) + } + defer { rail.sendGate = nil } + _ = try await service.send(bolt11: Self.invoice) + + XCTAssertNil(service.heldRailSendId(paymentHash: hash)) + } + func testAnOlderAttemptMissingFromTheListBeforeASendInDoubtKeepsItsHold() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared From 1525e18473fd5f6f378a5701ca81a067b7815fbd Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 16:26:29 +0100 Subject: [PATCH 43/64] fix: spark keeps a settled send settled A Spark send call that fails after its outcome arrived no longer puts the send back in doubt. The status lookups read Spark's list again when a hold ends while it is read. A row alike both its kept and previous writer's stamps, or cut off twice before it was saved, stays its previous writer's. Verified: BitkitTests pass, including new early-outcome and cut-write tests. --- Bitkit/Services/CoreService.swift | 10 ++++-- Bitkit/Services/LightningService.swift | 32 +++++++++++++++++--- BitkitTests/ChannelFreeRailTests.swift | 23 ++++++++++++++ BitkitTests/SparkRelaunchActivityTests.swift | 13 ++++++++ 4 files changed, 70 insertions(+), 8 deletions(-) diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 9b2e9941da..2dad736d55 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -2957,7 +2957,10 @@ struct ChannelFreeRowAttempts: @unchecked Sendable { Self.lock.withLock { var entries = defaults.array(forKey: Self.key) as? [[String]] ?? [] let previous = entries.last { $0.first == hash } - let entry = if let previous, previous.count >= 3 { + let entry = if let previous, previous.count == 5, previousRowStamp == previous[4] { + // A write cut off before its row was saved: the row is still the previous writer's. + [hash, attemptId, stamp, previous[3], previous[4]] + } else if let previous, previous.count >= 3 { [hash, attemptId, stamp, previous[1], previous[2]] } else { [hash, attemptId, stamp, "", previousRowStamp ?? ""] @@ -2981,10 +2984,11 @@ struct ChannelFreeRowAttempts: @unchecked Sendable { } } - /// The writer of `row`: the kept one, unless `row` still matches the previous writer's stamp and not the kept one's. + /// The writer of `row`: the kept one, unless `row` still matches the previous writer's stamp, as a write cut off + /// before its row was saved leaves it. private func writer(forPaymentHash paymentHash: String, row: LightningActivity?) -> (id: String, stamp: String)? { guard let entry = entry(forPaymentHash: paymentHash), entry.count >= 3 else { return nil } - if entry.count == 5, let row, Self.stamp(row) != entry[2], Self.stamp(row) == entry[4] { + if entry.count == 5, let row, Self.stamp(row) == entry[4] { return entry[3].isEmpty ? nil : (entry[3], entry[4]) } return (entry[1], entry[2]) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 4c37a38646..279eb6d64d 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1183,9 +1183,10 @@ 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. + // A send that failed once submitted may still go out, so its outcome waits for a later sync, unless an + // outcome or sync already settled it while the call returned. if let paymentHash { - markRailSendUncertain(paymentHash: paymentHash, since: mark, earlierAttemptIds: earlierAttemptIds) + markRailSendUncertain(paymentHash: paymentHash, since: mark, earlierAttemptIds: earlierAttemptIds, ifStillInDoubt: true) } throw error } @@ -1705,12 +1706,18 @@ class LightningService: NodeLifecycleService { /// A rail send about to be submitted, or that failed after it was, until a sync after it and its invoice's expiry /// settle it. The expiry is the one kept beside the hash. - private func markRailSendUncertain(paymentHash: String, since mark: AttemptMark, earlierAttemptIds: [String]?) { + private func markRailSendUncertain( + paymentHash: String, + since mark: AttemptMark, + earlierAttemptIds: [String]?, + ifStillInDoubt: Bool = false + ) { let hash = paymentHash.lowercased() let failedAt = Int(max(0, now().timeIntervalSince1970)) eventCallbackLock.withLock { guard attemptsRecorded(since: mark.records, key: Self.railAttemptsKey).contains(hash) else { return } var uncertain = uncertainRailSendFailedAt() + guard !ifStillInDoubt || uncertain[hash] != nil else { return } if uncertain[hash] == nil { var started = uncertainRailSendStartedAt() started[hash] = failedAt @@ -1838,12 +1845,27 @@ class LightningService: NodeLifecycleService { /// Spark's payments as the app's status lookups read them: a send still held reads as pending while Spark lists none /// of its own attempts, only earlier failed ones or nothing, until its hold ends past the invoice's expiry. func channelFreeRailSendStatuses() async throws -> [ChannelFreeRailPayment] { - try await withHeldRailSends(channelFreeRailPayments()) + let heldBefore = heldRailSendHashes() + let payments = try await channelFreeRailPayments() + // A hold that ended while the list was read ended on an outcome the list may not show yet. + guard heldBefore.isSubset(of: heldRailSendHashes()) else { + return try await withHeldRailSends(channelFreeRailPayments()) + } + return withHeldRailSends(payments) + } + + private func heldRailSendHashes() -> Set { + eventCallbackLock.withLock { heldRailSendHashesLocked() } + } + + /// Callers hold `eventCallbackLock`. + private func heldRailSendHashesLocked() -> Set { + Set(takenRailSendIds().keys).union(uncertainRailSendEarlierAttempts().keys).union(uncertainRailSendFailedAt().keys) } func withHeldRailSends(_ payments: [ChannelFreeRailPayment]) -> [ChannelFreeRailPayment] { eventCallbackLock.withLock { - let held = Set(takenRailSendIds().keys).union(uncertainRailSendEarlierAttempts().keys).union(uncertainRailSendFailedAt().keys) + let held = heldRailSendHashesLocked() guard !held.isEmpty else { return payments } var statuses = payments.filter { payment in let hash = payment.paymentHash.lowercased() diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 93534947db..0fb4a11d44 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1182,6 +1182,26 @@ extension ChannelFreeRailTests { XCTAssertNil(service.heldRailSendId(paymentHash: hash)) } + func testASendCallFailingAfterItsOutcomeArrivedLeavesItSettled() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + rail.balanceSats = 100_000 + rail.afterSubmission = { + service.emitChannelFreeRailEvent( + .paymentSuccessful(paymentId: hash, paymentHash: hash, paymentPreimage: "pp", feePaidMsat: 1000), railPaymentId: "sent" + ) + } + rail.errorAfterSubmission = NSError(domain: "spark", code: 2) + defer { + rail.afterSubmission = nil + rail.errorAfterSubmission = nil + } + _ = try? await service.send(bolt11: Self.invoice) + + XCTAssertNil(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(service.withHeldRailSends([]), paymentHash: hash)) + } + func testAnOlderAttemptMissingFromTheListBeforeASendInDoubtKeepsItsHold() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared @@ -2475,6 +2495,8 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { var onList: (() -> Void)? /// Runs as a send is about to be submitted, before `beforeSubmission`. var beforeSubmit: (() -> Void)? + /// Runs once the send was submitted, before `errorAfterSubmission`. + var afterSubmission: (() -> Void)? /// Thrown after the send was submitted, as when the connection drops inside Spark's send. var errorAfterSubmission: Error? /// Whether the rail's last sync reached it, after the given seconds when there are any. @@ -2500,6 +2522,7 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { } beforeSubmit?() try beforeSubmission() + afterSubmission?() if let refusalAfterSubmission { throw refusalAfterSubmission } diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index f4702fda2a..228368cadc 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -299,6 +299,19 @@ final class SparkRelaunchActivityTests: XCTestCase { XCTAssertEqual(attempts.attemptId(forPaymentHash: hash, row: row), "earlier") XCTAssertTrue(attempts.isUnchanged(row, forPaymentHash: hash)) + // A second write cut off the same way, or one alike the row, still leaves it to its real writer. + attempts.remember("third", forPaymentHash: hash, stamp: "400:800:0", previousRowStamp: ChannelFreeRowAttempts.stamp(row)) + XCTAssertEqual(attempts.attemptId(forPaymentHash: hash, row: row), "earlier") + attempts.remember( + "alike", + forPaymentHash: hash, + stamp: ChannelFreeRowAttempts.stamp(row), + previousRowStamp: ChannelFreeRowAttempts.stamp(row) + ) + XCTAssertEqual(attempts.attemptId(forPaymentHash: hash, row: row), "earlier") + attempts.remember("retry", forPaymentHash: hash, stamp: "300:700:0", previousRowStamp: ChannelFreeRowAttempts.stamp(row)) + XCTAssertEqual(attempts.attemptId(forPaymentHash: hash, row: row), "earlier") + // Once the retry's row is saved, it is the retry's. attempts.commit(forPaymentHash: hash) XCTAssertEqual(attempts.attemptId(forPaymentHash: hash, row: row), "retry") From 41ac3957a2df5f0c6d008ff8ffc1bb78c042be4c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 17:07:43 +0100 Subject: [PATCH 44/64] fix: spark reads a settled send's outcome A Spark send call that fails after the send's outcome arrived returns its payment hash as a returned send does, so the send screen reads the outcome instead of showing the call's error. Verified: BitkitTests pass; the early-outcome test checks the hash comes back. --- Bitkit/Services/LightningService.swift | 22 ++++++++++++++-------- BitkitTests/ChannelFreeRailTests.swift | 4 +++- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 279eb6d64d..5e4cae963b 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1183,10 +1183,13 @@ 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, unless an - // outcome or sync already settled it while the call returned. - if let paymentHash { - markRailSendUncertain(paymentHash: paymentHash, since: mark, earlierAttemptIds: earlierAttemptIds, ifStillInDoubt: true) + // A send that failed once submitted may still go out, so its outcome waits for a later sync. One an outcome + // already settled while the call returned is read as sent, so its caller reads that outcome. + if let paymentHash, + markRailSendUncertain(paymentHash: paymentHash, since: mark, earlierAttemptIds: earlierAttemptIds, ifStillInDoubt: true) + { + Logger.info("Spark's send call of '\(paymentHash)' failed after its outcome arrived: \(error)", context: "LightningService") + return paymentHash } throw error } @@ -1706,18 +1709,20 @@ class LightningService: NodeLifecycleService { /// A rail send about to be submitted, or that failed after it was, until a sync after it and its invoice's expiry /// settle it. The expiry is the one kept beside the hash. + /// True when `ifStillInDoubt` found the send already settled. + @discardableResult private func markRailSendUncertain( paymentHash: String, since mark: AttemptMark, earlierAttemptIds: [String]?, ifStillInDoubt: Bool = false - ) { + ) -> Bool { let hash = paymentHash.lowercased() let failedAt = Int(max(0, now().timeIntervalSince1970)) - eventCallbackLock.withLock { - guard attemptsRecorded(since: mark.records, key: Self.railAttemptsKey).contains(hash) else { return } + return eventCallbackLock.withLock { + guard attemptsRecorded(since: mark.records, key: Self.railAttemptsKey).contains(hash) else { return false } var uncertain = uncertainRailSendFailedAt() - guard !ifStillInDoubt || uncertain[hash] != nil else { return } + guard !ifStillInDoubt || uncertain[hash] != nil else { return true } if uncertain[hash] == nil { var started = uncertainRailSendStartedAt() started[hash] = failedAt @@ -1733,6 +1738,7 @@ class LightningService: NodeLifecycleService { } uncertain[hash] = failedAt railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) + return false } } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 0fb4a11d44..610b0d21e2 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1197,8 +1197,10 @@ extension ChannelFreeRailTests { rail.afterSubmission = nil rail.errorAfterSubmission = nil } - _ = try? await service.send(bolt11: Self.invoice) + // The call's failure gives way to the outcome already delivered, so its caller reads that outcome. + let sent = try await service.send(bolt11: Self.invoice) + XCTAssertEqual(sent, hash) XCTAssertNil(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(service.withHeldRailSends([]), paymentHash: hash)) } From 349ea4d21d3a13fc3d73ba83d635ebffaab9920f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 17:25:40 +0100 Subject: [PATCH 45/64] fix: spark claims early only up to the shown fee The early-claim fee ceiling a swipe approves is never above the one its quote showed, as the requote before sending can raise it. Verified: BitkitTests pass, including the new shown-ceiling test. --- Bitkit/ViewModels/SparkTransferFlow.swift | 11 ++++++++--- Bitkit/Views/Transfer/SpendingConfirm.swift | 4 ++-- BitkitTests/SparkTransferFlowTests.swift | 14 ++++++++++++++ 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/Bitkit/ViewModels/SparkTransferFlow.swift b/Bitkit/ViewModels/SparkTransferFlow.swift index f22c886037..ac94a64906 100644 --- a/Bitkit/ViewModels/SparkTransferFlow.swift +++ b/Bitkit/ViewModels/SparkTransferFlow.swift @@ -349,9 +349,14 @@ final class SparkTransferFlow { } /// Records the early-claim ceiling and speed the user swiped, as the confirm screen keeps requoting while a payment - /// whose outcome is unknown waits on the pending screen. - func approveSwipe() { - approved = (ceilingSats: quote?.claimFees.instantMaxSats ?? 0, speed: speed) + /// whose outcome is unknown waits on the pending screen. The ceiling is never above `shownCeilingSats`, the one the + /// swiped quote showed, as the requote before sending can raise it. Returns the approved ceiling. + @discardableResult + func approveSwipe(shownCeilingSats: UInt64? = nil) -> UInt64 { + let current = quote?.claimFees.instantMaxSats ?? 0 + let ceilingSats = shownCeilingSats.map { min($0, current) } ?? current + approved = (ceilingSats: ceilingSats, speed: speed) + return ceilingSats } /// Ties the last swipe's approval to the funding it left unresolved. A later swipe rejected while that funding is diff --git a/Bitkit/Views/Transfer/SpendingConfirm.swift b/Bitkit/Views/Transfer/SpendingConfirm.swift index f338dffcb8..560078afc2 100644 --- a/Bitkit/Views/Transfer/SpendingConfirm.swift +++ b/Bitkit/Views/Transfer/SpendingConfirm.swift @@ -141,7 +141,7 @@ struct SpendingConfirm: View { throw SpendingFeesIncreasedError() } - flow.approveSwipe() + let ceilingSats = flow.approveSwipe(shownCeilingSats: shown.claimFees.instantMaxSats) do { let txid = try await transfer.fundSpark( address: fresh.address, @@ -150,7 +150,7 @@ struct SpendingConfirm: View { txFee: fresh.networkFeeSats, isMaxAmount: flow.isMaxAmount ) - flow.onBroadcast(txid: txid) + flow.onBroadcast(txid: txid, ceilingSats: ceilingSats) await wallet.updateBalanceState() navigation.navigate(.settingUp) DispatchQueue.main.asyncAfter(deadline: .now() + 1) { diff --git a/BitkitTests/SparkTransferFlowTests.swift b/BitkitTests/SparkTransferFlowTests.swift index 2016d73b0a..6443b85714 100644 --- a/BitkitTests/SparkTransferFlowTests.swift +++ b/BitkitTests/SparkTransferFlowTests.swift @@ -392,6 +392,20 @@ final class SparkTransferFlowTests: XCTestCase { XCTAssertEqual(flow.claimState, .repriced(feeSats: 800), "Paid an early claim fee the user never approved") } + @MainActor + func testASwipeApprovesNoHigherCeilingThanTheQuoteItShowed() async { + let flow = pollingFlow(offers: [choice(earlyFee: 800)], claims: [.claimed]) + // The requote before sending raised the ceiling over the one the swiped quote showed. + flow.quote = quote(instantMax: 3010) + let ceilingSats = flow.approveSwipe(shownCeilingSats: 337) + XCTAssertEqual(ceilingSats, 337) + + flow.onBroadcast(txid: "txid", ceilingSats: ceilingSats) + await flow.waitForClaim() + + XCTAssertEqual(flow.claimState, .repriced(feeSats: 800), "Claimed early at a ceiling the swipe never showed") + } + @MainActor func testARecoveredFundingKeepsItsOwnApprovalWhenALaterSwipeIsRejected() async { let flow = pollingFlow(offers: [choice(earlyFee: 800)], claims: [.claimed]) From 9c9232253ec8fb496810e8a5b276323fcc9ea4ea Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 18:15:37 +0100 Subject: [PATCH 46/64] fix: spark orders a same-second retry past its hold A same-second tie between Spark attempts also reads the earlier attempts kept past the send's hold, so a retry whose hold a listing ended before its failure was recorded still takes the row from the first attempt. Verified: BitkitTests pass, including the new ended-hold tie test. --- Bitkit/Services/CoreService.swift | 7 ++++--- BitkitTests/SparkRelaunchActivityTests.swift | 22 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 2dad736d55..bb709202e5 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1025,14 +1025,15 @@ class ActivityService { paymentId: railPaymentId )), // Spark dates an attempt at its start, so an older one's failure is dated before the row's attempt, or - // in the same second when the retry started at once; then the row's own Spark id tells them apart. The - // held attempt's own failure always writes. + // in the same second when the retry started at once; then the row's own Spark id tells them apart, with the + // send's earlier attempts kept past its hold. The held attempt's own failure always writes. isOlderChannelFreeAttempt: rail == .channelFree && payment.direction == .outbound && (railPaymentId == nil || railPaymentId != LightningService.shared.heldRailSendId(paymentHash: payment.id)) && (paymentTimestamp < existing.timestamp || paymentTimestamp == existing.timestamp && Self.isOtherRowAttempt( railPaymentId, rowAttemptId: Self.channelFreeRowAttempts.attemptId(forPaymentHash: payment.id, row: existing), - earlierAttemptIds: LightningService.shared.railSendEarlierAttemptIds[payment.id.lowercased()] + earlierAttemptIds: (LightningService.shared.railSendEarlierAttemptIds[payment.id.lowercased()] ?? []) + + LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: payment.id) ) || Self.isKnownEarlierAttempt( railPaymentId, rowAttemptId: Self.channelFreeRowAttempts.attemptId(forPaymentHash: payment.id, row: existing), diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index 228368cadc..a7c93b8a73 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -164,6 +164,28 @@ final class SparkRelaunchActivityTests: XCTestCase { XCTAssertEqual(current?.value, 700) } + func testASameSecondRetryTakesTheRowAfterItsHoldEnded() async throws { + let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "ea", count: 16) + func failed(sats: UInt64, feeSats: UInt64, at timestamp: UInt64) -> PaymentDetails { + PaymentDetails( + id: hash, + kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), + amountMsat: sats * 1000, feePaidMsat: feeSats * 1000, direction: .outbound, status: .failed, latestUpdateTimestamp: timestamp + ) + } + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 300, feeSats: 1, at: 200), railPaymentId: "first") + // A retry in the same second followed the first attempt, and a listing that showed it failed ended its hold + // before its own failure was recorded: only the attempts kept past the hold still order the two. + LightningService.shared.keepEarlierAttemptsForTesting(hash: hash, ids: ["first"]) + + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 0, at: 200), railPaymentId: "retry") + guard case let .lightning(row)? = try await CoreService.shared.activity.getActivity(id: hash) else { + return XCTFail("the row is missing") + } + XCTAssertEqual(row.value, 500, "the first attempt's amount stayed over the retry's") + XCTAssertEqual(row.fee, 0) + } + func testChannelFreeRowAttemptsKeepTheLatestRowWritersUpToTheLimit() throws { let suite = "ChannelFreeRowAttemptsTests-\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) From c46a805ebd234f4937d7d08f637be69c68628450 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 18:53:29 +0100 Subject: [PATCH 47/64] fix: spark orders two earlier attempts by date A Spark attempt a later send followed counts as earlier than the row's only when the row's own attempt isn't one it followed too; otherwise their dates order them, so a newer attempt's replay takes the row. Verified: BitkitTests pass, including the new third-send replay test. --- Bitkit/Services/CoreService.swift | 5 ++-- BitkitTests/ChannelFreeRailTests.swift | 2 ++ BitkitTests/SparkRelaunchActivityTests.swift | 29 ++++++++++++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index bb709202e5..10c9750191 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1141,10 +1141,11 @@ class ActivityService { } } - /// Whether `railPaymentId` is an attempt a send of the invoice followed, other than the row's, whatever Spark's dates. + /// Whether `railPaymentId` is an attempt a send of the invoice followed, before the row's, whatever Spark's dates. When + /// the row's attempt is one such send followed too, the list doesn't order the two, so their dates do. static func isKnownEarlierAttempt(_ railPaymentId: String?, rowAttemptId: String?, keptEarlierAttemptIds: Set) -> Bool { guard let railPaymentId, railPaymentId != rowAttemptId else { return false } - return keptEarlierAttemptIds.contains(railPaymentId) + return keptEarlierAttemptIds.contains(railPaymentId) && !(rowAttemptId.map(keptEarlierAttemptIds.contains) ?? false) } /// Whether `railPaymentId` is another attempt than the row's, and not the send that went out after it: the send in diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 610b0d21e2..b61078bfa9 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1396,6 +1396,8 @@ extension ChannelFreeRailTests { XCTAssertFalse(ActivityService.isKnownEarlierAttempt("a1", rowAttemptId: "a1", keptEarlierAttemptIds: ["a1"])) XCTAssertFalse(ActivityService.isKnownEarlierAttempt("later", rowAttemptId: "retry", keptEarlierAttemptIds: ["a1"])) XCTAssertFalse(ActivityService.isKnownEarlierAttempt(nil, rowAttemptId: "retry", keptEarlierAttemptIds: ["a1"])) + // Two attempts a later send both followed aren't ordered by it. + XCTAssertFalse(ActivityService.isKnownEarlierAttempt("a2", rowAttemptId: "a1", keptEarlierAttemptIds: ["a1", "a2"])) } func testAnExpiredHoldWritesALiveRetryOverAFailureWithTheSameTimestamp() async { diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index a7c93b8a73..e06075d1f5 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -186,6 +186,35 @@ final class SparkRelaunchActivityTests: XCTestCase { XCTAssertEqual(row.fee, 0) } + func testALaterAttemptsReplayTakesTheRowWhenAThirdSendNeverWroteOne() async throws { + let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "eb", count: 16) + func failed(sats: UInt64, feeSats: UInt64, at timestamp: UInt64) -> PaymentDetails { + PaymentDetails( + id: hash, + kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), + amountMsat: sats * 1000, feePaidMsat: feeSats * 1000, direction: .outbound, status: .failed, latestUpdateTimestamp: timestamp + ) + } + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 300, feeSats: 1, at: 200), railPaymentId: "first") + // The second attempt's row write failed, and a third send, which never wrote a row, followed both. + LightningService.shared.keepEarlierAttemptsForTesting(hash: hash, ids: ["first", "second"]) + + // After a restart, the second attempt's replay is newer than the row's attempt, so it takes the row. + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 2, at: 300), railPaymentId: "second") + guard case let .lightning(row)? = try await CoreService.shared.activity.getActivity(id: hash) else { + return XCTFail("the row is missing") + } + XCTAssertEqual(row.value, 500, "the first attempt's amount stayed over the second's") + XCTAssertEqual(row.fee, 2) + + // The first attempt's replay doesn't take it back. + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 300, feeSats: 1, at: 200), railPaymentId: "first") + guard case let .lightning(replayed)? = try await CoreService.shared.activity.getActivity(id: hash) else { + return XCTFail("the row is missing") + } + XCTAssertEqual(replayed.value, 500) + } + func testChannelFreeRowAttemptsKeepTheLatestRowWritersUpToTheLimit() throws { let suite = "ChannelFreeRowAttemptsTests-\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) From f5a0ccefb23065d7b1203649dede895ca2ac0621 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 19:48:26 +0100 Subject: [PATCH 48/64] fix: spark settles a send by its call's result A failure Spark reports while a send of its invoice is still in Spark's send call can't be told from an earlier attempt's, so it no longer ends the hold. The call's own result settles it: a send the call returns as failed ends its hold and reports the failure once, and Spark's later event for that attempt is skipped. A send in doubt reads as pending whatever failure Spark lists. Verified: swiftformat lint; BitkitTests on the iPhone 17 Pro 2x simulator, new ChannelFreeRailTests cases included --- Bitkit/Managers/SparkManager.swift | 4 +- Bitkit/Services/LightningService.swift | 43 ++++++++++++++++---- BitkitTests/ChannelFreeRailTests.swift | 56 ++++++++++++++++++++++++-- 3 files changed, 91 insertions(+), 12 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 8d97d37077..8ce7256165 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -659,7 +659,7 @@ final class SparkManager: ChannelFreeLightningRail { sats: UInt64?, maxFeeSats: UInt64?, beforeSubmission: @escaping () throws -> Void - ) async throws -> (paymentHash: PaymentHash, paymentId: String?) { + ) async throws -> (paymentHash: PaymentHash, paymentId: String?, isFailed: Bool) { let prepared: PrepareSendPaymentResponse let sdk: BreezSdk do { @@ -699,7 +699,7 @@ final class SparkManager: ChannelFreeLightningRail { } } Logger.info("Sent Spark payment '\(response.payment.id)' with status '\(response.payment.status)'", context: "SparkManager") - return (invoiceDetails.paymentHash, response.payment.id) + return (invoiceDetails.paymentHash, response.payment.id, response.payment.status == .failed) } nonisolated static func checkSendFee(_ feeSats: UInt64, maxFeeSats: UInt64?) throws { diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 5e4cae963b..9aa5893b05 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -12,9 +12,10 @@ protocol ChannelFreeLightningRail: AnyObject { @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. Returns the payment's hash and the rail's id of this attempt. + /// payment goes out, as the node path does. Returns the payment's hash, the rail's id of this attempt and whether it + /// already failed. func send(bolt11: String, sats: UInt64?, maxFeeSats: UInt64?, beforeSubmission: @escaping () throws -> Void) async throws - -> (paymentHash: PaymentHash, paymentId: String?) + -> (paymentHash: PaymentHash, paymentId: String?, isFailed: Bool) 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] @@ -167,6 +168,9 @@ class LightningService: NodeLifecycleService { private var attemptRails: [String: LightningPaymentRail] = [:] /// Payment hashes inside a rail send, which Spark lists only once it returns. private var railSendsInFlight: Set = [] + /// Rail ids of attempts whose send call returned them failed and reported it, so Spark's own event for them is + /// dropped and the failure reaches watchers once. + private var railFailuresReportedByCall: Set = [] /// Counts attempts recorded in this run, so a listing drops a hash just when the hash was recorded before the /// listing was read, never a retry recorded while it was read. private var attemptRecords = 0 @@ -1159,7 +1163,21 @@ class LightningService: NodeLifecycleService { } } ) - if let paymentHash { + if let paymentHash, sent.isFailed { + // A failure Spark reported during the call was ignored, so the call's own failed result settles the + // send and reports it. + endRailSend(paymentHash: paymentHash) + isRailSendEnded = true + defer { + if let paymentId = sent.paymentId { + eventCallbackLock.withLock { _ = railFailuresReportedByCall.insert(paymentId) } + } + } + emitChannelFreeRailEvent( + .paymentFailed(paymentId: paymentHash, paymentHash: paymentHash, reason: .unexpectedError), + railPaymentId: sent.paymentId + ) + } else if let paymentHash { // Spark took the send, which may still be pending: its own id and its earlier attempts stay known until // it settles, so their failures don't end its hold. takeRailSend(hash: paymentHash.lowercased(), paymentId: sent.paymentId, since: mark) @@ -1849,7 +1867,8 @@ class LightningService: NodeLifecycleService { } /// Spark's payments as the app's status lookups read them: a send still held reads as pending while Spark lists none - /// of its own attempts, only earlier failed ones or nothing, until its hold ends past the invoice's expiry. + /// of its own attempts, only earlier failed ones or nothing, until its hold ends past the invoice's expiry, and one + /// in Spark's send call or in doubt reads as pending whatever failure Spark lists. func channelFreeRailSendStatuses() async throws -> [ChannelFreeRailPayment] { let heldBefore = heldRailSendHashes() let payments = try await channelFreeRailPayments() @@ -1864,19 +1883,23 @@ class LightningService: NodeLifecycleService { eventCallbackLock.withLock { heldRailSendHashesLocked() } } - /// Callers hold `eventCallbackLock`. + /// The hashes of rail sends held: in Spark's send call, in doubt, or taken. Callers hold `eventCallbackLock`. private func heldRailSendHashesLocked() -> Set { Set(takenRailSendIds().keys).union(uncertainRailSendEarlierAttempts().keys).union(uncertainRailSendFailedAt().keys) + .union(railSendsInFlight) } func withHeldRailSends(_ payments: [ChannelFreeRailPayment]) -> [ChannelFreeRailPayment] { eventCallbackLock.withLock { let held = heldRailSendHashesLocked() guard !held.isEmpty else { return payments } + // A send in Spark's send call or in doubt may still go out, whatever failure Spark lists for its invoice. + let inDoubt = Set(uncertainRailSendFailedAt().keys).union(railSendsInFlight) var statuses = payments.filter { payment in let hash = payment.paymentHash.lowercased() return !(payment.direction == .outbound && payment.status == .failed && held.contains(hash) - && isEarlierThanUncertainRailSendLocked(hash: hash, createdAt: payment.timestamp, paymentId: payment.id)) + && (inDoubt.contains(hash) + || isEarlierThanUncertainRailSendLocked(hash: hash, createdAt: payment.timestamp, paymentId: payment.id))) } let listed = Set(statuses.filter { $0.direction == .outbound }.map { $0.paymentHash.lowercased() }) for hash in held.subtracting(listed).sorted() { @@ -1985,6 +2008,8 @@ class LightningService: NodeLifecycleService { private func settleRailFailure(paymentHash: String, createdAt: UInt64?, paymentId: String?) -> Bool { let hash = paymentHash.lowercased() return eventCallbackLock.withLock { + // While a send of the invoice is in Spark's send call, its result settles it, whichever attempt failed. + guard !railSendsInFlight.contains(hash) else { return false } if let createdAt, isEarlierThanUncertainRailSendLocked(hash: hash, createdAt: createdAt, paymentId: paymentId) { return false } @@ -2746,10 +2771,14 @@ extension LightningService { func emitChannelFreeRailEvent(_ event: Event, paymentCreatedAt: UInt64? = nil, railPaymentId: String? = nil) { switch event { case let .paymentFailed(_, paymentHash?, _): + if let railPaymentId, eventCallbackLock.withLock({ railFailuresReportedByCall.remove(railPaymentId) != nil }) { + Logger.info("Ignored a Spark failure its send call already reported: \(event)", context: "LightningService") + return + } // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held; the // failure of the send itself may arrive while its send call is still returning. guard settleRailFailure(paymentHash: paymentHash, createdAt: paymentCreatedAt, paymentId: railPaymentId) else { - Logger.info("Ignored a Spark failure of an attempt before the send still in doubt: \(event)", context: "LightningService") + Logger.info("Ignored a Spark failure while a send of its invoice is in flight or in doubt: \(event)", context: "LightningService") return } case let .paymentSuccessful(_, paymentHash, _, _): diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index b61078bfa9..8284914102 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1182,6 +1182,40 @@ extension ChannelFreeRailTests { XCTAssertNil(service.heldRailSendId(paymentHash: hash)) } + func testAFailureDuringTheSendCallLeavesTheCallsResultToSettleIt() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + rail.balanceSats = 100_000 + rail.sentPaymentId = "sent" + rail.afterSubmission = { + service.emitChannelFreeRailEvent( + .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), paymentCreatedAt: 1000, railPaymentId: "earlier" + ) + } + defer { rail.afterSubmission = nil } + _ = try await service.send(bolt11: Self.invoice) + + // Spark took the send, so it is held, whatever failure arrived while its call ran. + XCTAssertEqual(service.heldRailSendId(paymentHash: hash), "sent") + } + + func testASendInDoubtReadsPendingWhateverFailureSparkLists() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + rail.balanceSats = 100_000 + rail.errorAfterSubmission = NSError(domain: "spark", code: 2) + defer { rail.errorAfterSubmission = nil } + _ = try? await service.send(bolt11: Self.invoice) + + let failed = Bitkit.ChannelFreeRailPayment( + paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: 1005, id: "own" + ) + let send = Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(service.withHeldRailSends([failed]), paymentHash: hash) + XCTAssertEqual(send?.status, .pending) + } + func testASendCallFailingAfterItsOutcomeArrivedLeavesItSettled() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared @@ -1728,11 +1762,19 @@ extension ChannelFreeRailTests { await assertRefusedAsDuplicate() } - func testASparkFailureReportedWhileItsSendIsInFlightStillReleasesTheHold() async throws { + func testASendWhoseCallReturnsTheFailureSparkReportedDuringItReleasesTheHold() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) var release: CheckedContinuation? rail.sendGate = { await withCheckedContinuation { release = $0 } } + rail.sentFailed = true + rail.sentPaymentId = "retry" rail.balanceSats = 100_000 + var failures = 0 + Bitkit.LightningService.shared.setEventCallback { event in + if case .paymentFailed = event { + failures += 1 + } + } let send = Task { try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) } var waited = 0 while release == nil, waited < 500 { @@ -1744,6 +1786,12 @@ extension ChannelFreeRailTests { Bitkit.LightningService.shared.emitChannelFreeRailEvent(.paymentFailed(paymentId: hash, paymentHash: hash, reason: nil)) release?.resume() _ = try await send.value + // Spark's own event for the attempt, arriving after the call returned it, isn't reported again. + Bitkit.LightningService.shared.emitChannelFreeRailEvent( + .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), + railPaymentId: "retry" + ) + XCTAssertEqual(failures, 1, "The failure didn't reach watchers exactly once") rail.listError = NSError(domain: "spark", code: 1) rail.balanceSats = 0 @@ -2490,6 +2538,8 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { var sentBolt11: String? /// The rail's id of the attempt a send returns. var sentPaymentId: String? + /// Whether a send returns its attempt as failed. + var sentFailed = false var sends = 0 var sentFeeLimitSats: UInt64? var sendGate: (() async -> Void)? @@ -2519,7 +2569,7 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { } func send(bolt11: String, sats: UInt64?, maxFeeSats: UInt64?, beforeSubmission: @escaping () throws -> Void) async throws - -> (paymentHash: PaymentHash, paymentId: String?) + -> (paymentHash: PaymentHash, paymentId: String?, isFailed: Bool) { if let refusal { throw refusal @@ -2537,7 +2587,7 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { sentFeeLimitSats = maxFeeSats sentBolt11 = bolt11 sends += 1 - return ("ee", sentPaymentId) + return ("ee", sentPaymentId, sentFailed) } func estimateRoutingFees(bolt11: String, amountSats: UInt64?) async throws -> UInt64 { From a70b8139c27c4d6378502eb43f0cd715d56f6c40 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 19:58:17 +0100 Subject: [PATCH 49/64] fix: spark orders kept attempts by send Two failed attempts in the same second, both kept past a third send's hold, were not ordered: the second's replay lost the row to the first. Each send adds the attempts before it to the kept list as it goes out, with the one Spark took last at the end, so that list is in send order and now decides which of two kept attempts is later. Verified: swiftformat lint; BitkitTests on the iPhone 17 Pro 2x simulator, new SparkRelaunchActivityTests case included --- Bitkit/Managers/SparkManager.swift | 4 +-- Bitkit/Services/CoreService.swift | 28 +++++++++++---- Bitkit/Services/LightningService.swift | 13 ++++--- BitkitTests/SparkRelaunchActivityTests.swift | 38 ++++++++++++++++++++ 4 files changed, 70 insertions(+), 13 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 8ce7256165..9cf81eebd5 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -1863,7 +1863,7 @@ final class SparkManager: ChannelFreeLightningRail { return await Self.recordExpiredHold( paymentHash: paymentHash, payments: payments, - earlierAttemptIds: LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: paymentHash), + earlierAttemptIds: Set(LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: paymentHash)), record: { await self.recordActivity($0) }, failStoredSend: { await Self.failHeldSendRow(paymentHash: $0, ownAttemptId: nil) } ) @@ -1873,7 +1873,7 @@ final class SparkManager: ChannelFreeLightningRail { await (try? CoreService.shared.activity.failPendingLightningSend( id: paymentHash, ownAttemptId: ownAttemptId, - earlierAttemptIds: LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: paymentHash) + earlierAttemptIds: Set(LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: paymentHash)) )) != nil } diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 10c9750191..25a1c1e28c 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1033,7 +1033,8 @@ class ActivityService { railPaymentId, rowAttemptId: Self.channelFreeRowAttempts.attemptId(forPaymentHash: payment.id, row: existing), earlierAttemptIds: (LightningService.shared.railSendEarlierAttemptIds[payment.id.lowercased()] ?? []) - + LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: payment.id) + + LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: payment.id), + keptEarlierAttemptIds: LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: payment.id) ) || Self.isKnownEarlierAttempt( railPaymentId, rowAttemptId: Self.channelFreeRowAttempts.attemptId(forPaymentHash: payment.id, row: existing), @@ -1142,16 +1143,29 @@ class ActivityService { } /// Whether `railPaymentId` is an attempt a send of the invoice followed, before the row's, whatever Spark's dates. When - /// the row's attempt is one such send followed too, the list doesn't order the two, so their dates do. - static func isKnownEarlierAttempt(_ railPaymentId: String?, rowAttemptId: String?, keptEarlierAttemptIds: Set) -> Bool { - guard let railPaymentId, railPaymentId != rowAttemptId else { return false } - return keptEarlierAttemptIds.contains(railPaymentId) && !(rowAttemptId.map(keptEarlierAttemptIds.contains) ?? false) + /// the row's attempt is one such send followed too, the kept list's order, which is the order they went out, decides. + static func isKnownEarlierAttempt(_ railPaymentId: String?, rowAttemptId: String?, keptEarlierAttemptIds: [String]) -> Bool { + guard let railPaymentId, railPaymentId != rowAttemptId, + let index = keptEarlierAttemptIds.firstIndex(of: railPaymentId) else { return false } + guard let rowIndex = rowAttemptId.flatMap(keptEarlierAttemptIds.firstIndex(of:)) else { return true } + return index < rowIndex } /// Whether `railPaymentId` is another attempt than the row's, and not the send that went out after it: the send in - /// flight lists the attempts before it, and its failure is recorded before that list goes. - static func isOtherRowAttempt(_ railPaymentId: String?, rowAttemptId: String?, earlierAttemptIds: [String]? = nil) -> Bool { + /// flight lists the attempts before it, and its failure is recorded before that list goes. Two attempts both kept past + /// a later send's hold are ordered by the kept list. + static func isOtherRowAttempt( + _ railPaymentId: String?, + rowAttemptId: String?, + earlierAttemptIds: [String]? = nil, + keptEarlierAttemptIds: [String] = [] + ) -> Bool { guard let railPaymentId, let rowAttemptId, railPaymentId != rowAttemptId else { return false } + if let index = keptEarlierAttemptIds.firstIndex(of: railPaymentId), + let rowIndex = keptEarlierAttemptIds.firstIndex(of: rowAttemptId) + { + return index < rowIndex + } let isLaterSend = earlierAttemptIds.map { $0.contains(rowAttemptId) && !$0.contains(railPaymentId) } ?? false return !isLaterSend } diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 9aa5893b05..328cb74773 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1752,7 +1752,11 @@ class LightningService: NodeLifecycleService { var earlier = uncertainRailSendEarlierAttempts() earlier[hash] = earlierAttemptIds.map { ids in takenBefore.map { ids.contains($0) ? ids : ids + [$0] } ?? ids } railAttemptsStore.set(earlier, forKey: Self.uncertainRailSendsEarlierAttemptsKey) - keepEarlierAttempts(hash: hash, ids: (earlierAttemptIds ?? []) + (takenBefore.map { [$0] } ?? [])) + // The send Spark took last goes after the ones it listed. + keepEarlierAttempts( + hash: hash, + ids: (earlierAttemptIds ?? []).filter { $0 != takenBefore } + (takenBefore.map { [$0] } ?? []) + ) } uncertain[hash] = failedAt railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) @@ -1777,12 +1781,13 @@ class LightningService: NodeLifecycleService { } #endif - /// Spark's ids of every attempt a send of `paymentHash` followed, kept past its hold. - func keptRailSendEarlierAttemptIds(paymentHash: String) -> Set { + /// Spark's ids of every attempt a send of `paymentHash` followed, kept past its hold in the order they went out: each + /// send adds the attempts before it as it goes out. + func keptRailSendEarlierAttemptIds(paymentHash: String) -> [String] { let hash = paymentHash.lowercased() return eventCallbackLock.withLock { let entries = railAttemptsStore.array(forKey: Self.keptRailSendEarlierAttemptsKey) as? [[String]] ?? [] - return Set(entries.last { $0.first == hash }?.dropFirst() ?? []) + return Array(entries.last { $0.first == hash }?.dropFirst() ?? []) } } diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index e06075d1f5..f5a671c1da 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -215,6 +215,37 @@ final class SparkRelaunchActivityTests: XCTestCase { XCTAssertEqual(replayed.value, 500) } + func testASameSecondLaterAttemptsReplayTakesTheRowWhenAThirdSendNeverWroteOne() async throws { + let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "ec", count: 16) + func failed(sats: UInt64, feeSats: UInt64) -> PaymentDetails { + PaymentDetails( + id: hash, + kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), + amountMsat: sats * 1000, feePaidMsat: feeSats * 1000, direction: .outbound, status: .failed, latestUpdateTimestamp: 200 + ) + } + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 300, feeSats: 1), railPaymentId: "first") + // The second attempt went out in the same second and kept the first as earlier; its row write failed. A third + // send, which never wrote a row, followed both. + LightningService.shared.keepEarlierAttemptsForTesting(hash: hash, ids: ["first"]) + LightningService.shared.keepEarlierAttemptsForTesting(hash: hash, ids: ["second", "first"]) + + // After a restart, the second attempt's replay went out after the row's attempt, so it takes the row. + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 2), railPaymentId: "second") + guard case let .lightning(row)? = try await CoreService.shared.activity.getActivity(id: hash) else { + return XCTFail("the row is missing") + } + XCTAssertEqual(row.value, 500, "the first attempt's amount stayed over the second's") + XCTAssertEqual(row.fee, 2) + + // The first attempt's replay doesn't take it back. + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 300, feeSats: 1), railPaymentId: "first") + guard case let .lightning(replayed)? = try await CoreService.shared.activity.getActivity(id: hash) else { + return XCTFail("the row is missing") + } + XCTAssertEqual(replayed.value, 500) + } + func testChannelFreeRowAttemptsKeepTheLatestRowWritersUpToTheLimit() throws { let suite = "ChannelFreeRowAttemptsTests-\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) @@ -279,6 +310,13 @@ final class SparkRelaunchActivityTests: XCTestCase { // Another attempt of the same second keeps the row when nothing orders the two. XCTAssertTrue(ActivityService.isOtherRowAttempt("first", rowAttemptId: "retry")) XCTAssertTrue(ActivityService.isOtherRowAttempt("first", rowAttemptId: "retry", earlierAttemptIds: ["older"])) + // Two kept attempts are ordered by the kept list, whatever else lists them. + XCTAssertFalse(ActivityService.isOtherRowAttempt( + "second", rowAttemptId: "first", earlierAttemptIds: ["first", "second"], keptEarlierAttemptIds: ["first", "second"] + )) + XCTAssertTrue(ActivityService.isOtherRowAttempt( + "first", rowAttemptId: "second", earlierAttemptIds: ["first", "second"], keptEarlierAttemptIds: ["first", "second"] + )) // The retry in flight lists the row's attempt before it, so its failure takes the row. XCTAssertFalse(ActivityService.isOtherRowAttempt("retry", rowAttemptId: "first", earlierAttemptIds: ["first"])) // While it is in flight, an attempt it lists as earlier still keeps the row. From 64502865fe3762f482531b25343cdf8a63bc23a6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 21:03:30 +0100 Subject: [PATCH 50/64] fix: spark dates decide between kept attempts A send's read of Spark's list can miss an earlier attempt, which a later send then keeps after a newer one, so the kept order may be wrong. Spark's dates decide between two kept attempts again; the kept order only breaks a same-second tie. Verified: swiftformat lint; BitkitTests on the iPhone 17 Pro 2x simulator, new SparkRelaunchActivityTests case fails without the fix --- Bitkit/Services/CoreService.swift | 12 +++++------- BitkitTests/SparkRelaunchActivityTests.swift | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 25a1c1e28c..dd0fcc26f8 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1143,17 +1143,15 @@ class ActivityService { } /// Whether `railPaymentId` is an attempt a send of the invoice followed, before the row's, whatever Spark's dates. When - /// the row's attempt is one such send followed too, the kept list's order, which is the order they went out, decides. + /// the row's attempt is one such send followed too, a send's read can miss an earlier attempt, so their dates decide. static func isKnownEarlierAttempt(_ railPaymentId: String?, rowAttemptId: String?, keptEarlierAttemptIds: [String]) -> Bool { - guard let railPaymentId, railPaymentId != rowAttemptId, - let index = keptEarlierAttemptIds.firstIndex(of: railPaymentId) else { return false } - guard let rowIndex = rowAttemptId.flatMap(keptEarlierAttemptIds.firstIndex(of:)) else { return true } - return index < rowIndex + guard let railPaymentId, railPaymentId != rowAttemptId else { return false } + return keptEarlierAttemptIds.contains(railPaymentId) && !(rowAttemptId.map(keptEarlierAttemptIds.contains) ?? false) } /// Whether `railPaymentId` is another attempt than the row's, and not the send that went out after it: the send in - /// flight lists the attempts before it, and its failure is recorded before that list goes. Two attempts both kept past - /// a later send's hold are ordered by the kept list. + /// flight lists the attempts before it, and its failure is recorded before that list goes. Of two attempts in the same + /// second both kept past a later send's hold, the kept list's order, the order they went out, tells the later. static func isOtherRowAttempt( _ railPaymentId: String?, rowAttemptId: String?, diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index f5a671c1da..709b7054a4 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -246,6 +246,26 @@ final class SparkRelaunchActivityTests: XCTestCase { XCTAssertEqual(replayed.value, 500) } + func testANewerFailureTakesTheRowWhateverTheKeptOrder() async throws { + let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "ed", count: 16) + func failed(sats: UInt64, feeSats: UInt64, at timestamp: UInt64) -> PaymentDetails { + PaymentDetails( + id: hash, + kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), + amountMsat: sats * 1000, feePaidMsat: feeSats * 1000, direction: .outbound, status: .failed, latestUpdateTimestamp: timestamp + ) + } + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 300, feeSats: 1, at: 200), railPaymentId: "first") + // A send's read missed the first attempt, so a later send kept it after the second. + LightningService.shared.keepEarlierAttemptsForTesting(hash: hash, ids: ["second", "first"]) + + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 2, at: 300), railPaymentId: "second") + guard case let .lightning(row)? = try await CoreService.shared.activity.getActivity(id: hash) else { + return XCTFail("the row is missing") + } + XCTAssertEqual(row.value, 500, "the kept order outranked Spark's dates") + } + func testChannelFreeRowAttemptsKeepTheLatestRowWritersUpToTheLimit() throws { let suite = "ChannelFreeRowAttemptsTests-\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) From 496e01ccb078cead3c7afe8052d4d7465848a605 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 21:50:39 +0100 Subject: [PATCH 51/64] fix: spark replays a failure held during its send call A failure Spark reported while a send's call ran was dropped, so a call that returned the same payment pending left it held with no failure reported. The failure is now kept during the call and replayed once when the call returns that payment failed or pending; a succeeded result drops it. A wipe clears it. Verified: swiftformat lint; BitkitTests on the iPhone 17 Pro 2x simulator, new ChannelFreeRailTests cases included --- Bitkit/Managers/SparkManager.swift | 4 +- Bitkit/Services/LightningService.swift | 48 ++++++++++++++------ BitkitTests/ChannelFreeRailTests.swift | 62 +++++++++++++++++++++++--- 3 files changed, 94 insertions(+), 20 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 9cf81eebd5..068a7d2a42 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -659,7 +659,7 @@ final class SparkManager: ChannelFreeLightningRail { sats: UInt64?, maxFeeSats: UInt64?, beforeSubmission: @escaping () throws -> Void - ) async throws -> (paymentHash: PaymentHash, paymentId: String?, isFailed: Bool) { + ) async throws -> (paymentHash: PaymentHash, paymentId: String?, status: LDKNode.PaymentStatus) { let prepared: PrepareSendPaymentResponse let sdk: BreezSdk do { @@ -699,7 +699,7 @@ final class SparkManager: ChannelFreeLightningRail { } } Logger.info("Sent Spark payment '\(response.payment.id)' with status '\(response.payment.status)'", context: "SparkManager") - return (invoiceDetails.paymentHash, response.payment.id, response.payment.status == .failed) + return (invoiceDetails.paymentHash, response.payment.id, Self.ldkStatus(response.payment.status)) } nonisolated static func checkSendFee(_ feeSats: UInt64, maxFeeSats: UInt64?) throws { diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 328cb74773..1cbecfc18d 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -12,10 +12,9 @@ protocol ChannelFreeLightningRail: AnyObject { @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. Returns the payment's hash, the rail's id of this attempt and whether it - /// already failed. + /// payment goes out, as the node path does. Returns the payment's hash, the rail's id of this attempt and its status. func send(bolt11: String, sats: UInt64?, maxFeeSats: UInt64?, beforeSubmission: @escaping () throws -> Void) async throws - -> (paymentHash: PaymentHash, paymentId: String?, isFailed: Bool) + -> (paymentHash: PaymentHash, paymentId: String?, status: PaymentStatus) 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] @@ -171,6 +170,9 @@ class LightningService: NodeLifecycleService { /// Rail ids of attempts whose send call returned them failed and reported it, so Spark's own event for them is /// dropped and the failure reaches watchers once. private var railFailuresReportedByCall: Set = [] + /// The rail id of the last failure Spark reported for each invoice while a send of it was in Spark's send call, kept + /// for the call's result to settle. + private var railFailuresDuringCall: [String: String] = [:] /// Counts attempts recorded in this run, so a listing drops a hash just when the hash was recorded before the /// listing was read, never a retry recorded while it was read. private var attemptRecords = 0 @@ -1163,11 +1165,19 @@ class LightningService: NodeLifecycleService { } } ) - if let paymentHash, sent.isFailed { - // A failure Spark reported during the call was ignored, so the call's own failed result settles the - // send and reports it. - endRailSend(paymentHash: paymentHash) + if let paymentHash { + if sent.status != .failed { + // Spark took the send, which may still be pending: its own id and its earlier attempts stay known + // until it settles, so their failures don't end its hold. + takeRailSend(hash: paymentHash.lowercased(), paymentId: sent.paymentId, since: mark) + } + let failedDuringCall = endRailSendTakingFailure(paymentHash: paymentHash) isRailSendEnded = true + // A failure Spark reported during the call was held back, so the call's result settles the send: a + // failed result, or a pending one Spark had already failed under the same id, ends its hold. + let isFailed = sent.status == .failed + || sent.status == .pending && sent.paymentId != nil && failedDuringCall == sent.paymentId + guard isFailed else { return sent.paymentHash } defer { if let paymentId = sent.paymentId { eventCallbackLock.withLock { _ = railFailuresReportedByCall.insert(paymentId) } @@ -1177,10 +1187,6 @@ class LightningService: NodeLifecycleService { .paymentFailed(paymentId: paymentHash, paymentHash: paymentHash, reason: .unexpectedError), railPaymentId: sent.paymentId ) - } else if let paymentHash { - // Spark took the send, which may still be pending: its own id and its earlier attempts stay known until - // it settles, so their failures don't end its hold. - takeRailSend(hash: paymentHash.lowercased(), paymentId: sent.paymentId, since: mark) } return sent.paymentHash } catch let refusal as ChannelFreeRailSendRefused { @@ -1488,6 +1494,8 @@ class LightningService: NodeLifecycleService { railAttemptsStore.removeObject(forKey: Self.railAttemptsKey) railAttemptsStore.removeObject(forKey: Self.expiriesKey(Self.railAttemptsKey)) attemptRecordedAt[Self.railAttemptsKey] = nil + railFailuresDuringCall.removeAll() + railFailuresReportedByCall.removeAll() } } @@ -2014,7 +2022,12 @@ class LightningService: NodeLifecycleService { let hash = paymentHash.lowercased() return eventCallbackLock.withLock { // While a send of the invoice is in Spark's send call, its result settles it, whichever attempt failed. - guard !railSendsInFlight.contains(hash) else { return false } + guard !railSendsInFlight.contains(hash) else { + if let paymentId { + railFailuresDuringCall[hash] = paymentId + } + return false + } if let createdAt, isEarlierThanUncertainRailSendLocked(hash: hash, createdAt: createdAt, paymentId: paymentId) { return false } @@ -2226,7 +2239,16 @@ class LightningService: NodeLifecycleService { func endRailSend(paymentHash: String?) { guard let paymentHash else { return } - _ = eventCallbackLock.withLock { railSendsInFlight.remove(paymentHash.lowercased()) } + _ = endRailSendTakingFailure(paymentHash: paymentHash) + } + + /// Ends the send's time in Spark's send call and returns the rail id of a failure Spark reported for it meanwhile. + private func endRailSendTakingFailure(paymentHash: String) -> String? { + let hash = paymentHash.lowercased() + return eventCallbackLock.withLock { + railSendsInFlight.remove(hash) + return railFailuresDuringCall.removeValue(forKey: hash) + } } private func isRailSendInFlight(paymentHash: String) -> Bool { diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 8284914102..be818f547e 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1766,7 +1766,7 @@ extension ChannelFreeRailTests { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) var release: CheckedContinuation? rail.sendGate = { await withCheckedContinuation { release = $0 } } - rail.sentFailed = true + rail.sentStatus = .failed rail.sentPaymentId = "retry" rail.balanceSats = 100_000 var failures = 0 @@ -1798,6 +1798,58 @@ extension ChannelFreeRailTests { await assertReachesTheNode() } + func testASendReturnedPendingAfterSparkFailedItDuringTheCallReleasesTheHold() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + rail.sentPaymentId = "retry" + rail.balanceSats = 100_000 + var failures = 0 + Bitkit.LightningService.shared.setEventCallback { event in + if case .paymentFailed = event { + failures += 1 + } + } + // Spark fails the attempt while its send call hands it over, and the call returns it pending. + rail.sendGate = { + Bitkit.LightningService.shared.emitChannelFreeRailEvent( + .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), + railPaymentId: "retry" + ) + } + + _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + XCTAssertEqual(failures, 1, "The failure didn't reach watchers exactly once") + rail.listError = NSError(domain: "spark", code: 1) + rail.balanceSats = 0 + + await assertReachesTheNode() + } + + func testAnEarlierAttemptsFailureDuringTheCallLeavesAPendingSendHeld() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + rail.sentPaymentId = "retry" + rail.balanceSats = 100_000 + var failures = 0 + Bitkit.LightningService.shared.setEventCallback { event in + if case .paymentFailed = event { + failures += 1 + } + } + rail.sendGate = { + Bitkit.LightningService.shared.emitChannelFreeRailEvent( + .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), + railPaymentId: "earlier" + ) + } + + _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + XCTAssertEqual(failures, 0, "An earlier attempt's failure was reported for the pending send") + rail.sentBolt11 = nil + rail.listError = NSError(domain: "spark", code: 1) + rail.balanceSats = 0 + + await assertRefusedAsDuplicate() + } + // MARK: - Restore /// Marks the wallet restored `offset` seconds after the fixture invoice was created. @@ -2538,8 +2590,8 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { var sentBolt11: String? /// The rail's id of the attempt a send returns. var sentPaymentId: String? - /// Whether a send returns its attempt as failed. - var sentFailed = false + /// The status a send returns its attempt with. + var sentStatus: LDKNode.PaymentStatus = .pending var sends = 0 var sentFeeLimitSats: UInt64? var sendGate: (() async -> Void)? @@ -2569,7 +2621,7 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { } func send(bolt11: String, sats: UInt64?, maxFeeSats: UInt64?, beforeSubmission: @escaping () throws -> Void) async throws - -> (paymentHash: PaymentHash, paymentId: String?, isFailed: Bool) + -> (paymentHash: PaymentHash, paymentId: String?, status: LDKNode.PaymentStatus) { if let refusal { throw refusal @@ -2587,7 +2639,7 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { sentFeeLimitSats = maxFeeSats sentBolt11 = bolt11 sends += 1 - return ("ee", sentPaymentId, sentFailed) + return ("ee", sentPaymentId, sentStatus) } func estimateRoutingFees(bolt11: String, amountSats: UInt64?) async throws -> UInt64 { From 081bfdc22d6af2d849262b5d2a3e8b3d479b7169 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 22:38:12 +0100 Subject: [PATCH 52/64] fix: spark settles a held failure once A failure held during a send call that then threw was dropped; it is now replayed with Spark's date, so the rules of a send in doubt settle it. Whether the call's result fails the send is decided with the call's end, before the send is taken, so the taken-send expiry sweep never reports it too. Verified: swiftformat lint; BitkitTests on the iPhone 17 Pro 2x simulator, new ChannelFreeRailTests case included --- Bitkit/Services/LightningService.swift | 64 ++++++++++++++++---------- BitkitTests/ChannelFreeRailTests.swift | 28 +++++++++++ 2 files changed, 67 insertions(+), 25 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 1cbecfc18d..80b8665524 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -170,9 +170,9 @@ class LightningService: NodeLifecycleService { /// Rail ids of attempts whose send call returned them failed and reported it, so Spark's own event for them is /// dropped and the failure reaches watchers once. private var railFailuresReportedByCall: Set = [] - /// The rail id of the last failure Spark reported for each invoice while a send of it was in Spark's send call, kept - /// for the call's result to settle. - private var railFailuresDuringCall: [String: String] = [:] + /// The last failure Spark reported for each invoice while a send of it was in Spark's send call, by its rail id and + /// date, kept for the call's result to settle. + private var railFailuresDuringCall: [String: (id: String?, createdAt: UInt64?)] = [:] /// Counts attempts recorded in this run, so a listing drops a hash just when the hash was recorded before the /// listing was read, never a retry recorded while it was read. private var attemptRecords = 0 @@ -1166,27 +1166,15 @@ class LightningService: NodeLifecycleService { } ) if let paymentHash { - if sent.status != .failed { + isRailSendEnded = true + if endRailSendFailedByItsCall(paymentHash: paymentHash, paymentId: sent.paymentId, status: sent.status) { + // Reported without its rail id, which now drops Spark's own event for the attempt. + emitChannelFreeRailEvent(.paymentFailed(paymentId: paymentHash, paymentHash: paymentHash, reason: .unexpectedError)) + } else if sent.status != .failed { // Spark took the send, which may still be pending: its own id and its earlier attempts stay known // until it settles, so their failures don't end its hold. takeRailSend(hash: paymentHash.lowercased(), paymentId: sent.paymentId, since: mark) } - let failedDuringCall = endRailSendTakingFailure(paymentHash: paymentHash) - isRailSendEnded = true - // A failure Spark reported during the call was held back, so the call's result settles the send: a - // failed result, or a pending one Spark had already failed under the same id, ends its hold. - let isFailed = sent.status == .failed - || sent.status == .pending && sent.paymentId != nil && failedDuringCall == sent.paymentId - guard isFailed else { return sent.paymentHash } - defer { - if let paymentId = sent.paymentId { - eventCallbackLock.withLock { _ = railFailuresReportedByCall.insert(paymentId) } - } - } - emitChannelFreeRailEvent( - .paymentFailed(paymentId: paymentHash, paymentHash: paymentHash, reason: .unexpectedError), - railPaymentId: sent.paymentId - ) } return sent.paymentHash } catch let refusal as ChannelFreeRailSendRefused { @@ -1215,6 +1203,15 @@ class LightningService: NodeLifecycleService { Logger.info("Spark's send call of '\(paymentHash)' failed after its outcome arrived: \(error)", context: "LightningService") return paymentHash } + // A failure Spark reported during the call is settled by the rules of a send in doubt. + if let paymentHash, let failure = endRailSendTakingFailure(paymentHash: paymentHash) { + isRailSendEnded = true + emitChannelFreeRailEvent( + .paymentFailed(paymentId: paymentHash, paymentHash: paymentHash, reason: .unexpectedError), + paymentCreatedAt: failure.createdAt, + railPaymentId: failure.id + ) + } throw error } } @@ -2023,9 +2020,7 @@ class LightningService: NodeLifecycleService { return eventCallbackLock.withLock { // While a send of the invoice is in Spark's send call, its result settles it, whichever attempt failed. guard !railSendsInFlight.contains(hash) else { - if let paymentId { - railFailuresDuringCall[hash] = paymentId - } + railFailuresDuringCall[hash] = (paymentId, createdAt) return false } if let createdAt, isEarlierThanUncertainRailSendLocked(hash: hash, createdAt: createdAt, paymentId: paymentId) { @@ -2242,8 +2237,8 @@ class LightningService: NodeLifecycleService { _ = endRailSendTakingFailure(paymentHash: paymentHash) } - /// Ends the send's time in Spark's send call and returns the rail id of a failure Spark reported for it meanwhile. - private func endRailSendTakingFailure(paymentHash: String) -> String? { + /// Ends the send's time in Spark's send call and returns a failure Spark reported for it meanwhile. + private func endRailSendTakingFailure(paymentHash: String) -> (id: String?, createdAt: UInt64?)? { let hash = paymentHash.lowercased() return eventCallbackLock.withLock { railSendsInFlight.remove(hash) @@ -2251,6 +2246,25 @@ class LightningService: NodeLifecycleService { } } + /// Ends the send's time in Spark's send call and whether the call's result fails the send still held: a failed result, + /// or a pending one Spark failed under the same id during the call. Decided with the call's end, before the send is + /// taken, so no other path reports it; Spark's own event for the attempt is then dropped. + private func endRailSendFailedByItsCall(paymentHash: String, paymentId: String?, status: PaymentStatus) -> Bool { + let hash = paymentHash.lowercased() + return eventCallbackLock.withLock { + railSendsInFlight.remove(hash) + let failedDuringCall = railFailuresDuringCall.removeValue(forKey: hash) + // An outcome delivered during the call already settled it. + guard uncertainRailSendFailedAt()[hash] != nil else { return false } + let isFailed = status == .failed || status == .pending && paymentId != nil && failedDuringCall?.id == paymentId + guard isFailed else { return false } + if let paymentId { + railFailuresReportedByCall.insert(paymentId) + } + return true + } + } + private func isRailSendInFlight(paymentHash: String) -> Bool { eventCallbackLock.withLock { railSendsInFlight.contains(paymentHash.lowercased()) } } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index be818f547e..1c393270aa 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1824,6 +1824,34 @@ extension ChannelFreeRailTests { await assertReachesTheNode() } + func testAFailureDuringASendCallThatThenThrowsSettlesTheSendInDoubt() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + rail.balanceSats = 100_000 + var failures = 0 + Bitkit.LightningService.shared.setEventCallback { event in + if case .paymentFailed = event { + failures += 1 + } + } + // Spark fails the attempt during its send call, and the call then loses its connection. + rail.afterSubmission = { + Bitkit.LightningService.shared.emitChannelFreeRailEvent(.paymentFailed(paymentId: hash, paymentHash: hash, reason: nil)) + } + rail.errorAfterSubmission = NSError(domain: "spark", code: 2) + + do { + _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + XCTFail("The send call's error was swallowed") + } catch {} + XCTAssertEqual(failures, 1, "The failure held during the call was lost") + rail.afterSubmission = nil + rail.errorAfterSubmission = nil + rail.listError = NSError(domain: "spark", code: 1) + rail.balanceSats = 0 + + await assertReachesTheNode() + } + func testAnEarlierAttemptsFailureDuringTheCallLeavesAPendingSendHeld() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) rail.sentPaymentId = "retry" From a0ba3e12b1f2cdc55092ce91768b18208d43d121 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 20 Nov 2026 23:37:08 +0100 Subject: [PATCH 53/64] fix: spark holds a retry until its send settles A Lightning invoice is never sent through Spark again while an earlier Spark attempt on it is unresolved; the payment shows as pending until Spark settles or fails it. The send's start, kept in the existing uncertain-send record, decides: a failure Spark dates no more than 10 seconds before it is the send's own and ends it at once; an older one is an earlier attempt's and is ignored. A send Spark never settles ends at its invoice's expiry once a sync since the send reached Spark. Removes the retry hold layer and its saved journal from earlier pushes: attempt ids, taken and kept attempts, row writers, the in-call failure buffer and the 10-minute grace. Verified: unit suite (BitkitTests selection) passes on an iPhone 17 Pro simulator, iOS 26.5. --- Bitkit/Managers/SparkManager.swift | 86 +- Bitkit/Services/CoreService.swift | 263 +----- Bitkit/Services/LightningService.swift | 585 ++---------- .../Services/PaykitPaymentProofService.swift | 6 +- .../QuickPayPaymentCoordinator.swift | 2 +- Bitkit/ViewModels/WalletViewModel.swift | 2 +- BitkitTests/ChannelFreeRailTests.swift | 839 ++---------------- BitkitTests/SparkRelaunchActivityTests.swift | 329 ------- 8 files changed, 223 insertions(+), 1889 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 068a7d2a42..314b5eb197 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -420,10 +420,7 @@ final class SparkManager: ChannelFreeLightningRail { // Registered before the first refresh marks Spark ready, so Lightning calls never see it ready while they // still go to LDK, even when that refresh or the activity sync fails. An emergency exit keeps it out. LightningService.shared.channelFreePaymentHistory = self - LightningService.shared.railSendHoldExpired = { [weak self] hash in await self?.recordExpiredHold(paymentHash: hash) ?? false } - LightningService.shared.railTakenSendUnlisted = { hash, ownAttemptId in - await Self.failHeldSendRow(paymentHash: hash, ownAttemptId: ownAttemptId) - } + LightningService.shared.railSendExpired = { [weak self] hash in await self?.recordExpiredSend(paymentHash: hash) ?? false } if !isExiting { LightningService.shared.channelFreeRail = self } @@ -659,7 +656,7 @@ final class SparkManager: ChannelFreeLightningRail { sats: UInt64?, maxFeeSats: UInt64?, beforeSubmission: @escaping () throws -> Void - ) async throws -> (paymentHash: PaymentHash, paymentId: String?, status: LDKNode.PaymentStatus) { + ) async throws -> PaymentHash { let prepared: PrepareSendPaymentResponse let sdk: BreezSdk do { @@ -699,7 +696,7 @@ final class SparkManager: ChannelFreeLightningRail { } } Logger.info("Sent Spark payment '\(response.payment.id)' with status '\(response.payment.status)'", context: "SparkManager") - return (invoiceDetails.paymentHash, response.payment.id, Self.ldkStatus(response.payment.status)) + return invoiceDetails.paymentHash } nonisolated static func checkSendFee(_ feeSats: UInt64, maxFeeSats: UInt64?) throws { @@ -783,8 +780,7 @@ final class SparkManager: ChannelFreeLightningRail { status: Self.ldkStatus(payment.status), preimage: htlcDetails.preimage, timestamp: payment.timestamp, - feeSats: Self.sats(payment.fees), - id: payment.id + feeSats: Self.sats(payment.fees) ) } } @@ -1856,64 +1852,33 @@ final class SparkManager: ChannelFreeLightningRail { return result } - /// Writes the activity of a send whose hold ended at its invoice's expiry: Spark's latest send of it, or a failure - /// of the stored pending send when Spark lists none. Returns whether it was saved. - private func recordExpiredHold(paymentHash: String) async -> Bool { + /// Writes the Activity row of a send Spark never settled once its invoice expired: Spark's own attempt of it, not one + /// listed before it went out, or a failure of the stored pending send when Spark lists none. Returns whether it was saved. + private func recordExpiredSend(paymentHash: String) async -> Bool { guard let payments = try? await requireSdk().listPayments(request: ListPaymentsRequest()).payments else { return false } - return await Self.recordExpiredHold( - paymentHash: paymentHash, - payments: payments, - earlierAttemptIds: Set(LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: paymentHash)), - record: { await self.recordActivity($0) }, - failStoredSend: { await Self.failHeldSendRow(paymentHash: $0, ownAttemptId: nil) } - ) - } - - private static func failHeldSendRow(paymentHash: String, ownAttemptId: String?) async -> Bool { - await (try? CoreService.shared.activity.failPendingLightningSend( - id: paymentHash, - ownAttemptId: ownAttemptId, - earlierAttemptIds: Set(LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: paymentHash)) - )) != nil - } - - static func recordExpiredHold( - paymentHash: String, - payments: [Payment], - earlierAttemptIds: Set = [], - record: (Payment) async -> Bool, - failStoredSend: (String) async -> Bool - ) async -> Bool { - let sends = payments.filter { payment in - guard payment.paymentType == .send, case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details else { return false } - return htlcDetails.paymentHash.caseInsensitiveCompare(paymentHash) == .orderedSame - } - // A live send is the one that pays the invoice: not one the held send followed, then the newest. A listed failure - // may be an earlier attempt's, whose amount and fee aren't the held send's, so without a live send the stored row - // is failed in place. - if let live = sends.filter({ $0.status != .failed }) - .max(by: { (earlierAttemptIds.contains($0.id) ? 0 : 1, $0.timestamp) < (earlierAttemptIds.contains($1.id) ? 0 : 1, $1.timestamp) }) - { - return await record(live) + let own = payments.filter { payment in + guard payment.paymentType == .send, case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details, + htlcDetails.paymentHash.caseInsensitiveCompare(paymentHash) == .orderedSame else { return false } + return !LightningService.shared.isEarlierRailAttempt(paymentHash: paymentHash, createdAt: payment.timestamp) + } + if let latest = own.max(by: { $0.timestamp < $1.timestamp }) { + return await recordActivity(latest) } - return await failStoredSend(paymentHash) + return await (try? CoreService.shared.activity.failPendingLightningSend(id: paymentHash)) != nil } /// Payment hashes whose every Lightning send failed, so a hold on a channel retry can be released. A failure of an - /// attempt before a send Spark took doesn't count: that send may still pay the invoice. + /// attempt before a send Spark hasn't settled yet doesn't count: that send may still pay the invoice. nonisolated static func failedSendHashes( _ payments: [Payment], - earlierAttemptIds: [String: [String]] = [:], - takenIds: [String: String] = [:] + isEarlierAttempt: (_ hash: String, _ createdAt: UInt64) -> Bool = { _, _ in false } ) -> [String] { var failed: [String] = [] var live: Set = [] for payment in payments where payment.paymentType == .send { guard case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details else { continue } if payment.status == .failed { - guard !LightningService.isEarlierRailAttempt( - id: payment.id, hash: htlcDetails.paymentHash.lowercased(), taken: takenIds, earlier: earlierAttemptIds - ) else { continue } + guard !isEarlierAttempt(htlcDetails.paymentHash, payment.timestamp) else { continue } failed.append(htlcDetails.paymentHash) } else { live.insert(htlcDetails.paymentHash) @@ -1942,10 +1907,9 @@ final class SparkManager: ChannelFreeLightningRail { /// so a retry the user started meanwhile keeps its hold, as does one recorded or ending while the list is read. static func releaseFailedSendHolds(listPayments: () async throws -> [Payment]) async { let mark = LightningService.shared.attemptMark - let earlier = LightningService.shared.railSendEarlierAttemptIds - let taken = LightningService.shared.railSendTakenIds guard let latest = try? await listPayments() else { return } - for paymentHash in failedSendHashes(latest, earlierAttemptIds: earlier, takenIds: taken) { + let isEarlierAttempt = { LightningService.shared.isEarlierRailAttempt(paymentHash: $0, createdAt: $1) } + for paymentHash in failedSendHashes(latest, isEarlierAttempt: isEarlierAttempt) { LightningService.shared.releaseRailAttempt(paymentHash: paymentHash, since: mark) } } @@ -1991,7 +1955,7 @@ final class SparkManager: ChannelFreeLightningRail { await Self.handleSettledPayment( payment, record: { await self.recordActivity($0) }, - emit: { LightningService.shared.emitChannelFreeRailEvent($0, paymentCreatedAt: payment.timestamp, railPaymentId: payment.id) }, + emit: { LightningService.shared.emitChannelFreeRailEvent($0, paymentCreatedAt: payment.timestamp) }, refresh: { try await self.refresh() } ) case let .paymentPending(payment): @@ -2028,6 +1992,12 @@ final class SparkManager: ChannelFreeLightningRail { @discardableResult private func recordActivity(_ payment: Payment) async -> Bool { guard case let .lightning(description, invoice, _, htlcDetails, _, _, _, _) = payment.details else { return true } + // A failure of an attempt before a send Spark hasn't settled yet leaves that send's row pending. + if payment.paymentType == .send, payment.status == .failed, + LightningService.shared.isEarlierRailAttempt(paymentHash: htlcDetails.paymentHash, createdAt: payment.timestamp) + { + return true + } let details = PaymentDetails( id: htlcDetails.paymentHash, kind: .bolt11( @@ -2049,7 +2019,7 @@ final class SparkManager: ChannelFreeLightningRail { sendsRecordedWithoutFee.remove(payment.id) } do { - try await CoreService.shared.activity.recordChannelFreeRailPayment(details, railPaymentId: payment.id) + try await CoreService.shared.activity.recordChannelFreeRailPayment(details) unsavedPayments.remove(payment.id) return true } catch { diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index dd0fcc26f8..f768327fe7 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -951,9 +951,9 @@ class ActivityService { /// Records a Lightning payment the channel-free rail sent or received the way an LDK payment is recorded, so it keeps /// its Paykit contact and seen state across syncs. - func recordChannelFreeRailPayment(_ payment: PaymentDetails, railPaymentId: String? = nil) async throws { + func recordChannelFreeRailPayment(_ payment: PaymentDetails) async throws { try await ServiceQueue.background(.core) { - try await self.processLightningPayment(payment, rail: .channelFree, railPaymentId: railPaymentId) + try await self.processLightningPayment(payment, rail: .channelFree) } } @@ -961,30 +961,16 @@ class ActivityService { /// so a send recorded after the app was killed mid-payment still names its contact. nonisolated(unsafe) static var sentPaymentContacts = SentPaymentContacts(defaults: .standard) - /// The Spark id of the attempt each channel-free send row was last written from, by payment hash. - nonisolated(unsafe) static var channelFreeRowAttempts = ChannelFreeRowAttempts(defaults: .standard) - - /// Whether a Lightning activity keeps its status against an update: a settled payment stays settled, a failure from - /// the rail that didn't carry the latest attempt is stale, and a failed Spark send keeps its row against the failure - /// of an older attempt, as Spark lists one failure per attempt, each with its own amount and fee. The row's own - /// attempt and later ones still update it. - static func keepsLightningStatus( - existing: BitkitCore.PaymentState, - update: BitkitCore.PaymentState, - isStaleRailFailure: Bool, - isOlderChannelFreeAttempt: Bool = false - ) -> Bool { + /// Whether a Lightning activity keeps its status against an update: a settled payment stays settled, and a failure + /// from the rail that didn't carry the latest attempt is stale. + static func keepsLightningStatus(existing: BitkitCore.PaymentState, update: BitkitCore.PaymentState, isStaleRailFailure: Bool) -> Bool { if existing == .succeeded, update != .succeeded { return true } - if isOlderChannelFreeAttempt, existing == .failed, update == .failed { - return true - } return update == .failed && existing != .failed && isStaleRailFailure } - /// `railPaymentId` is the channel-free rail's id of the attempt, which a retried invoice lists once per attempt. - private func processLightningPayment(_ payment: PaymentDetails, rail: LightningPaymentRail = .ldk, railPaymentId: String? = nil) async throws { + private func processLightningPayment(_ payment: PaymentDetails, rail: LightningPaymentRail = .ldk) async throws { guard case let .bolt11(_, preimage, _, description, bolt11) = payment.kind else { return } // Skip pending inbound payments - just means they created an invoice @@ -1018,28 +1004,6 @@ class ActivityService { existing: existing.status, update: state, isStaleRailFailure: LightningService.shared.isStaleFailure(paymentHash: payment.id, from: rail) - // Spark's failure of an attempt it created before a retry still in doubt went out. - || (rail == .channelFree && LightningService.shared.isEarlierThanUncertainRailSend( - paymentHash: payment.id, - createdAt: paymentTimestamp, - paymentId: railPaymentId - )), - // Spark dates an attempt at its start, so an older one's failure is dated before the row's attempt, or - // in the same second when the retry started at once; then the row's own Spark id tells them apart, with the - // send's earlier attempts kept past its hold. The held attempt's own failure always writes. - isOlderChannelFreeAttempt: rail == .channelFree && payment.direction == .outbound - && (railPaymentId == nil || railPaymentId != LightningService.shared.heldRailSendId(paymentHash: payment.id)) - && (paymentTimestamp < existing.timestamp || paymentTimestamp == existing.timestamp && Self.isOtherRowAttempt( - railPaymentId, - rowAttemptId: Self.channelFreeRowAttempts.attemptId(forPaymentHash: payment.id, row: existing), - earlierAttemptIds: (LightningService.shared.railSendEarlierAttemptIds[payment.id.lowercased()] ?? []) - + LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: payment.id), - keptEarlierAttemptIds: LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: payment.id) - ) || Self.isKnownEarlierAttempt( - railPaymentId, - rowAttemptId: Self.channelFreeRowAttempts.attemptId(forPaymentHash: payment.id, row: existing), - keptEarlierAttemptIds: LightningService.shared.keptRailSendEarlierAttemptIds(paymentHash: payment.id) - )) ) { return @@ -1093,81 +1057,27 @@ class ActivityService { try self.settleMove(latest, receiveState: state) return } - // The writer is kept before the row is written, so a stop between the two never leaves the row to an earlier - // writer, and put back when the write fails. - let previousWriter = Self.channelFreeRowAttempts.entry(forPaymentHash: payment.id) - let isWriterKept = rail == .channelFree && payment.direction == .outbound && railPaymentId != nil - if isWriterKept, let railPaymentId { - let previousRow: LightningActivity? = if case let .lightning(latest)? = latestActivity { - latest - } else { - nil - } - Self.channelFreeRowAttempts.remember( - railPaymentId, - forPaymentHash: payment.id, - stamp: ChannelFreeRowAttempts.stamp(ln), - previousRowStamp: previousRow.map(ChannelFreeRowAttempts.stamp) - ) - } - do { - guard let latestActivity else { - try upsertActivity(activity: .lightning(ln)) - if isWriterKept { - Self.channelFreeRowAttempts.commit(forPaymentHash: payment.id) - } - self.updateBoostTxIdsCache(for: .lightning(ln)) - self.activitiesChangedSubject.send() - return - } - var updated = ln - if case let .lightning(latest) = latestActivity, latest.contact != existingLightning?.contact { - updated.contact = latest.contact - } - if self.isContactDetached(activityId: payment.id, walletId: ln.walletId) { - updated.contact = nil - } - try updateActivity(activityId: payment.id, activity: .lightning(updated)) - if isWriterKept { - Self.channelFreeRowAttempts.commit(forPaymentHash: payment.id) - } + guard let latestActivity else { + try upsertActivity(activity: .lightning(ln)) + self.updateBoostTxIdsCache(for: .lightning(ln)) self.activitiesChangedSubject.send() - } catch { - Self.channelFreeRowAttempts.restore(previousWriter, forPaymentHash: payment.id) - throw error + return + } + var updated = ln + if case let .lightning(latest) = latestActivity, latest.contact != existingLightning?.contact { + updated.contact = latest.contact } + if self.isContactDetached(activityId: payment.id, walletId: ln.walletId) { + updated.contact = nil + } + try updateActivity(activityId: payment.id, activity: .lightning(updated)) + self.activitiesChangedSubject.send() } if payment.direction == .outbound, ln.contact != nil, payment.status != .pending { Self.sentPaymentContacts.forget(paymentHash: payment.id) } } - /// Whether `railPaymentId` is an attempt a send of the invoice followed, before the row's, whatever Spark's dates. When - /// the row's attempt is one such send followed too, a send's read can miss an earlier attempt, so their dates decide. - static func isKnownEarlierAttempt(_ railPaymentId: String?, rowAttemptId: String?, keptEarlierAttemptIds: [String]) -> Bool { - guard let railPaymentId, railPaymentId != rowAttemptId else { return false } - return keptEarlierAttemptIds.contains(railPaymentId) && !(rowAttemptId.map(keptEarlierAttemptIds.contains) ?? false) - } - - /// Whether `railPaymentId` is another attempt than the row's, and not the send that went out after it: the send in - /// flight lists the attempts before it, and its failure is recorded before that list goes. Of two attempts in the same - /// second both kept past a later send's hold, the kept list's order, the order they went out, tells the later. - static func isOtherRowAttempt( - _ railPaymentId: String?, - rowAttemptId: String?, - earlierAttemptIds: [String]? = nil, - keptEarlierAttemptIds: [String] = [] - ) -> Bool { - guard let railPaymentId, let rowAttemptId, railPaymentId != rowAttemptId else { return false } - if let index = keptEarlierAttemptIds.firstIndex(of: railPaymentId), - let rowIndex = keptEarlierAttemptIds.firstIndex(of: rowAttemptId) - { - return index < rowIndex - } - let isLaterSend = earlierAttemptIds.map { $0.contains(rowAttemptId) && !$0.contains(railPaymentId) } ?? false - return !isLaterSend - } - /// A succeeded Spark receive proves the move's LDK send settled, so the send's row becomes succeeded and keeps its amount and fee. private func settleMove(_ sent: LightningActivity, receiveState: BitkitCore.PaymentState) throws { guard receiveState == .succeeded, sent.status != .succeeded else { return } @@ -1490,40 +1400,16 @@ class ActivityService { return !onchain.doesExist && onchain.txType == .sent && txIdsInBoostTxIds.contains(onchain.txId) } - /// Marks the stored Lightning send `id` failed while it is still pending. - /// Read, checked and written in one core-queue operation, so a change saved meanwhile isn't overwritten. The row is - /// the held send's now: it takes `ownAttemptId` as the attempt that wrote it when known, and otherwise drops one of - /// `earlierAttemptIds`. Saved before the row fails, so a stop in between finds the row pending and redoes both. - func failPendingLightningSend(id: String, ownAttemptId: String? = nil, earlierAttemptIds: Set = []) async throws { + /// Marks the stored Lightning send `id` failed while it is still pending, read, checked and written in one core-queue + /// operation, so a change saved meanwhile isn't overwritten. + func failPendingLightningSend(id: String) async throws { try await ServiceQueue.background(.core) { guard case let .lightning(activity) = try getActivityById(walletId: WalletScope.default, activityId: id), activity.txType == .sent, activity.status == .pending else { return } - let previousWriter = Self.channelFreeRowAttempts.entry(forPaymentHash: id) var failed = activity failed.status = .failed - if let ownAttemptId { - Self.channelFreeRowAttempts.remember( - ownAttemptId, - forPaymentHash: id, - stamp: ChannelFreeRowAttempts.stamp(failed), - previousRowStamp: ChannelFreeRowAttempts.stamp(activity) - ) - } else if let rowAttemptId = Self.channelFreeRowAttempts.attemptId(forPaymentHash: id, row: activity), - earlierAttemptIds.contains(rowAttemptId), - !Self.channelFreeRowAttempts.isUnchanged(activity, forPaymentHash: id) - { - // A retry wrote over the earlier attempt's row. One the earlier attempt still owns keeps its writer, so - // that attempt's final fee still lands. - Self.channelFreeRowAttempts.forget(paymentHash: id) - } - do { - try updateActivity(activityId: id, activity: .lightning(failed)) - Self.channelFreeRowAttempts.commit(forPaymentHash: id) - } catch { - Self.channelFreeRowAttempts.restore(previousWriter, forPaymentHash: id) - throw error - } + try updateActivity(activityId: id, activity: .lightning(failed)) self.activitiesChangedSubject.send() } } @@ -2951,106 +2837,3 @@ struct SentPaymentContacts: @unchecked Sendable { } } } - -/// Kept as `[hash, id]` pairs, oldest first, for the latest `limit` hashes and those of sends with kept earlier attempts. -struct ChannelFreeRowAttempts: @unchecked Sendable { - private static let key = "channelFreeRowAttemptIds" - private static let lock = NSLock() - static let limit = 100 - let defaults: UserDefaults - - /// The row as its writer left it, so a later write by another payment shows, even one alike but for its status. - static func stamp(_ row: LightningActivity) -> String { - "\(row.timestamp):\(row.value):\(row.fee ?? 0):\(row.status)" - } - - /// Kept ahead of the row it writes, beside the previous writer and its stamp (none: an empty id and the row's stamp - /// then), until `commit` once the row is saved, so a stop in between still finds the row's real writer. - func remember(_ attemptId: String, forPaymentHash paymentHash: String, stamp: String, previousRowStamp: String? = nil) { - let hash = paymentHash.lowercased() - Self.lock.withLock { - var entries = defaults.array(forKey: Self.key) as? [[String]] ?? [] - let previous = entries.last { $0.first == hash } - let entry = if let previous, previous.count == 5, previousRowStamp == previous[4] { - // A write cut off before its row was saved: the row is still the previous writer's. - [hash, attemptId, stamp, previous[3], previous[4]] - } else if let previous, previous.count >= 3 { - [hash, attemptId, stamp, previous[1], previous[2]] - } else { - [hash, attemptId, stamp, "", previousRowStamp ?? ""] - } - guard previous != entry, previous.map({ Array($0.prefix(3)) }) != [hash, attemptId, stamp] else { return } - entries.removeAll { $0.first == hash } - entries.append(entry) - defaults.set(capped(entries), forKey: Self.key) - } - } - - /// The row is saved: its writer no longer needs the previous one beside it. - func commit(forPaymentHash paymentHash: String) { - let hash = paymentHash.lowercased() - Self.lock.withLock { - guard var entries = defaults.array(forKey: Self.key) as? [[String]], - let index = entries.lastIndex(where: { $0.first == hash }), entries[index].count > 3 - else { return } - entries[index] = Array(entries[index].prefix(3)) - defaults.set(entries, forKey: Self.key) - } - } - - /// The writer of `row`: the kept one, unless `row` still matches the previous writer's stamp, as a write cut off - /// before its row was saved leaves it. - private func writer(forPaymentHash paymentHash: String, row: LightningActivity?) -> (id: String, stamp: String)? { - guard let entry = entry(forPaymentHash: paymentHash), entry.count >= 3 else { return nil } - if entry.count == 5, let row, Self.stamp(row) == entry[4] { - return entry[3].isEmpty ? nil : (entry[3], entry[4]) - } - return (entry[1], entry[2]) - } - - /// The kept entry of the row of `paymentHash`, to put back with `restore`. - func entry(forPaymentHash paymentHash: String) -> [String]? { - let hash = paymentHash.lowercased() - return (defaults.array(forKey: Self.key) as? [[String]])?.last { $0.first == hash } - } - - func restore(_ entry: [String]?, forPaymentHash paymentHash: String) { - let hash = paymentHash.lowercased() - Self.lock.withLock { - var entries = defaults.array(forKey: Self.key) as? [[String]] ?? [] - entries.removeAll { $0.first == hash } - if let entry { - entries.append(entry) - } - defaults.set(capped(entries), forKey: Self.key) - } - } - - /// Keeps the latest `limit` writers of sends without kept earlier attempts, and those of retried sends, which the - /// earlier attempts' own cap bounds. - private func capped(_ entries: [[String]]) -> [[String]] { - guard entries.count > Self.limit else { return entries } - let kept = defaults.array(forKey: LightningService.keptRailSendEarlierAttemptsKey) as? [[String]] ?? [] - let retried = Set(kept.compactMap(\.first)) - let dropped = Set(entries.compactMap(\.first).filter { !retried.contains($0) }.dropLast(Self.limit)) - return entries.filter { !dropped.contains($0.first ?? "") } - } - - /// Whether `row` is as its writer left it. - func isUnchanged(_ row: LightningActivity, forPaymentHash paymentHash: String) -> Bool { - writer(forPaymentHash: paymentHash, row: row)?.stamp == Self.stamp(row) - } - - func forget(paymentHash: String) { - let hash = paymentHash.lowercased() - Self.lock.withLock { - guard var pairs = defaults.array(forKey: Self.key) as? [[String]], pairs.contains(where: { $0.first == hash }) else { return } - pairs.removeAll { $0.first == hash } - defaults.set(pairs, forKey: Self.key) - } - } - - func attemptId(forPaymentHash paymentHash: String, row: LightningActivity? = nil) -> String? { - writer(forPaymentHash: paymentHash, row: row)?.id - } -} diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 80b8665524..cb4c78b867 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -12,9 +12,8 @@ protocol ChannelFreeLightningRail: AnyObject { @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. Returns the payment's hash, the rail's id of this attempt and its status. - func send(bolt11: String, sats: UInt64?, maxFeeSats: UInt64?, beforeSubmission: @escaping () throws -> Void) async throws - -> (paymentHash: PaymentHash, paymentId: String?, status: PaymentStatus) + /// payment goes out, as the node path does. + func send(bolt11: String, sats: UInt64?, maxFeeSats: UInt64?, 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] @@ -78,8 +77,6 @@ struct ChannelFreeRailPayment: Equatable { let preimage: String? var timestamp: UInt64 = 0 var feeSats: UInt64 = 0 - /// The rail's id of this attempt; a retried invoice lists one per attempt. - var id: String? /// The attempt that decides an outbound payment of `paymentHash`: a retried invoice is listed once per attempt, /// so a pending or settled one wins over failed ones, then the newest. @@ -167,12 +164,6 @@ class LightningService: NodeLifecycleService { private var attemptRails: [String: LightningPaymentRail] = [:] /// Payment hashes inside a rail send, which Spark lists only once it returns. private var railSendsInFlight: Set = [] - /// Rail ids of attempts whose send call returned them failed and reported it, so Spark's own event for them is - /// dropped and the failure reaches watchers once. - private var railFailuresReportedByCall: Set = [] - /// The last failure Spark reported for each invoice while a send of it was in Spark's send call, by its rail id and - /// date, kept for the call's result to settle. - private var railFailuresDuringCall: [String: (id: String?, createdAt: UInt64?)] = [:] /// Counts attempts recorded in this run, so a listing drops a hash just when the hash was recorded before the /// listing was read, never a retry recorded while it was read. private var attemptRecords = 0 @@ -184,12 +175,9 @@ class LightningService: NodeLifecycleService { /// The rail whose payments the duplicate-payment check reads, kept while an emergency exit takes Spark off /// Lightning: an invoice Spark paid or is paying is never paid again over a channel. weak var channelFreePaymentHistory: ChannelFreeLightningRail? - /// Writes the activity of a rail send in doubt once its hold ends at its invoice's expiry, as the failure of an - /// earlier attempt that came meanwhile left the row pending. Returns whether the activity was saved. - var railSendHoldExpired: ((String) async -> Bool)? - /// Fails the stored Activity row of a send Spark took but never listed, once its hold ends past its invoice's expiry, - /// keeping the row's own amount and fee. Returns whether the row was saved. - var railTakenSendUnlisted: ((_ paymentHash: String, _ ownAttemptId: String?) async -> Bool)? + /// Writes the Activity row of a rail send Spark never settled once its invoice expired: from Spark's own attempt of it + /// when listed, otherwise by failing the stored pending row. Returns whether the row was saved. + var railSendExpired: ((String) async -> Bool)? var onchainTransactionConfirmed: (@Sendable (String) async -> Void)? var onchainTransactionReceived: (@Sendable (String) async -> Void)? typealias OnchainActivityCompletion = @MainActor () async -> Void @@ -1105,15 +1093,13 @@ class LightningService: NodeLifecycleService { let mark = attemptMark if !channelsOnly, let rail = channelFreeRail, await shouldPayWithRail(rail, bolt11: bolt11, sats: sats) { // LDK refuses its own repeats; Spark doesn't, so a Spark send checks both rails. - var earlierAttemptIds: [String]? if let paid = try await settledEarlierAttempt( paymentHash: paymentHash, on: [.ldk, .channelFree], bolt11: bolt11, sats: sats, invoiceCreatedAt: invoice?.secondsSinceEpoch(), - invoiceExpiresAt: expiresAt, - readRailPayments: { earlierAttemptIds = Self.railAttemptIds($0, paymentHash: paymentHash) } + invoiceExpiresAt: expiresAt ) { return paid } @@ -1143,7 +1129,7 @@ class LightningService: NodeLifecycleService { } var isRefusedAtAdmission = false do { - let sent = try await rail.send( + return try await rail.send( bolt11: bolt11, sats: sats, maxFeeSats: params?.maxTotalRoutingFeeMsat.map { $0 / 1000 } @@ -1159,24 +1145,13 @@ 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) - // Kept until the call returns, so a send cut off by process death stays held after a relaunch. + // Kept until Spark settles the attempt, so no retry of the invoice starts meanwhile, also after a + // relaunch. if let paymentHash { - self?.markRailSendUncertain(paymentHash: paymentHash, since: mark, earlierAttemptIds: earlierAttemptIds) + self?.markRailSendUncertain(paymentHash: paymentHash, since: mark) } } ) - if let paymentHash { - isRailSendEnded = true - if endRailSendFailedByItsCall(paymentHash: paymentHash, paymentId: sent.paymentId, status: sent.status) { - // Reported without its rail id, which now drops Spark's own event for the attempt. - emitChannelFreeRailEvent(.paymentFailed(paymentId: paymentHash, paymentHash: paymentHash, reason: .unexpectedError)) - } else if sent.status != .failed { - // Spark took the send, which may still be pending: its own id and its earlier attempts stay known - // until it settles, so their failures don't end its hold. - takeRailSend(hash: paymentHash.lowercased(), paymentId: sent.paymentId, since: mark) - } - } - return sent.paymentHash } catch let refusal as ChannelFreeRailSendRefused { // Nothing left the wallet, and the checks above leave no earlier live attempt under this hash. if let paymentHash { @@ -1195,22 +1170,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. One an outcome - // already settled while the call returned is read as sent, so its caller reads that outcome. - if let paymentHash, - markRailSendUncertain(paymentHash: paymentHash, since: mark, earlierAttemptIds: earlierAttemptIds, ifStillInDoubt: true) - { - Logger.info("Spark's send call of '\(paymentHash)' failed after its outcome arrived: \(error)", context: "LightningService") - return paymentHash - } - // A failure Spark reported during the call is settled by the rules of a send in doubt. - if let paymentHash, let failure = endRailSendTakingFailure(paymentHash: paymentHash) { - isRailSendEnded = true - emitChannelFreeRailEvent( - .paymentFailed(paymentId: paymentHash, paymentHash: paymentHash, reason: .unexpectedError), - paymentCreatedAt: failure.createdAt, - railPaymentId: failure.id - ) + // A send that failed once submitted may still go out, so its outcome waits for a later sync. + if let paymentHash { + markRailSendUncertain(paymentHash: paymentHash, since: mark) } throw error } @@ -1269,26 +1231,10 @@ class LightningService: NodeLifecycleService { /// The clock a trim checks invoice expiries against; tests set it. var now: () -> Date = Date.init private static let railAttemptsKey = "channelFreeRailAttemptedPaymentHashes" - /// Rail sends submitted but not returned, or that failed after they were submitted, by hash, with the time they - /// were submitted or failed in seconds since 1970. Kept across launches, as Spark may still resume one after a - /// relaunch while its list shows an earlier failed attempt. + /// Rail sends Spark hasn't settled yet, from submission until Spark reports or lists their attempt succeeded or failed, + /// or their invoice expired, by hash, with the time they were submitted in seconds since 1970. No other + /// send of the invoice starts meanwhile. Kept across launches, as Spark may still resume one after a relaunch. private static let uncertainRailSendsKey = "channelFreeRailUncertainSendFailedAt" - /// When each of those sends was submitted, in seconds since 1970, so a failure Spark reports for a payment it created - /// before then is known to belong to an earlier attempt. - private static let uncertainRailSendsStartedKey = "channelFreeRailUncertainSendStartedAt" - /// The rail's ids of the attempts each of those sends followed, so a failure of one is told from the send's own. - private static let uncertainRailSendsEarlierAttemptsKey = "channelFreeRailUncertainSendEarlierAttempts" - /// The rail's ids of the attempts each send followed, kept past its hold as `[hash, ids…]` for the latest - /// `keptEarlierAttemptsLimit` hashes, so a failure of one never writes over the send's own row after a restart. - static let keptRailSendEarlierAttemptsKey = "channelFreeRailKeptSendEarlierAttempts" - static let keptEarlierAttemptsLimit = 100 - /// The rail's id of each send Spark took, by hash, until it settles: any other attempt's failure is an earlier one's. - private static let takenRailSendsKey = "channelFreeRailTakenSendIds" - /// Taken sends Spark never listed whose hold ended before their row was failed, with the attempt each took, by hash, - /// retried on each rail sync. - private static let unlistedTakenRailSendsUnfailedKey = "channelFreeRailUnlistedTakenSendsUnfailedIds" - /// Hashes whose hold ended at their invoice's expiry before their activity was saved, retried on each rail sync. - private static let expiredRailHoldsUnrecordedKey = "channelFreeRailExpiredHoldsUnrecorded" /// A listing drops the hashes it shows failed only, or paid once the invoice has expired, so the other rail can't /// pay it again, and ones it doesn't show once the invoice expired `unlistedAttemptSettleSeconds` ago. Paid or /// unlisted hashes with no known expiry (kept before expiries were, or whose invoice can't be parsed) are dropped @@ -1426,9 +1372,7 @@ class LightningService: NodeLifecycleService { if let mark, attemptsLive(since: mark, key: Self.railAttemptsKey).contains(hash) { return } - // The send's own outcome is known: its hold ends with the expiry the sweep would have ended it by. removeAttempt(paymentHash: hash, key: Self.railAttemptsKey) - clearRailSendUncertainty(hash: hash) } } @@ -1482,17 +1426,9 @@ class LightningService: NodeLifecycleService { func forgetRailAttempts() { eventCallbackLock.withLock { railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsKey) - railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsStartedKey) - railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsEarlierAttemptsKey) - railAttemptsStore.removeObject(forKey: Self.keptRailSendEarlierAttemptsKey) - railAttemptsStore.removeObject(forKey: Self.takenRailSendsKey) - railAttemptsStore.removeObject(forKey: Self.unlistedTakenRailSendsUnfailedKey) - railAttemptsStore.removeObject(forKey: Self.expiredRailHoldsUnrecordedKey) railAttemptsStore.removeObject(forKey: Self.railAttemptsKey) railAttemptsStore.removeObject(forKey: Self.expiriesKey(Self.railAttemptsKey)) attemptRecordedAt[Self.railAttemptsKey] = nil - railFailuresDuringCall.removeAll() - railFailuresReportedByCall.removeAll() } } @@ -1548,29 +1484,14 @@ class LightningService: NodeLifecycleService { let outbound = payments.filter { $0.direction == .outbound } let hashes = { (status: PaymentStatus) in Set(outbound.filter { $0.status == status }.map { $0.paymentHash.lowercased() }) } return eventCallbackLock.withLock { - // A held send's earlier attempts settle nothing: only its own failure, or any payment of the invoice, does. - let taken = takenRailSendIds() - let earlier = uncertainRailSendEarlierAttempts() - let held = Set(taken.keys).union(earlier.keys) - let ownFailed = Set(outbound.filter { payment in - let hash = payment.paymentHash.lowercased() - guard payment.status == .failed else { return false } - guard let id = payment.id else { return true } - return !Self.isEarlierRailAttempt(id: id, hash: hash, taken: taken, earlier: earlier) - }.map { $0.paymentHash.lowercased() }) + // A send Spark hasn't settled keeps its record and expiry, whatever its earlier attempts show. let live = hashes(.pending).union(attemptsLive(since: mark, key: Self.railAttemptsKey)) - .union(held.subtracting(ownFailed).subtracting(hashes(.succeeded))) + .union(uncertainRailSendFailedAt().keys) let paid = hashes(.succeeded).subtracting(live) let listed = Set(outbound.map { $0.paymentHash.lowercased() }) - let before = Set(railAttemptsStore.stringArray(forKey: Self.railAttemptsKey) ?? []) trimSettledAttempts( - paid: paid, failed: ownFailed.subtracting(paid).subtracting(live), listed: listed, live: live, key: Self.railAttemptsKey + paid: paid, failed: hashes(.failed).subtracting(paid).subtracting(live), listed: listed, live: live, key: Self.railAttemptsKey ) - // A hold ends with the record and expiry its sweep needs. - let after = Set(railAttemptsStore.stringArray(forKey: Self.railAttemptsKey) ?? []) - for hash in held.intersection(before.subtracting(after)) { - clearRailSendUncertainty(hash: hash) - } return live } } @@ -1591,8 +1512,7 @@ class LightningService: NodeLifecycleService { bolt11: String, sats: UInt64?, invoiceCreatedAt: UInt64?, - invoiceExpiresAt: Int?, - readRailPayments: ([ChannelFreeRailPayment]) -> Void = { _ in } + invoiceExpiresAt: Int? ) async throws -> PaymentHash? { guard let paymentHash else { return nil } var statuses: [PaymentStatus] = rails.contains(.channelFree) && isRailSendInFlight(paymentHash: paymentHash) ? [.pending] : [] @@ -1625,7 +1545,6 @@ class LightningService: NodeLifecycleService { if rails.contains(.channelFree) { let mark = attemptMark if let payments = await readableRailPayments() { - readRailPayments(payments) let live = keepRailAttempts(from: payments, since: mark) let payment = ChannelFreeRailPayment.latestOutboundAttempt(payments, paymentHash: paymentHash) if let payment { @@ -1730,237 +1649,54 @@ class LightningService: NodeLifecycleService { railAttemptsStore.dictionary(forKey: Self.uncertainRailSendsKey) as? [String: Int] ?? [:] } - /// A rail send about to be submitted, or that failed after it was, until a sync after it and its invoice's expiry - /// settle it. The expiry is the one kept beside the hash. - /// True when `ifStillInDoubt` found the send already settled. - @discardableResult - private func markRailSendUncertain( - paymentHash: String, - since mark: AttemptMark, - earlierAttemptIds: [String]?, - ifStillInDoubt: Bool = false - ) -> Bool { + /// A rail send about to be submitted, or that failed after it was, until Spark settles its attempt or a sync after its + /// invoice's expiry settles it. The expiry is the one kept beside the hash, and the time the one it was submitted at, + /// which a later failure of its call leaves as it is. + private func markRailSendUncertain(paymentHash: String, since mark: AttemptMark) { let hash = paymentHash.lowercased() - let failedAt = Int(max(0, now().timeIntervalSince1970)) - return eventCallbackLock.withLock { - guard attemptsRecorded(since: mark.records, key: Self.railAttemptsKey).contains(hash) else { return false } + let startedAt = Int(max(0, now().timeIntervalSince1970)) + eventCallbackLock.withLock { + guard attemptsRecorded(since: mark.records, key: Self.railAttemptsKey).contains(hash) else { return } var uncertain = uncertainRailSendFailedAt() - guard !ifStillInDoubt || uncertain[hash] != nil else { return true } - if uncertain[hash] == nil { - var started = uncertainRailSendStartedAt() - started[hash] = failedAt - railAttemptsStore.set(started, forKey: Self.uncertainRailSendsStartedKey) - // A send Spark took before this one is now an earlier attempt too, listed or not. - var taken = takenRailSendIds() - let takenBefore = taken.removeValue(forKey: hash) - railAttemptsStore.set(taken, forKey: Self.takenRailSendsKey) - var earlier = uncertainRailSendEarlierAttempts() - earlier[hash] = earlierAttemptIds.map { ids in takenBefore.map { ids.contains($0) ? ids : ids + [$0] } ?? ids } - railAttemptsStore.set(earlier, forKey: Self.uncertainRailSendsEarlierAttemptsKey) - // The send Spark took last goes after the ones it listed. - keepEarlierAttempts( - hash: hash, - ids: (earlierAttemptIds ?? []).filter { $0 != takenBefore } + (takenBefore.map { [$0] } ?? []) - ) - } - uncertain[hash] = failedAt + guard uncertain[hash] == nil else { return } + uncertain[hash] = startedAt railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) - return false } } - /// Callers hold `eventCallbackLock`. - private func keepEarlierAttempts(hash: String, ids: [String]) { - var entries = railAttemptsStore.array(forKey: Self.keptRailSendEarlierAttemptsKey) as? [[String]] ?? [] - let kept = entries.last { $0.first == hash }.map { Array($0.dropFirst()) } ?? [] - let merged = kept + ids.filter { !kept.contains($0) } - guard !merged.isEmpty, merged != kept else { return } - entries.removeAll { $0.first == hash } - entries.append([hash] + merged) - railAttemptsStore.set(Array(entries.suffix(Self.keptEarlierAttemptsLimit)), forKey: Self.keptRailSendEarlierAttemptsKey) - } - - #if DEBUG - func keepEarlierAttemptsForTesting(hash: String, ids: [String]) { - eventCallbackLock.withLock { keepEarlierAttempts(hash: hash.lowercased(), ids: ids) } - } - #endif + /// How far before a send's start, by this device's clock, Spark may date the send's own attempt. + static let railClockSkewSeconds: Int64 = 10 - /// Spark's ids of every attempt a send of `paymentHash` followed, kept past its hold in the order they went out: each - /// send adds the attempts before it as it goes out. - func keptRailSendEarlierAttemptIds(paymentHash: String) -> [String] { - let hash = paymentHash.lowercased() + /// Whether a Spark attempt of `paymentHash` created at `createdAt`, in seconds since 1970, came before the send of it + /// Spark hasn't settled yet: Spark dates an attempt at its start, and a retry starts only once the attempts before it + /// failed. Its failure settles nothing of that send, so it is ignored. + func isEarlierRailAttempt(paymentHash: String, createdAt: UInt64?) -> Bool { + guard let createdAt else { return false } return eventCallbackLock.withLock { - let entries = railAttemptsStore.array(forKey: Self.keptRailSendEarlierAttemptsKey) as? [[String]] ?? [] - return Array(entries.last { $0.first == hash }?.dropFirst() ?? []) - } - } - - /// Callers hold `eventCallbackLock`. - private func uncertainRailSendStartedAt() -> [String: Int] { - railAttemptsStore.dictionary(forKey: Self.uncertainRailSendsStartedKey) as? [String: Int] ?? [:] - } - - /// Spark took a retry of an unexpired invoice but lists only the attempts before it: their failures read pending, so - /// the node never pays the invoice the retry may still pay. - private func takenRetriesPending(_ payments: [ChannelFreeRailPayment], unexpired: Set) -> [ChannelFreeRailPayment] { - let (earlier, taken) = eventCallbackLock.withLock { (uncertainRailSendEarlierAttempts(), takenRailSendIds()) } - guard !earlier.isEmpty || !taken.isEmpty else { return payments } - let isEarlier = { (payment: ChannelFreeRailPayment) in - payment.id.map { Self.isEarlierRailAttempt(id: $0, hash: payment.paymentHash.lowercased(), taken: taken, earlier: earlier) } - ?? false - } - let retryListed = Set(payments.filter { $0.direction == .outbound && !isEarlier($0) }.map { $0.paymentHash.lowercased() }) - return payments.map { payment in - let hash = payment.paymentHash.lowercased() - guard payment.direction == .outbound, payment.status == .failed, isEarlier(payment), unexpired.contains(hash), - !retryListed.contains(hash) else { return payment } - var pending = ChannelFreeRailPayment( - paymentHash: payment.paymentHash, direction: payment.direction, status: .pending, preimage: payment.preimage, - timestamp: payment.timestamp, feeSats: payment.feeSats - ) - pending.id = payment.id - return pending - } - } - - /// The rail's ids of the attempts before each send in doubt or that Spark took, by hash. - var railSendEarlierAttemptIds: [String: [String]] { - eventCallbackLock.withLock { uncertainRailSendEarlierAttempts() } - } - - /// The rail's id of each send Spark took, by hash. - var railSendTakenIds: [String: String] { - eventCallbackLock.withLock { takenRailSendIds() } - } - - /// Whether the rail's attempt `id` of `hash` came before the send still held: once Spark took that send under an id - /// of its own, any other id, as Spark may list an older attempt only after the send went out; before, one listed - /// before the send went out. - nonisolated static func isEarlierRailAttempt(id: String, hash: String, taken: [String: String], earlier: [String: [String]]) -> Bool { - if let takenId = taken[hash] { - return id != takenId - } - return earlier[hash]?.contains(id) ?? false - } - - /// Callers hold `eventCallbackLock`. - private func takenRailSendIds() -> [String: String] { - railAttemptsStore.dictionary(forKey: Self.takenRailSendsKey) as? [String: String] ?? [:] - } - - /// Spark took the send of `hash`: it is no longer in doubt, and its own id is kept while the attempt it made still - /// holds the invoice, so a failure that ended it meanwhile leaves no id behind. - private func takeRailSend(hash: String, paymentId: String?, since mark: AttemptMark) { - eventCallbackLock.withLock { - // An outcome delivered before the send returned already ended its doubt and hold. - let isUnsettled = uncertainRailSendFailedAt()[hash] != nil - clearRailSendUncertainty(hash: hash, keepingEarlierAttempts: true) - guard isUnsettled, let paymentId, attemptsRecorded(since: mark.records, key: Self.railAttemptsKey).contains(hash) else { return } - var taken = takenRailSendIds() - taken[hash] = paymentId - railAttemptsStore.set(taken, forKey: Self.takenRailSendsKey) - } - } - - /// Callers hold `eventCallbackLock`. - private func uncertainRailSendEarlierAttempts() -> [String: [String]] { - railAttemptsStore.dictionary(forKey: Self.uncertainRailSendsEarlierAttemptsKey) as? [String: [String]] ?? [:] - } - - /// The rail's ids of its attempts to pay `paymentHash`, nil when one has none. - private static func railAttemptIds(_ payments: [ChannelFreeRailPayment], paymentHash: String?) -> [String]? { - guard let paymentHash else { return nil } - let attempts = payments.filter { $0.direction == .outbound && $0.paymentHash.caseInsensitiveCompare(paymentHash) == .orderedSame } - let ids = attempts.compactMap(\.id) - return ids.count == attempts.count ? ids : nil - } - - /// Spark's payments as the app's status lookups read them: a send still held reads as pending while Spark lists none - /// of its own attempts, only earlier failed ones or nothing, until its hold ends past the invoice's expiry, and one - /// in Spark's send call or in doubt reads as pending whatever failure Spark lists. - func channelFreeRailSendStatuses() async throws -> [ChannelFreeRailPayment] { - let heldBefore = heldRailSendHashes() - let payments = try await channelFreeRailPayments() - // A hold that ended while the list was read ended on an outcome the list may not show yet. - guard heldBefore.isSubset(of: heldRailSendHashes()) else { - return try await withHeldRailSends(channelFreeRailPayments()) - } - return withHeldRailSends(payments) - } - - private func heldRailSendHashes() -> Set { - eventCallbackLock.withLock { heldRailSendHashesLocked() } - } - - /// The hashes of rail sends held: in Spark's send call, in doubt, or taken. Callers hold `eventCallbackLock`. - private func heldRailSendHashesLocked() -> Set { - Set(takenRailSendIds().keys).union(uncertainRailSendEarlierAttempts().keys).union(uncertainRailSendFailedAt().keys) - .union(railSendsInFlight) - } - - func withHeldRailSends(_ payments: [ChannelFreeRailPayment]) -> [ChannelFreeRailPayment] { - eventCallbackLock.withLock { - let held = heldRailSendHashesLocked() - guard !held.isEmpty else { return payments } - // A send in Spark's send call or in doubt may still go out, whatever failure Spark lists for its invoice. - let inDoubt = Set(uncertainRailSendFailedAt().keys).union(railSendsInFlight) - var statuses = payments.filter { payment in - let hash = payment.paymentHash.lowercased() - return !(payment.direction == .outbound && payment.status == .failed && held.contains(hash) - && (inDoubt.contains(hash) - || isEarlierThanUncertainRailSendLocked(hash: hash, createdAt: payment.timestamp, paymentId: payment.id))) - } - let listed = Set(statuses.filter { $0.direction == .outbound }.map { $0.paymentHash.lowercased() }) - for hash in held.subtracting(listed).sorted() { - statuses.append(ChannelFreeRailPayment( - paymentHash: hash, direction: .outbound, status: .pending, preimage: nil, - timestamp: UInt64(max(0, now().timeIntervalSince1970)), id: takenRailSendIds()[hash] - )) - } - return statuses + uncertainRailSendFailedAt()[paymentHash.lowercased()].map { !Self.isOwnRailAttempt(createdAt: createdAt, startedAt: $0) } ?? false } } - /// Spark's id of the taken send that still holds the invoice of `paymentHash`, if any. - func heldRailSendId(paymentHash: String) -> String? { - eventCallbackLock.withLock { takenRailSendIds()[paymentHash.lowercased()] } - } - - /// Whether a failure of `paymentHash` may have ended an attempt before the send still in doubt, which Spark may still - /// finish: the rail's attempt `paymentId` is one listed before the send went out. Without both ids, a payment Spark - /// created before the send or within `railClockSkewSeconds` after it (Spark's clock and this phone's may differ) - /// may be earlier, so it keeps the hold too. - func isEarlierThanUncertainRailSend(paymentHash: String, createdAt: UInt64, paymentId: String? = nil) -> Bool { - eventCallbackLock.withLock { - isEarlierThanUncertainRailSendLocked(hash: paymentHash.lowercased(), createdAt: createdAt, paymentId: paymentId) - } + /// Whether Spark dated an attempt at or after a send's start, less the clock margin: that send's own. + private static func isOwnRailAttempt(createdAt: UInt64, startedAt: Int) -> Bool { + Int64(clamping: createdAt) >= Int64(startedAt) - railClockSkewSeconds } - /// Callers hold `eventCallbackLock`. - private func isEarlierThanUncertainRailSendLocked(hash: String, createdAt: UInt64, paymentId: String?) -> Bool { - // Known until the latest send settles, also once Spark took it, so its earlier attempts are told apart by id. - let taken = takenRailSendIds() - let earlier = uncertainRailSendEarlierAttempts() - if let paymentId, taken[hash] != nil || earlier[hash]?.contains(paymentId) == true { - return Self.isEarlierRailAttempt(id: paymentId, hash: hash, taken: taken, earlier: earlier) + /// Ends the sends Spark lists a settled attempt of: a success, or a failure of the send's own attempt. + private func settleListedRailSends(_ payments: [ChannelFreeRailPayment]) { + let settled = eventCallbackLock.withLock { + let uncertain = uncertainRailSendFailedAt() + return Set(payments.filter { payment in + guard payment.direction == .outbound, payment.status != .pending, + let startedAt = uncertain[payment.paymentHash.lowercased()] else { return false } + return payment.status == .succeeded || Self.isOwnRailAttempt(createdAt: payment.timestamp, startedAt: startedAt) + }.map { $0.paymentHash.lowercased() }) } - guard uncertainRailSendFailedAt()[hash] != nil else { return false } - // A send still in doubt has no id of its own yet, and the list read before it went out can lack an older attempt. - // Spark dates a payment at its start, so a failure that list doesn't name is an earlier attempt's only when created - // clearly before the send; one dated around it is the send's own. - if paymentId != nil, earlier[hash] != nil { - guard let startedAt = uncertainRailSendStartedAt()[hash] else { return true } - return Int64(clamping: createdAt) + Int64(Self.railClockSkewSeconds) <= Int64(startedAt) + for hash in settled { + endRailSendUncertainty(paymentHash: hash) } - // A send in doubt saved before its start was recorded can't be told from an earlier attempt, so it stays held - // until its invoice expires. - guard let startedAt = uncertainRailSendStartedAt()[hash] else { return true } - return createdAt < UInt64(max(0, startedAt)).addingReportingOverflow(Self.railClockSkewSeconds).partialValue } - static let railClockSkewSeconds: UInt64 = 10 - /// Rail sends whose outcome stayed unknown, listed as pending until a sync after them reaches the rail: Spark may /// still finish one, while its own list shows only an earlier attempt, or nothing. private func unsettledUncertainRailSends() async -> [ChannelFreeRailPayment] { @@ -1974,61 +1710,23 @@ class LightningService: NodeLifecycleService { return pending } - /// Spark's kept sends whose invoice is unexpired, or expired less than `unlistedRailSendGraceSeconds` ago. A sync can - /// still resume one Spark committed but lists no row for, also after a relaunch, so it is pending until then, the rule - /// `railSyncedSinceUncertainSend` holds. A send Spark took stays in until the expiry sweep ends it, so no listing - /// drops its hash and expiry before the sweep has the sync it needs. + /// Spark's kept sends whose invoice is unexpired. A sync can still resume one Spark committed but lists no row for, + /// also after a relaunch, so it is pending until its invoice expires, the rule `railSyncedSinceUncertainSend` holds. private func unexpiredRailAttempts() -> Set { let seconds = Int(now().timeIntervalSince1970) return eventCallbackLock.withLock { let expiries = attemptExpiries(key: Self.railAttemptsKey) let hashes = railAttemptsStore.stringArray(forKey: Self.railAttemptsKey) ?? [] - let awaitingSweep = Set(takenRailSendIds().keys).union(uncertainRailSendEarlierAttempts().keys) - return Set(hashes.filter { hash in - expiries[hash].map { $0 > seconds - Self.unlistedRailSendGraceSeconds || awaitingSweep.contains(hash) } ?? false - }) + return Set(hashes.filter { hash in expiries[hash].map { $0 > seconds } ?? false }) } } private func endRailSendUncertainty(paymentHash: String) { - eventCallbackLock.withLock { clearRailSendUncertainty(hash: paymentHash.lowercased()) } - } - - /// Callers hold `eventCallbackLock`. - private func clearRailSendUncertainty(hash: String, keepingEarlierAttempts: Bool = false) { - var started = uncertainRailSendStartedAt() - if started.removeValue(forKey: hash) != nil { - railAttemptsStore.set(started, forKey: Self.uncertainRailSendsStartedKey) - } - var earlier = uncertainRailSendEarlierAttempts() - if !keepingEarlierAttempts, earlier.removeValue(forKey: hash) != nil { - railAttemptsStore.set(earlier, forKey: Self.uncertainRailSendsEarlierAttemptsKey) - } - var taken = takenRailSendIds() - if !keepingEarlierAttempts, taken.removeValue(forKey: hash) != nil { - railAttemptsStore.set(taken, forKey: Self.takenRailSendsKey) - } - var uncertain = uncertainRailSendFailedAt() - guard uncertain.removeValue(forKey: hash) != nil else { return } - railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) - } - - /// Ends the hold a Spark failure settles, unless it ended an attempt before the send still in doubt; checked and - /// ended under one lock, so a retry recorded in between keeps its hold. False when the failure is ignored. - private func settleRailFailure(paymentHash: String, createdAt: UInt64?, paymentId: String?) -> Bool { let hash = paymentHash.lowercased() - return eventCallbackLock.withLock { - // While a send of the invoice is in Spark's send call, its result settles it, whichever attempt failed. - guard !railSendsInFlight.contains(hash) else { - railFailuresDuringCall[hash] = (paymentId, createdAt) - return false - } - if let createdAt, isEarlierThanUncertainRailSendLocked(hash: hash, createdAt: createdAt, paymentId: paymentId) { - return false - } - clearRailSendUncertainty(hash: hash) - removeAttempt(paymentHash: hash, key: Self.railAttemptsKey) - return true + eventCallbackLock.withLock { + var uncertain = uncertainRailSendFailedAt() + guard uncertain.removeValue(forKey: hash) != nil else { return } + railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) } } @@ -2042,118 +1740,25 @@ class LightningService: NodeLifecycleService { guard let uncertain else { return true } // Spark keeps a send it committed but didn't finish in a cache no call exposes, and a sync that reached Spark // 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) - Self.unlistedRailSendGraceSeconds >= expiresAt - else { return false } - // Absence proves nothing until a sync that started past the grace reached Spark. During an exit Spark no longer - // sends but still syncs its history, which settles the send the same way. - let settledAfter = max(uncertain.failedAt, UInt64(max(0, expiresAt + Self.unlistedRailSendGraceSeconds))) - guard let rail = channelFreeRail ?? channelFreePaymentHistory, await rail.hasSynced(after: settledAfter) else { + 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: uncertain.failedAt) else { return false } - eventCallbackLock.withLock { - var unrecorded = Set(railAttemptsStore.stringArray(forKey: Self.expiredRailHoldsUnrecordedKey) ?? []) - unrecorded.insert(hash) - railAttemptsStore.set(Array(unrecorded), forKey: Self.expiredRailHoldsUnrecordedKey) - clearRailSendUncertainty(hash: hash) + // Its Activity row is written first, so a stop in between finds the send held and writes it again. + if let record = railSendExpired, await !record(hash) { + return false } - await recordExpiredRailHold(hash) + endRailSendUncertainty(paymentHash: hash) return true } - /// Writes the activity of each send whose hold ended earlier but wasn't saved, then ends the holds of rail sends in - /// doubt whose invoice expired since a sync reached the rail. + /// Ends the sends Spark never settled whose invoice expired since, once a sync after the grace reached Spark. func endExpiredRailSendUncertainties() async { - let unrecorded = eventCallbackLock.withLock { railAttemptsStore.stringArray(forKey: Self.expiredRailHoldsUnrecordedKey) ?? [] } - for hash in unrecorded { - await recordExpiredRailHold(hash) - } let hashes = eventCallbackLock.withLock { Array(uncertainRailSendFailedAt().keys) } for hash in hashes { _ = await railSyncedSinceUncertainSend(paymentHash: hash) } - await endExpiredUnlistedTakenRailSends() - } - - /// How long past its invoice's expiry a rail send Spark lists no outcome of still counts as live: an HTLC under way - /// at the expiry can still settle a little after it. - static let unlistedRailSendGraceSeconds = 10 * 60 - - /// Ends the holds of sends Spark took whose own outcome it still doesn't list, only an earlier attempt's failure or - /// nothing, once their invoice expired `unlistedRailSendGraceSeconds` ago and a sync since reached Spark, and fails - /// their stored Activity row, as an earlier attempt's row would bring its own amount and fee. A send Spark lists is - /// left to its own outcome. - private func endExpiredUnlistedTakenRailSends() async { - let unfailed = eventCallbackLock.withLock { unlistedTakenRailSendsUnfailed() } - for (hash, ownAttemptId) in unfailed { - await failUnlistedTakenRailSend(hash, ownAttemptId: ownAttemptId.isEmpty ? nil : ownAttemptId) - } - let nowSeconds = Int(now().timeIntervalSince1970) - let (expired, taken, earlier) = eventCallbackLock.withLock { - let uncertain = uncertainRailSendFailedAt() - let taken = takenRailSendIds() - let earlier = uncertainRailSendEarlierAttempts() - let expiries = attemptExpiries(key: Self.railAttemptsKey) - let held = Set(taken.keys).union(earlier.keys).subtracting(uncertain.keys) - var expired: [String: Int] = [:] - for hash in held { - if let expiresAt = expiries[hash], nowSeconds - Self.unlistedRailSendGraceSeconds >= expiresAt { - expired[hash] = expiresAt - } - } - return (expired, taken, earlier) - } - guard !expired.isEmpty, let rail = channelFreeRail ?? channelFreePaymentHistory else { return } - // Absence proves nothing until a sync that started past the grace reached Spark. - var synced: [String] = [] - for (hash, expiresAt) in expired { - if await rail.hasSynced(after: UInt64(max(0, expiresAt + Self.unlistedRailSendGraceSeconds))) { - synced.append(hash) - } - } - guard !synced.isEmpty, let payments = try? await rail.lightningPayments() else { return } - for hash in synced { - let isListed = payments.contains { payment in - payment.direction == .outbound && payment.paymentHash.lowercased() == hash - && !(payment.id.map { Self.isEarlierRailAttempt(id: $0, hash: hash, taken: taken, earlier: earlier) } ?? false) - } - guard !isListed else { continue } - let isEnded = eventCallbackLock.withLock { - // Left alone if a new send of the invoice started meanwhile. - guard takenRailSendIds()[hash] == taken[hash], uncertainRailSendEarlierAttempts()[hash] == earlier[hash], - uncertainRailSendFailedAt()[hash] == nil else { return false } - var unfailed = unlistedTakenRailSendsUnfailed() - unfailed[hash] = taken[hash] ?? "" - railAttemptsStore.set(unfailed, forKey: Self.unlistedTakenRailSendsUnfailedKey) - clearRailSendUncertainty(hash: hash) - removeAttempt(paymentHash: hash, key: Self.railAttemptsKey) - return true - } - guard isEnded else { continue } - await failUnlistedTakenRailSend(hash, ownAttemptId: taken[hash]) - } - } - - private func failUnlistedTakenRailSend(_ hash: String, ownAttemptId: String? = nil) async { - guard let fail = railTakenSendUnlisted, await fail(hash, ownAttemptId) else { return } - eventCallbackLock.withLock { - var unfailed = unlistedTakenRailSendsUnfailed() - unfailed.removeValue(forKey: hash) - railAttemptsStore.set(unfailed, forKey: Self.unlistedTakenRailSendsUnfailedKey) - } - } - - /// Sends whose hold ended but whose Activity row isn't failed yet, each with Spark's id of the attempt it took (empty - /// when none). Callers hold `eventCallbackLock`. - private func unlistedTakenRailSendsUnfailed() -> [String: String] { - railAttemptsStore.dictionary(forKey: Self.unlistedTakenRailSendsUnfailedKey) as? [String: String] ?? [:] - } - - private func recordExpiredRailHold(_ hash: String) async { - guard let record = railSendHoldExpired, await record(hash) else { return } - eventCallbackLock.withLock { - let unrecorded = railAttemptsStore.stringArray(forKey: Self.expiredRailHoldsUnrecordedKey) ?? [] - railAttemptsStore.set(unrecorded.filter { $0 != hash }, forKey: Self.expiredRailHoldsUnrecordedKey) - } } private static func pendingDuplicate(paymentHash: String?) -> NodeError { @@ -2234,35 +1839,7 @@ class LightningService: NodeLifecycleService { func endRailSend(paymentHash: String?) { guard let paymentHash else { return } - _ = endRailSendTakingFailure(paymentHash: paymentHash) - } - - /// Ends the send's time in Spark's send call and returns a failure Spark reported for it meanwhile. - private func endRailSendTakingFailure(paymentHash: String) -> (id: String?, createdAt: UInt64?)? { - let hash = paymentHash.lowercased() - return eventCallbackLock.withLock { - railSendsInFlight.remove(hash) - return railFailuresDuringCall.removeValue(forKey: hash) - } - } - - /// Ends the send's time in Spark's send call and whether the call's result fails the send still held: a failed result, - /// or a pending one Spark failed under the same id during the call. Decided with the call's end, before the send is - /// taken, so no other path reports it; Spark's own event for the attempt is then dropped. - private func endRailSendFailedByItsCall(paymentHash: String, paymentId: String?, status: PaymentStatus) -> Bool { - let hash = paymentHash.lowercased() - return eventCallbackLock.withLock { - railSendsInFlight.remove(hash) - let failedDuringCall = railFailuresDuringCall.removeValue(forKey: hash) - // An outcome delivered during the call already settled it. - guard uncertainRailSendFailedAt()[hash] != nil else { return false } - let isFailed = status == .failed || status == .pending && paymentId != nil && failedDuringCall?.id == paymentId - guard isFailed else { return false } - if let paymentId { - railFailuresReportedByCall.insert(paymentId) - } - return true - } + _ = eventCallbackLock.withLock { railSendsInFlight.remove(paymentHash.lowercased()) } } private func isRailSendInFlight(paymentHash: String) -> Bool { @@ -2807,21 +2384,19 @@ extension LightningService { } /// Spark runs before the node starts, so its events wait until the node's event callback is set rather than being lost. - /// `paymentCreatedAt` is when Spark created the payment the event is about, in seconds since 1970, and `railPaymentId` - /// Spark's id of it. - func emitChannelFreeRailEvent(_ event: Event, paymentCreatedAt: UInt64? = nil, railPaymentId: String? = nil) { + /// `paymentCreatedAt` is when Spark created the payment the event is about, in seconds since 1970. + func emitChannelFreeRailEvent(_ event: Event, paymentCreatedAt: UInt64? = nil) { switch event { case let .paymentFailed(_, paymentHash?, _): - if let railPaymentId, eventCallbackLock.withLock({ railFailuresReportedByCall.remove(railPaymentId) != nil }) { - Logger.info("Ignored a Spark failure its send call already reported: \(event)", context: "LightningService") - return - } - // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held; the - // failure of the send itself may arrive while its send call is still returning. - guard settleRailFailure(paymentHash: paymentHash, createdAt: paymentCreatedAt, paymentId: railPaymentId) else { - Logger.info("Ignored a Spark failure while a send of its invoice is in flight or in doubt: \(event)", context: "LightningService") + // An attempt before the send Spark hasn't settled yet ended: that send may still pay, so nothing changes. + guard !isEarlierRailAttempt(paymentHash: paymentHash, createdAt: paymentCreatedAt) else { + Logger.info("Ignored a Spark failure of an attempt before an unsettled send: \(event)", context: "LightningService") return } + // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. + endRailSendUncertainty(paymentHash: paymentHash) + // The failure of the send itself, which may arrive while its send call is still returning. + releaseRailAttempt(paymentHash: paymentHash, unlessInFlight: false) case let .paymentSuccessful(_, paymentHash, _, _): endRailSendUncertainty(paymentHash: paymentHash) default: @@ -2876,9 +2451,13 @@ extension LightningService { // 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. - let unsettled = await unsettledUncertainRailSends() + let unsettledBefore = await unsettledUncertainRailSends() let kept = unexpiredRailAttempts() - let payments = try await takenRetriesPending(rail.lightningPayments(), unexpired: kept) + 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) + let stillUnsettled = eventCallbackLock.withLock { Set(uncertainRailSendFailedAt().keys) } + let unsettled = unsettledBefore.filter { stillUnsettled.contains($0.paymentHash) } 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() } diff --git a/Bitkit/Services/PaykitPaymentProofService.swift b/Bitkit/Services/PaykitPaymentProofService.swift index 0922ec2975..2065c5c3f9 100644 --- a/Bitkit/Services/PaykitPaymentProofService.swift +++ b/Bitkit/Services/PaykitPaymentProofService.swift @@ -308,10 +308,10 @@ struct PaykitLightningPaymentProofLookup: PaykitLightningPaymentProofLookingUp { } } - /// Spark payments are not in LDK's list, so a proof whose completion event was missed settles from Spark's own record, - /// with a send still held read as pending. Unavailable while Spark can't list its payments. + /// Spark payments are not in LDK's list, so a proof whose completion event was missed settles from Spark's own record. + /// Unavailable while Spark can't list its payments. static func railStatus(paymentHash: String) async -> PaykitLightningPaymentProofStatus { - guard let payments = try? await LightningService.shared.channelFreeRailSendStatuses() else { + guard let payments = try? await LightningService.shared.channelFreeRailPayments() else { return .unavailable } guard let payment = ChannelFreeRailPayment.latestOutboundAttempt(payments, paymentHash: paymentHash) else { diff --git a/Bitkit/Utilities/QuickPayPaymentCoordinator.swift b/Bitkit/Utilities/QuickPayPaymentCoordinator.swift index da5fd5bad4..5a4351d7dc 100644 --- a/Bitkit/Utilities/QuickPayPaymentCoordinator.swift +++ b/Bitkit/Utilities/QuickPayPaymentCoordinator.swift @@ -70,7 +70,7 @@ final class QuickPayPaymentCoordinator { } self.listRows = listRows ?? { try await Self.reconcileRows( - railPayments: { try await LightningService.shared.channelFreeRailSendStatuses() }, + railPayments: { try await LightningService.shared.channelFreeRailPayments() }, nodePayments: { await LightningService.shared.listPayments() } ) } diff --git a/Bitkit/ViewModels/WalletViewModel.swift b/Bitkit/ViewModels/WalletViewModel.swift index 755c9039b7..8cc8b4c539 100644 --- a/Bitkit/ViewModels/WalletViewModel.swift +++ b/Bitkit/ViewModels/WalletViewModel.swift @@ -1373,7 +1373,7 @@ class WalletViewModel: ObservableObject { } // A retry over a channel settles from LDK; an earlier Spark attempt's outcome doesn't decide it. guard lightningService.attemptRail(paymentHash: hash) != .ldk else { return } - let payments = await (try? lightningService.channelFreeRailSendStatuses()) ?? [] + let payments = await (try? lightningService.channelFreeRailPayments()) ?? [] let payment = ChannelFreeRailPayment.latestOutboundAttempt(payments, paymentHash: hash) switch payment?.status { case .succeeded: diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 1c393270aa..007320a473 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -229,8 +229,6 @@ extension ChannelFreeRailTests { service.nodePayments = { [] } _ = try await service.send(bolt11: Self.invoice) rail.sentBolt11 = nil - // Spark's next sync ends the expired send it took but never listed. - await service.endExpiredRailSendUncertainties() service.nodePayments = { nil } _ = try await service.send(bolt11: Self.invoice) @@ -278,8 +276,6 @@ extension ChannelFreeRailTests { service.nodePayments = { [failed] } _ = try await service.send(bolt11: Self.invoice) rail.sentBolt11 = nil - // Spark's next sync ends the expired send it took but never listed. - await service.endExpiredRailSendUncertainties() service.nodePayments = { nil } _ = try await service.send(bolt11: Self.invoice) @@ -673,14 +669,6 @@ extension ChannelFreeRailTests { rail.syncedAfter = { _ in true } let expiresAt = try Self.invoiceExpiresAt() Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: expiresAt) } - // An HTLC under way at the expiry can still settle a little after it. - await assertRefusedAsDuplicate() - let graceEnds = expiresAt + TimeInterval(Bitkit.LightningService.unlistedRailSendGraceSeconds) - Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: graceEnds) } - // Absence proves nothing until a sync that started past the grace reached Spark. - rail.syncedAfter = { ($0 ?? 0) < UInt64(graceEnds) } - await assertRefusedAsDuplicate() - rail.syncedAfter = { _ in true } await assertReachesTheNode() } @@ -698,14 +686,6 @@ extension ChannelFreeRailTests { await assertRefusedAsDuplicate() Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: expiresAt) } - // An HTLC under way at the expiry can still settle a little after it. - await assertRefusedAsDuplicate() - let graceEnds = expiresAt + TimeInterval(Bitkit.LightningService.unlistedRailSendGraceSeconds) - Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: graceEnds) } - // Absence proves nothing until a sync that started past the grace reached Spark. - rail.syncedAfter = { ($0 ?? 0) < UInt64(graceEnds) } - await assertRefusedAsDuplicate() - rail.syncedAfter = { _ in true } await assertReachesTheNode() } @@ -744,8 +724,6 @@ extension ChannelFreeRailTests { XCTAssertEqual(status, .pending, "a send Spark can still resume was read as never made") await assertRefusedAsDuplicate() service.now = { Date(timeIntervalSince1970: TimeInterval(expiresAt)) } - await assertRefusedAsDuplicate() - service.now = { Date(timeIntervalSince1970: TimeInterval(expiresAt + Bitkit.LightningService.unlistedRailSendGraceSeconds)) } await assertReachesTheNode() } @@ -834,620 +812,6 @@ extension ChannelFreeRailTests { await assertReachesTheNode() } - func testALateFailureOfAnEarlierAttemptKeepsARetryInDoubtHeld() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - // Spark lists an earlier attempt of the invoice when the retry goes out. - rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier")] - rail.balanceSats = 100_000 - rail.errorAfterSubmission = NSError(domain: "spark", code: 2) - _ = try? await service.send(bolt11: Self.invoice) - rail.errorAfterSubmission = nil - rail.syncedAfter = { ($0 ?? 0) < 1000 } - rail.balanceSats = 0 - - // The earlier attempt's failure keeps the hold, whatever Spark's clock stamped on it; the retry's own ends it. A - // failure the list doesn't name keeps it only when dated clearly before the retry, as an older attempt the list lacked. - for createdAt: UInt64 in [995, 1000, 1005] { - XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: createdAt, paymentId: "earlier")) - XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: createdAt, paymentId: "retry")) - } - XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 990, paymentId: "older")) - // Without Spark's id, a failure stamped before the send or within the clock margin after it keeps the hold. - XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 995)) - XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 1005)) - XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 1010)) - - // The earlier attempt's failure arrives stamped five seconds before the retry. - service.emitChannelFreeRailEvent( - .paymentFailed(paymentId: "earlier", paymentHash: hash, reason: nil), - paymentCreatedAt: 995, - railPaymentId: "earlier" - ) - await assertRefusedAsDuplicate() - // An ambiguous failure without Spark's id, stamped at the retry's start, keeps the hold too. - service.emitChannelFreeRailEvent(.paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), paymentCreatedAt: 1000) - await assertRefusedAsDuplicate() - - // The failure of the retry itself ends the hold, even stamped before it by a clock behind. - service.emitChannelFreeRailEvent( - .paymentFailed(paymentId: "retry", paymentHash: hash, reason: nil), - paymentCreatedAt: 995, - railPaymentId: "retry" - ) - await assertReachesTheNode() - } - - func testASendInDoubtSavedBeforeTheUpgradeStaysHeldAgainstAnyFailure() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - rail.balanceSats = 100_000 - rail.errorAfterSubmission = NSError(domain: "spark", code: 2) - _ = try? await service.send(bolt11: Self.invoice) - rail.errorAfterSubmission = nil - // An earlier app version recorded neither the send's start nor its earlier attempts. - service.railAttemptsStore.removeObject(forKey: "channelFreeRailUncertainSendStartedAt") - service.railAttemptsStore.removeObject(forKey: "channelFreeRailUncertainSendEarlierAttempts") - rail.syncedAfter = { ($0 ?? 0) < 1000 } - rail.balanceSats = 0 - - XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 2000, paymentId: "any")) - service.emitChannelFreeRailEvent( - .paymentFailed(paymentId: "any", paymentHash: hash, reason: nil), - paymentCreatedAt: 2000, - railPaymentId: "any" - ) - await assertRefusedAsDuplicate() - } - - func testAnEarlierAttemptsFailureAfterSparkTookTheRetryKeepsItsHold() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier")] - rail.balanceSats = 100_000 - // Spark takes the retry, which stays pending. - _ = try await service.send(bolt11: Self.invoice) - rail.sentBolt11 = nil - rail.payments = [ - Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier"), - Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .pending, preimage: nil, id: "retry"), - ] - rail.balanceSats = 0 - - XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 2000, paymentId: "earlier")) - XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 2000, paymentId: "retry")) - service.emitChannelFreeRailEvent( - .paymentFailed(paymentId: "earlier", paymentHash: hash, reason: nil), - paymentCreatedAt: 900, - railPaymentId: "earlier" - ) - await assertRefusedAsDuplicate() - - // The retry's own failure ends it. - rail.payments = [ - Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier"), - Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "retry"), - ] - service.emitChannelFreeRailEvent( - .paymentFailed(paymentId: "retry", paymentHash: hash, reason: nil), - paymentCreatedAt: 1000, - railPaymentId: "retry" - ) - await assertReachesTheNode() - } - - func testARetrySparkTookButDoesntListYetKeepsTheNodeFromPaying() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - let earlier = Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier") - rail.payments = [earlier] - rail.balanceSats = 100_000 - _ = try await service.send(bolt11: Self.invoice) - rail.sentBolt11 = nil - rail.balanceSats = 0 - - // Spark took the retry but still lists only the earlier failure. - await assertRefusedAsDuplicate() - - // Once it lists the retry failed, the invoice can be paid again. - rail.payments = [ - earlier, - Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "retry"), - ] - await assertReachesTheNode() - } - - func testARetrySparkTookStaysHeldAfterARelaunchWhileSparkListsOnlyTheEarlierFailure() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - let earlier = Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier") - rail.payments = [earlier] - rail.balanceSats = 100_000 - _ = try await service.send(bolt11: Self.invoice) - rail.sentBolt11 = nil - rail.balanceSats = 0 - try simulateRelaunch() - - // The launch's sync reads Spark's list, which still shows only the earlier failed attempt. - await SparkManager.releaseFailedSendHolds { [Self.sparkPayment(hash: hash, status: .failed, id: "earlier")] } - let kept = service.railAttemptsStore.stringArray(forKey: Self.railAttemptsKey) ?? [] - XCTAssertTrue(kept.contains(hash), "an earlier attempt's failure released a retry Spark took") - await assertRefusedAsDuplicate() - - // Once it lists the retry failed, the invoice can be paid again. - await SparkManager.releaseFailedSendHolds { - [Self.sparkPayment(hash: hash, status: .failed, id: "earlier"), Self.sparkPayment(hash: hash, status: .failed, id: "retry")] - } - rail.payments = [ - earlier, - Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "retry"), - ] - await assertReachesTheNode() - } - - func testAnOlderAttemptSparkListsOnlyAfterATakenRetryKeepsItsHold() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - // Spark lists no earlier attempt before the retry goes out, and takes the retry under its own id. - rail.balanceSats = 100_000 - rail.sentPaymentId = "retry" - _ = try await service.send(bolt11: Self.invoice) - rail.sentBolt11 = nil - rail.balanceSats = 0 - - // An older attempt shows up afterwards, failed, while the retry is still unlisted. - let older = Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "older") - XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 2000, paymentId: "older")) - XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 2000, paymentId: "retry")) - service.emitChannelFreeRailEvent( - .paymentFailed(paymentId: "older", paymentHash: hash, reason: nil), - paymentCreatedAt: 2000, - railPaymentId: "older" - ) - rail.payments = [older] - await assertRefusedAsDuplicate() - try simulateRelaunch() - await SparkManager.releaseFailedSendHolds { [Self.sparkPayment(hash: hash, status: .failed, id: "older")] } - let kept = service.railAttemptsStore.stringArray(forKey: Self.railAttemptsKey) ?? [] - XCTAssertTrue(kept.contains(hash), "an older attempt's failure released the retry Spark took") - await assertRefusedAsDuplicate() - - // Once Spark lists the retry itself failed, the invoice can be paid again. - await SparkManager.releaseFailedSendHolds { - [Self.sparkPayment(hash: hash, status: .failed, id: "older"), Self.sparkPayment(hash: hash, status: .failed, id: "retry")] - } - rail.payments = [ - older, - Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "retry"), - ] - await assertReachesTheNode() - } - - func testATakenRetrySparkNeverListsEndsPastTheInvoicesExpiry() async throws { - let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) - let hash = String(invoice.paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - let earlier = Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier") - rail.payments = [earlier] - rail.balanceSats = 100_000 - rail.sentPaymentId = "retry" - _ = try await service.send(bolt11: Self.invoice) - rail.sentBolt11 = nil - rail.balanceSats = 0 - var replayed: [String] = [] - var failed: [String] = [] - var failedAttemptIds: [String?] = [] - var saves = false - let previousHook = service.railSendHoldExpired - let previousUnlisted = service.railTakenSendUnlisted - defer { - service.railSendHoldExpired = previousHook - service.railTakenSendUnlisted = previousUnlisted - } - service.railSendHoldExpired = { replayed.append($0); return true } - service.railTakenSendUnlisted = { hash, ownAttemptId in - failed.append(hash) - failedAttemptIds.append(ownAttemptId) - return saves - } - - let expiresAt = invoice.secondsSinceEpoch() + invoice.expiryTimeSeconds() - let graceEnds = expiresAt + UInt64(Bitkit.LightningService.unlistedRailSendGraceSeconds) - service.now = { Date(timeIntervalSince1970: TimeInterval(expiresAt)) } - await service.endExpiredRailSendUncertainties() - XCTAssertEqual(failed, [], "a retry Spark took ended at the invoice's expiry") - XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900, paymentId: "earlier")) - - // Past the grace, absence proves nothing until a sync that started since reached Spark, and a listing meanwhile, for - // another invoice's send, keeps the retry held, so the sweep still finds it. - service.now = { Date(timeIntervalSince1970: TimeInterval(graceEnds)) } - rail.syncedAfter = { ($0 ?? 0) < graceEnds } - await service.endExpiredRailSendUncertainties() - XCTAssertEqual(failed, [], "a partial sync's list ended a retry Spark took") - _ = try? await service.send(bolt11: "lnbcrt1rail", sats: 1000) - await assertRefusedAsDuplicate() - - // Spark listing the retry leaves it to its own outcome. - rail.syncedAfter = { _ in true } - rail.payments = [ - earlier, - Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .pending, preimage: nil, id: "retry"), - ] - await service.endExpiredRailSendUncertainties() - XCTAssertEqual(failed, []) - - // Listing only the earlier failure ends it and fails the retry's own row, never replaying the earlier attempt. - rail.payments = [earlier] - await service.endExpiredRailSendUncertainties() - XCTAssertEqual(failed, [hash], "a retry Spark never lists stayed pending past its invoice's expiry") - XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900, paymentId: "earlier")) - - // The write failed, so the next sync tries it again, until it is saved. - saves = true - await service.endExpiredRailSendUncertainties() - XCTAssertEqual(failed, [hash, hash], "a row that failed to save wasn't retried") - XCTAssertEqual(failedAttemptIds, ["retry", "retry"], "the retried write lost the taken attempt's id") - await service.endExpiredRailSendUncertainties() - XCTAssertEqual(failed, [hash, hash], "a saved row was failed again") - XCTAssertEqual(replayed, [], "the earlier attempt's row replaced the retry's") - } - - func testAHeldTakenRetryReadsPendingWhileSparkListsOnlyAnEarlierFailure() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - let earlier = Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier") - let other = Bitkit.ChannelFreeRailPayment(paymentHash: "other", direction: .outbound, status: .failed, preimage: nil, id: "o") - rail.payments = [earlier] - rail.balanceSats = 100_000 - rail.sentPaymentId = "retry" - _ = try await service.send(bolt11: Self.invoice) - - // Spark lists only the earlier failure, or nothing: the retry it took reads as pending, and other sends as they are. - for listed in [[earlier, other], [other]] { - let statuses = service.withHeldRailSends(listed) - let send = Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(statuses, paymentHash: hash) - XCTAssertEqual(send?.status, .pending) - XCTAssertEqual(send?.id, "retry") - XCTAssertFalse(statuses.contains(earlier)) - XCTAssertTrue(statuses.contains(other)) - } - - // Spark listing the retry's own outcome decides it. - let failedRetry = Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "retry") - let statuses = service.withHeldRailSends([earlier, failedRetry]) - XCTAssertEqual(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(statuses, paymentHash: hash), failedRetry) - } - - func testOnlyAHeldSendsOwnListedFailureEndsItsHold() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - let earlier = Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "earlier") - rail.payments = [earlier] - rail.balanceSats = 100_000 - rail.sentPaymentId = "retry" - _ = try await service.send(bolt11: Self.invoice) - rail.sentPaymentId = "other" - - // A listing that shows only the earlier failure keeps the retry held. - do { - _ = try await service.send(bolt11: Self.invoice) - XCTFail("a retry Spark took was paid again while held") - } catch {} - XCTAssertEqual(service.heldRailSendId(paymentHash: hash), "retry") - - // One that shows the retry's own failure ends its hold, so the invoice can be paid again. - let failedRetry = Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, id: "retry") - rail.payments = [earlier, failedRetry] - _ = try await service.send(bolt11: Self.invoice) - XCTAssertEqual(service.heldRailSendId(paymentHash: hash), "other") - } - - func testAHeldSendReleasedOnItsOwnFailureEndsItsHold() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - rail.balanceSats = 100_000 - rail.sentPaymentId = "retry" - _ = try await service.send(bolt11: Self.invoice) - XCTAssertEqual(service.heldRailSendId(paymentHash: hash), "retry") - - service.releaseRailAttempt(paymentHash: hash) - XCTAssertNil(service.heldRailSendId(paymentHash: hash)) - XCTAssertNil(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(service.withHeldRailSends([]), paymentHash: hash)) - } - - func testASuccessBeforeTheSendReturnsLeavesNoHold() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - rail.balanceSats = 100_000 - rail.sentPaymentId = "retry" - rail.sendGate = { - service.emitChannelFreeRailEvent( - .paymentSuccessful(paymentId: hash, paymentHash: hash, paymentPreimage: "pp", feePaidMsat: 1000), railPaymentId: "retry" - ) - } - defer { rail.sendGate = nil } - _ = try await service.send(bolt11: Self.invoice) - - XCTAssertNil(service.heldRailSendId(paymentHash: hash)) - } - - func testAFailureDuringTheSendCallLeavesTheCallsResultToSettleIt() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - rail.balanceSats = 100_000 - rail.sentPaymentId = "sent" - rail.afterSubmission = { - service.emitChannelFreeRailEvent( - .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), paymentCreatedAt: 1000, railPaymentId: "earlier" - ) - } - defer { rail.afterSubmission = nil } - _ = try await service.send(bolt11: Self.invoice) - - // Spark took the send, so it is held, whatever failure arrived while its call ran. - XCTAssertEqual(service.heldRailSendId(paymentHash: hash), "sent") - } - - func testASendInDoubtReadsPendingWhateverFailureSparkLists() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - rail.balanceSats = 100_000 - rail.errorAfterSubmission = NSError(domain: "spark", code: 2) - defer { rail.errorAfterSubmission = nil } - _ = try? await service.send(bolt11: Self.invoice) - - let failed = Bitkit.ChannelFreeRailPayment( - paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: 1005, id: "own" - ) - let send = Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(service.withHeldRailSends([failed]), paymentHash: hash) - XCTAssertEqual(send?.status, .pending) - } - - func testASendCallFailingAfterItsOutcomeArrivedLeavesItSettled() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - rail.balanceSats = 100_000 - rail.afterSubmission = { - service.emitChannelFreeRailEvent( - .paymentSuccessful(paymentId: hash, paymentHash: hash, paymentPreimage: "pp", feePaidMsat: 1000), railPaymentId: "sent" - ) - } - rail.errorAfterSubmission = NSError(domain: "spark", code: 2) - defer { - rail.afterSubmission = nil - rail.errorAfterSubmission = nil - } - // The call's failure gives way to the outcome already delivered, so its caller reads that outcome. - let sent = try await service.send(bolt11: Self.invoice) - - XCTAssertEqual(sent, hash) - XCTAssertNil(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(service.withHeldRailSends([]), paymentHash: hash)) - } - - func testAnOlderAttemptMissingFromTheListBeforeASendInDoubtKeepsItsHold() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - // Spark lists no earlier attempt before the send goes out, and the send's call throws after submission. - rail.balanceSats = 100_000 - rail.errorAfterSubmission = NSError(domain: "spark", code: 2) - _ = try? await service.send(bolt11: Self.invoice) - rail.errorAfterSubmission = nil - rail.syncedAfter = { ($0 ?? 0) < 1000 } - rail.balanceSats = 0 - - // An older attempt Spark created well before the send shows up failed: the send stays held. - service.emitChannelFreeRailEvent( - .paymentFailed(paymentId: "older", paymentHash: hash, reason: nil), - paymentCreatedAt: 900, - railPaymentId: "older" - ) - await assertRefusedAsDuplicate() - - // The send's own failure, dated at its start, ends the hold. - service.emitChannelFreeRailEvent( - .paymentFailed(paymentId: "own", paymentHash: hash, reason: nil), - paymentCreatedAt: 1000, - railPaymentId: "own" - ) - await assertReachesTheNode() - } - - func testAFailureWithoutSparkIdsKeepsTheHoldUntilPastTheClockMargin() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - // Spark's earlier attempt carries no id, so attempts can't be told apart by id. - rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil)] - rail.balanceSats = 100_000 - rail.errorAfterSubmission = NSError(domain: "spark", code: 2) - _ = try? await service.send(bolt11: Self.invoice) - rail.errorAfterSubmission = nil - rail.syncedAfter = { ($0 ?? 0) < 1000 } - rail.balanceSats = 0 - - XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 1005, paymentId: "retry")) - service.emitChannelFreeRailEvent( - .paymentFailed(paymentId: "retry", paymentHash: hash, reason: nil), - paymentCreatedAt: 1005, - railPaymentId: "retry" - ) - await assertRefusedAsDuplicate() - - service.emitChannelFreeRailEvent( - .paymentFailed(paymentId: "retry", paymentHash: hash, reason: nil), - paymentCreatedAt: 1010, - railPaymentId: "retry" - ) - await assertReachesTheNode() - } - - func testAHoldThatEndsAtTheInvoicesExpiryWritesTheSendsActivity() async throws { - let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) - let hash = String(invoice.paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - rail.balanceSats = 100_000 - rail.errorAfterSubmission = NSError(domain: "spark", code: 2) - _ = try? await service.send(bolt11: Self.invoice) - rail.errorAfterSubmission = nil - rail.syncedAfter = { _ in true } - var expired: [String] = [] - let previousHook = service.railSendHoldExpired - defer { service.railSendHoldExpired = previousHook } - var saves = false - service.railSendHoldExpired = { expired.append($0); return saves } - - await service.endExpiredRailSendUncertainties() - XCTAssertEqual(expired, [], "a hold ended before the invoice expired") - XCTAssertTrue(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900)) - - let expiresAt = invoice.secondsSinceEpoch() + invoice.expiryTimeSeconds() - let graceEnds = expiresAt + UInt64(Bitkit.LightningService.unlistedRailSendGraceSeconds) - service.now = { Date(timeIntervalSince1970: TimeInterval(expiresAt)) } - await service.endExpiredRailSendUncertainties() - XCTAssertEqual(expired, [], "a hold Spark may still settle ended at the invoice's expiry") - service.now = { Date(timeIntervalSince1970: TimeInterval(graceEnds)) } - await service.endExpiredRailSendUncertainties() - XCTAssertEqual(expired, [hash], "the send's activity wasn't written when its hold ended") - XCTAssertFalse(service.isEarlierThanUncertainRailSend(paymentHash: hash, createdAt: 900)) - - // The write failed, so the next sync tries it again, until it is saved. - saves = true - await service.endExpiredRailSendUncertainties() - XCTAssertEqual(expired, [hash, hash], "an activity that failed to save wasn't retried") - await service.endExpiredRailSendUncertainties() - XCTAssertEqual(expired, [hash, hash], "a saved activity was written again") - } - - func testAHoldEndsAtTheInvoicesExpiryDuringAnExit() async throws { - let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) - let hash = String(invoice.paymentHash()) - let service = Bitkit.LightningService.shared - service.now = { Date(timeIntervalSince1970: 1000) } - rail.balanceSats = 100_000 - rail.errorAfterSubmission = NSError(domain: "spark", code: 2) - _ = try? await service.send(bolt11: Self.invoice) - rail.errorAfterSubmission = nil - rail.syncedAfter = { _ in true } - var expired: [String] = [] - let previousHook = service.railSendHoldExpired - let previousHistory = service.channelFreePaymentHistory - defer { - service.railSendHoldExpired = previousHook - service.channelFreePaymentHistory = previousHistory - } - service.railSendHoldExpired = { expired.append($0); return true } - // The exit takes Spark off sending and keeps its history. - service.channelFreePaymentHistory = rail - service.channelFreeRail = nil - - let expiresAt = invoice.secondsSinceEpoch() + invoice.expiryTimeSeconds() - let graceEnds = expiresAt + UInt64(Bitkit.LightningService.unlistedRailSendGraceSeconds) - service.now = { Date(timeIntervalSince1970: TimeInterval(expiresAt)) } - await service.endExpiredRailSendUncertainties() - XCTAssertEqual(expired, [], "a hold Spark may still settle ended at the invoice's expiry") - service.now = { Date(timeIntervalSince1970: TimeInterval(graceEnds)) } - await service.endExpiredRailSendUncertainties() - XCTAssertEqual(expired, [hash], "the send stayed pending through the exit") - } - - func testAnExpiredHoldWritesSparksLiveSendOrFailsTheStoredOne() async { - let hash = "ab" - var recorded: [String] = [] - var failed: [String] = [] - let payments = [ - Self.sparkPayment(hash: hash, status: .failed, id: "earlier", timestamp: 1), - Self.sparkPayment(hash: hash, status: .completed, id: "retry", timestamp: 5), - Self.sparkPayment(hash: "cd", status: .completed, id: "other", timestamp: 9), - ] - _ = await SparkManager.recordExpiredHold( - paymentHash: hash, payments: payments, - record: { recorded.append($0.id); return true }, failStoredSend: { failed.append($0); return true } - ) - XCTAssertEqual(recorded, ["retry"]) - XCTAssertEqual(failed, []) - - // Only failures listed: one may be an earlier attempt's, with its own amount and fee, so the stored row fails. - _ = await SparkManager.recordExpiredHold( - paymentHash: hash, payments: [Self.sparkPayment(hash: hash, status: .failed, id: "earlier", timestamp: 1)], - record: { recorded.append($0.id); return true }, failStoredSend: { failed.append($0); return true } - ) - XCTAssertEqual(recorded, ["retry"], "an earlier attempt's failure replaced the held send's row") - XCTAssertEqual(failed, [hash]) - - _ = await SparkManager.recordExpiredHold( - paymentHash: "ef", payments: payments, - record: { recorded.append($0.id); return true }, failStoredSend: { failed.append($0); return true } - ) - XCTAssertEqual(recorded, ["retry"]) - XCTAssertEqual(failed, [hash, "ef"], "a send Spark lists none of stayed pending") - } - - func testAnExpiredHoldWritesTheHeldSendOverALiveAttemptItFollowed() async { - let hash = "ab" - let earlier = Self.sparkPayment(hash: hash, status: .pending, id: "earlier", timestamp: 5) - let retry = Self.sparkPayment(hash: hash, status: .pending, id: "retry", timestamp: 5) - for payments in [[earlier, retry], [retry, earlier]] { - var recorded: [String] = [] - _ = await SparkManager.recordExpiredHold( - paymentHash: hash, payments: payments, earlierAttemptIds: ["earlier"], - record: { recorded.append($0.id); return true }, failStoredSend: { _ in true } - ) - XCTAssertEqual(recorded, ["retry"]) - } - } - - func testASendsEarlierAttemptsAreKeptPastItsHoldForTheLatestInvoices() throws { - let service = Bitkit.LightningService.shared - let defaults = try XCTUnwrap(UserDefaults(suiteName: "KeptEarlierAttempts-\(UUID().uuidString)")) - let previousStore = service.railAttemptsStore - defer { service.railAttemptsStore = previousStore } - service.railAttemptsStore = defaults - for index in 0 ... Bitkit.LightningService.keptEarlierAttemptsLimit { - service.keepEarlierAttemptsForTesting(hash: "hash\(index)", ids: ["a\(index)"]) - } - service.keepEarlierAttemptsForTesting(hash: "hash1", ids: ["b1"]) - - XCTAssertEqual(service.keptRailSendEarlierAttemptIds(paymentHash: "hash0"), []) - XCTAssertEqual(service.keptRailSendEarlierAttemptIds(paymentHash: "HASH1"), ["a1", "b1"]) - // A known earlier attempt's failure keeps the row whatever its date; the row's own attempt still writes it. - XCTAssertTrue(ActivityService.isKnownEarlierAttempt("a1", rowAttemptId: "retry", keptEarlierAttemptIds: ["a1"])) - XCTAssertFalse(ActivityService.isKnownEarlierAttempt("a1", rowAttemptId: "a1", keptEarlierAttemptIds: ["a1"])) - XCTAssertFalse(ActivityService.isKnownEarlierAttempt("later", rowAttemptId: "retry", keptEarlierAttemptIds: ["a1"])) - XCTAssertFalse(ActivityService.isKnownEarlierAttempt(nil, rowAttemptId: "retry", keptEarlierAttemptIds: ["a1"])) - // Two attempts a later send both followed aren't ordered by it. - XCTAssertFalse(ActivityService.isKnownEarlierAttempt("a2", rowAttemptId: "a1", keptEarlierAttemptIds: ["a1", "a2"])) - } - - func testAnExpiredHoldWritesALiveRetryOverAFailureWithTheSameTimestamp() async { - let hash = "ab" - let failed = Self.sparkPayment(hash: hash, status: .failed, id: "earlier", timestamp: 5) - let pending = Self.sparkPayment(hash: hash, status: .pending, id: "retry", timestamp: 5) - for payments in [[failed, pending], [pending, failed]] { - var recorded: [String] = [] - _ = await SparkManager.recordExpiredHold( - paymentHash: hash, payments: payments, - record: { recorded.append($0.id); return true }, failStoredSend: { _ in true } - ) - XCTAssertEqual(recorded, ["retry"], "a failure tied with the live retry replaced its row") - } - } - func testAnUnknownSparkSendStaysHeldAfterARelaunchWhenSparkListsOnlyAnOlderFailedAttempt() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared @@ -1476,7 +840,7 @@ extension ChannelFreeRailTests { rail.balanceSats = 100_000 _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) // Spark returned the send, then reports that it failed. - rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil)] + rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: 1000)] rail.balanceSats = 0 await assertReachesTheNode() @@ -1491,14 +855,14 @@ extension ChannelFreeRailTests { kept.forEach { service.railAttemptsStore.set($0.value, forKey: $0.key) } } - private static func sparkPayment(hash: String, status: BreezSdkSpark.PaymentStatus, id: String? = nil, timestamp: UInt64 = 1) -> Payment { + private static func sparkPayment(hash: String, status: BreezSdkSpark.PaymentStatus) -> Payment { Payment( - id: id ?? hash, + id: hash, paymentType: .send, status: status, amount: 20000, fees: 0, - timestamp: timestamp, + timestamp: 1, method: .lightning, details: .lightning( description: nil, @@ -1762,19 +1126,11 @@ extension ChannelFreeRailTests { await assertRefusedAsDuplicate() } - func testASendWhoseCallReturnsTheFailureSparkReportedDuringItReleasesTheHold() async throws { + func testASparkFailureReportedWhileItsSendIsInFlightStillReleasesTheHold() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) var release: CheckedContinuation? rail.sendGate = { await withCheckedContinuation { release = $0 } } - rail.sentStatus = .failed - rail.sentPaymentId = "retry" rail.balanceSats = 100_000 - var failures = 0 - Bitkit.LightningService.shared.setEventCallback { event in - if case .paymentFailed = event { - failures += 1 - } - } let send = Task { try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) } var waited = 0 while release == nil, waited < 500 { @@ -1786,98 +1142,12 @@ extension ChannelFreeRailTests { Bitkit.LightningService.shared.emitChannelFreeRailEvent(.paymentFailed(paymentId: hash, paymentHash: hash, reason: nil)) release?.resume() _ = try await send.value - // Spark's own event for the attempt, arriving after the call returned it, isn't reported again. - Bitkit.LightningService.shared.emitChannelFreeRailEvent( - .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), - railPaymentId: "retry" - ) - XCTAssertEqual(failures, 1, "The failure didn't reach watchers exactly once") - rail.listError = NSError(domain: "spark", code: 1) - rail.balanceSats = 0 - - await assertReachesTheNode() - } - - func testASendReturnedPendingAfterSparkFailedItDuringTheCallReleasesTheHold() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - rail.sentPaymentId = "retry" - rail.balanceSats = 100_000 - var failures = 0 - Bitkit.LightningService.shared.setEventCallback { event in - if case .paymentFailed = event { - failures += 1 - } - } - // Spark fails the attempt while its send call hands it over, and the call returns it pending. - rail.sendGate = { - Bitkit.LightningService.shared.emitChannelFreeRailEvent( - .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), - railPaymentId: "retry" - ) - } - - _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) - XCTAssertEqual(failures, 1, "The failure didn't reach watchers exactly once") rail.listError = NSError(domain: "spark", code: 1) rail.balanceSats = 0 await assertReachesTheNode() } - func testAFailureDuringASendCallThatThenThrowsSettlesTheSendInDoubt() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - rail.balanceSats = 100_000 - var failures = 0 - Bitkit.LightningService.shared.setEventCallback { event in - if case .paymentFailed = event { - failures += 1 - } - } - // Spark fails the attempt during its send call, and the call then loses its connection. - rail.afterSubmission = { - Bitkit.LightningService.shared.emitChannelFreeRailEvent(.paymentFailed(paymentId: hash, paymentHash: hash, reason: nil)) - } - rail.errorAfterSubmission = NSError(domain: "spark", code: 2) - - do { - _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) - XCTFail("The send call's error was swallowed") - } catch {} - XCTAssertEqual(failures, 1, "The failure held during the call was lost") - rail.afterSubmission = nil - rail.errorAfterSubmission = nil - rail.listError = NSError(domain: "spark", code: 1) - rail.balanceSats = 0 - - await assertReachesTheNode() - } - - func testAnEarlierAttemptsFailureDuringTheCallLeavesAPendingSendHeld() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - rail.sentPaymentId = "retry" - rail.balanceSats = 100_000 - var failures = 0 - Bitkit.LightningService.shared.setEventCallback { event in - if case .paymentFailed = event { - failures += 1 - } - } - rail.sendGate = { - Bitkit.LightningService.shared.emitChannelFreeRailEvent( - .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), - railPaymentId: "earlier" - ) - } - - _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) - XCTAssertEqual(failures, 0, "An earlier attempt's failure was reported for the pending send") - rail.sentBolt11 = nil - rail.listError = NSError(domain: "spark", code: 1) - rail.balanceSats = 0 - - await assertRefusedAsDuplicate() - } - // MARK: - Restore /// Marks the wallet restored `offset` seconds after the fixture invoice was created. @@ -2153,7 +1423,9 @@ extension ChannelFreeRailTests { try await sendOverSpark() // The send failed, for example with no route: Spark lists it failed, and the operators show it failed once // every attempt at its hash was returned. - rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil)] + rail.payments = [ + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: Self.sparkNow()), + ] rail.sendStatus = .success(.failed) try await sendOverSpark() @@ -2260,7 +1532,9 @@ extension ChannelFreeRailTests { rail.sendStatus = .success(nil) rail.onSendStatus = { [rail] in _ = try? await service.send(bolt11: Self.invoice) - rail?.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: status, preimage: nil)] + rail?.payments = [ + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: status, preimage: nil, timestamp: Self.sparkNow()), + ] afterCompeting() } return try await service.send(bolt11: Self.invoice) @@ -2328,6 +1602,78 @@ extension ChannelFreeRailTests { XCTAssertFalse(Bitkit.SparkManager.paysBySparkTransfer(prefersSpark: false, sparkTransferFeeSats: nil)) } + /// Now on the service's clock, as Spark dates an attempt at its start. + private static func sparkNow() -> UInt64 { + UInt64(Bitkit.LightningService.shared.now().timeIntervalSince1970) + } + + /// Sends the fixture invoice over Spark while Spark lists an earlier attempt of it that failed, `first`. + private func sendARetryAfterAFailedAttempt() async throws -> String { + let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) + let hash = String(invoice.paymentHash()) + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: TimeInterval(invoice.secondsSinceEpoch() + 60)) } + rail.payments = [ + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: 100), + ] + try await sendOverSpark() + rail.balanceSats = 0 + return hash + } + + func testASentRetryStaysHeldWhileSparkListsOnlyAnEarlierFailure() async throws { + let hash = try await sendARetryAfterAFailedAttempt() + + // Spark took the retry but lists only the attempt before it. + await assertRefusedAsDuplicate() + let status = await PaykitLightningPaymentProofLookup.railStatus(paymentHash: hash) + XCTAssertEqual(status, .pending, "the retry read as failed by the earlier attempt's failure") + + rail.payments.append( + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: Self.sparkNow()) + ) + await assertReachesTheNode() + } + + func testALateFailureOfAnEarlierAttemptKeepsARetryHeld() async throws { + let hash = try await sendARetryAfterAFailedAttempt() + + // A failure Spark dates before the send is an earlier attempt's; one dated at the send is its own and ends it. + Bitkit.LightningService.shared.emitChannelFreeRailEvent( + .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), + paymentCreatedAt: 100 + ) + await assertRefusedAsDuplicate() + Bitkit.LightningService.shared.emitChannelFreeRailEvent( + .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), + paymentCreatedAt: Self.sparkNow() + ) + await assertReachesTheNode() + } + + func testASentRetrySparkNeverListsEndsPastItsInvoicesExpiry() async throws { + _ = try await sendARetryAfterAFailedAttempt() + await assertRefusedAsDuplicate() + + let expiresAt = try Self.invoiceExpiresAt() + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: expiresAt - 1) } + await assertRefusedAsDuplicate() + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: expiresAt) } + await assertReachesTheNode() + } + + func testARetryIsRefusedWhileSparkListsAnyAttemptPending() async throws { + let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) + let hash = String(invoice.paymentHash()) + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: TimeInterval(invoice.secondsSinceEpoch() + 60)) } + rail.payments = [ + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .pending, preimage: nil, timestamp: 100), + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: 200), + ] + rail.balanceSats = 100_000 + + await assertRefusedAsDuplicate() + } + private func sendOverSpark() async throws { rail.balanceSats = 100_000 _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) @@ -2526,12 +1872,6 @@ extension ChannelFreeRailTests { XCTAssertTrue(ActivityService.keepsLightningStatus(existing: .succeeded, update: .failed, isStaleRailFailure: false)) XCTAssertTrue(ActivityService.keepsLightningStatus(existing: .pending, update: .failed, isStaleRailFailure: true)) XCTAssertFalse(ActivityService.keepsLightningStatus(existing: .pending, update: .failed, isStaleRailFailure: false)) - // A failed Spark send keeps its row against an older attempt's failure, which carries that attempt's amount, and - // takes its own attempt's or a later one's. - XCTAssertTrue(ActivityService.keepsLightningStatus( - existing: .failed, update: .failed, isStaleRailFailure: false, isOlderChannelFreeAttempt: true - )) - XCTAssertFalse(ActivityService.keepsLightningStatus(existing: .failed, update: .failed, isStaleRailFailure: false)) XCTAssertFalse(ActivityService.keepsLightningStatus(existing: .failed, update: .succeeded, isStaleRailFailure: false)) XCTAssertFalse(ActivityService.keepsLightningStatus(existing: .pending, update: .succeeded, isStaleRailFailure: true)) } @@ -2616,10 +1956,6 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { var estimateError: Error? var listError: Error? var sentBolt11: String? - /// The rail's id of the attempt a send returns. - var sentPaymentId: String? - /// The status a send returns its attempt with. - var sentStatus: LDKNode.PaymentStatus = .pending var sends = 0 var sentFeeLimitSats: UInt64? var sendGate: (() async -> Void)? @@ -2629,8 +1965,6 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { var onList: (() -> Void)? /// Runs as a send is about to be submitted, before `beforeSubmission`. var beforeSubmit: (() -> Void)? - /// Runs once the send was submitted, before `errorAfterSubmission`. - var afterSubmission: (() -> Void)? /// Thrown after the send was submitted, as when the connection drops inside Spark's send. var errorAfterSubmission: Error? /// Whether the rail's last sync reached it, after the given seconds when there are any. @@ -2648,15 +1982,12 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { "lnbcrt1fake" } - func send(bolt11: String, sats: UInt64?, maxFeeSats: UInt64?, beforeSubmission: @escaping () throws -> Void) async throws - -> (paymentHash: PaymentHash, paymentId: String?, status: LDKNode.PaymentStatus) - { + func send(bolt11: String, sats: UInt64?, maxFeeSats: UInt64?, beforeSubmission: @escaping () throws -> Void) async throws -> PaymentHash { if let refusal { throw refusal } beforeSubmit?() try beforeSubmission() - afterSubmission?() if let refusalAfterSubmission { throw refusalAfterSubmission } @@ -2667,7 +1998,7 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { sentFeeLimitSats = maxFeeSats sentBolt11 = bolt11 sends += 1 - return ("ee", sentPaymentId, sentStatus) + return "ee" } func estimateRoutingFees(bolt11: String, amountSats: UInt64?) async throws -> UInt64 { diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index 709b7054a4..15bab32b61 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -97,333 +97,4 @@ final class SparkRelaunchActivityTests: XCTestCase { guard case let .lightning(lightning)? = activity else { return XCTFail("The send wasn't recorded") } XCTAssertEqual(lightning.contact, "pk:contact") } - - func testAFailedSparkRowKeepsItsDetailsAgainstAnOlderAttemptButTakesItsOwnAndLaterOnes() async throws { - let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "e7", count: 16) - func failed(sats: UInt64, feeSats: UInt64, at timestamp: UInt64) -> PaymentDetails { - PaymentDetails( - id: hash, - kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), - amountMsat: sats * 1000, feePaidMsat: feeSats * 1000, direction: .outbound, status: .failed, latestUpdateTimestamp: timestamp - ) - } - func row() async throws -> LightningActivity? { - guard case let .lightning(lightning)? = try await CoreService.shared.activity.getActivity(id: hash) else { return nil } - return lightning - } - // An amountless invoice's retry, at another amount, failed and was recorded. - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 0, at: 200)) - - // A replay of the first attempt's failure leaves the retry's details. - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 300, feeSats: 0, at: 100)) - var current = try await row() - XCTAssertEqual(current?.value, 500, "an older attempt's failure replaced the retry's amount") - - // The retry's own fee correction still lands. - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 3, at: 200)) - current = try await row() - XCTAssertEqual(current?.fee, 3) - - // A later attempt's failure takes the row. - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 700, feeSats: 0, at: 300)) - current = try await row() - XCTAssertEqual(current?.value, 700) - } - - func testAFailedSparkRowKeepsItsAttemptAgainstAnotherAttemptOfTheSameSecond() async throws { - let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "e8", count: 16) - func failed(sats: UInt64, feeSats: UInt64, at timestamp: UInt64) -> PaymentDetails { - PaymentDetails( - id: hash, - kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), - amountMsat: sats * 1000, feePaidMsat: feeSats * 1000, direction: .outbound, status: .failed, latestUpdateTimestamp: timestamp - ) - } - func row() async throws -> LightningActivity? { - guard case let .lightning(lightning)? = try await CoreService.shared.activity.getActivity(id: hash) else { return nil } - return lightning - } - // A retry started in the same second as the first attempt, at another amount, failed and was recorded. - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 0, at: 200), railPaymentId: "retry") - - // A replay of the first attempt's failure, dated the same second, leaves the retry's details. - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 300, feeSats: 1, at: 200), railPaymentId: "first") - var current = try await row() - XCTAssertEqual(current?.value, 500, "another attempt of the same second replaced the retry's amount") - XCTAssertEqual(current?.fee, 0, "another attempt of the same second replaced the retry's fee") - - // The retry's own fee correction still lands. - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 3, at: 200), railPaymentId: "retry") - current = try await row() - XCTAssertEqual(current?.fee, 3) - - // A later attempt's failure takes the row, and then owns it. - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 700, feeSats: 0, at: 300), railPaymentId: "third") - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 3, at: 300), railPaymentId: "retry") - current = try await row() - XCTAssertEqual(current?.value, 700) - } - - func testASameSecondRetryTakesTheRowAfterItsHoldEnded() async throws { - let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "ea", count: 16) - func failed(sats: UInt64, feeSats: UInt64, at timestamp: UInt64) -> PaymentDetails { - PaymentDetails( - id: hash, - kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), - amountMsat: sats * 1000, feePaidMsat: feeSats * 1000, direction: .outbound, status: .failed, latestUpdateTimestamp: timestamp - ) - } - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 300, feeSats: 1, at: 200), railPaymentId: "first") - // A retry in the same second followed the first attempt, and a listing that showed it failed ended its hold - // before its own failure was recorded: only the attempts kept past the hold still order the two. - LightningService.shared.keepEarlierAttemptsForTesting(hash: hash, ids: ["first"]) - - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 0, at: 200), railPaymentId: "retry") - guard case let .lightning(row)? = try await CoreService.shared.activity.getActivity(id: hash) else { - return XCTFail("the row is missing") - } - XCTAssertEqual(row.value, 500, "the first attempt's amount stayed over the retry's") - XCTAssertEqual(row.fee, 0) - } - - func testALaterAttemptsReplayTakesTheRowWhenAThirdSendNeverWroteOne() async throws { - let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "eb", count: 16) - func failed(sats: UInt64, feeSats: UInt64, at timestamp: UInt64) -> PaymentDetails { - PaymentDetails( - id: hash, - kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), - amountMsat: sats * 1000, feePaidMsat: feeSats * 1000, direction: .outbound, status: .failed, latestUpdateTimestamp: timestamp - ) - } - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 300, feeSats: 1, at: 200), railPaymentId: "first") - // The second attempt's row write failed, and a third send, which never wrote a row, followed both. - LightningService.shared.keepEarlierAttemptsForTesting(hash: hash, ids: ["first", "second"]) - - // After a restart, the second attempt's replay is newer than the row's attempt, so it takes the row. - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 2, at: 300), railPaymentId: "second") - guard case let .lightning(row)? = try await CoreService.shared.activity.getActivity(id: hash) else { - return XCTFail("the row is missing") - } - XCTAssertEqual(row.value, 500, "the first attempt's amount stayed over the second's") - XCTAssertEqual(row.fee, 2) - - // The first attempt's replay doesn't take it back. - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 300, feeSats: 1, at: 200), railPaymentId: "first") - guard case let .lightning(replayed)? = try await CoreService.shared.activity.getActivity(id: hash) else { - return XCTFail("the row is missing") - } - XCTAssertEqual(replayed.value, 500) - } - - func testASameSecondLaterAttemptsReplayTakesTheRowWhenAThirdSendNeverWroteOne() async throws { - let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "ec", count: 16) - func failed(sats: UInt64, feeSats: UInt64) -> PaymentDetails { - PaymentDetails( - id: hash, - kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), - amountMsat: sats * 1000, feePaidMsat: feeSats * 1000, direction: .outbound, status: .failed, latestUpdateTimestamp: 200 - ) - } - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 300, feeSats: 1), railPaymentId: "first") - // The second attempt went out in the same second and kept the first as earlier; its row write failed. A third - // send, which never wrote a row, followed both. - LightningService.shared.keepEarlierAttemptsForTesting(hash: hash, ids: ["first"]) - LightningService.shared.keepEarlierAttemptsForTesting(hash: hash, ids: ["second", "first"]) - - // After a restart, the second attempt's replay went out after the row's attempt, so it takes the row. - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 2), railPaymentId: "second") - guard case let .lightning(row)? = try await CoreService.shared.activity.getActivity(id: hash) else { - return XCTFail("the row is missing") - } - XCTAssertEqual(row.value, 500, "the first attempt's amount stayed over the second's") - XCTAssertEqual(row.fee, 2) - - // The first attempt's replay doesn't take it back. - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 300, feeSats: 1), railPaymentId: "first") - guard case let .lightning(replayed)? = try await CoreService.shared.activity.getActivity(id: hash) else { - return XCTFail("the row is missing") - } - XCTAssertEqual(replayed.value, 500) - } - - func testANewerFailureTakesTheRowWhateverTheKeptOrder() async throws { - let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "ed", count: 16) - func failed(sats: UInt64, feeSats: UInt64, at timestamp: UInt64) -> PaymentDetails { - PaymentDetails( - id: hash, - kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), - amountMsat: sats * 1000, feePaidMsat: feeSats * 1000, direction: .outbound, status: .failed, latestUpdateTimestamp: timestamp - ) - } - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 300, feeSats: 1, at: 200), railPaymentId: "first") - // A send's read missed the first attempt, so a later send kept it after the second. - LightningService.shared.keepEarlierAttemptsForTesting(hash: hash, ids: ["second", "first"]) - - try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(sats: 500, feeSats: 2, at: 300), railPaymentId: "second") - guard case let .lightning(row)? = try await CoreService.shared.activity.getActivity(id: hash) else { - return XCTFail("the row is missing") - } - XCTAssertEqual(row.value, 500, "the kept order outranked Spark's dates") - } - - func testChannelFreeRowAttemptsKeepTheLatestRowWritersUpToTheLimit() throws { - let suite = "ChannelFreeRowAttemptsTests-\(UUID().uuidString)" - let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) - defer { defaults.removePersistentDomain(forName: suite) } - let attempts = ChannelFreeRowAttempts(defaults: defaults) - for index in 0 ... ChannelFreeRowAttempts.limit { - attempts.remember("id\(index)", forPaymentHash: "hash\(index)", stamp: "1:2:3") - } - attempts.remember("newer", forPaymentHash: "HASH1", stamp: "1:2:3") - // A failed row write puts the writer before it back, or removes the one it added. - let before = attempts.entry(forPaymentHash: "hash1") - attempts.remember("failed-write", forPaymentHash: "hash1", stamp: "4:5:6") - attempts.restore(before, forPaymentHash: "hash1") - attempts.remember("unwritten", forPaymentHash: "fresh", stamp: "1:2:3") - attempts.restore(nil, forPaymentHash: "fresh") - XCTAssertNil(attempts.attemptId(forPaymentHash: "fresh")) - - XCTAssertNil(attempts.attemptId(forPaymentHash: "hash0")) - XCTAssertEqual(attempts.attemptId(forPaymentHash: "hash1"), "newer") - XCTAssertEqual(attempts.attemptId(forPaymentHash: "hash\(ChannelFreeRowAttempts.limit)"), "id\(ChannelFreeRowAttempts.limit)") - } - - func testChannelFreeRowAttemptsKeepARetriedSendsWriterPastTheLatestSends() throws { - let suite = "ChannelFreeRowAttemptsTests-\(UUID().uuidString)" - let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) - defer { defaults.removePersistentDomain(forName: suite) } - defaults.set([["retried", "earlier"]], forKey: LightningService.keptRailSendEarlierAttemptsKey) - let attempts = ChannelFreeRowAttempts(defaults: defaults) - attempts.remember("original", forPaymentHash: "retried", stamp: "1:2:3") - attempts.remember("id", forPaymentHash: "plain", stamp: "1:2:3") - for index in 0 ..< ChannelFreeRowAttempts.limit { - attempts.remember("id\(index)", forPaymentHash: "later\(index)", stamp: "1:2:3") - } - - XCTAssertEqual(attempts.entry(forPaymentHash: "retried"), ["retried", "original", "1:2:3", "", ""]) - XCTAssertNil(attempts.entry(forPaymentHash: "plain")) - XCTAssertEqual(attempts.attemptId(forPaymentHash: "later0"), "id0") - XCTAssertEqual((defaults.array(forKey: "channelFreeRowAttemptIds") as? [[String]])?.count, ChannelFreeRowAttempts.limit + 1) - } - - func testChannelFreeRowAttemptsKeepANewSendsWriterBesideAFullSetOfRetriedSends() throws { - let suite = "ChannelFreeRowAttemptsTests-\(UUID().uuidString)" - let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) - defer { defaults.removePersistentDomain(forName: suite) } - let retried = (0 ..< ChannelFreeRowAttempts.limit).map { "retried\($0)" } - defaults.set(retried.map { [$0, "earlier"] }, forKey: LightningService.keptRailSendEarlierAttemptsKey) - let attempts = ChannelFreeRowAttempts(defaults: defaults) - for hash in retried { - attempts.remember("id", forPaymentHash: hash, stamp: "1:2:3") - } - attempts.remember("new", forPaymentHash: "plain", stamp: "1:2:3") - - XCTAssertEqual(attempts.attemptId(forPaymentHash: "plain"), "new") - XCTAssertEqual(attempts.attemptId(forPaymentHash: "retried0"), "id") - } - - func testASameSecondFailureTakesTheRowOnlyAsTheSendAfterTheRowsAttempt() { - // The row's own attempt, and a row or failure without an id, write it. - XCTAssertFalse(ActivityService.isOtherRowAttempt("first", rowAttemptId: "first")) - XCTAssertFalse(ActivityService.isOtherRowAttempt(nil, rowAttemptId: "first")) - XCTAssertFalse(ActivityService.isOtherRowAttempt("retry", rowAttemptId: nil)) - // Another attempt of the same second keeps the row when nothing orders the two. - XCTAssertTrue(ActivityService.isOtherRowAttempt("first", rowAttemptId: "retry")) - XCTAssertTrue(ActivityService.isOtherRowAttempt("first", rowAttemptId: "retry", earlierAttemptIds: ["older"])) - // Two kept attempts are ordered by the kept list, whatever else lists them. - XCTAssertFalse(ActivityService.isOtherRowAttempt( - "second", rowAttemptId: "first", earlierAttemptIds: ["first", "second"], keptEarlierAttemptIds: ["first", "second"] - )) - XCTAssertTrue(ActivityService.isOtherRowAttempt( - "first", rowAttemptId: "second", earlierAttemptIds: ["first", "second"], keptEarlierAttemptIds: ["first", "second"] - )) - // The retry in flight lists the row's attempt before it, so its failure takes the row. - XCTAssertFalse(ActivityService.isOtherRowAttempt("retry", rowAttemptId: "first", earlierAttemptIds: ["first"])) - // While it is in flight, an attempt it lists as earlier still keeps the row. - XCTAssertTrue(ActivityService.isOtherRowAttempt("older", rowAttemptId: "first", earlierAttemptIds: ["first", "older"])) - } - - func testFailingAHeldSparkRowInPlaceKeepsAWriterItDidntFollow() async throws { - let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "e9", count: 16) - let pending = PaymentDetails( - id: hash, - kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), - amountMsat: 500_000, feePaidMsat: 0, direction: .outbound, status: .pending, latestUpdateTimestamp: 200 - ) - try await CoreService.shared.activity.recordChannelFreeRailPayment(pending, railPaymentId: "earlier") - XCTAssertEqual(ActivityService.channelFreeRowAttempts.attemptId(forPaymentHash: hash), "earlier") - - // An attempt that isn't one the held send followed stays the row's writer. - try await CoreService.shared.activity.failPendingLightningSend(id: hash, earlierAttemptIds: ["older"]) - XCTAssertEqual(ActivityService.channelFreeRowAttempts.attemptId(forPaymentHash: hash), "earlier") - } - - func testFailingAHeldSparkRowInPlaceMakesItTheHeldAttemptsOwn() async throws { - func pendingRow(_ hash: String) async throws { - let pending = PaymentDetails( - id: hash, - kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), - amountMsat: 500_000, feePaidMsat: 0, direction: .outbound, status: .pending, latestUpdateTimestamp: 200 - ) - try await CoreService.shared.activity.recordChannelFreeRailPayment(pending, railPaymentId: "earlier") - } - let taken = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "ea", count: 16) - try await pendingRow(taken) - // The held send's own id becomes the writer, so it keeps the row against an older failure of the same second. - try await CoreService.shared.activity.failPendingLightningSend(id: taken, ownAttemptId: "retry", earlierAttemptIds: ["earlier"]) - XCTAssertEqual(ActivityService.channelFreeRowAttempts.attemptId(forPaymentHash: taken), "retry") - - let owned = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "eb", count: 16) - try await pendingRow(owned) - // Without its own id, a row the earlier attempt still owns keeps its writer, so that attempt's final fee lands. - try await CoreService.shared.activity.failPendingLightningSend(id: owned, earlierAttemptIds: ["earlier"]) - XCTAssertEqual(ActivityService.channelFreeRowAttempts.attemptId(forPaymentHash: owned), "earlier") - - let overwritten = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "ec", count: 16) - try await pendingRow(overwritten) - // The retry's send wrote over the earlier attempt's row without a Spark id, so that attempt no longer owns it. - guard case var .lightning(row)? = try await CoreService.shared.activity.getActivity(id: overwritten) else { - return XCTFail("the earlier attempt's row is missing") - } - row.value = 700 - try await CoreService.shared.activity.update(id: overwritten, activity: .lightning(row)) - try await CoreService.shared.activity.failPendingLightningSend(id: overwritten, earlierAttemptIds: ["earlier"]) - XCTAssertNil(ActivityService.channelFreeRowAttempts.attemptId(forPaymentHash: overwritten)) - } - - func testAStopBetweenKeepingAWriterAndSavingItsRowLeavesTheRowToItsRealWriter() async throws { - let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "ed", count: 16) - let pending = PaymentDetails( - id: hash, - kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), - amountMsat: 500_000, feePaidMsat: 0, direction: .outbound, status: .pending, latestUpdateTimestamp: 200 - ) - try await CoreService.shared.activity.recordChannelFreeRailPayment(pending, railPaymentId: "earlier") - guard case let .lightning(row)? = try await CoreService.shared.activity.getActivity(id: hash) else { - return XCTFail("the earlier payment's row is missing") - } - let attempts = ActivityService.channelFreeRowAttempts - // The retry's writer was kept, then the app stopped before its row was saved. - attempts.remember("retry", forPaymentHash: hash, stamp: "300:700:0", previousRowStamp: ChannelFreeRowAttempts.stamp(row)) - XCTAssertEqual(attempts.attemptId(forPaymentHash: hash, row: row), "earlier") - XCTAssertTrue(attempts.isUnchanged(row, forPaymentHash: hash)) - - // A second write cut off the same way, or one alike the row, still leaves it to its real writer. - attempts.remember("third", forPaymentHash: hash, stamp: "400:800:0", previousRowStamp: ChannelFreeRowAttempts.stamp(row)) - XCTAssertEqual(attempts.attemptId(forPaymentHash: hash, row: row), "earlier") - attempts.remember( - "alike", - forPaymentHash: hash, - stamp: ChannelFreeRowAttempts.stamp(row), - previousRowStamp: ChannelFreeRowAttempts.stamp(row) - ) - XCTAssertEqual(attempts.attemptId(forPaymentHash: hash, row: row), "earlier") - attempts.remember("retry", forPaymentHash: hash, stamp: "300:700:0", previousRowStamp: ChannelFreeRowAttempts.stamp(row)) - XCTAssertEqual(attempts.attemptId(forPaymentHash: hash, row: row), "earlier") - - // Once the retry's row is saved, it is the retry's. - attempts.commit(forPaymentHash: hash) - XCTAssertEqual(attempts.attemptId(forPaymentHash: hash, row: row), "retry") - XCTAssertFalse(attempts.isUnchanged(row, forPaymentHash: hash)) - } } From 0bec1768e4c8f5b3fe4d5e469e86fae207863967 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 00:31:35 +0100 Subject: [PATCH 54/64] fix: spark keeps the later failed attempt's row Spark dates each attempt at its start, so of two failed attempts of one invoice the later one's amount, fee and time now stay in Activity: an older attempt's failure no longer replaces them, and a later attempt's failure replaces an older one's also when the fees match. Verified: Spark relaunch activity, channel-free rail, payment safety and wallet activity suites pass on an iPhone 17 Pro simulator, iOS 26.5. --- Bitkit/Services/CoreService.swift | 8 +++- BitkitTests/SparkRelaunchActivityTests.swift | 39 ++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index f768327fe7..0129fa61f2 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1015,8 +1015,14 @@ class ActivityService { // The Spark receive of a move can settle the send before the node's routing fee is recorded. let feeChanging = payment.feePaidMsat.map { $0 / 1000 != existing.fee } ?? false let needsPrivateContactAttribution = existing.contact == nil && payment.direction == .inbound + // Spark dates each attempt at its start: of two failed attempts, the later one's amount, fee and time stay. + let isRailFailureOverFailure = rail == .channelFree && state == .failed && existing.status == .failed + if isRailFailureOverFailure, existing.timestamp > paymentTimestamp { + return + } + let isLaterRailFailure = isRailFailureOverFailure && paymentTimestamp > existing.timestamp if existingUpdatedAt > paymentTimestamp && !statusChanging && !feeChanging && !needsPrivateContactAttribution - && !replacesSelfReceive + && !replacesSelfReceive && !isLaterRailFailure { return } diff --git a/BitkitTests/SparkRelaunchActivityTests.swift b/BitkitTests/SparkRelaunchActivityTests.swift index 15bab32b61..3aa6e358fa 100644 --- a/BitkitTests/SparkRelaunchActivityTests.swift +++ b/BitkitTests/SparkRelaunchActivityTests.swift @@ -97,4 +97,43 @@ final class SparkRelaunchActivityTests: XCTestCase { guard case let .lightning(lightning)? = activity else { return XCTFail("The send wasn't recorded") } XCTAssertEqual(lightning.contact, "pk:contact") } + + func testAnOlderSparkAttemptsFailureKeepsTheLaterFailedAttemptsRow() async throws { + let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "e7", count: 16) + func failed(at timestamp: UInt64, amountMsat: UInt64, feeMsat: UInt64) -> PaymentDetails { + PaymentDetails( + id: hash, + kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), + amountMsat: amountMsat, feePaidMsat: feeMsat, direction: .outbound, status: .failed, latestUpdateTimestamp: timestamp + ) + } + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(at: 200, amountMsat: 300_000, feeMsat: 3000)) + + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(at: 100, amountMsat: 250_000, feeMsat: 1000)) + + let activity = try await CoreService.shared.activity.getActivity(id: hash) + guard case let .lightning(lightning)? = activity else { return XCTFail("The send wasn't recorded") } + XCTAssertEqual(lightning.value, 300) + XCTAssertEqual(lightning.fee, 3) + XCTAssertEqual(lightning.timestamp, 200, "the earlier attempt's failure replaced the later attempt's row") + } + + func testALaterSparkAttemptsFailureReplacesAnEarlierFailedAttemptsRow() async throws { + let hash = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() + String(repeating: "f8", count: 16) + func failed(at timestamp: UInt64, amountMsat: UInt64) -> PaymentDetails { + PaymentDetails( + id: hash, + kind: .bolt11(hash: hash, preimage: nil, secret: nil, description: nil, bolt11: "lnbcrt1"), + amountMsat: amountMsat, feePaidMsat: 1000, direction: .outbound, status: .failed, latestUpdateTimestamp: timestamp + ) + } + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(at: 100, amountMsat: 250_000)) + + try await CoreService.shared.activity.recordChannelFreeRailPayment(failed(at: 200, amountMsat: 300_000)) + + let activity = try await CoreService.shared.activity.getActivity(id: hash) + guard case let .lightning(lightning)? = activity else { return XCTFail("The send wasn't recorded") } + XCTAssertEqual(lightning.value, 300) + XCTAssertEqual(lightning.timestamp, 200) + } } From 0ab63c1030f642e935f9a6c0ce2f38e16d09b047 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 04:49:59 +0100 Subject: [PATCH 55/64] fix: spark keeps an earlier failure off a retry not yet submitted A retry in Spark's send call that wasn't submitted yet has nothing at Spark, so a failure arriving then is an earlier attempt's: it no longer reaches the retry's screen or releases its attempt. Verified: Spark relaunch activity, channel-free rail, payment safety and wallet activity suites pass on an iPhone 17 Pro simulator, iOS 26.5. --- Bitkit/Services/LightningService.swift | 11 ++++++++++- BitkitTests/ChannelFreeRailTests.swift | 27 ++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index cb4c78b867..1a418a8f1e 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1846,6 +1846,13 @@ class LightningService: NodeLifecycleService { eventCallbackLock.withLock { railSendsInFlight.contains(paymentHash.lowercased()) } } + /// A send in Spark's send call that wasn't submitted yet: nothing of it reached Spark, so any failure is an earlier + /// attempt's. + private func isUnsubmittedRailSendInFlight(paymentHash: String) -> Bool { + let hash = paymentHash.lowercased() + return eventCallbackLock.withLock { railSendsInFlight.contains(hash) && uncertainRailSendFailedAt()[hash] == nil } + } + static func submitPayment( beforeSubmission: @escaping () throws -> Void, send: @escaping () throws -> Result @@ -2389,7 +2396,9 @@ extension LightningService { switch event { case let .paymentFailed(_, paymentHash?, _): // An attempt before the send Spark hasn't settled yet ended: that send may still pay, so nothing changes. - guard !isEarlierRailAttempt(paymentHash: paymentHash, createdAt: paymentCreatedAt) else { + guard !isEarlierRailAttempt(paymentHash: paymentHash, createdAt: paymentCreatedAt), + !isUnsubmittedRailSendInFlight(paymentHash: paymentHash) + else { Logger.info("Ignored a Spark failure of an attempt before an unsettled send: \(event)", context: "LightningService") return } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 007320a473..57d77f0309 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1661,6 +1661,33 @@ extension ChannelFreeRailTests { await assertReachesTheNode() } + func testAnEarlierFailureWhileARetryEntersSparksSendCallStaysOffItsScreen() async throws { + let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) + let hash = String(invoice.paymentHash()) + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: TimeInterval(invoice.secondsSinceEpoch() + 60)) } + final class Failures: @unchecked Sendable { var count = 0 } + let failures = Failures() + Bitkit.LightningService.shared.setEventCallback { event in + if case .paymentFailed = event { + failures.count += 1 + } + } + // The earlier attempt's failure arrives while the retry is in Spark's send call, before it is submitted. + rail.beforeSubmit = { + Bitkit.LightningService.shared.emitChannelFreeRailEvent( + .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), + paymentCreatedAt: 100 + ) + } + + try await sendOverSpark() + + XCTAssertEqual(failures.count, 0, "an earlier attempt's failure reached the retry's screen") + rail.beforeSubmit = nil + rail.balanceSats = 0 + await assertRefusedAsDuplicate() + } + func testARetryIsRefusedWhileSparkListsAnyAttemptPending() async throws { let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) let hash = String(invoice.paymentHash()) From b0e47679efa97beefa36842df2a8a471353c2f0a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 06:06:08 +0100 Subject: [PATCH 56/64] fix: spark keeps a retry's hold when an earlier send settles A failure event, a listing or an expired invoice ended whatever hold the invoice had once checked. If the send ended and a retry took a new hold in between, the retry lost it and could be sent again while unresolved. Each now ends only the hold it read, by its start. Verified: ChannelFreeRailTests, SparkRelaunchActivityTests, SparkPaymentSafetyTests and WalletActivityTests pass on an iPhone 17 Pro simulator, iOS 26.5; the new test fails without the fix --- Bitkit/Services/LightningService.swift | 45 +++++++++++++++++++------- BitkitTests/ChannelFreeRailTests.swift | 23 +++++++++++++ 2 files changed, 56 insertions(+), 12 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 1a418a8f1e..f196020c80 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1686,14 +1686,16 @@ class LightningService: NodeLifecycleService { private func settleListedRailSends(_ payments: [ChannelFreeRailPayment]) { let settled = eventCallbackLock.withLock { let uncertain = uncertainRailSendFailedAt() - return Set(payments.filter { payment in - guard payment.direction == .outbound, payment.status != .pending, - let startedAt = uncertain[payment.paymentHash.lowercased()] else { return false } - return payment.status == .succeeded || Self.isOwnRailAttempt(createdAt: payment.timestamp, startedAt: startedAt) - }.map { $0.paymentHash.lowercased() }) + return payments.reduce(into: [String: Int]()) { settled, payment in + let hash = payment.paymentHash.lowercased() + guard payment.direction == .outbound, payment.status != .pending, let startedAt = uncertain[hash], + payment.status == .succeeded || Self.isOwnRailAttempt(createdAt: payment.timestamp, startedAt: startedAt) + else { return } + settled[hash] = startedAt + } } - for hash in settled { - endRailSendUncertainty(paymentHash: hash) + for (hash, startedAt) in settled { + endRailSendUncertainty(paymentHash: hash, startedAt: startedAt) } } @@ -1722,34 +1724,50 @@ class LightningService: NodeLifecycleService { } private func endRailSendUncertainty(paymentHash: String) { + endRailSendUncertainty(paymentHash: paymentHash) { _ in true } + } + + /// Ends the send held since `startedAt` only: once it ended, a retry may hold the invoice again, and that retry stays + /// held. + private func endRailSendUncertainty(paymentHash: String, startedAt: Int) { + endRailSendUncertainty(paymentHash: paymentHash) { $0 == startedAt } + } + + private func endRailSendUncertainty(paymentHash: String, where isEnded: (Int) -> Bool) { let hash = paymentHash.lowercased() eventCallbackLock.withLock { var uncertain = uncertainRailSendFailedAt() - guard uncertain.removeValue(forKey: hash) != nil else { return } + guard let startedAt = uncertain[hash], isEnded(startedAt) else { return } + uncertain.removeValue(forKey: hash) railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) } } + /// When the send of `paymentHash` Spark hasn't settled yet started, by this device's clock. + private func railSendStartedAt(paymentHash: String) -> Int? { + eventCallbackLock.withLock { uncertainRailSendFailedAt()[paymentHash.lowercased()] } + } + /// 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. private func railSyncedSinceUncertainSend(paymentHash: String) async -> Bool { let hash = paymentHash.lowercased() let uncertain = eventCallbackLock.withLock { - uncertainRailSendFailedAt()[hash].map { (failedAt: UInt64($0), expiresAt: attemptExpiries(key: Self.railAttemptsKey)[hash]) } + uncertainRailSendFailedAt()[hash].map { (startedAt: $0, expiresAt: attemptExpiries(key: Self.railAttemptsKey)[hash]) } } guard let uncertain else { return true } // Spark keeps a send it committed but didn't finish in a cache no call exposes, and a sync that reached Spark // 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: uncertain.failedAt) else { + guard let rail = channelFreeRail ?? channelFreePaymentHistory, await rail.hasSynced(after: UInt64(uncertain.startedAt)) else { return false } // Its Activity row is written first, so a stop in between finds the send held and writes it again. if let record = railSendExpired, await !record(hash) { return false } - endRailSendUncertainty(paymentHash: hash) + endRailSendUncertainty(paymentHash: hash, startedAt: uncertain.startedAt) return true } @@ -2395,6 +2413,7 @@ extension LightningService { func emitChannelFreeRailEvent(_ event: Event, paymentCreatedAt: UInt64? = nil) { switch event { case let .paymentFailed(_, paymentHash?, _): + let startedAt = railSendStartedAt(paymentHash: paymentHash) // An attempt before the send Spark hasn't settled yet ended: that send may still pay, so nothing changes. guard !isEarlierRailAttempt(paymentHash: paymentHash, createdAt: paymentCreatedAt), !isUnsubmittedRailSendInFlight(paymentHash: paymentHash) @@ -2403,7 +2422,9 @@ extension LightningService { return } // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. - endRailSendUncertainty(paymentHash: paymentHash) + if let startedAt { + endRailSendUncertainty(paymentHash: paymentHash, startedAt: startedAt) + } // The failure of the send itself, which may arrive while its send call is still returning. releaseRailAttempt(paymentHash: paymentHash, unlessInFlight: false) case let .paymentSuccessful(_, paymentHash, _, _): diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 57d77f0309..661c5978c3 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1661,6 +1661,29 @@ extension ChannelFreeRailTests { await assertReachesTheNode() } + func testARetryThatHoldsTheInvoiceWhileAnExpiredSendSettlesStaysHeld() async throws { + let hash = try await sendARetryAfterAFailedAttempt() + let service = Bitkit.LightningService.shared + let previousRecord = service.railSendExpired + 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 } + // 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()) + try? await sendOverSpark() + return true + } + + await service.endExpiredRailSendUncertainties() + + rail.balanceSats = 0 + await assertRefusedAsDuplicate() + } + func testAnEarlierFailureWhileARetryEntersSparksSendCallStaysOffItsScreen() async throws { let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) let hash = String(invoice.paymentHash()) From ce175472e928956797dd1e256db4db4453ebfe87 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 06:46:54 +0100 Subject: [PATCH 57/64] fix: spark keeps an earlier failure off a retry's screen A Spark failure event checked the invoice's hold and ended it in separate steps, so a retry that took the hold in between could still get the earlier send's failure on its screen. The check and the end are now one step under the lock, judged by whichever send holds the invoice then. Verified: ChannelFreeRailTests, SparkRelaunchActivityTests, SparkPaymentSafetyTests and WalletActivityTests pass on an iPhone 17 Pro simulator, iOS 26.5 --- Bitkit/Services/LightningService.swift | 36 +++++++++++++------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index f196020c80..bdc6c56a5c 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1743,9 +1743,22 @@ class LightningService: NodeLifecycleService { } } - /// When the send of `paymentHash` Spark hasn't settled yet started, by this device's clock. - private func railSendStartedAt(paymentHash: String) -> Int? { - eventCallbackLock.withLock { uncertainRailSendFailedAt()[paymentHash.lowercased()] } + /// Whether a Spark failure, of an attempt created at `createdAt`, is the failure of the invoice's send, ending its hold + /// if it has one, in one step, so a retry that holds the invoice meanwhile is judged by its own hold. Not when Spark + /// dated it before the send Spark hasn't settled yet, or while a send in Spark's send call wasn't submitted yet, as + /// nothing of it reached Spark: an earlier attempt's, while that send may still pay. + private func endRailSendByFailure(paymentHash: String, createdAt: UInt64?) -> Bool { + let hash = paymentHash.lowercased() + return eventCallbackLock.withLock { + var uncertain = uncertainRailSendFailedAt() + guard let startedAt = uncertain[hash] else { return !railSendsInFlight.contains(hash) } + if let createdAt, !Self.isOwnRailAttempt(createdAt: createdAt, startedAt: startedAt) { + return false + } + uncertain.removeValue(forKey: hash) + railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) + return true + } } /// True unless the hash's last rail send failed after it was submitted and may still go out: no sync has reached the @@ -1864,13 +1877,6 @@ class LightningService: NodeLifecycleService { eventCallbackLock.withLock { railSendsInFlight.contains(paymentHash.lowercased()) } } - /// A send in Spark's send call that wasn't submitted yet: nothing of it reached Spark, so any failure is an earlier - /// attempt's. - private func isUnsubmittedRailSendInFlight(paymentHash: String) -> Bool { - let hash = paymentHash.lowercased() - return eventCallbackLock.withLock { railSendsInFlight.contains(hash) && uncertainRailSendFailedAt()[hash] == nil } - } - static func submitPayment( beforeSubmission: @escaping () throws -> Void, send: @escaping () throws -> Result @@ -2413,18 +2419,12 @@ extension LightningService { func emitChannelFreeRailEvent(_ event: Event, paymentCreatedAt: UInt64? = nil) { switch event { case let .paymentFailed(_, paymentHash?, _): - let startedAt = railSendStartedAt(paymentHash: paymentHash) // An attempt before the send Spark hasn't settled yet ended: that send may still pay, so nothing changes. - guard !isEarlierRailAttempt(paymentHash: paymentHash, createdAt: paymentCreatedAt), - !isUnsubmittedRailSendInFlight(paymentHash: paymentHash) - else { + // Otherwise the event settles a send whose outcome was unknown, so retries of its invoice are no longer held. + guard endRailSendByFailure(paymentHash: paymentHash, createdAt: paymentCreatedAt) else { Logger.info("Ignored a Spark failure of an attempt before an unsettled send: \(event)", context: "LightningService") return } - // The event settles a send whose outcome was unknown, so retries of its invoice are no longer held. - if let startedAt { - endRailSendUncertainty(paymentHash: paymentHash, startedAt: startedAt) - } // The failure of the send itself, which may arrive while its send call is still returning. releaseRailAttempt(paymentHash: paymentHash, unlessInFlight: false) case let .paymentSuccessful(_, paymentHash, _, _): From af3eb2929efdb03ae32179fa804dbe1806288bdf Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 12:17:55 +0100 Subject: [PATCH 58/64] fix: spark dates a retry after the failures it knows A failed attempt Spark dated within the clock margin before a retry read as the retry's own: it could end the retry's hold, fail its screen, replace its Activity row and, at expiry, copy its details into the retry's row. A send's saved start is now at least the margin plus one second after the latest failure Spark dated for the invoice, from its list or its events, so a known earlier failure never reads as the retry's. Nothing new is saved. Startup also ends a held send from the own failure or success it reads, before releasing it, so a channel retry no longer waits on a later read of Spark's history. Verified: ChannelFreeRailTests, SparkRelaunchActivityTests, SparkPaymentSafetyTests and WalletActivityTests pass on an iPhone 17 Pro simulator, iOS 26.5; the two new retry tests fail without the floor --- Bitkit/Managers/SparkManager.swift | 53 ++++++++------ Bitkit/Services/LightningService.swift | 26 +++++-- BitkitTests/ChannelFreeRailTests.swift | 97 +++++++++++++++++++++++++- 3 files changed, 150 insertions(+), 26 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 314b5eb197..5b83f07eaa 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -772,17 +772,19 @@ final class SparkManager: ChannelFreeLightningRail { nonisolated func lightningPayments() async throws -> [ChannelFreeRailPayment] { let payments = try await requireSdk().listPayments(request: ListPaymentsRequest(sortAscending: false)).payments - return payments.compactMap { payment in - guard case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details else { return nil } - return ChannelFreeRailPayment( - paymentHash: htlcDetails.paymentHash, - direction: payment.paymentType == .send ? .outbound : .inbound, - status: Self.ldkStatus(payment.status), - preimage: htlcDetails.preimage, - timestamp: payment.timestamp, - feeSats: Self.sats(payment.fees) - ) - } + return payments.compactMap(Self.railPayment) + } + + nonisolated static func railPayment(_ payment: Payment) -> ChannelFreeRailPayment? { + guard case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details else { return nil } + return ChannelFreeRailPayment( + paymentHash: htlcDetails.paymentHash, + direction: payment.paymentType == .send ? .outbound : .inbound, + status: ldkStatus(payment.status), + preimage: htlcDetails.preimage, + timestamp: payment.timestamp, + feeSats: sats(payment.fees) + ) } nonisolated func estimateRoutingFees(bolt11: String, amountSats: UInt64?) async throws -> UInt64 { @@ -1856,17 +1858,26 @@ final class SparkManager: ChannelFreeLightningRail { /// listed before it went out, or a failure of the stored pending send when Spark lists none. Returns whether it was saved. private func recordExpiredSend(paymentHash: String) async -> Bool { guard let payments = try? await requireSdk().listPayments(request: ListPaymentsRequest()).payments else { return false } - let own = payments.filter { payment in - guard payment.paymentType == .send, case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details, - htlcDetails.paymentHash.caseInsensitiveCompare(paymentHash) == .orderedSame else { return false } - return !LightningService.shared.isEarlierRailAttempt(paymentHash: paymentHash, createdAt: payment.timestamp) - } - if let latest = own.max(by: { $0.timestamp < $1.timestamp }) { - return await recordActivity(latest) + let isEarlierAttempt = { LightningService.shared.isEarlierRailAttempt(paymentHash: $0, createdAt: $1) } + if let own = Self.expiredSendAttempt(payments, paymentHash: paymentHash, isEarlierAttempt: isEarlierAttempt) { + return await recordActivity(own) } return await (try? CoreService.shared.activity.failPendingLightningSend(id: paymentHash)) != nil } + /// The latest of Spark's attempts of a send whose invoice expired, none when Spark lists only attempts before it. + nonisolated static func expiredSendAttempt( + _ payments: [Payment], + paymentHash: String, + isEarlierAttempt: (_ hash: String, _ createdAt: UInt64) -> Bool + ) -> Payment? { + payments.filter { payment in + guard payment.paymentType == .send, case let .lightning(_, _, _, htlcDetails, _, _, _, _) = payment.details, + htlcDetails.paymentHash.caseInsensitiveCompare(paymentHash) == .orderedSame else { return false } + return !isEarlierAttempt(paymentHash, payment.timestamp) + }.max { $0.timestamp < $1.timestamp } + } + /// Payment hashes whose every Lightning send failed, so a hold on a channel retry can be released. A failure of an /// attempt before a send Spark hasn't settled yet doesn't count: that send may still pay the invoice. nonisolated static func failedSendHashes( @@ -1903,11 +1914,13 @@ final class SparkManager: ChannelFreeLightningRail { } } - /// Releases the holds of the sends Spark's list shows failed. The list is read after the activities were recorded, - /// so a retry the user started meanwhile keeps its hold, as does one recorded or ending while the list is read. + /// Releases the holds of the sends Spark's list shows failed, first ending those it shows settled, so a later read + /// of Spark's history that fails doesn't hold them again. The list is read after the activities were recorded, so a + /// retry the user started meanwhile keeps its hold, as does one recorded or ending while the list is read. static func releaseFailedSendHolds(listPayments: () async throws -> [Payment]) async { let mark = LightningService.shared.attemptMark guard let latest = try? await listPayments() else { return } + LightningService.shared.settleListedRailSends(latest.compactMap(railPayment)) let isEarlierAttempt = { LightningService.shared.isEarlierRailAttempt(paymentHash: $0, createdAt: $1) } for paymentHash in failedSendHashes(latest, isEarlierAttempt: isEarlierAttempt) { LightningService.shared.releaseRailAttempt(paymentHash: paymentHash, since: mark) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index bdc6c56a5c..b51ba7f8f2 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -164,6 +164,9 @@ class LightningService: NodeLifecycleService { private var attemptRails: [String: LightningPaymentRail] = [:] /// Payment hashes inside a rail send, which Spark lists only once it returns. private var railSendsInFlight: Set = [] + /// Per payment hash, the latest time Spark dated a failed attempt of it, from its list or its events, so a send's + /// start is saved after it and that failure never reads as the send's own. + private var railFailureCreatedAt: [String: UInt64] = [:] /// Counts attempts recorded in this run, so a listing drops a hash just when the hash was recorded before the /// listing was read, never a retry recorded while it was read. private var attemptRecords = 0 @@ -1429,6 +1432,7 @@ class LightningService: NodeLifecycleService { railAttemptsStore.removeObject(forKey: Self.railAttemptsKey) railAttemptsStore.removeObject(forKey: Self.expiriesKey(Self.railAttemptsKey)) attemptRecordedAt[Self.railAttemptsKey] = nil + railFailureCreatedAt = [:] } } @@ -1651,15 +1655,17 @@ class LightningService: NodeLifecycleService { /// A rail send about to be submitted, or that failed after it was, until Spark settles its attempt or a sync after its /// invoice's expiry settles it. The expiry is the one kept beside the hash, and the time the one it was submitted at, - /// which a later failure of its call leaves as it is. + /// which a later failure of its call leaves as it is. That time is past the clock margin after any failed attempt + /// Spark dated for the hash so far, so that failure reads as an earlier attempt's, also after a relaunch. private func markRailSendUncertain(paymentHash: String, since mark: AttemptMark) { let hash = paymentHash.lowercased() - let startedAt = Int(max(0, now().timeIntervalSince1970)) + let now = Int64(max(0, now().timeIntervalSince1970)) eventCallbackLock.withLock { guard attemptsRecorded(since: mark.records, key: Self.railAttemptsKey).contains(hash) else { return } var uncertain = uncertainRailSendFailedAt() guard uncertain[hash] == nil else { return } - uncertain[hash] = startedAt + let afterKnownFailure = railFailureCreatedAt[hash].map { Int64(clamping: $0) + Self.railClockSkewSeconds + 1 } ?? 0 + uncertain[hash] = Int(clamping: max(now, afterKnownFailure)) railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) } } @@ -1683,8 +1689,11 @@ class LightningService: NodeLifecycleService { } /// Ends the sends Spark lists a settled attempt of: a success, or a failure of the send's own attempt. - private func settleListedRailSends(_ payments: [ChannelFreeRailPayment]) { + func settleListedRailSends(_ payments: [ChannelFreeRailPayment]) { let settled = eventCallbackLock.withLock { + for payment in payments where payment.direction == .outbound && payment.status == .failed { + noteRailFailure(paymentHash: payment.paymentHash, createdAt: payment.timestamp) + } let uncertain = uncertainRailSendFailedAt() return payments.reduce(into: [String: Int]()) { settled, payment in let hash = payment.paymentHash.lowercased() @@ -1743,6 +1752,12 @@ class LightningService: NodeLifecycleService { } } + /// Callers hold `eventCallbackLock`. + private func noteRailFailure(paymentHash: String, createdAt: UInt64) { + let hash = paymentHash.lowercased() + railFailureCreatedAt[hash] = max(railFailureCreatedAt[hash] ?? 0, createdAt) + } + /// Whether a Spark failure, of an attempt created at `createdAt`, is the failure of the invoice's send, ending its hold /// if it has one, in one step, so a retry that holds the invoice meanwhile is judged by its own hold. Not when Spark /// dated it before the send Spark hasn't settled yet, or while a send in Spark's send call wasn't submitted yet, as @@ -1750,6 +1765,9 @@ class LightningService: NodeLifecycleService { private func endRailSendByFailure(paymentHash: String, createdAt: UInt64?) -> Bool { let hash = paymentHash.lowercased() return eventCallbackLock.withLock { + if let createdAt { + noteRailFailure(paymentHash: hash, createdAt: createdAt) + } var uncertain = uncertainRailSendFailedAt() guard let startedAt = uncertain[hash] else { return !railSendsInFlight.contains(hash) } if let createdAt, !Self.isOwnRailAttempt(createdAt: createdAt, startedAt: startedAt) { diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 661c5978c3..30e47c7514 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -834,6 +834,24 @@ extension ChannelFreeRailTests { await assertRefusedAsDuplicate() } + func testALaunchThatReadsASparkSendsOwnFailureLetsTheNodeRetryWhileSparkCantList() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + service.now = { Date(timeIntervalSince1970: 1000) } + rail.balanceSats = 100_000 + rail.errorAfterSubmission = NSError(domain: "spark", code: 2) + _ = try? await service.send(bolt11: Self.invoice) + rail.errorAfterSubmission = nil + try simulateRelaunch() + + // The launch's sync reads the send's own failure, then Spark's history can't be read. + await SparkManager.releaseFailedSendHolds { [Self.sparkPayment(hash: hash, status: .failed, timestamp: 1000)] } + rail.listError = NSError(domain: "spark", code: 3) + rail.balanceSats = 0 + + await assertReachesTheNode() + } + func testASparkSendThatReturnedLetsTheNodeRetryOnceSparkListsItFailed() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: 1000) } @@ -855,14 +873,14 @@ extension ChannelFreeRailTests { kept.forEach { service.railAttemptsStore.set($0.value, forKey: $0.key) } } - private static func sparkPayment(hash: String, status: BreezSdkSpark.PaymentStatus) -> Payment { + private static func sparkPayment(hash: String, status: BreezSdkSpark.PaymentStatus, timestamp: UInt64 = 1) -> Payment { Payment( id: hash, paymentType: .send, status: status, amount: 20000, fees: 0, - timestamp: 1, + timestamp: timestamp, method: .lightning, details: .lightning( description: nil, @@ -1428,7 +1446,13 @@ extension ChannelFreeRailTests { ] rail.sendStatus = .success(.failed) + let retriedAt = Bitkit.LightningService.shared.now().addingTimeInterval(20) + Bitkit.LightningService.shared.now = { retriedAt } try await sendOverSpark() + // The retry failed too, so neither rail has a send of the invoice left that may pay. + rail.payments.append( + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: Self.sparkNow()) + ) rail.balanceSats = 0 await assertReachesTheNode() } @@ -1684,6 +1708,75 @@ extension ChannelFreeRailTests { await assertRefusedAsDuplicate() } + /// Attempt A starts at 995 and fails; Spark lists its failure before retry B starts at 1000, inside the clock margin. + private func sendARetryFiveSecondsAfterAFailedAttempt() async throws -> (hash: String, startedAt: UInt64) { + let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) + let hash = String(invoice.paymentHash()) + let startedAt = invoice.secondsSinceEpoch() + 60 + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: TimeInterval(startedAt)) } + rail.payments = [ + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: startedAt - 5), + ] + try await sendOverSpark() + rail.balanceSats = 0 + return (hash, startedAt) + } + + func testAFailureOfAnAttemptFiveSecondsBeforeARetryKeepsTheRetryHeld() async throws { + let (hash, startedAt) = try await sendARetryFiveSecondsAfterAFailedAttempt() + final class Failures: @unchecked Sendable { var count = 0 } + let failures = Failures() + Bitkit.LightningService.shared.setEventCallback { event in + if case .paymentFailed = event { + failures.count += 1 + } + } + + // Spark lists only A's failure, then A's failure event arrives late. + await assertRefusedAsDuplicate() + Bitkit.LightningService.shared.emitChannelFreeRailEvent( + .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), + paymentCreatedAt: startedAt - 5 + ) + XCTAssertEqual(failures.count, 0, "A's failure reached B's screen") + await assertRefusedAsDuplicate() + XCTAssertTrue(Bitkit.LightningService.shared.isEarlierRailAttempt(paymentHash: hash, createdAt: startedAt - 5)) + + // B's own failure ends it. + Bitkit.LightningService.shared.emitChannelFreeRailEvent( + .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), + paymentCreatedAt: startedAt + ) + await assertReachesTheNode() + } + + func testAnExpiredRetryFailsItsOwnRowWhenSparkListsOnlyTheFailureFiveSecondsBeforeIt() async throws { + let (hash, startedAt) = try await sendARetryFiveSecondsAfterAFailedAttempt() + let service = Bitkit.LightningService.shared + let previousRecord = service.railSendExpired + defer { service.railSendExpired = previousRecord } + final class Written: @unchecked Sendable { var attempt: Payment?; var calls = 0 } + let written = Written() + service.railSendExpired = { hash in + written.calls += 1 + written.attempt = SparkManager.expiredSendAttempt( + [Self.sparkPayment(hash: hash, status: .failed, timestamp: startedAt - 5)], paymentHash: hash + ) { service.isEarlierRailAttempt(paymentHash: $0, createdAt: $1) } + return true + } + let expiresAt = try Self.invoiceExpiresAt() + service.now = { Date(timeIntervalSince1970: expiresAt) } + + await service.endExpiredRailSendUncertainties() + + XCTAssertEqual(written.calls, 1) + XCTAssertNil(written.attempt, "A's details were picked for B's row instead of failing it in place") + XCTAssertNotNil( + SparkManager + .expiredSendAttempt([Self.sparkPayment(hash: hash, status: .failed, timestamp: startedAt)], paymentHash: hash) { _, _ in false } + ) + } + func testAnEarlierFailureWhileARetryEntersSparksSendCallStaysOffItsScreen() async throws { let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) let hash = String(invoice.paymentHash()) From ffd88188250652c719ceb7c308cfb048f0d962ac Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 12:48:00 +0100 Subject: [PATCH 59/64] fix: spark dates a retry past now when it can't list A retry sent while Spark's list can't be read knows no earlier failure after a relaunch, so one Spark dated within the clock margin before it could still read as its own. Its start is now saved past the margin after now, as Spark may have dated a failure of the invoice up to then. Verified: ChannelFreeRailTests, SparkRelaunchActivityTests, SparkPaymentSafetyTests and WalletActivityTests pass on an iPhone 17 Pro simulator, iOS 26.5; the new test fails without the change --- Bitkit/Services/LightningService.swift | 9 ++++++++- BitkitTests/ChannelFreeRailTests.swift | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index b51ba7f8f2..f1cb125900 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1548,7 +1548,14 @@ class LightningService: NodeLifecycleService { let isPaidOverTheNode = statuses.contains(.succeeded) if rails.contains(.channelFree) { let mark = attemptMark - if let payments = await readableRailPayments() { + let payments = await readableRailPayments() + if payments == nil { + // Spark may have dated a failure of the invoice up to now that this run hasn't seen, so a send now + // starts past it. + let seconds = UInt64(max(0, now().timeIntervalSince1970)) + eventCallbackLock.withLock { noteRailFailure(paymentHash: paymentHash, createdAt: seconds) } + } + if let payments { let live = keepRailAttempts(from: payments, since: mark) let payment = ChannelFreeRailPayment.latestOutboundAttempt(payments, paymentHash: paymentHash) if let payment { diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 30e47c7514..936d26020d 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1750,6 +1750,24 @@ extension ChannelFreeRailTests { await assertReachesTheNode() } + func testARetrySentWhileSparkCantListStaysHeldByAFailureDatedBeforeIt() async throws { + let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) + let hash = String(invoice.paymentHash()) + let startedAt = invoice.secondsSinceEpoch() + 60 + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: TimeInterval(startedAt)) } + // After a relaunch the run knows no earlier failure, and Spark's list can't be read as the retry goes out. + rail.listError = NSError(domain: "spark", code: 3) + try await sendOverSpark() + rail.listError = nil + rail.balanceSats = 0 + + Bitkit.LightningService.shared.emitChannelFreeRailEvent( + .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), + paymentCreatedAt: startedAt - 5 + ) + await assertRefusedAsDuplicate() + } + func testAnExpiredRetryFailsItsOwnRowWhenSparkListsOnlyTheFailureFiveSecondsBeforeIt() async throws { let (hash, startedAt) = try await sendARetryFiveSecondsAfterAFailedAttempt() let service = Bitkit.LightningService.shared From e87975ab754767b2c7cb8e2768f615bb79128558 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 13:24:27 +0100 Subject: [PATCH 60/64] fix: spark refuses a send it can't date A Spark send whose list can't be read saved its start past now, so its own failure read as an earlier attempt's and kept it held until its invoice expired. Such a send is now refused before anything goes out, unless Spark's operators show no send of the invoice at all after a restore. A listing also settles only the holds taken before it was read, so a send that starts meanwhile is never settled from the older list. Verified: ChannelFreeRailTests, SparkRelaunchActivityTests, SparkPaymentSafetyTests and WalletActivityTests pass on an iPhone 17 Pro simulator, iOS 26.5; both new tests fail without their change --- Bitkit/Managers/SparkManager.swift | 3 +- Bitkit/Services/LightningService.swift | 51 ++++++++++++++++---------- BitkitTests/ChannelFreeRailTests.swift | 42 ++++++++++++++------- 3 files changed, 62 insertions(+), 34 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 5b83f07eaa..17f5189371 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -1919,8 +1919,9 @@ final class SparkManager: ChannelFreeLightningRail { /// retry the user started meanwhile keeps its hold, as does one recorded or ending while the list is read. static func releaseFailedSendHolds(listPayments: () async throws -> [Payment]) async { let mark = LightningService.shared.attemptMark + let heldBefore = LightningService.shared.railSendHolds guard let latest = try? await listPayments() else { return } - LightningService.shared.settleListedRailSends(latest.compactMap(railPayment)) + LightningService.shared.settleListedRailSends(latest.compactMap(railPayment), heldBefore: heldBefore) let isEarlierAttempt = { LightningService.shared.isEarlierRailAttempt(paymentHash: $0, createdAt: $1) } for paymentHash in failedSendHashes(latest, isEarlierAttempt: isEarlierAttempt) { LightningService.shared.releaseRailAttempt(paymentHash: paymentHash, since: mark) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index f1cb125900..89f87419f6 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1102,7 +1102,8 @@ class LightningService: NodeLifecycleService { bolt11: bolt11, sats: sats, invoiceCreatedAt: invoice?.secondsSinceEpoch(), - invoiceExpiresAt: expiresAt + invoiceExpiresAt: expiresAt, + sendsOverRail: true ) { return paid } @@ -1516,7 +1517,8 @@ class LightningService: NodeLifecycleService { bolt11: String, sats: UInt64?, invoiceCreatedAt: UInt64?, - invoiceExpiresAt: Int? + invoiceExpiresAt: Int?, + sendsOverRail: Bool = false ) async throws -> PaymentHash? { guard let paymentHash else { return nil } var statuses: [PaymentStatus] = rails.contains(.channelFree) && isRailSendInFlight(paymentHash: paymentHash) ? [.pending] : [] @@ -1548,14 +1550,7 @@ class LightningService: NodeLifecycleService { let isPaidOverTheNode = statuses.contains(.succeeded) if rails.contains(.channelFree) { let mark = attemptMark - let payments = await readableRailPayments() - if payments == nil { - // Spark may have dated a failure of the invoice up to now that this run hasn't seen, so a send now - // starts past it. - let seconds = UInt64(max(0, now().timeIntervalSince1970)) - eventCallbackLock.withLock { noteRailFailure(paymentHash: paymentHash, createdAt: seconds) } - } - if let payments { + if let payments = await readableRailPayments() { let live = keepRailAttempts(from: payments, since: mark) let payment = ChannelFreeRailPayment.latestOutboundAttempt(payments, paymentHash: paymentHash) if let payment { @@ -1586,10 +1581,16 @@ class LightningService: NodeLifecycleService { } else if isPaidOverTheNode { Logger.info("Skipped Spark's restore checks of '\(paymentHash)', the node already paid it", context: "LightningService") } else { - try await refuseUnverifiedRestoredInvoice( + let hasNoSparkSend = try await refuseUnverifiedRestoredInvoice( paymentHash: paymentHash, bolt11: bolt11, sats: sats, invoiceCreatedAt: invoiceCreatedAt, invoiceExpiresAt: invoiceExpiresAt ) + // A Spark send's start must come after every failure Spark dated for the invoice, which only its list + // shows after a relaunch, so it doesn't go out unlisted, unless Spark's operators show no send of it. + if sendsOverRail, !hasNoSparkSend { + Logger.warn("Refused paying '\(paymentHash)' over Spark, Spark can't list its payments now", context: "LightningService") + throw ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description")) + } } } if statuses.contains(.succeeded) { @@ -1606,26 +1607,29 @@ class LightningService: NodeLifecycleService { /// After a restore, refuses a still-valid invoice created before it, as Spark's list can lack a send it made then, /// unless Spark's operators show no live or paid Lightning send of it and it can't have been paid by a direct Spark /// transfer, which they can't see. A send they show sent or pending, or no answer, refuses it until it expires. A - /// failed one counts as unsent, as they show it failed only once every attempt at the hash was returned. + /// failed one counts as unsent, as they show it failed only once every attempt at the hash was returned. Returns + /// whether they show no send of it at all, so there is no earlier attempt. + @discardableResult private func refuseUnverifiedRestoredInvoice( paymentHash: String, bolt11: String, sats: UInt64?, invoiceCreatedAt: UInt64?, invoiceExpiresAt: Int? - ) async throws { + ) async throws -> Bool { guard let restoredAt = sparkRestoredAt, Self.holdsRestoredInvoice( restoredAt: restoredAt, invoiceCreatedAt: invoiceCreatedAt, invoiceExpiresAt: invoiceExpiresAt, now: Int(now().timeIntervalSince1970) - ) else { return } + ) else { return false } let rail = channelFreeRail ?? channelFreePaymentHistory let sparkRuns = rail != nil ? true : await channelFreeRailSupported() - guard sparkRuns else { return } + guard sparkRuns else { return false } do { guard let rail else { throw ChannelFreeRailUnavailable() } - if let status = try await rail.lightningSendStatus(bolt11: bolt11), status != .failed { + let status = try await rail.lightningSendStatus(bolt11: bolt11) + if let status, status != .failed { Logger.warn("Refused paying '\(paymentHash)', a pre-restore invoice Spark shows as '\(status)'", context: "LightningService") throw ChannelFreeRailSendRefused.restoredInvoiceUnverified() } @@ -1634,6 +1638,7 @@ class LightningService: NodeLifecycleService { throw ChannelFreeRailSendRefused.restoredInvoiceUnverified() } Logger.info("Found no live or paid Spark operator send of pre-restore invoice '\(paymentHash)'", context: "LightningService") + return status == nil } catch let refusal as ChannelFreeRailSendRefused { throw refusal } catch { @@ -1695,8 +1700,14 @@ class LightningService: NodeLifecycleService { Int64(clamping: createdAt) >= Int64(startedAt) - railClockSkewSeconds } - /// Ends the sends Spark lists a settled attempt of: a success, or a failure of the send's own attempt. - func settleListedRailSends(_ payments: [ChannelFreeRailPayment]) { + /// The held rail sends and when each started, read before a listing so it settles only those. + var railSendHolds: [String: Int] { + eventCallbackLock.withLock { uncertainRailSendFailedAt() } + } + + /// Ends the sends Spark lists a settled attempt of: a success, or a failure of the send's own attempt. Only the holds + /// in `heldBefore`, read before the listing, as one taken since started after Spark's list was read. + func settleListedRailSends(_ payments: [ChannelFreeRailPayment], heldBefore: [String: Int]) { let settled = eventCallbackLock.withLock { for payment in payments where payment.direction == .outbound && payment.status == .failed { noteRailFailure(paymentHash: payment.paymentHash, createdAt: payment.timestamp) @@ -1705,6 +1716,7 @@ class LightningService: NodeLifecycleService { return payments.reduce(into: [String: Int]()) { settled, payment in let hash = payment.paymentHash.lowercased() guard payment.direction == .outbound, payment.status != .pending, let startedAt = uncertain[hash], + heldBefore[hash] == startedAt, payment.status == .succeeded || Self.isOwnRailAttempt(createdAt: payment.timestamp, startedAt: startedAt) else { return } settled[hash] = startedAt @@ -2508,9 +2520,10 @@ extension LightningService { // Read before the listing, so a sync that ends while it is read can't settle a send the listing predates. 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) + settleListedRailSends(payments, heldBefore: heldBefore) let stillUnsettled = eventCallbackLock.withLock { Set(uncertainRailSendFailedAt().keys) } let unsettled = unsettledBefore.filter { stillUnsettled.contains($0.paymentHash) } if let since = sparkHistoryUnseededSince, await rail.hasSynced(after: UInt64(clamping: since)) { diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 936d26020d..ce1dd1cb55 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -898,6 +898,7 @@ extension ChannelFreeRailTests { private static let ldkAttemptsKey = "ldkAttemptedPaymentHashes" private static let railAttemptsKey = "channelFreeRailAttemptedPaymentHashes" + private static let uncertainRailSendsKey = "channelFreeRailUncertainSendFailedAt" private static func nodePayment(_ hash: String, status: LDKNode.PaymentStatus) -> LDKNode.PaymentDetails { LDKNode.PaymentDetails( @@ -1750,22 +1751,35 @@ extension ChannelFreeRailTests { await assertReachesTheNode() } - func testARetrySentWhileSparkCantListStaysHeldByAFailureDatedBeforeIt() async throws { - let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) - let hash = String(invoice.paymentHash()) - let startedAt = invoice.secondsSinceEpoch() + 60 - Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: TimeInterval(startedAt)) } - // After a relaunch the run knows no earlier failure, and Spark's list can't be read as the retry goes out. + func testASparkSendIsRefusedWhileSparkCantList() async throws { + // After a relaunch only Spark's list shows the failures Spark dated for the invoice, so the send can't be dated. rail.listError = NSError(domain: "spark", code: 3) - try await sendOverSpark() - rail.listError = nil - rail.balanceSats = 0 + rail.balanceSats = 100_000 - Bitkit.LightningService.shared.emitChannelFreeRailEvent( - .paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), - paymentCreatedAt: startedAt - 5 - ) - await assertRefusedAsDuplicate() + do { + _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + XCTFail("Expected the Spark send to be refused") + } catch { + XCTAssertTrue(error is Bitkit.ChannelFreeRailSendRefused, "\(error)") + } + XCTAssertNil(rail.sentBolt11) + } + + func testASendHeldWhileSparksListIsReadIsNotSettledFromThatList() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + let startedAt = 1000 + rail.payments = [ + Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil, timestamp: UInt64(startedAt)), + ] + // A send of the invoice is held while the list is read, so the list was read before it started. + rail.onList = { + service.railAttemptsStore.set([hash: startedAt], forKey: Self.uncertainRailSendsKey) + } + + _ = try await service.channelFreeRailPayments() + + XCTAssertEqual(service.railSendHolds[hash], startedAt, "a list read before the send settled it") } func testAnExpiredRetryFailsItsOwnRowWhenSparkListsOnlyTheFailureFiveSecondsBeforeIt() async throws { From c99c29421e7f8b3c666b3eee3d50b5bd92dd014d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 21 Nov 2026 13:36:53 +0100 Subject: [PATCH 61/64] fix: spark refuses an undated restored invoice as unverified After a restore, an unsynced Spark whose operators show a pre-restore invoice's sends all failed can't date a new send after them, so it was refused with the generic payment failure. It now gets the restored invoice refusal, as on Android. Verified: ChannelFreeRailTests, SparkRelaunchActivityTests, SparkPaymentSafetyTests and WalletActivityTests pass on an iPhone 17 Pro simulator, iOS 26.5 --- Bitkit/Services/LightningService.swift | 26 ++++++++++++++++++-------- BitkitTests/ChannelFreeRailTests.swift | 11 +++++++++++ 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 89f87419f6..e588df913a 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1581,15 +1581,17 @@ class LightningService: NodeLifecycleService { } else if isPaidOverTheNode { Logger.info("Skipped Spark's restore checks of '\(paymentHash)', the node already paid it", context: "LightningService") } else { - let hasNoSparkSend = try await refuseUnverifiedRestoredInvoice( + let restoredSends = try await refuseUnverifiedRestoredInvoice( paymentHash: paymentHash, bolt11: bolt11, sats: sats, invoiceCreatedAt: invoiceCreatedAt, invoiceExpiresAt: invoiceExpiresAt ) // A Spark send's start must come after every failure Spark dated for the invoice, which only its list // shows after a relaunch, so it doesn't go out unlisted, unless Spark's operators show no send of it. - if sendsOverRail, !hasNoSparkSend { + if sendsOverRail, restoredSends != .noSend { Logger.warn("Refused paying '\(paymentHash)' over Spark, Spark can't list its payments now", context: "LightningService") - throw ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description")) + throw restoredSends == .allFailed + ? ChannelFreeRailSendRefused.restoredInvoiceUnverified() + : ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description")) } } } @@ -1608,7 +1610,7 @@ class LightningService: NodeLifecycleService { /// unless Spark's operators show no live or paid Lightning send of it and it can't have been paid by a direct Spark /// transfer, which they can't see. A send they show sent or pending, or no answer, refuses it until it expires. A /// failed one counts as unsent, as they show it failed only once every attempt at the hash was returned. Returns - /// whether they show no send of it at all, so there is no earlier attempt. + /// what they show of a pre-restore invoice's sends, nil for any other invoice. @discardableResult private func refuseUnverifiedRestoredInvoice( paymentHash: String, @@ -1616,16 +1618,16 @@ class LightningService: NodeLifecycleService { sats: UInt64?, invoiceCreatedAt: UInt64?, invoiceExpiresAt: Int? - ) async throws -> Bool { + ) async throws -> RestoredInvoiceSends? { guard let restoredAt = sparkRestoredAt, Self.holdsRestoredInvoice( restoredAt: restoredAt, invoiceCreatedAt: invoiceCreatedAt, invoiceExpiresAt: invoiceExpiresAt, now: Int(now().timeIntervalSince1970) - ) else { return false } + ) else { return nil } let rail = channelFreeRail ?? channelFreePaymentHistory let sparkRuns = rail != nil ? true : await channelFreeRailSupported() - guard sparkRuns else { return false } + guard sparkRuns else { return nil } do { guard let rail else { throw ChannelFreeRailUnavailable() } let status = try await rail.lightningSendStatus(bolt11: bolt11) @@ -1638,7 +1640,7 @@ class LightningService: NodeLifecycleService { throw ChannelFreeRailSendRefused.restoredInvoiceUnverified() } Logger.info("Found no live or paid Spark operator send of pre-restore invoice '\(paymentHash)'", context: "LightningService") - return status == nil + return status == nil ? .noSend : .allFailed } catch let refusal as ChannelFreeRailSendRefused { throw refusal } catch { @@ -1650,6 +1652,14 @@ class LightningService: NodeLifecycleService { } } + /// What Spark's operators show of a pre-restore invoice's sends that leaves it payable. + enum RestoredInvoiceSends { + /// No send of it. + case noSend + /// Sends that all failed. + case allFailed + } + /// An unknown time counts as before the restore and never expiring. static func holdsRestoredInvoice(restoredAt: Int, invoiceCreatedAt: UInt64?, invoiceExpiresAt: Int?, now: Int) -> Bool { Int(clamping: invoiceCreatedAt ?? 0) < restoredAt && invoiceExpiresAt.map { now < $0 } ?? true diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index ce1dd1cb55..33f5e7a2e2 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1501,6 +1501,17 @@ extension ChannelFreeRailTests { XCTAssertEqual(rail.sendStatusFetches, 1) } + func testAPreRestoreInvoiceTheOperatorsShowFailedIsRefusedOverAnUnsyncedSpark() async throws { + try restore(secondsAfterTheInvoice: 60) + try pinTheClockWhileTheInvoiceIsValid() + leaveSparkUnsyncedAndEmpty() + rail.balanceSats = 100_000 + // Earlier attempts exist, and Spark can't list them yet to date the send after them. + rail.sendStatus = .success(.failed) + + await assertRefusedAsUnverifiedPreRestoreInvoice() + } + func testAPreRestoreInvoiceSparkMayHavePaidByTransferIsRefusedOnBothRails() async throws { for sparkFunded in [false, true] { try await holdForTheOperators(sparkFunded: sparkFunded) From 7bfe23fc079e254f0b65929541cc54c09ab59862 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 23 Nov 2026 12:58:56 +0100 Subject: [PATCH 62/64] fix: spark retry success during a list read stays pending A retry's success event could end its hold while Spark's list was read, with the list holding only the first attempt's failure, so the invoice read as failed until the next read and Paykit could drop the paid request's proof. The list is now read again when a hold ends during the read, and a hold still ending on the last of three reads stays pending. Verified: SwiftFormat lint on the changed files; SparkRelaunchActivityTests, ChannelFreeRailTests, SparkPaymentSafetyTests and WalletActivityTests pass on an iPhone 17 Pro simulator, iOS 26.5; the new test fails with the LightningService change reverted. --- Bitkit/Services/LightningService.swift | 25 +++++++++++++++++++----- BitkitTests/ChannelFreeRailTests.swift | 27 ++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 5 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index e588df913a..8265c49690 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -2528,14 +2528,29 @@ extension LightningService { // 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. - let unsettledBefore = await unsettledUncertainRailSends() - let kept = unexpiredRailAttempts() - let heldBefore = railSendHolds - let payments = try await rail.lightningPayments() + var unsettledBefore: [ChannelFreeRailPayment] + var kept: Set + var heldBefore: [String: Int] + var payments: [ChannelFreeRailPayment] + var endedDuringRead: Set + var reads = 0 + // A hold that ended while the list was read (a success event) may have no row in it yet, so the list is + // read again; one still ending after the last read stays pending. + repeat { + unsettledBefore = await unsettledUncertainRailSends() + kept = unexpiredRailAttempts() + heldBefore = railSendHolds + payments = try await rail.lightningPayments() + reads += 1 + let heldAfter = railSendHolds + endedDuringRead = Set(heldBefore.filter { heldAfter[$0.key] != $0.value }.keys) + } while !endedDuringRead.isEmpty && reads < 3 // 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 unsettled = unsettledBefore.filter { stillUnsettled.contains($0.paymentHash) } + let unsettled = unsettledBefore.filter { + stillUnsettled.contains($0.paymentHash) || endedDuringRead.contains($0.paymentHash) + } 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() } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 33f5e7a2e2..68c752041f 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1793,6 +1793,33 @@ extension ChannelFreeRailTests { XCTAssertEqual(service.railSendHolds[hash], startedAt, "a list read before the send settled it") } + func testARetrySucceedingWhileSparksListIsReadNeverReadsAsFailed() async throws { + let (hash, startedAt) = try await sendARetryFiveSecondsAfterAFailedAttempt() + let service = Bitkit.LightningService.shared + let rail = try XCTUnwrap(rail) + final class Reads: @unchecked Sendable { var count = 0 } + let reads = Reads() + // The retry's success event ends its hold while the first read lists only A's failure; Spark lists the success + // from the next read on. + rail.onList = { + reads.count += 1 + if reads.count == 1 { + service.railAttemptsStore.set([String: Int](), forKey: Self.uncertainRailSendsKey) + } else { + rail.payments.append( + Bitkit.ChannelFreeRailPayment( + paymentHash: hash, direction: .outbound, status: .succeeded, preimage: nil, timestamp: startedAt + ) + ) + } + } + + let payments = try await service.channelFreeRailPayments().filter { $0.paymentHash == hash } + + XCTAssertEqual(reads.count, 2) + XCTAssertTrue(payments.contains { $0.status == .succeeded }, "the retry's success was read as A's failure") + } + func testAnExpiredRetryFailsItsOwnRowWhenSparkListsOnlyTheFailureFiveSecondsBeforeIt() async throws { let (hash, startedAt) = try await sendARetryFiveSecondsAfterAFailedAttempt() let service = Bitkit.LightningService.shared From 41ed0d36cdd03628157638663a2c4e7129b08dac Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 23 Nov 2026 13:49:38 +0100 Subject: [PATCH 63/64] fix: spark held send stays pending without its listed result A retry's success event could end its hold just after c9937ed's re-read check, or before Spark listed the success, so the retry still read as the earlier attempt's failure and Paykit could drop the paid request's proof. A held send now keeps its pending row unless the same list shows its result: a success, or a failure dated as its own. The re-read loop is gone. Verified: SwiftFormat lint on the changed files; SparkRelaunchActivityTests, ChannelFreeRailTests, SparkPaymentSafetyTests and WalletActivityTests pass on an iPhone 17 Pro simulator, iOS 26.5; the new test fails on 6e58693's code. --- Bitkit/Services/LightningService.swift | 37 +++++++++++++------------- BitkitTests/ChannelFreeRailTests.swift | 24 ++++------------- 2 files changed, 24 insertions(+), 37 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 8265c49690..03976e1237 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1710,6 +1710,17 @@ class LightningService: NodeLifecycleService { Int64(clamping: createdAt) >= Int64(startedAt) - railClockSkewSeconds } + private static func listsResult(_ payments: [ChannelFreeRailPayment], paymentHash: String, startedAt: Int?) -> Bool { + payments.contains { payment in + guard payment.direction == .outbound, payment.paymentHash.lowercased() == paymentHash.lowercased() else { return false } + if payment.status == .succeeded { + return true + } + guard payment.status == .failed, let startedAt else { return false } + return isOwnRailAttempt(createdAt: payment.timestamp, startedAt: startedAt) + } + } + /// The held rail sends and when each started, read before a listing so it settles only those. var railSendHolds: [String: Int] { eventCallbackLock.withLock { uncertainRailSendFailedAt() } @@ -2528,28 +2539,18 @@ extension LightningService { // 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. - var unsettledBefore: [ChannelFreeRailPayment] - var kept: Set - var heldBefore: [String: Int] - var payments: [ChannelFreeRailPayment] - var endedDuringRead: Set - var reads = 0 - // A hold that ended while the list was read (a success event) may have no row in it yet, so the list is - // read again; one still ending after the last read stays pending. - repeat { - unsettledBefore = await unsettledUncertainRailSends() - kept = unexpiredRailAttempts() - heldBefore = railSendHolds - payments = try await rail.lightningPayments() - reads += 1 - let heldAfter = railSendHolds - endedDuringRead = Set(heldBefore.filter { heldAfter[$0.key] != $0.value }.keys) - } while !endedDuringRead.isEmpty && reads < 3 + 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) } + // 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) || endedDuringRead.contains($0.paymentHash) + stillUnsettled.contains($0.paymentHash) + || !Self.listsResult(payments, paymentHash: $0.paymentHash, startedAt: heldBefore[$0.paymentHash]) } 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 68c752041f..8496709b42 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1793,31 +1793,17 @@ extension ChannelFreeRailTests { XCTAssertEqual(service.railSendHolds[hash], startedAt, "a list read before the send settled it") } - func testARetrySucceedingWhileSparksListIsReadNeverReadsAsFailed() async throws { - let (hash, startedAt) = try await sendARetryFiveSecondsAfterAFailedAttempt() + func testARetryWhoseHoldEndsDuringTheReadWithoutItsResultListedStaysPending() async throws { + let (hash, _) = try await sendARetryFiveSecondsAfterAFailedAttempt() let service = Bitkit.LightningService.shared - let rail = try XCTUnwrap(rail) - final class Reads: @unchecked Sendable { var count = 0 } - let reads = Reads() - // The retry's success event ends its hold while the first read lists only A's failure; Spark lists the success - // from the next read on. + // The retry's success event ends its hold during the read, and Spark lists only A's failure on every read. rail.onList = { - reads.count += 1 - if reads.count == 1 { - service.railAttemptsStore.set([String: Int](), forKey: Self.uncertainRailSendsKey) - } else { - rail.payments.append( - Bitkit.ChannelFreeRailPayment( - paymentHash: hash, direction: .outbound, status: .succeeded, preimage: nil, timestamp: startedAt - ) - ) - } + service.railAttemptsStore.set([String: Int](), forKey: Self.uncertainRailSendsKey) } let payments = try await service.channelFreeRailPayments().filter { $0.paymentHash == hash } - XCTAssertEqual(reads.count, 2) - XCTAssertTrue(payments.contains { $0.status == .succeeded }, "the retry's success was read as A's failure") + XCTAssertTrue(payments.contains { $0.status == .pending }, "the retry read as A's failure") } func testAnExpiredRetryFailsItsOwnRowWhenSparkListsOnlyTheFailureFiveSecondsBeforeIt() async throws { From befad53e8053321685931fdb9608a08289d8b9ed Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 24 Nov 2026 15:32:24 +0100 Subject: [PATCH 64/64] fix: drop duplicate spark exit locale keys The rebase onto master left three spark exit keys twice in every locale, the extra copy with older wording. Keep master's line. Verified: no duplicate keys in any Localizable.strings; node scripts/validate-translations.js passes. --- Bitkit/Resources/Localization/ar.lproj/Localizable.strings | 3 --- Bitkit/Resources/Localization/ca.lproj/Localizable.strings | 3 --- Bitkit/Resources/Localization/cs.lproj/Localizable.strings | 3 --- Bitkit/Resources/Localization/de.lproj/Localizable.strings | 3 --- Bitkit/Resources/Localization/el.lproj/Localizable.strings | 3 --- Bitkit/Resources/Localization/es-419.lproj/Localizable.strings | 3 --- Bitkit/Resources/Localization/es.lproj/Localizable.strings | 3 --- Bitkit/Resources/Localization/fr.lproj/Localizable.strings | 3 --- Bitkit/Resources/Localization/it.lproj/Localizable.strings | 3 --- Bitkit/Resources/Localization/nl.lproj/Localizable.strings | 3 --- Bitkit/Resources/Localization/pl.lproj/Localizable.strings | 3 --- Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings | 3 --- Bitkit/Resources/Localization/pt.lproj/Localizable.strings | 3 --- Bitkit/Resources/Localization/ru.lproj/Localizable.strings | 3 --- 14 files changed, 42 deletions(-) diff --git a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings index 818bf8f82b..e93f8bcd7e 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -382,8 +382,6 @@ "lightning__spark_exit__leftover_swept" = "أُرسل {amount} من رسوم الطوارئ غير المستخدمة إلى المدخرات."; "lightning__spark_exit__leftover_sending" = "جارٍ إرسال {amount} من رسوم الطوارئ غير المستخدمة إلى المدخرات."; "lightning__spark_exit__leftover_dust" = "{amount} من رسوم الطوارئ غير المستخدمة أصغر من أن يُرسل ويبقى في {address}، مسار الاشتقاق {path}."; -"lightning__spark_exit__earlier_addresses" = "عناوين الخروج السابقة"; -"lightning__spark_exit__earlier_addresses_text" = "استخدمت عمليات الخروج الطارئ السابقة عناوين التمويل هذه. تبقى العملات المتروكة في أحدها ملكًا لك: أنفقها باستخدام عبارة الاسترداد ومسار الاشتقاق."; "lightning__spark_exit__earlier_path" = "مسار الاشتقاق"; "lightning__spark_exit__lost_leaves" = "طالب مالك سابق لهذه الأموال بمبلغ {amount} على السلسلة ولا يمكن استرداده."; "lightning__spark_exit__notification_lost" = "لا يمكن استرداد {amount} من تحويلك القسري. افتح Bitkit لمعرفة السبب."; @@ -407,7 +405,6 @@ "lightning__spark_exit__rebuilt_from_chain" = "تعذّر على Bitkit قراءة التقدم المحفوظ لهذا التحويل، لذا يعيد بناءه من السلسلة."; "lightning__spark_exit__leftover_rejected" = "تعذّر إرسال {amount} من رسوم الطوارئ غير المستخدمة ويبقى في {address}، مسار الاشتقاق {path}."; "lightning__spark_exit__notification_not_moving" = "التحويل القسري لا يتقدم. افتح Bitkit لمعرفة السبب."; -"lightning__spark_exit__note_notifications_button" = "تفعيل الإشعارات"; "lightning__spark_exit__waiting_operators" = "{amount} الذي نقله مشغّلو Spark إلى السلسلة ينتظر أن يحرروه. يطلب Bitkit ذلك مجددًا لمدة تصل إلى أسبوع."; "lightning__spark_exit__fee_rose" = "ارتفعت رسوم الشبكة فوق رسوم هذا التحويل. قد يتباطأ."; "lightning__spark_exit__fee_bump_button" = "ادفع رسومًا أعلى"; diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings index c4a6f4d6e7..6a20f58a6c 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -419,8 +419,6 @@ "lightning__spark_exit__leftover_swept" = "{amount} de comissions d'emergència no utilitzades s'han enviat als estalvis."; "lightning__spark_exit__leftover_sending" = "S'estan enviant {amount} de comissions d'emergència no utilitzades als estalvis."; "lightning__spark_exit__leftover_dust" = "{amount} de comissions d'emergència no utilitzades són massa petits per enviar-se i es queden a {address}, camí de derivació {path}."; -"lightning__spark_exit__earlier_addresses" = "Adreces de sortida anteriors"; -"lightning__spark_exit__earlier_addresses_text" = "Les sortides d'emergència anteriors van fer servir aquestes adreces de finançament. Les monedes que hi quedin continuen sent teves: gasta-les amb la teva frase de recuperació i el camí de derivació."; "lightning__spark_exit__earlier_path" = "Camí de derivació"; "lightning__spark_exit__lost_leaves" = "Un propietari anterior d'aquests fons ha reclamat {amount} on-chain i no es pot recuperar."; "lightning__spark_exit__notification_lost" = "{amount} de la teva transferència forçosa no es pot recuperar. Obre Bitkit per veure'n el motiu."; @@ -444,7 +442,6 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit no ha pogut llegir el progrés desat d'aquesta transferència, així que el reconstrueix a partir de la cadena."; "lightning__spark_exit__leftover_rejected" = "{amount} de comissions d'emergència no utilitzades no s'han pogut enviar i es queden a {address}, camí de derivació {path}."; "lightning__spark_exit__notification_not_moving" = "La teva transferència forçosa no avança. Obre Bitkit per saber per què."; -"lightning__spark_exit__note_notifications_button" = "Activa les notificacions"; "lightning__spark_exit__waiting_operators" = "{amount} que els operadors de Spark han mogut on-chain espera que l'alliberin. Bitkit ho torna a demanar durant una setmana com a màxim."; "lightning__spark_exit__fee_rose" = "Les comissions de xarxa han superat la comissió d'aquesta transferència. Pot alentir-se."; "lightning__spark_exit__fee_bump_button" = "Paga una comissió més alta"; diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings index 8cc355d113..1df2176300 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -434,8 +434,6 @@ "lightning__spark_exit__leftover_swept" = "{amount} nepoužitých nouzových poplatků bylo odesláno do úspor."; "lightning__spark_exit__leftover_sending" = "Odesílání {amount} nepoužitých nouzových poplatků do úspor."; "lightning__spark_exit__leftover_dust" = "{amount} nepoužitých nouzových poplatků je příliš málo na odeslání a zůstává na adrese {address}, derivační cesta {path}."; -"lightning__spark_exit__earlier_addresses" = "Dřívější adresy pro výstup"; -"lightning__spark_exit__earlier_addresses_text" = "Dřívější nouzové výstupy používaly tyto adresy pro krytí poplatků. Mince, které na některé zůstaly, jsou stále vaše: utratíte je pomocí obnovovací fráze a derivační cesty."; "lightning__spark_exit__earlier_path" = "Derivační cesta"; "lightning__spark_exit__lost_leaves" = "{amount} si on-chain nárokoval dřívější vlastník těchto prostředků a nelze to získat zpět."; "lightning__spark_exit__notification_lost" = "{amount} z vašeho vynuceného převodu nelze obnovit. Otevřete Bitkit a zjistěte proč."; @@ -459,7 +457,6 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit nemohl přečíst uložený průběh tohoto převodu, proto ho znovu sestaví z blockchainu."; "lightning__spark_exit__leftover_rejected" = "{amount} nepoužitých nouzových poplatků se nepodařilo odeslat a zůstává na adrese {address}, derivační cesta {path}."; "lightning__spark_exit__notification_not_moving" = "Váš vynucený převod nepostupuje. Otevřete Bitkit a zjistěte proč."; -"lightning__spark_exit__note_notifications_button" = "Zapnout oznámení"; "lightning__spark_exit__waiting_operators" = "{amount}, které operátoři Spark přesunuli na blockchain, čeká, až je uvolní. Bitkit se bude ptát znovu až týden."; "lightning__spark_exit__fee_rose" = "Síťové poplatky vzrostly nad poplatek tohoto převodu. Může se zpomalit."; "lightning__spark_exit__fee_bump_button" = "Zaplatit vyšší poplatek"; diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings index f7a3dba3e0..2a86b8eec5 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -432,8 +432,6 @@ "lightning__spark_exit__leftover_swept" = "{amount} nicht verbrauchte Notfallgebühren wurden an dein Sparkonto gesendet."; "lightning__spark_exit__leftover_sending" = "{amount} nicht verbrauchte Notfallgebühren werden an dein Sparkonto gesendet."; "lightning__spark_exit__leftover_dust" = "{amount} nicht verbrauchte Notfallgebühren sind zu klein zum Senden und bleiben bei {address}, Ableitungspfad {path}."; -"lightning__spark_exit__earlier_addresses" = "Frühere Ausstiegsadressen"; -"lightning__spark_exit__earlier_addresses_text" = "Frühere Notausstiege nutzten diese Finanzierungsadressen. Coins, die auf einer zurückbleiben, gehören weiterhin dir: Gib sie mit deiner Wiederherstellungsphrase und ihrem Ableitungspfad aus."; "lightning__spark_exit__earlier_path" = "Ableitungspfad"; "lightning__spark_exit__lost_leaves" = "{amount} wurden von einem früheren Besitzer dieser Mittel on-chain beansprucht und können nicht wiederhergestellt werden."; "lightning__spark_exit__notification_lost" = "{amount} deiner forcierten Übertragung können nicht zurückgeholt werden. Öffne Bitkit, um den Grund zu sehen."; @@ -457,7 +455,6 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit konnte den gespeicherten Fortschritt dieser Übertragung nicht lesen und stellt ihn daher aus der Chain wieder her."; "lightning__spark_exit__leftover_rejected" = "{amount} nicht verbrauchte Notfallgebühren konnten nicht gesendet werden und bleiben bei {address}, Ableitungspfad {path}."; "lightning__spark_exit__notification_not_moving" = "Deine forcierte Übertragung kommt nicht voran. Öffne Bitkit, um den Grund zu sehen."; -"lightning__spark_exit__note_notifications_button" = "Benachrichtigungen aktivieren"; "lightning__spark_exit__waiting_operators" = "{amount}, die die Spark-Betreiber on-chain verschoben haben, warten darauf, dass sie sie freigeben. Bitkit fragt bis zu einer Woche lang erneut nach."; "lightning__spark_exit__fee_rose" = "Die Netzgebühren sind über die Gebühr dieser Übertragung gestiegen. Sie kann sich verlangsamen."; "lightning__spark_exit__fee_bump_button" = "Höhere Gebühr zahlen"; diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings index 93c7209070..ef4a376a81 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -406,8 +406,6 @@ "lightning__spark_exit__leftover_swept" = "Τα {amount} αχρησιμοποίητων έκτακτων τελών στάλθηκαν στις αποταμιεύσεις."; "lightning__spark_exit__leftover_sending" = "Αποστολή {amount} αχρησιμοποίητων έκτακτων τελών στις αποταμιεύσεις."; "lightning__spark_exit__leftover_dust" = "Τα {amount} αχρησιμοποίητων έκτακτων τελών είναι πολύ μικρά για αποστολή και παραμένουν στη διεύθυνση {address}, διαδρομή παραγωγής {path}."; -"lightning__spark_exit__earlier_addresses" = "Προηγούμενες διευθύνσεις εξόδου"; -"lightning__spark_exit__earlier_addresses_text" = "Οι προηγούμενες έξοδοι έκτακτης ανάγκης χρησιμοποίησαν αυτές τις διευθύνσεις χρηματοδότησης. Τα νομίσματα που έμειναν σε μία παραμένουν δικά σας: ξοδέψτε τα με τη φράση ανάκτησης και τη διαδρομή παραγωγής."; "lightning__spark_exit__earlier_path" = "Διαδρομή παραγωγής"; "lightning__spark_exit__lost_leaves" = "{amount} διεκδικήθηκε on-chain από προηγούμενο κάτοχο αυτών των κεφαλαίων και δεν μπορεί να ανακτηθεί."; "lightning__spark_exit__notification_lost" = "Τα {amount} της αναγκαστικής μεταφοράς σας δεν μπορούν να ανακτηθούν. Ανοίξτε το Bitkit για να δείτε γιατί."; @@ -431,7 +429,6 @@ "lightning__spark_exit__rebuilt_from_chain" = "Το Bitkit δεν μπόρεσε να διαβάσει την αποθηκευμένη πρόοδο αυτής της μεταφοράς, γι' αυτό την ανακατασκευάζει από την αλυσίδα."; "lightning__spark_exit__leftover_rejected" = "Τα {amount} αχρησιμοποίητων έκτακτων τελών δεν μπόρεσαν να σταλούν και παραμένουν στη διεύθυνση {address}, διαδρομή παραγωγής {path}."; "lightning__spark_exit__notification_not_moving" = "Η αναγκαστική μεταφορά σας δεν προχωρά. Ανοίξτε το Bitkit για να δείτε γιατί."; -"lightning__spark_exit__note_notifications_button" = "Ενεργοποίηση ειδοποιήσεων"; "lightning__spark_exit__waiting_operators" = "{amount} που μετέφεραν on-chain οι διαχειριστές του Spark περιμένει να το αποδεσμεύσουν. Το Bitkit ζητά ξανά για έως μία εβδομάδα."; "lightning__spark_exit__fee_rose" = "Τα τέλη δικτύου ανέβηκαν πάνω από το τέλος αυτής της μεταφοράς. Μπορεί να καθυστερήσει."; "lightning__spark_exit__fee_bump_button" = "Πληρωμή υψηλότερου τέλους"; diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings index 90b75e2500..ca649c6214 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -435,8 +435,6 @@ "lightning__spark_exit__leftover_swept" = "{amount} de comisiones de emergencia sin usar se envió a tus ahorros."; "lightning__spark_exit__leftover_sending" = "Enviando {amount} de comisiones de emergencia sin usar a tus ahorros."; "lightning__spark_exit__leftover_dust" = "{amount} de comisiones de emergencia sin usar es demasiado pequeño para enviarse y se queda en {address}, ruta de derivación {path}."; -"lightning__spark_exit__earlier_addresses" = "Direcciones de salida anteriores"; -"lightning__spark_exit__earlier_addresses_text" = "Las salidas de emergencia anteriores usaron estas direcciones de fondeo. Las monedas que queden en una siguen siendo tuyas: gástalas con tu frase de recuperación y su ruta de derivación."; "lightning__spark_exit__earlier_path" = "Ruta de derivación"; "lightning__spark_exit__lost_leaves" = "Un propietario anterior de estos fondos reclamó {amount} on-chain y no se puede recuperar."; "lightning__spark_exit__notification_lost" = "{amount} de tu transferencia forzada no se puede recuperar. Abre Bitkit para ver por qué."; @@ -460,7 +458,6 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit no pudo leer el progreso guardado de esta transferencia, así que lo reconstruye a partir de la cadena."; "lightning__spark_exit__leftover_rejected" = "{amount} de comisiones de emergencia sin usar no se pudo enviar y se queda en {address}, ruta de derivación {path}."; "lightning__spark_exit__notification_not_moving" = "Tu transferencia forzada no avanza. Abre Bitkit para ver por qué."; -"lightning__spark_exit__note_notifications_button" = "Activar notificaciones"; "lightning__spark_exit__waiting_operators" = "{amount} que los operadores de Spark movieron on-chain espera a que lo liberen. Bitkit vuelve a pedirlo durante hasta una semana."; "lightning__spark_exit__fee_rose" = "Las comisiones de la red superaron la comisión de esta transferencia. Puede ralentizarse."; "lightning__spark_exit__fee_bump_button" = "Pagar una comisión más alta"; diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings index 094a104dee..6f3a20cf9f 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -420,8 +420,6 @@ "lightning__spark_exit__leftover_swept" = "Se han enviado a tus ahorros {amount} de comisiones de emergencia sin usar."; "lightning__spark_exit__leftover_sending" = "Enviando {amount} de comisiones de emergencia sin usar a tus ahorros."; "lightning__spark_exit__leftover_dust" = "{amount} de comisiones de emergencia sin usar es demasiado poco para enviarse y se queda en {address}, ruta de derivación {path}."; -"lightning__spark_exit__earlier_addresses" = "Direcciones de salida anteriores"; -"lightning__spark_exit__earlier_addresses_text" = "Las salidas de emergencia anteriores usaron estas direcciones de fondeo. Las monedas que queden en una siguen siendo tuyas: gástalas con tu frase de recuperación y su ruta de derivación."; "lightning__spark_exit__earlier_path" = "Ruta de derivación"; "lightning__spark_exit__lost_leaves" = "Un propietario anterior de estos fondos reclamó {amount} on-chain y no se puede recuperar."; "lightning__spark_exit__notification_lost" = "{amount} de tu transferencia forzada no se puede recuperar. Abre Bitkit para ver el motivo."; @@ -445,7 +443,6 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit no pudo leer el progreso guardado de esta transferencia, así que lo reconstruye a partir de la cadena."; "lightning__spark_exit__leftover_rejected" = "{amount} de comisiones de emergencia sin usar no se pudo enviar y se queda en {address}, ruta de derivación {path}."; "lightning__spark_exit__notification_not_moving" = "Tu transferencia forzada no avanza. Abre Bitkit para ver por qué."; -"lightning__spark_exit__note_notifications_button" = "Activar notificaciones"; "lightning__spark_exit__waiting_operators" = "{amount} que los operadores de Spark movieron on-chain espera a que lo liberen. Bitkit vuelve a pedirlo durante hasta una semana."; "lightning__spark_exit__fee_rose" = "Las comisiones de la red superaron la comisión de esta transferencia. Puede ralentizarse."; "lightning__spark_exit__fee_bump_button" = "Pagar una comisión más alta"; diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings index c4fab2bfa5..6c2f99f64e 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -435,8 +435,6 @@ "lightning__spark_exit__leftover_swept" = "{amount} de frais d'urgence inutilisés ont été envoyés vers l'épargne."; "lightning__spark_exit__leftover_sending" = "Envoi de {amount} de frais d'urgence inutilisés vers l'épargne."; "lightning__spark_exit__leftover_dust" = "{amount} de frais d'urgence inutilisés est trop faible pour être envoyé et reste à {address}, chemin de dérivation {path}."; -"lightning__spark_exit__earlier_addresses" = "Anciennes adresses de sortie"; -"lightning__spark_exit__earlier_addresses_text" = "Les sorties d'urgence précédentes ont utilisé ces adresses de financement. Les pièces restées sur l'une d'elles vous appartiennent toujours : dépensez-les avec votre phrase de récupération et son chemin de dérivation."; "lightning__spark_exit__earlier_path" = "Chemin de dérivation"; "lightning__spark_exit__lost_leaves" = "{amount} a été réclamé on-chain par un ancien propriétaire de ces fonds et ne peut pas être récupéré."; "lightning__spark_exit__notification_lost" = "{amount} de votre transfert forcé ne peut pas être récupéré. Ouvrez Bitkit pour savoir pourquoi."; @@ -460,7 +458,6 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit n'a pas pu lire la progression enregistrée de ce transfert, il la reconstruit donc à partir de la chaîne."; "lightning__spark_exit__leftover_rejected" = "{amount} de frais d'urgence inutilisés n'a pas pu être envoyé et reste à {address}, chemin de dérivation {path}."; "lightning__spark_exit__notification_not_moving" = "Votre transfert forcé n'avance pas. Ouvrez Bitkit pour savoir pourquoi."; -"lightning__spark_exit__note_notifications_button" = "Activer les notifications"; "lightning__spark_exit__waiting_operators" = "{amount} que les opérateurs Spark ont déplacé on-chain attend qu'ils le libèrent. Bitkit redemande pendant une semaine au maximum."; "lightning__spark_exit__fee_rose" = "Les frais de réseau ont dépassé ceux de ce transfert. Il peut ralentir."; "lightning__spark_exit__fee_bump_button" = "Payer des frais plus élevés"; diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings index baca29d6c2..554de26e65 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -429,8 +429,6 @@ "lightning__spark_exit__leftover_swept" = "{amount} di commissioni di emergenza non utilizzate è stato inviato ai risparmi."; "lightning__spark_exit__leftover_sending" = "Invio di {amount} di commissioni di emergenza non utilizzate ai risparmi."; "lightning__spark_exit__leftover_dust" = "{amount} di commissioni di emergenza non utilizzate è troppo poco per essere inviato e resta su {address}, percorso di derivazione {path}."; -"lightning__spark_exit__earlier_addresses" = "Indirizzi di uscita precedenti"; -"lightning__spark_exit__earlier_addresses_text" = "Le precedenti uscite di emergenza hanno usato questi indirizzi di finanziamento. Le monete rimaste su uno restano tue: spendile con la tua recovery phrase e il suo percorso di derivazione."; "lightning__spark_exit__earlier_path" = "Percorso di derivazione"; "lightning__spark_exit__lost_leaves" = "{amount} è stato riscattato on-chain da un precedente proprietario di questi fondi e non può essere recuperato."; "lightning__spark_exit__notification_lost" = "{amount} del tuo trasferimento forzato non può essere recuperato. Apri Bitkit per scoprire perché."; @@ -454,7 +452,6 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit non è riuscito a leggere l'avanzamento salvato di questo trasferimento, quindi lo ricostruisce dalla blockchain."; "lightning__spark_exit__leftover_rejected" = "{amount} di commissioni di emergenza non utilizzate non ha potuto essere inviato e resta su {address}, percorso di derivazione {path}."; "lightning__spark_exit__notification_not_moving" = "Il tuo trasferimento forzato non avanza. Apri Bitkit per scoprire perché."; -"lightning__spark_exit__note_notifications_button" = "Attiva le notifiche"; "lightning__spark_exit__waiting_operators" = "{amount} che gli operatori Spark hanno spostato on-chain attende che lo rilascino. Bitkit lo richiede per un massimo di una settimana."; "lightning__spark_exit__fee_rose" = "Le commissioni di rete hanno superato quella di questo trasferimento. Potrebbe rallentare."; "lightning__spark_exit__fee_bump_button" = "Paga una commissione più alta"; diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings index 22d683ee01..63964e4301 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -432,8 +432,6 @@ "lightning__spark_exit__leftover_swept" = "{amount} aan ongebruikte noodkosten is naar spaargeld gestuurd."; "lightning__spark_exit__leftover_sending" = "{amount} aan ongebruikte noodkosten wordt naar spaargeld gestuurd."; "lightning__spark_exit__leftover_dust" = "{amount} aan ongebruikte noodkosten is te klein om te versturen en blijft op {address}, afleidingspad {path}."; -"lightning__spark_exit__earlier_addresses" = "Eerdere exitadressen"; -"lightning__spark_exit__earlier_addresses_text" = "Eerdere noodexits gebruikten deze financieringsadressen. Coins die op een adres zijn achtergebleven, blijven van jou: besteed ze met je herstelwoorden en het afleidingspad."; "lightning__spark_exit__earlier_path" = "Afleidingspad"; "lightning__spark_exit__lost_leaves" = "{amount} is on-chain geclaimd door een eerdere eigenaar van dit geld en kan niet worden teruggehaald."; "lightning__spark_exit__notification_lost" = "{amount} van uw geforceerde overboeking kan niet worden hersteld. Open Bitkit om te zien waarom."; @@ -457,7 +455,6 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit kon de opgeslagen voortgang van deze overboeking niet lezen en bouwt die daarom opnieuw op vanaf de chain."; "lightning__spark_exit__leftover_rejected" = "{amount} aan ongebruikte noodkosten kon niet worden verstuurd en blijft op {address}, afleidingspad {path}."; "lightning__spark_exit__notification_not_moving" = "Uw geforceerde overboeking komt niet verder. Open Bitkit om te zien waarom."; -"lightning__spark_exit__note_notifications_button" = "Meldingen aanzetten"; "lightning__spark_exit__waiting_operators" = "{amount} dat de Spark-operators on-chain hebben gezet, wacht tot zij het vrijgeven. Bitkit vraagt het tot een week lang opnieuw."; "lightning__spark_exit__fee_rose" = "De netwerkkosten zijn hoger geworden dan de kosten van deze overboeking. Het kan vertragen."; "lightning__spark_exit__fee_bump_button" = "Hogere vergoeding betalen"; diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings index d71bffd76b..a20787f268 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -434,8 +434,6 @@ "lightning__spark_exit__leftover_swept" = "{amount} niewykorzystanych opłat awaryjnych zostało wysłane do oszczędności."; "lightning__spark_exit__leftover_sending" = "Wysyłanie {amount} niewykorzystanych opłat awaryjnych do oszczędności."; "lightning__spark_exit__leftover_dust" = "{amount} niewykorzystanych opłat awaryjnych to za mało, by je wysłać, i pozostaje pod adresem {address}, ścieżka derywacji {path}."; -"lightning__spark_exit__earlier_addresses" = "Wcześniejsze adresy wyjścia"; -"lightning__spark_exit__earlier_addresses_text" = "Wcześniejsze wyjścia awaryjne korzystały z tych adresów finansowania. Środki pozostawione na jednym z nich nadal należą do Ciebie: wydaj je za pomocą frazy odzyskiwania i ścieżki derywacji."; "lightning__spark_exit__earlier_path" = "Ścieżka derywacji"; "lightning__spark_exit__lost_leaves" = "{amount} zostało przejęte on-chain przez poprzedniego właściciela tych środków i nie można go odzyskać."; "lightning__spark_exit__notification_lost" = "{amount} z Twojego wymuszonego transferu nie można odzyskać. Otwórz Bitkit, aby zobaczyć powód."; @@ -459,7 +457,6 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit nie mógł odczytać zapisanego postępu tego transferu, więc odbudowuje go z łańcucha."; "lightning__spark_exit__leftover_rejected" = "{amount} niewykorzystanych opłat awaryjnych nie udało się wysłać i pozostaje pod adresem {address}, ścieżka derywacji {path}."; "lightning__spark_exit__notification_not_moving" = "Twój wymuszony transfer nie postępuje. Otwórz Bitkit, aby sprawdzić dlaczego."; -"lightning__spark_exit__note_notifications_button" = "Włącz powiadomienia"; "lightning__spark_exit__waiting_operators" = "{amount} przeniesione on-chain przez operatorów Spark czeka, aż je wydadzą. Bitkit będzie pytać ponownie przez maksymalnie tydzień."; "lightning__spark_exit__fee_rose" = "Opłaty sieciowe wzrosły powyżej opłaty tego transferu. Może on zwolnić."; "lightning__spark_exit__fee_bump_button" = "Zapłać wyższą opłatę"; diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings index ea9a7c7f02..2bab732b1f 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -434,8 +434,6 @@ "lightning__spark_exit__leftover_swept" = "{amount} de taxas de emergência não utilizadas foi enviado para a poupança."; "lightning__spark_exit__leftover_sending" = "Enviando {amount} de taxas de emergência não utilizadas para a poupança."; "lightning__spark_exit__leftover_dust" = "{amount} de taxas de emergência não utilizadas é pequeno demais para enviar e fica em {address}, caminho de derivação {path}."; -"lightning__spark_exit__earlier_addresses" = "Endereços de saída anteriores"; -"lightning__spark_exit__earlier_addresses_text" = "As saídas de emergência anteriores usaram estes endereços de financiamento. As moedas deixadas em um deles continuam sendo suas: gaste-as com sua frase de recuperação e o caminho de derivação dela."; "lightning__spark_exit__earlier_path" = "Caminho de derivação"; "lightning__spark_exit__lost_leaves" = "{amount} foi resgatado on-chain por um antigo dono desses fundos e não pode ser recuperado."; "lightning__spark_exit__notification_lost" = "{amount} da sua transferência forçada não pode ser recuperado. Abra a Bitkit para ver o motivo."; @@ -459,7 +457,6 @@ "lightning__spark_exit__rebuilt_from_chain" = "A Bitkit não conseguiu ler o progresso salvo desta transferência, então o reconstrói a partir da blockchain."; "lightning__spark_exit__leftover_rejected" = "{amount} de taxas de emergência não utilizadas não pôde ser enviado e fica em {address}, caminho de derivação {path}."; "lightning__spark_exit__notification_not_moving" = "Sua transferência forçada não está avançando. Abra a Bitkit para ver o motivo."; -"lightning__spark_exit__note_notifications_button" = "Ativar notificações"; "lightning__spark_exit__waiting_operators" = "{amount} que os operadores da Spark moveram on-chain aguarda que eles o liberem. A Bitkit pede novamente por até uma semana."; "lightning__spark_exit__fee_rose" = "As taxas de rede subiram acima da taxa desta transferência. Ela pode ficar mais lenta."; "lightning__spark_exit__fee_bump_button" = "Pagar uma taxa maior"; diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings index dd0c3e22de..eaff83932f 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -434,8 +434,6 @@ "lightning__spark_exit__leftover_swept" = "{amount} de taxas de emergência não utilizadas foi enviado para a poupança."; "lightning__spark_exit__leftover_sending" = "A enviar {amount} de taxas de emergência não utilizadas para a poupança."; "lightning__spark_exit__leftover_dust" = "{amount} de taxas de emergência não utilizadas é demasiado pequeno para enviar e fica em {address}, caminho de derivação {path}."; -"lightning__spark_exit__earlier_addresses" = "Endereços de saída anteriores"; -"lightning__spark_exit__earlier_addresses_text" = "As saídas de emergência anteriores usaram estes endereços de financiamento. As moedas deixadas num deles continuam a ser suas: gaste-as com a sua frase de recuperação e o respetivo caminho de derivação."; "lightning__spark_exit__earlier_path" = "Caminho de derivação"; "lightning__spark_exit__lost_leaves" = "{amount} foi reclamado on-chain por um antigo dono destes fundos e não pode ser recuperado."; "lightning__spark_exit__notification_lost" = "{amount} da sua transferência forçada não pode ser recuperado. Abra a Bitkit para ver porquê."; @@ -459,7 +457,6 @@ "lightning__spark_exit__rebuilt_from_chain" = "A Bitkit não conseguiu ler o progresso guardado desta transferência, por isso reconstrói-o a partir da blockchain."; "lightning__spark_exit__leftover_rejected" = "{amount} de taxas de emergência não utilizadas não pôde ser enviado e fica em {address}, caminho de derivação {path}."; "lightning__spark_exit__notification_not_moving" = "A sua transferência forçada não está a avançar. Abra a Bitkit para ver porquê."; -"lightning__spark_exit__note_notifications_button" = "Ativar notificações"; "lightning__spark_exit__waiting_operators" = "{amount} que os operadores da Spark moveram on-chain aguarda que o libertem. A Bitkit volta a pedir durante até uma semana."; "lightning__spark_exit__fee_rose" = "As taxas de rede subiram acima da taxa desta transferência. Pode ficar mais lenta."; "lightning__spark_exit__fee_bump_button" = "Pagar uma taxa mais alta"; diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings index f5e2d7af09..5ba62a1073 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -430,8 +430,6 @@ "lightning__spark_exit__leftover_swept" = "Неиспользованные экстренные комиссии ({amount}) отправлены в сбережения."; "lightning__spark_exit__leftover_sending" = "Отправка неиспользованных экстренных комиссий ({amount}) в сбережения."; "lightning__spark_exit__leftover_dust" = "Неиспользованные экстренные комиссии в размере {amount} слишком малы для отправки и остаются на {address}, путь деривации {path}."; -"lightning__spark_exit__earlier_addresses" = "Прежние адреса выхода"; -"lightning__spark_exit__earlier_addresses_text" = "Прежние экстренные выходы использовали эти адреса пополнения. Монеты, оставшиеся на одном из них, по-прежнему ваши: потратьте их с помощью фразы восстановления и её пути деривации."; "lightning__spark_exit__earlier_path" = "Путь деривации"; "lightning__spark_exit__lost_leaves" = "{amount} забрал ончейн один из прежних владельцев этих средств, их нельзя вернуть."; "lightning__spark_exit__notification_lost" = "{amount} из вашего принудительного перевода нельзя вернуть. Откройте Bitkit, чтобы узнать причину."; @@ -455,7 +453,6 @@ "lightning__spark_exit__rebuilt_from_chain" = "Bitkit не смог прочитать сохранённый прогресс этого перевода, поэтому восстанавливает его по блокчейну."; "lightning__spark_exit__leftover_rejected" = "Неиспользованные экстренные комиссии в размере {amount} не удалось отправить, они остаются на {address}, путь деривации {path}."; "lightning__spark_exit__notification_not_moving" = "Ваш принудительный перевод не продвигается. Откройте Bitkit, чтобы узнать причину."; -"lightning__spark_exit__note_notifications_button" = "Включить уведомления"; "lightning__spark_exit__waiting_operators" = "{amount}, которые операторы Spark перевели ончейн, ждут, пока операторы их выдадут. Bitkit будет запрашивать снова в течение недели."; "lightning__spark_exit__fee_rose" = "Сетевые комиссии превысили комиссию этого перевода. Он может замедлиться."; "lightning__spark_exit__fee_bump_button" = "Заплатить больше";