From e2ac44ae3d2c42ab077143050079ecb9689c8bab Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 21:00:07 +0100 Subject: [PATCH 01/23] fix: reuse a spark send's key across retries Verified: unit suite with the CI selection on an iOS simulator, swiftformat --lint on the changed files --- Bitkit/Managers/SparkManager.swift | 82 +++++++++++++++++-- Bitkit/Services/SparkSendKey.swift | 83 +++++++++++++++++++ BitkitTests/SparkSendKeyTests.swift | 123 ++++++++++++++++++++++++++++ changelog.d/next/1412.fixed.md | 1 + 4 files changed, 284 insertions(+), 5 deletions(-) create mode 100644 Bitkit/Services/SparkSendKey.swift create mode 100644 BitkitTests/SparkSendKeyTests.swift create mode 100644 changelog.d/next/1412.fixed.md diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index fa0ded4bc..2c3bcf1e3 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -103,6 +103,8 @@ final class SparkManager: ChannelFreeLightningRail { /// Payments whose activity failed to save, written again at the next refresh. @ObservationIgnored private var unsavedPayments: Set = [] @ObservationIgnored private var sdk: BreezSdk? + /// The connected wallet's `SparkSendKey.secret`, derived once at connect. + @ObservationIgnored private var sendKeySecret: Data? /// Whether a wallet sync ended since this run connected, so the SDK's sync error describes this run. @ObservationIgnored private var syncedThisRun = false /// The last withdrawal quote, which the withdrawal reuses while it holds. @@ -220,6 +222,7 @@ final class SparkManager: ChannelFreeLightningRail { try? await sdk.disconnect() } sdk = nil + sendKeySecret = nil listenerId = nil do { let generation = connectGeneration @@ -477,6 +480,7 @@ final class SparkManager: ChannelFreeLightningRail { throw CustomServiceError.mnemonicNotFound } let passphrase = try Keychain.loadString(key: .bip39Passphrase(index: walletIndex)) + let secret = try SparkSendKey.secret(seed: mnemonicToSeed(mnemonicPhrase: mnemonic, passphrase: passphrase)) var config = Self.sdkConfig(network: network, apiKey: Env.breezApiKey, isExiting: isExiting) let chainAPI = try Self.configureLocalSpark(&config) let storageDir = Env.sparkStorage(walletIndex: walletIndex) @@ -497,6 +501,7 @@ final class SparkManager: ChannelFreeLightningRail { await self?.onSdkEvent(event) }) sdk = connected + sendKeySecret = secret Logger.info("Connected Spark wallet on '\(network)'", context: "SparkManager") await importRestoredExitState(walletIndex: walletIndex) Self.notifyExitStateChanged() @@ -603,6 +608,7 @@ final class SparkManager: ChannelFreeLightningRail { } } sdk = nil + sendKeySecret = nil listenerId = nil refreshAgain = false activitiesSynced = false @@ -626,6 +632,7 @@ final class SparkManager: ChannelFreeLightningRail { unsavedPayments = [] sentWithdrawalTxIds = [] preparedWithdrawal = nil + SparkSendAttempts.clear() Self.pendingContactWithdrawal = nil Self.contactWithdrawalTxIds = [] onStateChanged?() @@ -691,17 +698,37 @@ final class SparkManager: ChannelFreeLightningRail { } // The fee limit is checked on the quote that is sent, not only on the earlier estimate. try Self.checkSendFee(feeSats, maxFeeSats: maxFeeSats) + guard let secret = await sendKeySecret else { + throw ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description")) + } + // A retry keeps the latest attempt's key, so Spark returns that attempt's payment instead of paying again, and + // moves past each attempt Spark lists failed, as a failed key can't send again. A list that can't be read + // keeps the latest key, which can't pay twice either. + let failed = try? await sdk.listPayments(request: ListPaymentsRequest(typeFilter: [.send], statusFilter: [.failed])) + let paymentHash = invoiceDetails.paymentHash + let attempt = SparkSendAttempts.next( + paymentHash: paymentHash, + secret: secret, + failedIds: Set(failed?.payments.map(\.id) ?? []) + ) + let idempotencyKey = SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: attempt) + let isReusedKey = SparkSendAttempts.latest(paymentHash: paymentHash) == attempt + let (expiresAt, overflows) = invoiceDetails.timestamp.addingReportingOverflow(invoiceDetails.expiry) + SparkSendAttempts.set(paymentHash: paymentHash, attempt: attempt, expiresAt: overflows ? .max : expiresAt, now: Self.nowSecs()) // An exit that started while the quote was prepared refuses it here, before its hash is recorded. let response: SendPaymentResponse = try await spends.run { // A deadline that passed while the quote was prepared stops the payment here, before anything leaves. try beforeSubmission() do { - return try await sdk.sendPayment(request: SendPaymentRequest( - prepareResponse: prepared, - options: Self.bolt11SendOptions - )) + return try await Self.sendRetryingLeafSelection(canRetry: { (try? beforeSubmission()) != nil }) { + try await sdk.sendPayment(request: SendPaymentRequest( + prepareResponse: prepared, + options: Self.bolt11SendOptions, + idempotencyKey: idempotencyKey + )) + } } catch { - throw Self.sendPaymentFailure(error) + throw Self.bolt11SendFailure(error, isReusedKey: isReusedKey) } } Logger.info("Sent Spark payment '\(response.payment.id)' with status '\(response.payment.status)'", context: "SparkManager") @@ -721,6 +748,51 @@ final class SparkManager: ChannelFreeLightningRail { return !overflow && total <= balanceSats } + /// What a failure inside the BOLT11 `sendPayment` means for the caller. Spark picks the leaves to spend before the + /// operators see the key, so a short balance or leaves Spark can't select left nothing under a new key. Under a key an + /// earlier attempt used, either can hide the transfer that attempt committed: the send stays in doubt until Spark + /// syncs, rather than refused. + nonisolated static func bolt11SendFailure(_ error: Error, isReusedKey: Bool) -> Error { + if isReusedKey, case SdkError.InsufficientFunds = error { + return error + } + if isLeafSelectionFailure(error) { + return isReusedKey ? error : ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description"), underlying: error) + } + return sendPaymentFailure(error) + } + + /// Sends again under the same key while Spark can't select the leaves to spend, as right after a move to Spark lands. + /// Spark selects them before anything reaches the operators, so a retry under the key can't pay twice. `canRetry` + /// is checked before each retry, which otherwise ends with the last failure. + nonisolated static func sendRetryingLeafSelection( + retryDelay: Duration = .seconds(2), + canRetry: () -> Bool, + _ send: () async throws -> T + ) async throws -> T { + var retries = 0 + while true { + do { + return try await send() + } catch { + guard isLeafSelectionFailure(error), retries < leafSelectionRetries else { throw error } + retries += 1 + Logger.info("Retrying a Spark send as Spark could not select its leaves", context: "SparkManager") + try? await Task.sleep(for: retryDelay) + guard !Task.isCancelled, canRetry() else { throw error } + } + } + } + + nonisolated static let leafSelectionRetries = 3 + + /// Spark fails a send with this error when it holds the balance but can't select leaves to spend, before anything + /// reaches the operators (`select_leaves_with_retry` in the 0.28.3 SDK's `spark-wallet/src/wallet.rs`). + nonisolated static func isLeafSelectionFailure(_ error: Error) -> Bool { + guard case let SdkError.SparkError(message) = error else { return false } + return message.localizedCaseInsensitiveContains("Failed to select leaves after all retries") + } + /// What a failure inside `sendPayment` means for the caller. nonisolated static func sendPaymentFailure(_ error: Error) -> Error { // The SDK checks the expiry again before sending, so an invoice that expired on the confirm screen left nothing. diff --git a/Bitkit/Services/SparkSendKey.swift b/Bitkit/Services/SparkSendKey.swift new file mode 100644 index 000000000..ca7bc57ce --- /dev/null +++ b/Bitkit/Services/SparkSendKey.swift @@ -0,0 +1,83 @@ +import CryptoKit +import Foundation + +/// The idempotency key of a Spark send of an invoice. Spark makes one transfer per key, so a retry under the same key +/// never pays the invoice twice: it gets back the transfer an earlier try committed, or sends when none did. A key whose +/// payment failed can't send again, so the next attempt takes the next key. +/// +/// Keys derive from the wallet seed, the payment hash and the attempt number, so a restored wallet derives the same +/// keys, no other wallet can, and the operators can't link a transfer to its invoice. Android derives the same keys. +enum SparkSendKey { + private static let namespace = UUID(uuidString: "794acd96-39bc-4fd1-a09f-02b269a4a34d")! + private static let label = Data("bitkit spark send key".utf8) + + /// The secret all send keys derive from: an HMAC-SHA256 of a fixed label, keyed with the BIP39 `seed`. + static func secret(seed: Data) -> Data { + Data(HMAC.authenticationCode(for: label, using: SymmetricKey(data: seed))) + } + + /// The key of attempt `attempt` at paying the invoice with `paymentHash`: a UUIDv5 of `secret`, the hash's 32 bytes + /// and `attempt` as 4 bytes big-endian. + static func key(secret: Data, paymentHash: String, attempt: UInt32) -> String { + var name = secret + paymentHash.hexaData + withUnsafeBytes(of: attempt.bigEndian) { name.append(contentsOf: $0) } + var sha1 = Insecure.SHA1() + withUnsafeBytes(of: namespace.uuid) { sha1.update(bufferPointer: $0) } + sha1.update(data: name) + var bytes = Array(sha1.finalize().prefix(16)) + bytes[6] = bytes[6] & 0x0F | 0x50 + bytes[8] = bytes[8] & 0x3F | 0x80 + let uuid = bytes.withUnsafeBytes { $0.loadUnaligned(as: uuid_t.self) } + return UUID(uuid: uuid).uuidString.lowercased() + } +} + +/// The latest attempt at each invoice Spark sent, by payment hash, whose number picks the attempt's `SparkSendKey`. +enum SparkSendAttempts { + private static let storageKey = "sparkSendAttempts" + + private struct Attempt: Codable { + let attempt: UInt32 + let expiresAt: UInt64 + } + + /// The attempt whose key pays the invoice with `paymentHash`: the latest kept one, past each whose key is in + /// `failedIds`, the ids of the payments Spark lists as failed, as a failed key can't send again. An attempt Spark + /// may still commit keeps its key, so a retry gets back its payment instead of paying again. + static func next(paymentHash: String, secret: Data, failedIds: Set) -> UInt32 { + var attempt = stored[paymentHash.lowercased()]?.attempt ?? 0 + while failedIds.contains(SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: attempt)) { + attempt += 1 + } + return attempt + } + + /// The latest attempt kept for the invoice with `paymentHash`, nil before its first. + static func latest(paymentHash: String) -> UInt32? { + stored[paymentHash.lowercased()]?.attempt + } + + /// Keeps `attempt` as the latest at the invoice with `paymentHash`, which expires at `expiresAt`, and drops the + /// attempts of invoices expired before `now`, both in epoch seconds. + static func set(paymentHash: String, attempt: UInt32, expiresAt: UInt64, now: UInt64) { + var attempts = stored.filter { $0.value.expiresAt >= now } + attempts[paymentHash.lowercased()] = Attempt(attempt: attempt, expiresAt: expiresAt) + stored = attempts + } + + static func clear() { + UserDefaults.standard.removeObject(forKey: storageKey) + } + + private static var stored: [String: Attempt] { + get { + UserDefaults.standard.data(forKey: storageKey) + .flatMap { try? JSONDecoder().decode([String: Attempt].self, from: $0) } ?? [:] + } + set { + if let data = try? JSONEncoder().encode(newValue) { + UserDefaults.standard.set(data, forKey: storageKey) + } + } + } +} diff --git a/BitkitTests/SparkSendKeyTests.swift b/BitkitTests/SparkSendKeyTests.swift new file mode 100644 index 000000000..08e2e849a --- /dev/null +++ b/BitkitTests/SparkSendKeyTests.swift @@ -0,0 +1,123 @@ +@testable import Bitkit +import BreezSdkSpark +import XCTest + +final class SparkSendKeyTests: XCTestCase { + /// The BIP39 seed of `abandon … about` with passphrase `TREZOR`, from the BIP39 test vectors. + private let seed = ( + "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2c" + + "f141630c7a3c4ab7c81b2f001698e7463b04" + ).hexaData + /// Bytes 0 to 31. + private let paymentHash = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + + override func setUp() { + super.setUp() + SparkSendAttempts.clear() + } + + override func tearDown() { + SparkSendAttempts.clear() + super.tearDown() + } + + /// The same vector is asserted by Android's `SparkSendKeyTest`, so a wallet restored on the other app derives the + /// same keys. + func testDerivesTheSharedTestVector() { + let secret = SparkSendKey.secret(seed: seed) + + XCTAssertEqual(secret.hex, "577ceb10411255cef07e3f49bd7e5239de07586c7457f65ee72ee53737361a98") + XCTAssertEqual(SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: 0), "8d92d8bf-76f3-56fe-8958-8e440acb64fc") + XCTAssertEqual(SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: 1), "712dea1f-8268-5e52-a280-aac86bc60b59") + } + + func testReadsThePaymentHashInEitherCase() { + let secret = SparkSendKey.secret(seed: seed) + + XCTAssertEqual( + SparkSendKey.key(secret: secret, paymentHash: paymentHash.uppercased(), attempt: 0), + SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: 0) + ) + } + + func testAFirstAttemptTakesTheFirstKey() { + let secret = SparkSendKey.secret(seed: seed) + + XCTAssertEqual(SparkSendAttempts.next(paymentHash: paymentHash, secret: secret, failedIds: []), 0) + } + + func testARetryReusesItsAttemptsKeyUntilSparkListsThatAttemptFailed() { + let secret = SparkSendKey.secret(seed: seed) + SparkSendAttempts.set(paymentHash: paymentHash, attempt: 1, expiresAt: 2000, now: 1000) + let firstFailed: Set = [SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: 0)] + + XCTAssertEqual(SparkSendAttempts.next(paymentHash: paymentHash, secret: secret, failedIds: firstFailed), 1) + } + + func testARetryTakesTheNextKeyOnceSparkListsItsAttemptFailed() { + let secret = SparkSendKey.secret(seed: seed) + SparkSendAttempts.set(paymentHash: paymentHash, attempt: 0, expiresAt: 2000, now: 1000) + let failed = Set([0, 1].map { SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: $0) }) + + XCTAssertEqual(SparkSendAttempts.next(paymentHash: paymentHash, secret: secret, failedIds: failed), 2) + } + + func testAnExpiredInvoicesAttemptIsDropped() { + let secret = SparkSendKey.secret(seed: seed) + SparkSendAttempts.set(paymentHash: paymentHash, attempt: 3, expiresAt: 1500, now: 1000) + SparkSendAttempts.set(paymentHash: String(repeating: "ab", count: 32), attempt: 0, expiresAt: 3000, now: 2000) + + XCTAssertEqual(SparkSendAttempts.next(paymentHash: paymentHash, secret: secret, failedIds: []), 0) + } + + func testAShortBalanceUnderAReusedKeyStaysInDoubt() { + let shortBalance = SdkError.InsufficientFunds(tokenIdentifier: nil) + + // An earlier attempt under the key may have committed a transfer, which Spark returns once it can pick leaves. + let reused = Bitkit.SparkManager.bolt11SendFailure(shortBalance, isReusedKey: true) + let fresh = Bitkit.SparkManager.bolt11SendFailure(shortBalance, isReusedKey: false) + + XCTAssertFalse(reused is Bitkit.ChannelFreeRailSendRefused, "\(reused)") + XCTAssertTrue(fresh is Bitkit.ChannelFreeRailSendRefused, "\(fresh)") + } + + func testLeavesSparkCantSelectAreRefusedUnderANewKeyOnly() { + let reused = Bitkit.SparkManager.bolt11SendFailure(leafSelectionFailure, isReusedKey: true) + let fresh = Bitkit.SparkManager.bolt11SendFailure(leafSelectionFailure, isReusedKey: false) + + XCTAssertFalse(reused is Bitkit.ChannelFreeRailSendRefused, "\(reused)") + XCTAssertTrue(fresh is Bitkit.ChannelFreeRailSendRefused, "\(fresh)") + } + + func testASendRetriesWhileSparkCantSelectItsLeaves() async throws { + var sends = 0 + + let sent = try await Bitkit.SparkManager.sendRetryingLeafSelection(retryDelay: .zero, canRetry: { true }) { + sends += 1 + if sends == 1 { + throw leafSelectionFailure + } + return "sent" + } + + XCTAssertEqual(sent, "sent") + XCTAssertEqual(sends, 2) + } + + func testASendStopsRetryingOnceItCanNoLongerGo() async { + var sends = 0 + + do { + _ = try await Bitkit.SparkManager.sendRetryingLeafSelection(retryDelay: .zero, canRetry: { false }) { + sends += 1 + throw leafSelectionFailure + } + XCTFail("the send went out") + } catch { + XCTAssertTrue(Bitkit.SparkManager.isLeafSelectionFailure(error), "\(error)") + } + XCTAssertEqual(sends, 1) + } + + private let leafSelectionFailure = SdkError.SparkError("Tree service error: generic error: Failed to select leaves after all retries") +} diff --git a/changelog.d/next/1412.fixed.md b/changelog.d/next/1412.fixed.md new file mode 100644 index 000000000..e30693907 --- /dev/null +++ b/changelog.d/next/1412.fixed.md @@ -0,0 +1 @@ +Fixed a Lightning invoice paid through Spark being paid twice when the app retried it after an interrupted send, and a payment made right after moving funds to Spark staying pending. From b7eb6f3815a1b55499d2200ffa892908c886b0f9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 11:42:32 +0100 Subject: [PATCH 02/23] fix: retry a spark send whose leaves spark can't select The retry checked again through the send's admission, which already recorded the attempt, so it was refused and never ran; the admission now runs once. A send refused before reaching Spark puts back the attempt kept before it, so a retry refuses the same way instead of holding the invoice until it expires, and the attempt store is locked. Verified: unit suite with the CI selection (4320 tests, 0 failures), swiftformat --lint on the changed files --- Bitkit/Managers/SparkManager.swift | 41 ++++++++++++++++---------- Bitkit/Services/LightningService.swift | 2 ++ Bitkit/Services/SparkSendKey.swift | 21 ++++++++++--- BitkitTests/SparkSendKeyTests.swift | 39 ++++++++++++++++++++++++ 4 files changed, 84 insertions(+), 19 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 2c3bcf1e3..19ffdf6fe 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -712,24 +712,35 @@ final class SparkManager: ChannelFreeLightningRail { failedIds: Set(failed?.payments.map(\.id) ?? []) ) let idempotencyKey = SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: attempt) - let isReusedKey = SparkSendAttempts.latest(paymentHash: paymentHash) == attempt - let (expiresAt, overflows) = invoiceDetails.timestamp.addingReportingOverflow(invoiceDetails.expiry) - SparkSendAttempts.set(paymentHash: paymentHash, attempt: attempt, expiresAt: overflows ? .max : expiresAt, now: Self.nowSecs()) + let previousAttempt = SparkSendAttempts.latest(paymentHash: paymentHash) + let isReusedKey = previousAttempt == attempt + let (sum, overflows) = invoiceDetails.timestamp.addingReportingOverflow(invoiceDetails.expiry) + let expiresAt = overflows ? UInt64.max : sum + SparkSendAttempts.set(paymentHash: paymentHash, attempt: attempt, expiresAt: expiresAt, now: Self.nowSecs()) // An exit that started while the quote was prepared refuses it here, before its hash is recorded. - let response: SendPaymentResponse = try await spends.run { - // A deadline that passed while the quote was prepared stops the payment here, before anything leaves. - try beforeSubmission() - do { - return try await Self.sendRetryingLeafSelection(canRetry: { (try? beforeSubmission()) != nil }) { - try await sdk.sendPayment(request: SendPaymentRequest( - prepareResponse: prepared, - options: Self.bolt11SendOptions, - idempotencyKey: idempotencyKey - )) + let response: SendPaymentResponse + do { + response = try await spends.run { + // A deadline that passed while the quote was prepared stops the payment here, before anything leaves. + try beforeSubmission() + do { + return try await Self.sendRetryingLeafSelection(canRetry: { (try? beforeSubmission()) != nil }) { + try await sdk.sendPayment(request: SendPaymentRequest( + prepareResponse: prepared, + options: Self.bolt11SendOptions, + idempotencyKey: idempotencyKey + )) + } + } catch { + throw Self.bolt11SendFailure(error, isReusedKey: isReusedKey) } - } catch { - throw Self.bolt11SendFailure(error, isReusedKey: isReusedKey) } + } catch let refusal as ChannelFreeRailSendRefused { + // A refused attempt never reached Spark's operators, so its key stays unused and a retry refuses the same way. + if !isReusedKey { + SparkSendAttempts.restore(paymentHash: paymentHash, attempt: previousAttempt, expiresAt: expiresAt) + } + throw refusal } Logger.info("Sent Spark payment '\(response.payment.id)' with status '\(response.payment.status)'", context: "SparkManager") return invoiceDetails.paymentHash diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 78a1b612b..465384034 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1217,6 +1217,8 @@ class LightningService: NodeLifecycleService { ?? Self.paymentAmountSats(bolt11: bolt11, sats: sats).map(Self.defaultMaxFeeSats), beforeSubmission: { [weak self] in try beforeSubmission() + // Spark checks again before it retries the same attempt, which is already admitted. + guard !didRecordAttempt else { return } do { try self?.admitSend(paymentHash: paymentHash, on: .channelFree, since: mark) } catch { diff --git a/Bitkit/Services/SparkSendKey.swift b/Bitkit/Services/SparkSendKey.swift index ca7bc57ce..40601eca9 100644 --- a/Bitkit/Services/SparkSendKey.swift +++ b/Bitkit/Services/SparkSendKey.swift @@ -35,6 +35,7 @@ enum SparkSendKey { /// The latest attempt at each invoice Spark sent, by payment hash, whose number picks the attempt's `SparkSendKey`. enum SparkSendAttempts { private static let storageKey = "sparkSendAttempts" + private static let lock = NSLock() private struct Attempt: Codable { let attempt: UInt32 @@ -60,13 +61,25 @@ enum SparkSendAttempts { /// Keeps `attempt` as the latest at the invoice with `paymentHash`, which expires at `expiresAt`, and drops the /// attempts of invoices expired before `now`, both in epoch seconds. static func set(paymentHash: String, attempt: UInt32, expiresAt: UInt64, now: UInt64) { - var attempts = stored.filter { $0.value.expiresAt >= now } - attempts[paymentHash.lowercased()] = Attempt(attempt: attempt, expiresAt: expiresAt) - stored = attempts + lock.withLock { + var attempts = stored.filter { $0.value.expiresAt >= now } + attempts[paymentHash.lowercased()] = Attempt(attempt: attempt, expiresAt: expiresAt) + stored = attempts + } + } + + /// Puts back `attempt`, the latest kept before a send whose key never reached Spark, or drops the invoice's entry + /// when it had none. + static func restore(paymentHash: String, attempt: UInt32?, expiresAt: UInt64) { + lock.withLock { + var attempts = stored + attempts[paymentHash.lowercased()] = attempt.map { Attempt(attempt: $0, expiresAt: expiresAt) } + stored = attempts + } } static func clear() { - UserDefaults.standard.removeObject(forKey: storageKey) + lock.withLock { UserDefaults.standard.removeObject(forKey: storageKey) } } private static var stored: [String: Attempt] { diff --git a/BitkitTests/SparkSendKeyTests.swift b/BitkitTests/SparkSendKeyTests.swift index 08e2e849a..4ce26eb33 100644 --- a/BitkitTests/SparkSendKeyTests.swift +++ b/BitkitTests/SparkSendKeyTests.swift @@ -119,5 +119,44 @@ final class SparkSendKeyTests: XCTestCase { XCTAssertEqual(sends, 1) } + func testASendStopsRetryingAfterItsLastRetry() async { + var sends = 0 + + do { + _ = try await Bitkit.SparkManager.sendRetryingLeafSelection(retryDelay: .zero, canRetry: { true }) { + sends += 1 + throw leafSelectionFailure + } + XCTFail("the send went out") + } catch { + XCTAssertTrue(Bitkit.SparkManager.isLeafSelectionFailure(error), "\(error)") + } + XCTAssertEqual(sends, 1 + Bitkit.SparkManager.leafSelectionRetries) + } + + func testASendIsNotRetriedForOtherFailures() async { + var sends = 0 + + do { + _ = try await Bitkit.SparkManager.sendRetryingLeafSelection(retryDelay: .zero, canRetry: { true }) { + sends += 1 + throw SdkError.InsufficientFunds(tokenIdentifier: nil) + } + XCTFail("the send went out") + } catch {} + XCTAssertEqual(sends, 1) + } + + func testARefusedAttemptGivesBackTheEarlierOne() { + SparkSendAttempts.set(paymentHash: paymentHash, attempt: 1, expiresAt: 2000, now: 1000) + SparkSendAttempts.set(paymentHash: paymentHash, attempt: 2, expiresAt: 2000, now: 1000) + + SparkSendAttempts.restore(paymentHash: paymentHash, attempt: 1, expiresAt: 2000) + XCTAssertEqual(SparkSendAttempts.latest(paymentHash: paymentHash), 1) + + SparkSendAttempts.restore(paymentHash: paymentHash, attempt: nil, expiresAt: 2000) + XCTAssertNil(SparkSendAttempts.latest(paymentHash: paymentHash)) + } + private let leafSelectionFailure = SdkError.SparkError("Tree service error: generic error: Failed to select leaves after all retries") } From e15f481660ba7e47f642a07687744d936daff039 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 12:23:52 +0100 Subject: [PATCH 03/23] fix: keep a spark send attempt only once it is admitted A send its caller refused before it left (an expired request, a duplicate payment) kept its attempt, so a retry counted the unused key as reused. The attempt is now kept after the caller's checks, and the attempt store reads under its lock. Verified: unit suite with the CI selection (0 failures), swiftformat --lint on the changed files --- Bitkit/Managers/SparkManager.swift | 3 ++- Bitkit/Services/SparkSendKey.swift | 4 ++-- BitkitTests/ChannelFreeRailTests.swift | 15 ++++++++++++++- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 19ffdf6fe..b2c61e751 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -716,13 +716,14 @@ final class SparkManager: ChannelFreeLightningRail { let isReusedKey = previousAttempt == attempt let (sum, overflows) = invoiceDetails.timestamp.addingReportingOverflow(invoiceDetails.expiry) let expiresAt = overflows ? UInt64.max : sum - SparkSendAttempts.set(paymentHash: paymentHash, attempt: attempt, expiresAt: expiresAt, now: Self.nowSecs()) // An exit that started while the quote was prepared refuses it here, before its hash is recorded. let response: SendPaymentResponse do { response = try await spends.run { // A deadline that passed while the quote was prepared stops the payment here, before anything leaves. try beforeSubmission() + // Kept once the send is admitted, so a send refused before it leaves keeps the earlier attempt. + SparkSendAttempts.set(paymentHash: paymentHash, attempt: attempt, expiresAt: expiresAt, now: Self.nowSecs()) do { return try await Self.sendRetryingLeafSelection(canRetry: { (try? beforeSubmission()) != nil }) { try await sdk.sendPayment(request: SendPaymentRequest( diff --git a/Bitkit/Services/SparkSendKey.swift b/Bitkit/Services/SparkSendKey.swift index 40601eca9..02bc95890 100644 --- a/Bitkit/Services/SparkSendKey.swift +++ b/Bitkit/Services/SparkSendKey.swift @@ -46,7 +46,7 @@ enum SparkSendAttempts { /// `failedIds`, the ids of the payments Spark lists as failed, as a failed key can't send again. An attempt Spark /// may still commit keeps its key, so a retry gets back its payment instead of paying again. static func next(paymentHash: String, secret: Data, failedIds: Set) -> UInt32 { - var attempt = stored[paymentHash.lowercased()]?.attempt ?? 0 + var attempt = lock.withLock { stored[paymentHash.lowercased()]?.attempt } ?? 0 while failedIds.contains(SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: attempt)) { attempt += 1 } @@ -55,7 +55,7 @@ enum SparkSendAttempts { /// The latest attempt kept for the invoice with `paymentHash`, nil before its first. static func latest(paymentHash: String) -> UInt32? { - stored[paymentHash.lowercased()]?.attempt + lock.withLock { stored[paymentHash.lowercased()]?.attempt } } /// Keeps `attempt` as the latest at the invoice with `paymentHash`, which expires at `expiresAt`, and drops the diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 76aaab435..4ff339477 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1878,6 +1878,15 @@ extension ChannelFreeRailTests { XCTAssertTrue(payments.contains { $0.status == .pending }, "the retry read as A's failure") } + func testASparkSendCheckedAgainBeforeARetryGoesOut() async throws { + rail.balanceSats = 100_000 + rail.submissionChecks = 2 + + _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + + XCTAssertEqual(rail.sends, 1) + } + func testASparkSendFailingBeforeItRecordsItsAttemptTakesNoHold() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared @@ -2307,6 +2316,8 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { var onSend: (() -> Void)? /// Runs as a send is about to be submitted, before `beforeSubmission`. var beforeSubmit: (() -> Void)? + /// How often the send checks `beforeSubmission`, as Spark does again before each retry of the same attempt. + var submissionChecks = 1 /// 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. @@ -2330,7 +2341,9 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { throw refusal } beforeSubmit?() - try beforeSubmission() + for _ in 0 ..< submissionChecks { + try beforeSubmission() + } if let refusalAfterSubmission { throw refusalAfterSubmission } From 91da213daa06c4c74eed3fc12660de1a6196d921 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 12:55:46 +0100 Subject: [PATCH 04/23] test: keep the host app's spark send attempts The tests cleared the attempts the simulator wallet saved; they now put them back after each test. Verified: SparkSendKeyTests on the simulator, swiftformat --lint on the changed file --- BitkitTests/SparkSendKeyTests.swift | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/BitkitTests/SparkSendKeyTests.swift b/BitkitTests/SparkSendKeyTests.swift index 4ce26eb33..893ac8b05 100644 --- a/BitkitTests/SparkSendKeyTests.swift +++ b/BitkitTests/SparkSendKeyTests.swift @@ -11,13 +11,17 @@ final class SparkSendKeyTests: XCTestCase { /// Bytes 0 to 31. private let paymentHash = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + /// The host app's saved attempts, put back after each test. + private var savedAttempts: Data? + override func setUp() { super.setUp() + savedAttempts = UserDefaults.standard.data(forKey: "sparkSendAttempts") SparkSendAttempts.clear() } override func tearDown() { - SparkSendAttempts.clear() + UserDefaults.standard.set(savedAttempts, forKey: "sparkSendAttempts") super.tearDown() } From f9d11056e25a98278efc24510498e0244c74300a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 13:29:01 +0100 Subject: [PATCH 05/23] fix: keep the node off a refused spark send until spark syncs The SDK selects leaves again when it retries a failed submission, so a short balance or leaves it can't select under a new key can follow a transfer it committed. Such a refusal now keeps the invoice's attempt and notes when it was refused, and the node holds off the invoice until Spark has synced since. A retry over Spark isn't held, as one under the same key can't pay twice. Verified: unit suite with the CI selection (4322 tests, 0 failures), swiftformat --lint on the changed files --- Bitkit/Managers/SparkManager.swift | 25 ++++++--- Bitkit/Services/LightningService.swift | 71 +++++++++++++++++++++++++- BitkitTests/ChannelFreeRailTests.swift | 44 ++++++++++++++++ BitkitTests/SparkSendKeyTests.swift | 4 +- 4 files changed, 133 insertions(+), 11 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index b2c61e751..525424125 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -761,17 +761,26 @@ final class SparkManager: ChannelFreeLightningRail { } /// What a failure inside the BOLT11 `sendPayment` means for the caller. Spark picks the leaves to spend before the - /// operators see the key, so a short balance or leaves Spark can't select left nothing under a new key. Under a key an - /// earlier attempt used, either can hide the transfer that attempt committed: the send stays in doubt until Spark - /// syncs, rather than refused. + /// operators see the key on its first try, so a short balance or leaves Spark can't select are refused under a new + /// key; its retry of a failed submission selects them again, so the node stays off the invoice until Spark syncs. + /// Under a key an earlier attempt used, either can hide the transfer that attempt committed: the send stays in doubt + /// until Spark syncs, rather than refused. nonisolated static func bolt11SendFailure(_ error: Error, isReusedKey: Bool) -> Error { - if isReusedKey, case SdkError.InsufficientFunds = error { - return error + let isShortBalance = if case SdkError.InsufficientFunds = error { + true + } else { + false } - if isLeafSelectionFailure(error) { - return isReusedKey ? error : ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description"), underlying: error) + guard isShortBalance || isLeafSelectionFailure(error) else { return sendPaymentFailure(error) } + if isReusedKey { + return error } - return sendPaymentFailure(error) + var refusal = ChannelFreeRailSendRefused( + reason: isShortBalance ? t("other__pay_insufficient_spending_description") : t("wallet__payment_failed_description"), + underlying: error + ) + refusal.mayHaveReachedSpark = true + return refusal } /// Sends again under the same key while Spark can't select the leaves to spend, as right after a move to Spark lands. diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 465384034..11cc3f888 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -64,6 +64,9 @@ struct ChannelFreeRailSendRefused: LocalizedError { var underlying: Error? /// A still-valid invoice created before the restore, as Spark can't show it didn't pay it then. var isRestoredInvoiceUnverified = false + /// Refused after the SDK may have reached Spark's operators, as its retry of a failed submission selects leaves + /// again: the node stays off the invoice until Spark syncs. + var mayHaveReachedSpark = false static func restoredInvoiceUnverified() -> ChannelFreeRailSendRefused { ChannelFreeRailSendRefused(reason: t("wallet__payment_restored_invoice"), isRestoredInvoiceUnverified: true) @@ -1240,6 +1243,10 @@ class LightningService: NodeLifecycleService { // Nothing left the wallet. Refused before submission, this send recorded nothing, so another send's // attempt and hold of the invoice stay. if let paymentHash, didRecordAttempt { + // Kept before the holds go, so no stop in between frees the invoice. + if refusal.mayHaveReachedSpark { + noteRailSendRefused(paymentHash: paymentHash, expiresAt: expiresAt) + } endRailSendUncertainty(paymentHash: paymentHash) releaseRailAttempt(paymentHash: paymentHash, unlessInFlight: false) } @@ -1328,6 +1335,7 @@ class LightningService: NodeLifecycleService { /// 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" + private static let refusedRailSendsKey = "channelFreeRailRefusedSendAt" /// 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 @@ -1524,6 +1532,7 @@ class LightningService: NodeLifecycleService { func forgetRailAttempts() { eventCallbackLock.withLock { railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsKey) + railAttemptsStore.removeObject(forKey: Self.refusedRailSendsKey) railAttemptsStore.removeObject(forKey: Self.railAttemptsKey) railAttemptsStore.removeObject(forKey: Self.expiriesKey(Self.railAttemptsKey)) attemptRecordedAt[Self.railAttemptsKey] = nil @@ -1643,10 +1652,21 @@ class LightningService: NodeLifecycleService { // The node's paid row is final, so no uncertainty about Spark's pre-restore sends refuses it. let isPaidOverTheNode = statuses.contains(.succeeded) if rails.contains(.channelFree) { + // Read before the list, so a list read after the sync shows any transfer the refused send committed. A retry + // over Spark sends under that send's key, so only the node waits. + let refusal = sendsOverRail ? nil : await railSendRefusal(paymentHash: paymentHash) + if refusal?.isSynced == false { + Logger.info("Held '\(paymentHash)' until Spark syncs after its refused send", context: "LightningService") + statuses.append(.pending) + } let mark = attemptMark if let payments = await readableRailPayments() { let live = keepRailAttempts(from: payments, since: mark) let payment = ChannelFreeRailPayment.latestOutboundAttempt(payments, paymentHash: paymentHash) + // A transfer the refused send committed keeps the marker, which holds the invoice when Spark can't list. + if let refusal, refusal.isSynced, payment == nil || payment?.status == .failed { + endRailSendRefusal(paymentHash: paymentHash, refusedAt: refusal.refusedAt) + } if let payment { statuses.append(payment.status) } @@ -1670,7 +1690,7 @@ class LightningService: NodeLifecycleService { // Only a settled row ends the unknown send: a pending one may be the synthetic row it is listed as. endRailSendUncertainty(paymentHash: paymentHash) } - } else if hasRailAttempt(paymentHash: paymentHash) { + } else if refusal != nil || hasRailAttempt(paymentHash: paymentHash) { Logger.warn("Refused paying '\(paymentHash)', Spark can't list the earlier attempt now", context: "LightningService") throw Self.pendingDuplicate(paymentHash: paymentHash) } else if isPaidOverTheNode { @@ -1914,6 +1934,51 @@ class LightningService: NodeLifecycleService { } } + /// Callers hold `eventCallbackLock`. Spark sends refused after they may have reached Spark's operators: when each + /// was refused, and its invoice's expiry. + private func refusedRailSends() -> [String: [Int]] { + railAttemptsStore.dictionary(forKey: Self.refusedRailSendsKey) as? [String: [Int]] ?? [:] + } + + /// Keeps the node off the invoice of a Spark send refused after it may have reached Spark's operators, which may + /// still have committed a transfer, until Spark syncs. Drops the refusals whose invoice expired, which the node can no + /// longer pay. + private func noteRailSendRefused(paymentHash: String, expiresAt: Int?) { + let now = Int(max(0, now().timeIntervalSince1970)) + eventCallbackLock.withLock { + var refused = refusedRailSends().filter { $0.value.count == 2 && $0.value[1] > now } + refused[paymentHash.lowercased()] = [now, expiresAt ?? .max] + railAttemptsStore.set(refused, forKey: Self.refusedRailSendsKey) + } + } + + /// When the Spark send of an unexpired invoice was refused after it may have reached Spark's operators, and whether + /// Spark synced since, so its list shows any transfer the send committed. + private func railSendRefusal(paymentHash: String) async -> (refusedAt: Int, isSynced: Bool)? { + let nowSeconds = Int(now().timeIntervalSince1970) + let refusal = eventCallbackLock.withLock { refusedRailSends()[paymentHash.lowercased()] } + guard let refusal, refusal.count == 2, refusal[1] > nowSeconds else { return nil } + let rail = channelFreeRail ?? channelFreePaymentHistory + let isSynced = await rail?.hasSynced(after: UInt64(max(0, refusal[0]))) ?? false + return (refusal[0], isSynced) + } + + /// Callers hold `eventCallbackLock`. A refused Spark send of an unexpired invoice that no check ended yet. + private func hasRailSendRefusal(paymentHash hash: String) -> Bool { + refusedRailSends()[hash].map { $0.count == 2 && $0[1] > Int(now().timeIntervalSince1970) } ?? false + } + + /// Ends the refusal made at `refusedAt` only, as a later one waits for its own sync. + private func endRailSendRefusal(paymentHash: String, refusedAt: Int) { + let hash = paymentHash.lowercased() + eventCallbackLock.withLock { + var refused = refusedRailSends() + guard refused[hash]?.first == refusedAt else { return } + refused.removeValue(forKey: hash) + railAttemptsStore.set(refused, forKey: Self.refusedRailSendsKey) + } + } + /// True unless the hash's last rail send failed after it was submitted and may still go out: its invoice hasn't /// expired, or no sync has reached the rail since it did. private func railSyncedSinceUncertainSend(paymentHash: String) async -> Bool { @@ -1987,6 +2052,10 @@ class LightningService: NodeLifecycleService { Logger.warn("Refused paying '\(hash)', Spark sent it meanwhile", context: "LightningService") throw Self.pendingDuplicate(paymentHash: hash) } + if rail == .ldk, hasRailSendRefusal(paymentHash: hash) { + Logger.warn("Refused paying '\(hash)', a Spark send of it was refused meanwhile", context: "LightningService") + throw Self.pendingDuplicate(paymentHash: hash) + } if rail == .ldk { ldkSendsInFlight[hash, default: 0] += 1 } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 4ff339477..0feb7c46e 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1878,6 +1878,50 @@ extension ChannelFreeRailTests { XCTAssertTrue(payments.contains { $0.status == .pending }, "the retry read as A's failure") } + func testASparkSendRefusedAfterALeafFailureKeepsTheNodeOffUntilSparkSyncs() async throws { + try await refuseASparkSendAfterALeafFailure() + rail.balanceSats = 0 + + // The SDK may have selected leaves again after a committed transfer, which Spark lists only once it syncs. + rail.syncedAfter = { $0 == nil } + await assertRefusedAsDuplicate() + + // Synced, but a list Spark can't read shows nothing of the transfer. + rail.syncedAfter = { _ in true } + rail.listError = NSError(domain: "spark list", code: 1) + await assertRefusedAsDuplicate() + + rail.listError = nil + await assertReachesTheNode() + } + + func testASparkRetryOfASendRefusedAfterALeafFailureGoesOutBeforeSparkSyncs() async throws { + try await refuseASparkSendAfterALeafFailure() + // Synced once, so Spark lists its payments, but not since the refusal. + rail.syncedAfter = { $0 == nil } + + _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + + XCTAssertEqual(rail.sends, 1) + } + + /// Refuses a Spark send of `invoice`, before its expiry, after it may have reached Spark's operators. + private func refuseASparkSendAfterALeafFailure() async throws { + let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: TimeInterval(invoice.secondsSinceEpoch())) } + rail.balanceSats = 100_000 + var refusal = Bitkit.ChannelFreeRailSendRefused(reason: "leaves") + refusal.mayHaveReachedSpark = true + rail.refusalAfterSubmission = refusal + 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)") + } + rail.refusalAfterSubmission = nil + } + func testASparkSendCheckedAgainBeforeARetryGoesOut() async throws { rail.balanceSats = 100_000 rail.submissionChecks = 2 diff --git a/BitkitTests/SparkSendKeyTests.swift b/BitkitTests/SparkSendKeyTests.swift index 893ac8b05..4c2ebe434 100644 --- a/BitkitTests/SparkSendKeyTests.swift +++ b/BitkitTests/SparkSendKeyTests.swift @@ -82,7 +82,7 @@ final class SparkSendKeyTests: XCTestCase { let fresh = Bitkit.SparkManager.bolt11SendFailure(shortBalance, isReusedKey: false) XCTAssertFalse(reused is Bitkit.ChannelFreeRailSendRefused, "\(reused)") - XCTAssertTrue(fresh is Bitkit.ChannelFreeRailSendRefused, "\(fresh)") + XCTAssertTrue((fresh as? Bitkit.ChannelFreeRailSendRefused)?.mayHaveReachedSpark == true, "\(fresh)") } func testLeavesSparkCantSelectAreRefusedUnderANewKeyOnly() { @@ -90,7 +90,7 @@ final class SparkSendKeyTests: XCTestCase { let fresh = Bitkit.SparkManager.bolt11SendFailure(leafSelectionFailure, isReusedKey: false) XCTAssertFalse(reused is Bitkit.ChannelFreeRailSendRefused, "\(reused)") - XCTAssertTrue(fresh is Bitkit.ChannelFreeRailSendRefused, "\(fresh)") + XCTAssertTrue((fresh as? Bitkit.ChannelFreeRailSendRefused)?.mayHaveReachedSpark == true, "\(fresh)") } func testASendRetriesWhileSparkCantSelectItsLeaves() async throws { From d55ca61215216e7ee3d9c1953c3c24efd6758deb Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 14:19:25 +0100 Subject: [PATCH 06/23] test: cover the refusal of a spark send that may have reached spark Verified: ChannelFreeRailTests and SparkSendKeyTests on the simulator --- BitkitTests/ChannelFreeRailTests.swift | 32 ++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 0feb7c46e..93d19afcf 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1895,6 +1895,38 @@ extension ChannelFreeRailTests { await assertReachesTheNode() } + func testASparkSendRefusedAfterALeafFailureThatSparkListsPendingKeepsTheNodeOffWhileSparkCantList() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + try await refuseASparkSendAfterALeafFailure() + rail.balanceSats = 0 + rail.syncedAfter = { _ in true } + rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .pending, preimage: nil)] + await assertRefusedAsDuplicate() + + // The transfer the refused send committed keeps its refusal, so a list Spark can't read still holds the node. + rail.payments = [] + rail.listError = NSError(domain: "spark list", code: 1) + await assertRefusedAsDuplicate() + } + + func testANodeSendAdmittedAfterASparkSendWasRefusedAfterALeafFailureIsRefusedUntilTheInvoiceExpires() async throws { + let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) + let hash = String(invoice.paymentHash()) + let service = Bitkit.LightningService.shared + // The node send passed its checks before the Spark send was refused. + let mark = service.attemptMark + try await refuseASparkSendAfterALeafFailure() + + XCTAssertThrowsError(try service.admitSend(paymentHash: hash, on: .ldk, since: mark)) { + XCTAssertTrue(PrivatePaykitService.isDuplicatePaymentError($0), "\($0)") + } + + // Once the invoice expired, no node send can pay it. + service.now = { Date(timeIntervalSince1970: TimeInterval(invoice.secondsSinceEpoch() + invoice.expiryTimeSeconds())) } + XCTAssertNoThrow(try service.admitSend(paymentHash: hash, on: .ldk, since: service.attemptMark)) + service.endLdkSend(paymentHash: hash) + } + func testASparkRetryOfASendRefusedAfterALeafFailureGoesOutBeforeSparkSyncs() async throws { try await refuseASparkSendAfterALeafFailure() // Synced once, so Spark lists its payments, but not since the refusal. From bfd6edd0aeca4f76df6bdae255220aebdbbcc0f3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 14:37:47 +0100 Subject: [PATCH 07/23] fix: keep a spark send that may have reached spark uncertain in paykit and quickpay Verified: PaykitPaymentProofServiceTests, QuickPayPaymentCoordinatorTests and ChannelFreeRailTests on the simulator --- Bitkit/Services/PaykitPaymentProofService.swift | 6 ++++-- Bitkit/Utilities/QuickPayPaymentCoordinator.swift | 7 ++++--- BitkitTests/PaykitPaymentProofServiceTests.swift | 8 ++++++++ BitkitTests/QuickPayPaymentCoordinatorTests.swift | 9 +++++++++ 4 files changed, 25 insertions(+), 5 deletions(-) diff --git a/Bitkit/Services/PaykitPaymentProofService.swift b/Bitkit/Services/PaykitPaymentProofService.swift index 06db47a1f..30e503aaa 100644 --- a/Bitkit/Services/PaykitPaymentProofService.swift +++ b/Bitkit/Services/PaykitPaymentProofService.swift @@ -1385,8 +1385,10 @@ actor PaykitPaymentProofService { let underlyingError = (submissionError as? AppError)?.underlyingError ?? submissionError if underlyingError as? PaykitPaymentRequestError == .requestExpired { // The local deadline gate runs before submitting to the node. - } else if underlyingError is ChannelFreeRailSendRefused { - // Spark refused it before sending: not connected, not preparable, or over the fee limit. + } else if let refusal = underlyingError as? ChannelFreeRailSendRefused { + // Spark refused it before sending: not connected, not preparable, or over the fee limit. A refusal after it + // may have reached Spark's operators may still have sent it. + guard !refusal.mayHaveReachedSpark else { return false } } else if underlyingError is MoveToSparkError { // Any failed spending balance update happens before the invoice is paid, so nothing was sent. } else if let serviceError = underlyingError as? CustomServiceError { diff --git a/Bitkit/Utilities/QuickPayPaymentCoordinator.swift b/Bitkit/Utilities/QuickPayPaymentCoordinator.swift index 0b410281d..f6251d237 100644 --- a/Bitkit/Utilities/QuickPayPaymentCoordinator.swift +++ b/Bitkit/Utilities/QuickPayPaymentCoordinator.swift @@ -201,9 +201,10 @@ final class QuickPayPaymentCoordinator { } static func isHardReject(_ error: Error) -> Bool { - // Spark refuses only before anything leaves the wallet. - if error is ChannelFreeRailSendRefused || (error as? AppError)?.underlyingError is ChannelFreeRailSendRefused { - return true + // Spark refuses before anything leaves the wallet, unless the refusal came after the send may have reached its + // operators. + if let refusal = (error as? ChannelFreeRailSendRefused) ?? (error as? AppError)?.underlyingError as? ChannelFreeRailSendRefused { + return !refusal.mayHaveReachedSpark } guard let nodeError = nodeError(from: error) else { return false diff --git a/BitkitTests/PaykitPaymentProofServiceTests.swift b/BitkitTests/PaykitPaymentProofServiceTests.swift index 5552f93fa..7881308c7 100644 --- a/BitkitTests/PaykitPaymentProofServiceTests.swift +++ b/BitkitTests/PaykitPaymentProofServiceTests.swift @@ -1727,6 +1727,7 @@ final class PaykitPaymentProofServiceTests: XCTestCase { Bitkit.AppError(error: NodeError.PersistenceFailed(message: "io")), NodeError.DuplicatePayment(message: "pending"), NSError(domain: "payment", code: 1), + Bitkit.AppError(error: Self.refusalAfterReachingSpark), ] for error in errors { let record = try paymentRequestRecord() @@ -1768,6 +1769,13 @@ final class PaykitPaymentProofServiceTests: XCTestCase { } } + /// A Spark refusal after the send may have reached Spark's operators, which may still have sent it. + private static var refusalAfterReachingSpark: Bitkit.ChannelFreeRailSendRefused { + var refusal = Bitkit.ChannelFreeRailSendRefused(reason: "Spark could not select leaves") + refusal.mayHaveReachedSpark = true + return refusal + } + func testDefiniteLightningSubmissionFailureClearsProof() async throws { let errors: [Error] = [ PaykitPaymentRequestError.requestExpired, diff --git a/BitkitTests/QuickPayPaymentCoordinatorTests.swift b/BitkitTests/QuickPayPaymentCoordinatorTests.swift index 84c88208b..c6fdf9b88 100644 --- a/BitkitTests/QuickPayPaymentCoordinatorTests.swift +++ b/BitkitTests/QuickPayPaymentCoordinatorTests.swift @@ -53,6 +53,15 @@ final class QuickPayPaymentCoordinatorTests: XCTestCase { XCTAssertFalse(QuickPayPaymentCoordinator.isHardReject(NodeError.DuplicatePayment(message: "dup"))) } + func testASparkRefusalAfterTheSendMayHaveReachedSparkIsNotHardReject() { + var refusal = Bitkit.ChannelFreeRailSendRefused(reason: "leaves") + XCTAssertTrue(QuickPayPaymentCoordinator.isHardReject(refusal)) + + refusal.mayHaveReachedSpark = true + XCTAssertFalse(QuickPayPaymentCoordinator.isHardReject(refusal)) + XCTAssertFalse(QuickPayPaymentCoordinator.isHardReject(Bitkit.AppError(error: refusal))) + } + func testInvalidInvoiceIsHardReject() { XCTAssertTrue(QuickPayPaymentCoordinator.isHardReject(NodeError.InvalidInvoice(message: "bad"))) } From 72c94fd151fafe53433b214f2d568393f798e4ca Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 15:04:54 +0100 Subject: [PATCH 08/23] fix: show a refused spark send pending until spark syncs Paykit, QuickPay and private invoices read the rail's list, so a refusal that may have reached Spark reads pending over an earlier failure until a sync reached Spark since. A Spark retry still sends under the same key. Verified: ChannelFreeRailTests, SparkSendKeyTests, QuickPayPaymentCoordinatorTests and PaykitPaymentProofServiceTests on the simulator --- Bitkit/Services/LightningService.swift | 32 +++++++++++++++++++++----- BitkitTests/ChannelFreeRailTests.swift | 14 +++++++++++ 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 11cc3f888..24710cce8 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1660,7 +1660,8 @@ class LightningService: NodeLifecycleService { statuses.append(.pending) } let mark = attemptMark - if let payments = await readableRailPayments() { + // The refusal is checked above for the node, and a Spark retry sends under the refused send's key. + if let payments = await readableRailPayments(includingRefusedSends: false) { let live = keepRailAttempts(from: payments, since: mark) let payment = ChannelFreeRailPayment.latestOutboundAttempt(payments, paymentHash: paymentHash) // A transfer the refused send committed keeps the marker, which holds the invoice when Spark can't list. @@ -1781,8 +1782,8 @@ class LightningService: NodeLifecycleService { } /// Nil while the rail's payments can't be read: listing them failed, or the rail runs here but isn't connected. - private func readableRailPayments() async -> [ChannelFreeRailPayment]? { - try? await channelFreeRailPayments() + private func readableRailPayments(includingRefusedSends: Bool = true) async -> [ChannelFreeRailPayment]? { + try? await channelFreeRailPayments(includingRefusedSends: includingRefusedSends) } /// Callers hold `eventCallbackLock`. @@ -1968,6 +1969,18 @@ class LightningService: NodeLifecycleService { refusedRailSends()[hash].map { $0.count == 2 && $0[1] > Int(now().timeIntervalSince1970) } ?? false } + /// The refused Spark sends of unexpired invoices that no sync reached Spark since. + private func unsyncedRailSendRefusals() async -> Set { + let hashes = eventCallbackLock.withLock { Array(refusedRailSends().keys) } + var unsynced = Set() + for hash in hashes { + if let refusal = await railSendRefusal(paymentHash: hash), !refusal.isSynced { + unsynced.insert(hash) + } + } + return unsynced + } + /// Ends the refusal made at `refusedAt` only, as a later one waits for its own sync. private func endRailSendRefusal(paymentHash: String, refusedAt: Int) { let hash = paymentHash.lowercased() @@ -2715,8 +2728,9 @@ extension LightningService { /// The rail's Lightning payments, none where the rail doesn't run; throws when the rail could not list them, runs /// here but isn't connected, or no sync has reached it yet, so a payment it may hold is never read as one it never - /// made. - func channelFreeRailPayments() async throws -> [ChannelFreeRailPayment] { + /// made. A refused send that may have reached Spark's operators reads pending until a sync reached Spark since, + /// unless `includingRefusedSends` is false. + func channelFreeRailPayments(includingRefusedSends: Bool = true) async throws -> [ChannelFreeRailPayment] { // During an emergency exit Spark is off the rail but still lists the payments it made. if let rail = channelFreeRail ?? channelFreePaymentHistory { // A restored wallet fills its list on its first sync, so before a sync reaches Spark a missing send proves @@ -2728,6 +2742,7 @@ extension LightningService { let heldBefore = railSendHolds let unsettledBefore = await unsettledUncertainRailSends() let kept = unexpiredRailAttempts() + let refusedBefore = includingRefusedSends ? await unsyncedRailSendRefusals() : [] 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) @@ -2761,7 +2776,12 @@ extension LightningService { let listed = Set((payments + unsettled + heldDuringRead).filter { $0.direction == .outbound }.map { $0.paymentHash.lowercased() }) let unlisted = kept.subtracting(listed).sorted() .map { ChannelFreeRailPayment(paymentHash: $0, direction: .outbound, status: .pending, preimage: nil) } - return payments + unsettled + heldDuringRead + unlisted + // Not over an earlier attempt's failure, which a transfer the refused send committed may still follow. + let pendingOrPaid = Set((payments.filter { $0.status != .failed } + unsettled + heldDuringRead + unlisted) + .filter { $0.direction == .outbound }.map { $0.paymentHash.lowercased() }) + let refused = refusedBefore.subtracting(pendingOrPaid).sorted() + .map { ChannelFreeRailPayment(paymentHash: $0, direction: .outbound, status: .pending, preimage: nil) } + return payments + unsettled + heldDuringRead + unlisted + refused } if await channelFreeRailSupported() { throw ChannelFreeRailUnavailable() diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 93d19afcf..aa6d8ae3c 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1927,6 +1927,20 @@ extension ChannelFreeRailTests { service.endLdkSend(paymentHash: hash) } + func testASparkSendRefusedAfterALeafFailureReadsPendingOverAnEarlierFailureUntilSparkSyncs() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + try await refuseASparkSendAfterALeafFailure() + rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil)] + rail.syncedAfter = { $0 == nil } + + let held = try await Bitkit.LightningService.shared.channelFreeRailPayments() + XCTAssertEqual(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(held, paymentHash: hash)?.status, .pending) + + rail.syncedAfter = { _ in true } + let synced = try await Bitkit.LightningService.shared.channelFreeRailPayments() + XCTAssertEqual(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(synced, paymentHash: hash)?.status, .failed) + } + func testASparkRetryOfASendRefusedAfterALeafFailureGoesOutBeforeSparkSyncs() async throws { try await refuseASparkSendAfterALeafFailure() // Synced once, so Spark lists its payments, but not since the refusal. From 45950e286cdbf05d86aae54aeae560ddb4205e18 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 15:04:55 +0100 Subject: [PATCH 09/23] fix: refuse a spark send whose payment comes back failed Under a key Spark already failed, as when its failed list couldn't be read, Spark returns that failure and sends nothing, so the send is refused instead of read as submitted. Verified: SparkSendKeyTests on the simulator --- Bitkit/Managers/SparkManager.swift | 8 ++++++++ BitkitTests/SparkSendKeyTests.swift | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 525424125..0609d0df9 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -744,9 +744,17 @@ final class SparkManager: ChannelFreeLightningRail { throw refusal } Logger.info("Sent Spark payment '\(response.payment.id)' with status '\(response.payment.status)'", context: "SparkManager") + try Self.checkSentPayment(response.payment.status) return invoiceDetails.paymentHash } + /// A failed payment, as Spark returns under a key it already failed when its failed list couldn't be read to move + /// past it, paid nothing, so the send is refused instead of read as submitted. + nonisolated static func checkSentPayment(_ status: BreezSdkSpark.PaymentStatus) throws { + guard status == .failed else { return } + throw ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description")) + } + nonisolated static func checkSendFee(_ feeSats: UInt64, maxFeeSats: UInt64?) throws { guard let maxFeeSats, feeSats > maxFeeSats else { return } Logger.info("Spark fee of \(feeSats) sats exceeds the limit of \(maxFeeSats) sats", context: "SparkManager") diff --git a/BitkitTests/SparkSendKeyTests.swift b/BitkitTests/SparkSendKeyTests.swift index 4c2ebe434..d9528a9fa 100644 --- a/BitkitTests/SparkSendKeyTests.swift +++ b/BitkitTests/SparkSendKeyTests.swift @@ -93,6 +93,14 @@ final class SparkSendKeyTests: XCTestCase { XCTAssertTrue((fresh as? Bitkit.ChannelFreeRailSendRefused)?.mayHaveReachedSpark == true, "\(fresh)") } + func testAFailedPaymentSparkReturnsIsRefused() { + XCTAssertThrowsError(try Bitkit.SparkManager.checkSentPayment(.failed)) { + XCTAssertTrue($0 is Bitkit.ChannelFreeRailSendRefused, "\($0)") + } + XCTAssertNoThrow(try Bitkit.SparkManager.checkSentPayment(.pending)) + XCTAssertNoThrow(try Bitkit.SparkManager.checkSentPayment(.completed)) + } + func testASendRetriesWhileSparkCantSelectItsLeaves() async throws { var sends = 0 From 05cf2c1b2a44ee4caa9a258f708f26690eec39c0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 16:00:06 +0100 Subject: [PATCH 10/23] fix: keep the node off a refused spark send until its invoice expires A transfer the refused send committed can stay unlisted after a sync and still go out, so the refusal holds the node, a move to Spark ahead of a send and the rail's list until the invoice expires. A refusal made while the list is read counts too, and an invoice that expires during a leaf-selection retry ends it with the leaf failure. Verified: ChannelFreeRailTests, SparkSendKeyTests, QuickPayPaymentCoordinatorTests, PaykitPaymentProofServiceTests and MoveToSparkManagerTests on the simulator --- Bitkit/Managers/SparkManager.swift | 6 +- Bitkit/Services/LightningService.swift | 77 +++++++++----------------- BitkitTests/ChannelFreeRailTests.swift | 33 +++++++---- BitkitTests/SparkSendKeyTests.swift | 17 ++++++ 4 files changed, 71 insertions(+), 62 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 0609d0df9..6717cf653 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -793,7 +793,8 @@ final class SparkManager: ChannelFreeLightningRail { /// Sends again under the same key while Spark can't select the leaves to spend, as right after a move to Spark lands. /// Spark selects them before anything reaches the operators, so a retry under the key can't pay twice. `canRetry` - /// is checked before each retry, which otherwise ends with the last failure. + /// is checked before each retry, which otherwise ends with the last failure. An invoice that expires meanwhile ends it + /// with the leaf failure, which may follow a committed transfer, so its expiry never reads as a send that never left. nonisolated static func sendRetryingLeafSelection( retryDelay: Duration = .seconds(2), canRetry: () -> Bool, @@ -804,6 +805,9 @@ final class SparkManager: ChannelFreeLightningRail { do { return try await send() } catch { + if retries > 0, expiredInvoiceRefusal(error) != nil { + throw SdkError.SparkError("Failed to select leaves after all retries") + } guard isLeafSelectionFailure(error), retries < leafSelectionRetries else { throw error } retries += 1 Logger.info("Retrying a Spark send as Spark could not select its leaves", context: "SparkManager") diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 24710cce8..7940cf0fa 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1621,7 +1621,8 @@ class LightningService: NodeLifecycleService { sats: UInt64?, invoiceCreatedAt: UInt64?, invoiceExpiresAt: Int?, - sendsOverRail: Bool = false + sendsOverRail: Bool = false, + skipsRefusedSends: Bool? = nil ) async throws -> PaymentHash? { guard let paymentHash else { return nil } var statuses: [PaymentStatus] = rails.contains(.channelFree) && isRailSendInFlight(paymentHash: paymentHash) ? [.pending] : [] @@ -1652,11 +1653,13 @@ class LightningService: NodeLifecycleService { // The node's paid row is final, so no uncertainty about Spark's pre-restore sends refuses it. let isPaidOverTheNode = statuses.contains(.succeeded) if rails.contains(.channelFree) { - // Read before the list, so a list read after the sync shows any transfer the refused send committed. A retry - // over Spark sends under that send's key, so only the node waits. - let refusal = sendsOverRail ? nil : await railSendRefusal(paymentHash: paymentHash) - if refusal?.isSynced == false { - Logger.info("Held '\(paymentHash)' until Spark syncs after its refused send", context: "LightningService") + // A transfer the refused send committed can stay unlisted after a sync and still go out, so it holds the + // invoice until it expires. A retry over Spark sends under that send's key, so only the node waits. + let isRefused = !(skipsRefusedSends ?? sendsOverRail) && eventCallbackLock.withLock { + hasRailSendRefusal(paymentHash: paymentHash.lowercased()) + } + if isRefused { + Logger.info("Held '\(paymentHash)' until it expires after its refused Spark send", context: "LightningService") statuses.append(.pending) } let mark = attemptMark @@ -1664,10 +1667,6 @@ class LightningService: NodeLifecycleService { if let payments = await readableRailPayments(includingRefusedSends: false) { let live = keepRailAttempts(from: payments, since: mark) let payment = ChannelFreeRailPayment.latestOutboundAttempt(payments, paymentHash: paymentHash) - // A transfer the refused send committed keeps the marker, which holds the invoice when Spark can't list. - if let refusal, refusal.isSynced, payment == nil || payment?.status == .failed { - endRailSendRefusal(paymentHash: paymentHash, refusedAt: refusal.refusedAt) - } if let payment { statuses.append(payment.status) } @@ -1691,7 +1690,7 @@ class LightningService: NodeLifecycleService { // Only a settled row ends the unknown send: a pending one may be the synthetic row it is listed as. endRailSendUncertainty(paymentHash: paymentHash) } - } else if refusal != nil || hasRailAttempt(paymentHash: paymentHash) { + } else if isRefused || hasRailAttempt(paymentHash: paymentHash) { Logger.warn("Refused paying '\(paymentHash)', Spark can't list the earlier attempt now", context: "LightningService") throw Self.pendingDuplicate(paymentHash: paymentHash) } else if isPaidOverTheNode { @@ -1942,8 +1941,8 @@ class LightningService: NodeLifecycleService { } /// Keeps the node off the invoice of a Spark send refused after it may have reached Spark's operators, which may - /// still have committed a transfer, until Spark syncs. Drops the refusals whose invoice expired, which the node can no - /// longer pay. + /// still have committed a transfer, until the invoice expires. Drops the refusals whose invoice expired, which the node + /// can no longer pay. private func noteRailSendRefused(paymentHash: String, expiresAt: Int?) { let now = Int(max(0, now().timeIntervalSince1970)) eventCallbackLock.withLock { @@ -1953,43 +1952,15 @@ class LightningService: NodeLifecycleService { } } - /// When the Spark send of an unexpired invoice was refused after it may have reached Spark's operators, and whether - /// Spark synced since, so its list shows any transfer the send committed. - private func railSendRefusal(paymentHash: String) async -> (refusedAt: Int, isSynced: Bool)? { - let nowSeconds = Int(now().timeIntervalSince1970) - let refusal = eventCallbackLock.withLock { refusedRailSends()[paymentHash.lowercased()] } - guard let refusal, refusal.count == 2, refusal[1] > nowSeconds else { return nil } - let rail = channelFreeRail ?? channelFreePaymentHistory - let isSynced = await rail?.hasSynced(after: UInt64(max(0, refusal[0]))) ?? false - return (refusal[0], isSynced) - } - - /// Callers hold `eventCallbackLock`. A refused Spark send of an unexpired invoice that no check ended yet. + /// Callers hold `eventCallbackLock`. A Spark send of an unexpired invoice refused after it may have reached Spark's + /// operators. private func hasRailSendRefusal(paymentHash hash: String) -> Bool { refusedRailSends()[hash].map { $0.count == 2 && $0[1] > Int(now().timeIntervalSince1970) } ?? false } - /// The refused Spark sends of unexpired invoices that no sync reached Spark since. - private func unsyncedRailSendRefusals() async -> Set { - let hashes = eventCallbackLock.withLock { Array(refusedRailSends().keys) } - var unsynced = Set() - for hash in hashes { - if let refusal = await railSendRefusal(paymentHash: hash), !refusal.isSynced { - unsynced.insert(hash) - } - } - return unsynced - } - - /// Ends the refusal made at `refusedAt` only, as a later one waits for its own sync. - private func endRailSendRefusal(paymentHash: String, refusedAt: Int) { - let hash = paymentHash.lowercased() - eventCallbackLock.withLock { - var refused = refusedRailSends() - guard refused[hash]?.first == refusedAt else { return } - refused.removeValue(forKey: hash) - railAttemptsStore.set(refused, forKey: Self.refusedRailSendsKey) - } + /// The Spark sends of unexpired invoices refused after they may have reached Spark's operators. + private func unexpiredRailSendRefusals() -> Set { + eventCallbackLock.withLock { Set(refusedRailSends().keys.filter { hasRailSendRefusal(paymentHash: $0) }) } } /// True unless the hash's last rail send failed after it was submitted and may still go out: its invoice hasn't @@ -2035,7 +2006,9 @@ class LightningService: NodeLifecycleService { sats: sats, invoiceCreatedAt: invoice?.secondsSinceEpoch(), invoiceExpiresAt: expiresAt, - sendsOverRail: true + sendsOverRail: true, + // A move to Spark ahead of a send must not run while a refused send may still have paid the invoice. + skipsRefusedSends: false ) != nil } @@ -2728,8 +2701,8 @@ extension LightningService { /// The rail's Lightning payments, none where the rail doesn't run; throws when the rail could not list them, runs /// here but isn't connected, or no sync has reached it yet, so a payment it may hold is never read as one it never - /// made. A refused send that may have reached Spark's operators reads pending until a sync reached Spark since, - /// unless `includingRefusedSends` is false. + /// made. A refused send that may have reached Spark's operators reads pending until its invoice expires, unless + /// `includingRefusedSends` is false. func channelFreeRailPayments(includingRefusedSends: Bool = true) async throws -> [ChannelFreeRailPayment] { // During an emergency exit Spark is off the rail but still lists the payments it made. if let rail = channelFreeRail ?? channelFreePaymentHistory { @@ -2742,7 +2715,7 @@ extension LightningService { let heldBefore = railSendHolds let unsettledBefore = await unsettledUncertainRailSends() let kept = unexpiredRailAttempts() - let refusedBefore = includingRefusedSends ? await unsyncedRailSendRefusals() : [] + let refusedBefore = includingRefusedSends ? unexpiredRailSendRefusals() : [] 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) @@ -2779,7 +2752,9 @@ extension LightningService { // Not over an earlier attempt's failure, which a transfer the refused send committed may still follow. let pendingOrPaid = Set((payments.filter { $0.status != .failed } + unsettled + heldDuringRead + unlisted) .filter { $0.direction == .outbound }.map { $0.paymentHash.lowercased() }) - let refused = refusedBefore.subtracting(pendingOrPaid).sorted() + // Also a send refused while the list was read, whose holds ended meanwhile. + let refusedDuringRead = includingRefusedSends ? unexpiredRailSendRefusals() : [] + let refused = refusedBefore.union(refusedDuringRead).subtracting(pendingOrPaid).sorted() .map { ChannelFreeRailPayment(paymentHash: $0, direction: .outbound, status: .pending, preimage: nil) } return payments + unsettled + heldDuringRead + unlisted + refused } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index aa6d8ae3c..14e69522b 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1878,21 +1878,19 @@ extension ChannelFreeRailTests { XCTAssertTrue(payments.contains { $0.status == .pending }, "the retry read as A's failure") } - func testASparkSendRefusedAfterALeafFailureKeepsTheNodeOffUntilSparkSyncs() async throws { + func testASparkSendRefusedAfterALeafFailureKeepsTheNodeOffUntilItExpires() async throws { try await refuseASparkSendAfterALeafFailure() rail.balanceSats = 0 - // The SDK may have selected leaves again after a committed transfer, which Spark lists only once it syncs. + // The SDK may have selected leaves again after a committed transfer, which can stay unlisted after a sync. rail.syncedAfter = { $0 == nil } await assertRefusedAsDuplicate() - // Synced, but a list Spark can't read shows nothing of the transfer. rail.syncedAfter = { _ in true } - rail.listError = NSError(domain: "spark list", code: 1) await assertRefusedAsDuplicate() - rail.listError = nil - await assertReachesTheNode() + rail.listError = NSError(domain: "spark list", code: 1) + await assertRefusedAsDuplicate() } func testASparkSendRefusedAfterALeafFailureThatSparkListsPendingKeepsTheNodeOffWhileSparkCantList() async throws { @@ -1927,20 +1925,35 @@ extension ChannelFreeRailTests { service.endLdkSend(paymentHash: hash) } - func testASparkSendRefusedAfterALeafFailureReadsPendingOverAnEarlierFailureUntilSparkSyncs() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + func testASparkSendRefusedAfterALeafFailureReadsPendingOverAnEarlierFailureUntilItExpires() async throws { + let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) + let hash = String(invoice.paymentHash()) try await refuseASparkSendAfterALeafFailure() rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil)] - rail.syncedAfter = { $0 == nil } + rail.syncedAfter = { _ in true } let held = try await Bitkit.LightningService.shared.channelFreeRailPayments() XCTAssertEqual(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(held, paymentHash: hash)?.status, .pending) - rail.syncedAfter = { _ in true } + Bitkit.LightningService.shared.now = { + Date(timeIntervalSince1970: TimeInterval(invoice.secondsSinceEpoch() + invoice.expiryTimeSeconds())) + } let synced = try await Bitkit.LightningService.shared.channelFreeRailPayments() XCTAssertEqual(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(synced, paymentHash: hash)?.status, .failed) } + func testAMoveToSparkForASendRefusedAfterALeafFailureWaitsUntilSparkSyncs() async throws { + try await refuseASparkSendAfterALeafFailure() + rail.syncedAfter = { $0 == nil } + + do { + _ = try await Bitkit.LightningService.shared.hasSettledEarlierAttempt(bolt11: Self.invoice, sats: nil) + XCTFail("Expected the move to wait for Spark's sync") + } catch { + XCTAssertTrue(PrivatePaykitService.isDuplicatePaymentError(error), "\(error)") + } + } + func testASparkRetryOfASendRefusedAfterALeafFailureGoesOutBeforeSparkSyncs() async throws { try await refuseASparkSendAfterALeafFailure() // Synced once, so Spark lists its payments, but not since the refusal. diff --git a/BitkitTests/SparkSendKeyTests.swift b/BitkitTests/SparkSendKeyTests.swift index d9528a9fa..495d88e89 100644 --- a/BitkitTests/SparkSendKeyTests.swift +++ b/BitkitTests/SparkSendKeyTests.swift @@ -101,6 +101,23 @@ final class SparkSendKeyTests: XCTestCase { XCTAssertNoThrow(try Bitkit.SparkManager.checkSentPayment(.completed)) } + func testAnInvoiceExpiringDuringALeafRetryEndsWithTheLeafFailure() async { + var sends = 0 + + do { + _ = try await Bitkit.SparkManager.sendRetryingLeafSelection(retryDelay: .zero, canRetry: { true }) { + sends += 1 + if sends == 1 { + throw leafSelectionFailure + } + throw SdkError.InvalidInput("invoice has expired") + } + XCTFail("Expected the send to fail") + } catch { + XCTAssertTrue(Bitkit.SparkManager.isLeafSelectionFailure(error), "\(error)") + } + } + func testASendRetriesWhileSparkCantSelectItsLeaves() async throws { var sends = 0 From 87e5a6d546ea7cf8f686e80140dae05c9ba378ed Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 16:11:20 +0100 Subject: [PATCH 11/23] fix: refuse a node send of an invoice a refused spark send may still pay Until the invoice expires the node send is refused with a refusal that may have reached Spark, instead of held pending with no event to resolve it, unless an earlier send reads pending or paid. Verified: none (ChannelFreeRailTests run next) --- Bitkit/Services/LightningService.swift | 25 +++++++++++++++++-------- BitkitTests/ChannelFreeRailTests.swift | 25 ++++++++++++++++++------- 2 files changed, 35 insertions(+), 15 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 7940cf0fa..79ba1f533 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1652,16 +1652,15 @@ class LightningService: NodeLifecycleService { } // The node's paid row is final, so no uncertainty about Spark's pre-restore sends refuses it. let isPaidOverTheNode = statuses.contains(.succeeded) + var isRefused = false if rails.contains(.channelFree) { - // A transfer the refused send committed can stay unlisted after a sync and still go out, so it holds the - // invoice until it expires. A retry over Spark sends under that send's key, so only the node waits. - let isRefused = !(skipsRefusedSends ?? sendsOverRail) && eventCallbackLock.withLock { + // A transfer the refused send committed can stay unlisted after a sync and still go out, so it keeps the + // node off the invoice until it expires. A retry over Spark sends under that send's key, so only the node + // is refused, unless an earlier send reads pending or paid: a refusal, not a pending send no event would + // resolve. + isRefused = !(skipsRefusedSends ?? sendsOverRail) && eventCallbackLock.withLock { hasRailSendRefusal(paymentHash: paymentHash.lowercased()) } - if isRefused { - Logger.info("Held '\(paymentHash)' until it expires after its refused Spark send", context: "LightningService") - statuses.append(.pending) - } let mark = attemptMark // The refusal is checked above for the node, and a Spark retry sends under the refused send's key. if let payments = await readableRailPayments(includingRefusedSends: false) { @@ -1690,7 +1689,9 @@ class LightningService: NodeLifecycleService { // Only a settled row ends the unknown send: a pending one may be the synthetic row it is listed as. endRailSendUncertainty(paymentHash: paymentHash) } - } else if isRefused || hasRailAttempt(paymentHash: paymentHash) { + } else if isRefused { + throw Self.refusedAfterSparkSend(paymentHash: paymentHash) + } else if hasRailAttempt(paymentHash: paymentHash) { Logger.warn("Refused paying '\(paymentHash)', Spark can't list the earlier attempt now", context: "LightningService") throw Self.pendingDuplicate(paymentHash: paymentHash) } else if isPaidOverTheNode { @@ -1718,6 +1719,9 @@ class LightningService: NodeLifecycleService { Logger.info("Refused paying '\(paymentHash)', an earlier attempt is still pending", context: "LightningService") throw Self.pendingDuplicate(paymentHash: paymentHash) } + if isRefused { + throw Self.refusedAfterSparkSend(paymentHash: paymentHash) + } return nil } @@ -2012,6 +2016,11 @@ class LightningService: NodeLifecycleService { ) != nil } + private static func refusedAfterSparkSend(paymentHash: String) -> ChannelFreeRailSendRefused { + Logger.info("Refused paying '\(paymentHash)' until it expires after its refused Spark send", context: "LightningService") + return ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description"), mayHaveReachedSpark: true) + } + 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 14e69522b..e0dc1ab58 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1884,13 +1884,13 @@ extension ChannelFreeRailTests { // The SDK may have selected leaves again after a committed transfer, which can stay unlisted after a sync. rail.syncedAfter = { $0 == nil } - await assertRefusedAsDuplicate() + await assertRefusedAfterASparkSend() rail.syncedAfter = { _ in true } - await assertRefusedAsDuplicate() + await assertRefusedAfterASparkSend() rail.listError = NSError(domain: "spark list", code: 1) - await assertRefusedAsDuplicate() + await assertRefusedAfterASparkSend() } func testASparkSendRefusedAfterALeafFailureThatSparkListsPendingKeepsTheNodeOffWhileSparkCantList() async throws { @@ -1904,7 +1904,7 @@ extension ChannelFreeRailTests { // The transfer the refused send committed keeps its refusal, so a list Spark can't read still holds the node. rail.payments = [] rail.listError = NSError(domain: "spark list", code: 1) - await assertRefusedAsDuplicate() + await assertRefusedAfterASparkSend() } func testANodeSendAdmittedAfterASparkSendWasRefusedAfterALeafFailureIsRefusedUntilTheInvoiceExpires() async throws { @@ -1942,15 +1942,15 @@ extension ChannelFreeRailTests { XCTAssertEqual(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(synced, paymentHash: hash)?.status, .failed) } - func testAMoveToSparkForASendRefusedAfterALeafFailureWaitsUntilSparkSyncs() async throws { + func testAMoveToSparkForASendRefusedAfterALeafFailureIsRefusedUntilItExpires() async throws { try await refuseASparkSendAfterALeafFailure() rail.syncedAfter = { $0 == nil } do { _ = try await Bitkit.LightningService.shared.hasSettledEarlierAttempt(bolt11: Self.invoice, sats: nil) - XCTFail("Expected the move to wait for Spark's sync") + XCTFail("Expected the move to be refused") } catch { - XCTAssertTrue(PrivatePaykitService.isDuplicatePaymentError(error), "\(error)") + XCTAssertEqual((error as? Bitkit.ChannelFreeRailSendRefused)?.mayHaveReachedSpark, true, "\(error)") } } @@ -2133,6 +2133,17 @@ extension ChannelFreeRailTests { rail.sentBolt11 = nil } + private func assertRefusedAfterASparkSend(file: StaticString = #filePath, line: UInt = #line) async { + do { + _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + XCTFail("Expected the send to be refused", file: file, line: line) + } catch { + let refusal = error as? Bitkit.ChannelFreeRailSendRefused + XCTAssertEqual(refusal?.mayHaveReachedSpark, true, "\(error)", file: file, line: line) + } + XCTAssertNil(rail.sentBolt11, file: file, line: line) + } + private func assertRefusedAsDuplicate(file: StaticString = #filePath, line: UInt = #line) async { do { _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) From a7f3a67d367cae4ca27ab8d7e85ef9be6254298a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 16:12:08 +0100 Subject: [PATCH 12/23] fix: keep a refused spark send pending until a sync after its invoice expires A transfer committed before the expiry can settle after it, so the rail's list reads the refused send pending until Spark syncs past the expiry. A refusal noted while the earlier-attempt check reads Spark's list also counts. Verified: none (ChannelFreeRailTests run next) --- Bitkit/Managers/SparkManager.swift | 2 +- Bitkit/Services/LightningService.swift | 49 ++++++++++++++++++++------ BitkitTests/ChannelFreeRailTests.swift | 13 ++++--- 3 files changed, 49 insertions(+), 15 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 6717cf653..c4a6cedb4 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -770,7 +770,7 @@ final class SparkManager: ChannelFreeLightningRail { /// What a failure inside the BOLT11 `sendPayment` means for the caller. Spark picks the leaves to spend before the /// operators see the key on its first try, so a short balance or leaves Spark can't select are refused under a new - /// key; its retry of a failed submission selects them again, so the node stays off the invoice until Spark syncs. + /// key; its retry of a failed submission selects them again, so the node stays off the invoice until it expires. /// Under a key an earlier attempt used, either can hide the transfer that attempt committed: the send stays in doubt /// until Spark syncs, rather than refused. nonisolated static func bolt11SendFailure(_ error: Error, isReusedKey: Bool) -> Error { diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 79ba1f533..0647c30fc 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -65,7 +65,7 @@ struct ChannelFreeRailSendRefused: LocalizedError { /// A still-valid invoice created before the restore, as Spark can't show it didn't pay it then. var isRestoredInvoiceUnverified = false /// Refused after the SDK may have reached Spark's operators, as its retry of a failed submission selects leaves - /// again: the node stays off the invoice until Spark syncs. + /// again: the node stays off the invoice until it expires. var mayHaveReachedSpark = false static func restoredInvoiceUnverified() -> ChannelFreeRailSendRefused { @@ -1663,7 +1663,12 @@ class LightningService: NodeLifecycleService { } let mark = attemptMark // The refusal is checked above for the node, and a Spark retry sends under the refused send's key. - if let payments = await readableRailPayments(includingRefusedSends: false) { + let payments = await readableRailPayments(includingRefusedSends: false) + // A Spark send refused while the list was read keeps the node off the invoice too. + isRefused = isRefused || !(skipsRefusedSends ?? sendsOverRail) && eventCallbackLock.withLock { + hasRailSendRefusal(paymentHash: paymentHash.lowercased()) + } + if let payments { let live = keepRailAttempts(from: payments, since: mark) let payment = ChannelFreeRailPayment.latestOutboundAttempt(payments, paymentHash: paymentHash) if let payment { @@ -1945,12 +1950,12 @@ class LightningService: NodeLifecycleService { } /// Keeps the node off the invoice of a Spark send refused after it may have reached Spark's operators, which may - /// still have committed a transfer, until the invoice expires. Drops the refusals whose invoice expired, which the node - /// can no longer pay. + /// still have committed a transfer, until the invoice expires. The rail's list reads it pending until a sync after + /// that, which drops it. private func noteRailSendRefused(paymentHash: String, expiresAt: Int?) { let now = Int(max(0, now().timeIntervalSince1970)) eventCallbackLock.withLock { - var refused = refusedRailSends().filter { $0.value.count == 2 && $0.value[1] > now } + var refused = refusedRailSends().filter { $0.value.count == 2 } refused[paymentHash.lowercased()] = [now, expiresAt ?? .max] railAttemptsStore.set(refused, forKey: Self.refusedRailSendsKey) } @@ -1962,9 +1967,33 @@ class LightningService: NodeLifecycleService { refusedRailSends()[hash].map { $0.count == 2 && $0[1] > Int(now().timeIntervalSince1970) } ?? false } - /// The Spark sends of unexpired invoices refused after they may have reached Spark's operators. - private func unexpiredRailSendRefusals() -> Set { - eventCallbackLock.withLock { Set(refusedRailSends().keys.filter { hasRailSendRefusal(paymentHash: $0) }) } + /// The Spark sends refused after they may have reached Spark's operators that may still settle: their invoice hasn't + /// expired, or no sync has reached Spark since it did, as a transfer committed before the expiry can settle after + /// it. Drops the others. + private func unsettledRailSendRefusals() async -> Set { + let now = Int(max(0, now().timeIntervalSince1970)) + let refused = eventCallbackLock.withLock { refusedRailSends().filter { $0.value.count == 2 } } + var held = Set() + var settled = Set() + for (hash, times) in refused { + if times[1] > now { + held.insert(hash) + } else if let rail = channelFreeRail ?? channelFreePaymentHistory, + await !rail.hasSynced(after: UInt64(max(0, max(times[0], times[1])))) + { + held.insert(hash) + } else { + settled.insert(hash) + } + } + if !settled.isEmpty { + eventCallbackLock.withLock { + // Only the refusals read above, so one noted again meanwhile is kept. + let current = refusedRailSends().filter { !(settled.contains($0.key) && refused[$0.key] == $0.value) } + railAttemptsStore.set(current, forKey: Self.refusedRailSendsKey) + } + } + return held } /// True unless the hash's last rail send failed after it was submitted and may still go out: its invoice hasn't @@ -2724,7 +2753,7 @@ extension LightningService { let heldBefore = railSendHolds let unsettledBefore = await unsettledUncertainRailSends() let kept = unexpiredRailAttempts() - let refusedBefore = includingRefusedSends ? unexpiredRailSendRefusals() : [] + let refusedBefore = includingRefusedSends ? await unsettledRailSendRefusals() : [] 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) @@ -2762,7 +2791,7 @@ extension LightningService { let pendingOrPaid = Set((payments.filter { $0.status != .failed } + unsettled + heldDuringRead + unlisted) .filter { $0.direction == .outbound }.map { $0.paymentHash.lowercased() }) // Also a send refused while the list was read, whose holds ended meanwhile. - let refusedDuringRead = includingRefusedSends ? unexpiredRailSendRefusals() : [] + let refusedDuringRead = includingRefusedSends ? await unsettledRailSendRefusals() : [] let refused = refusedBefore.union(refusedDuringRead).subtracting(pendingOrPaid).sorted() .map { ChannelFreeRailPayment(paymentHash: $0, direction: .outbound, status: .pending, preimage: nil) } return payments + unsettled + heldDuringRead + unlisted + refused diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index e0dc1ab58..0f8a587e9 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1925,7 +1925,7 @@ extension ChannelFreeRailTests { service.endLdkSend(paymentHash: hash) } - func testASparkSendRefusedAfterALeafFailureReadsPendingOverAnEarlierFailureUntilItExpires() async throws { + func testASparkSendRefusedAfterALeafFailureReadsPendingOverAnEarlierFailureUntilASyncAfterItExpires() async throws { let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) let hash = String(invoice.paymentHash()) try await refuseASparkSendAfterALeafFailure() @@ -1935,9 +1935,14 @@ extension ChannelFreeRailTests { let held = try await Bitkit.LightningService.shared.channelFreeRailPayments() XCTAssertEqual(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(held, paymentHash: hash)?.status, .pending) - Bitkit.LightningService.shared.now = { - Date(timeIntervalSince1970: TimeInterval(invoice.secondsSinceEpoch() + invoice.expiryTimeSeconds())) - } + let expiresAt = invoice.secondsSinceEpoch() + invoice.expiryTimeSeconds() + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: TimeInterval(expiresAt)) } + // A transfer committed before the expiry can settle after it, until a sync after the expiry shows it didn't. + rail.syncedAfter = { ($0 ?? 0) < expiresAt } + let expired = try await Bitkit.LightningService.shared.channelFreeRailPayments() + XCTAssertEqual(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(expired, paymentHash: hash)?.status, .pending) + + rail.syncedAfter = { _ in true } let synced = try await Bitkit.LightningService.shared.channelFreeRailPayments() XCTAssertEqual(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(synced, paymentHash: hash)?.status, .failed) } From e4d3ce54316c284d734c02cf90f47f26633dc884 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 16:40:51 +0100 Subject: [PATCH 13/23] fix: keep a spark send in doubt when spark can't select its leaves Leaves Spark still can't select after its retries can follow a transfer the send committed, as the SDK selects them again after an operator error, so the send stays in doubt under any key until Spark settles it or its invoice expires, as any other unknown outcome does. This replaces the refusal marker, and the Paykit and QuickPay handling of a refusal that may have reached Spark, as the hold already keeps the node off the invoice and the proof, allowance and charge pending. Verified: none (suite on the simulator next) --- Bitkit/Managers/SparkManager.swift | 24 ++-- Bitkit/Services/LightningService.swift | 118 ++--------------- .../Services/PaykitPaymentProofService.swift | 6 +- .../QuickPayPaymentCoordinator.swift | 7 +- BitkitTests/ChannelFreeRailTests.swift | 119 ------------------ .../PaykitPaymentProofServiceTests.swift | 8 -- .../QuickPayPaymentCoordinatorTests.swift | 9 -- BitkitTests/SparkSendKeyTests.swift | 7 +- 8 files changed, 25 insertions(+), 273 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index c4a6cedb4..d897740cc 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -769,26 +769,18 @@ final class SparkManager: ChannelFreeLightningRail { } /// What a failure inside the BOLT11 `sendPayment` means for the caller. Spark picks the leaves to spend before the - /// operators see the key on its first try, so a short balance or leaves Spark can't select are refused under a new - /// key; its retry of a failed submission selects them again, so the node stays off the invoice until it expires. - /// Under a key an earlier attempt used, either can hide the transfer that attempt committed: the send stays in doubt - /// until Spark syncs, rather than refused. + /// operators see the key, so a short balance left nothing under a new key; under a key an earlier attempt used, it + /// can hide the transfer that attempt committed, so the send stays in doubt until Spark settles it. Leaves Spark + /// still can't select after its retries keep the send in doubt under any key, as the SDK selects them again after an + /// operator error, so the failure can follow a transfer this send committed. nonisolated static func bolt11SendFailure(_ error: Error, isReusedKey: Bool) -> Error { - let isShortBalance = if case SdkError.InsufficientFunds = error { - true - } else { - false + if isReusedKey, case SdkError.InsufficientFunds = error { + return error } - guard isShortBalance || isLeafSelectionFailure(error) else { return sendPaymentFailure(error) } - if isReusedKey { + if isLeafSelectionFailure(error) { return error } - var refusal = ChannelFreeRailSendRefused( - reason: isShortBalance ? t("other__pay_insufficient_spending_description") : t("wallet__payment_failed_description"), - underlying: error - ) - refusal.mayHaveReachedSpark = true - return refusal + return sendPaymentFailure(error) } /// Sends again under the same key while Spark can't select the leaves to spend, as right after a move to Spark lands. diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 0647c30fc..465384034 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -64,9 +64,6 @@ struct ChannelFreeRailSendRefused: LocalizedError { var underlying: Error? /// A still-valid invoice created before the restore, as Spark can't show it didn't pay it then. var isRestoredInvoiceUnverified = false - /// Refused after the SDK may have reached Spark's operators, as its retry of a failed submission selects leaves - /// again: the node stays off the invoice until it expires. - var mayHaveReachedSpark = false static func restoredInvoiceUnverified() -> ChannelFreeRailSendRefused { ChannelFreeRailSendRefused(reason: t("wallet__payment_restored_invoice"), isRestoredInvoiceUnverified: true) @@ -1243,10 +1240,6 @@ class LightningService: NodeLifecycleService { // Nothing left the wallet. Refused before submission, this send recorded nothing, so another send's // attempt and hold of the invoice stay. if let paymentHash, didRecordAttempt { - // Kept before the holds go, so no stop in between frees the invoice. - if refusal.mayHaveReachedSpark { - noteRailSendRefused(paymentHash: paymentHash, expiresAt: expiresAt) - } endRailSendUncertainty(paymentHash: paymentHash) releaseRailAttempt(paymentHash: paymentHash, unlessInFlight: false) } @@ -1335,7 +1328,6 @@ class LightningService: NodeLifecycleService { /// 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" - private static let refusedRailSendsKey = "channelFreeRailRefusedSendAt" /// 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 @@ -1532,7 +1524,6 @@ class LightningService: NodeLifecycleService { func forgetRailAttempts() { eventCallbackLock.withLock { railAttemptsStore.removeObject(forKey: Self.uncertainRailSendsKey) - railAttemptsStore.removeObject(forKey: Self.refusedRailSendsKey) railAttemptsStore.removeObject(forKey: Self.railAttemptsKey) railAttemptsStore.removeObject(forKey: Self.expiriesKey(Self.railAttemptsKey)) attemptRecordedAt[Self.railAttemptsKey] = nil @@ -1621,8 +1612,7 @@ class LightningService: NodeLifecycleService { sats: UInt64?, invoiceCreatedAt: UInt64?, invoiceExpiresAt: Int?, - sendsOverRail: Bool = false, - skipsRefusedSends: Bool? = nil + sendsOverRail: Bool = false ) async throws -> PaymentHash? { guard let paymentHash else { return nil } var statuses: [PaymentStatus] = rails.contains(.channelFree) && isRailSendInFlight(paymentHash: paymentHash) ? [.pending] : [] @@ -1652,23 +1642,9 @@ class LightningService: NodeLifecycleService { } // The node's paid row is final, so no uncertainty about Spark's pre-restore sends refuses it. let isPaidOverTheNode = statuses.contains(.succeeded) - var isRefused = false if rails.contains(.channelFree) { - // A transfer the refused send committed can stay unlisted after a sync and still go out, so it keeps the - // node off the invoice until it expires. A retry over Spark sends under that send's key, so only the node - // is refused, unless an earlier send reads pending or paid: a refusal, not a pending send no event would - // resolve. - isRefused = !(skipsRefusedSends ?? sendsOverRail) && eventCallbackLock.withLock { - hasRailSendRefusal(paymentHash: paymentHash.lowercased()) - } let mark = attemptMark - // The refusal is checked above for the node, and a Spark retry sends under the refused send's key. - let payments = await readableRailPayments(includingRefusedSends: false) - // A Spark send refused while the list was read keeps the node off the invoice too. - isRefused = isRefused || !(skipsRefusedSends ?? sendsOverRail) && eventCallbackLock.withLock { - hasRailSendRefusal(paymentHash: paymentHash.lowercased()) - } - 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 { @@ -1694,8 +1670,6 @@ class LightningService: NodeLifecycleService { // Only a settled row ends the unknown send: a pending one may be the synthetic row it is listed as. endRailSendUncertainty(paymentHash: paymentHash) } - } else if isRefused { - throw Self.refusedAfterSparkSend(paymentHash: paymentHash) } else if hasRailAttempt(paymentHash: paymentHash) { Logger.warn("Refused paying '\(paymentHash)', Spark can't list the earlier attempt now", context: "LightningService") throw Self.pendingDuplicate(paymentHash: paymentHash) @@ -1724,9 +1698,6 @@ class LightningService: NodeLifecycleService { Logger.info("Refused paying '\(paymentHash)', an earlier attempt is still pending", context: "LightningService") throw Self.pendingDuplicate(paymentHash: paymentHash) } - if isRefused { - throw Self.refusedAfterSparkSend(paymentHash: paymentHash) - } return nil } @@ -1790,8 +1761,8 @@ class LightningService: NodeLifecycleService { } /// Nil while the rail's payments can't be read: listing them failed, or the rail runs here but isn't connected. - private func readableRailPayments(includingRefusedSends: Bool = true) async -> [ChannelFreeRailPayment]? { - try? await channelFreeRailPayments(includingRefusedSends: includingRefusedSends) + private func readableRailPayments() async -> [ChannelFreeRailPayment]? { + try? await channelFreeRailPayments() } /// Callers hold `eventCallbackLock`. @@ -1943,59 +1914,6 @@ class LightningService: NodeLifecycleService { } } - /// Callers hold `eventCallbackLock`. Spark sends refused after they may have reached Spark's operators: when each - /// was refused, and its invoice's expiry. - private func refusedRailSends() -> [String: [Int]] { - railAttemptsStore.dictionary(forKey: Self.refusedRailSendsKey) as? [String: [Int]] ?? [:] - } - - /// Keeps the node off the invoice of a Spark send refused after it may have reached Spark's operators, which may - /// still have committed a transfer, until the invoice expires. The rail's list reads it pending until a sync after - /// that, which drops it. - private func noteRailSendRefused(paymentHash: String, expiresAt: Int?) { - let now = Int(max(0, now().timeIntervalSince1970)) - eventCallbackLock.withLock { - var refused = refusedRailSends().filter { $0.value.count == 2 } - refused[paymentHash.lowercased()] = [now, expiresAt ?? .max] - railAttemptsStore.set(refused, forKey: Self.refusedRailSendsKey) - } - } - - /// Callers hold `eventCallbackLock`. A Spark send of an unexpired invoice refused after it may have reached Spark's - /// operators. - private func hasRailSendRefusal(paymentHash hash: String) -> Bool { - refusedRailSends()[hash].map { $0.count == 2 && $0[1] > Int(now().timeIntervalSince1970) } ?? false - } - - /// The Spark sends refused after they may have reached Spark's operators that may still settle: their invoice hasn't - /// expired, or no sync has reached Spark since it did, as a transfer committed before the expiry can settle after - /// it. Drops the others. - private func unsettledRailSendRefusals() async -> Set { - let now = Int(max(0, now().timeIntervalSince1970)) - let refused = eventCallbackLock.withLock { refusedRailSends().filter { $0.value.count == 2 } } - var held = Set() - var settled = Set() - for (hash, times) in refused { - if times[1] > now { - held.insert(hash) - } else if let rail = channelFreeRail ?? channelFreePaymentHistory, - await !rail.hasSynced(after: UInt64(max(0, max(times[0], times[1])))) - { - held.insert(hash) - } else { - settled.insert(hash) - } - } - if !settled.isEmpty { - eventCallbackLock.withLock { - // Only the refusals read above, so one noted again meanwhile is kept. - let current = refusedRailSends().filter { !(settled.contains($0.key) && refused[$0.key] == $0.value) } - railAttemptsStore.set(current, forKey: Self.refusedRailSendsKey) - } - } - return held - } - /// True unless the hash's last rail send failed after it was submitted and may still go out: its invoice hasn't /// expired, or no sync has reached the rail since it did. private func railSyncedSinceUncertainSend(paymentHash: String) async -> Bool { @@ -2039,17 +1957,10 @@ class LightningService: NodeLifecycleService { sats: sats, invoiceCreatedAt: invoice?.secondsSinceEpoch(), invoiceExpiresAt: expiresAt, - sendsOverRail: true, - // A move to Spark ahead of a send must not run while a refused send may still have paid the invoice. - skipsRefusedSends: false + sendsOverRail: true ) != nil } - private static func refusedAfterSparkSend(paymentHash: String) -> ChannelFreeRailSendRefused { - Logger.info("Refused paying '\(paymentHash)' until it expires after its refused Spark send", context: "LightningService") - return ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description"), mayHaveReachedSpark: true) - } - private static func pendingDuplicate(paymentHash: String?) -> NodeError { .DuplicatePayment(message: "An earlier attempt to pay '\(paymentHash ?? "")' is still pending") } @@ -2076,10 +1987,6 @@ class LightningService: NodeLifecycleService { Logger.warn("Refused paying '\(hash)', Spark sent it meanwhile", context: "LightningService") throw Self.pendingDuplicate(paymentHash: hash) } - if rail == .ldk, hasRailSendRefusal(paymentHash: hash) { - Logger.warn("Refused paying '\(hash)', a Spark send of it was refused meanwhile", context: "LightningService") - throw Self.pendingDuplicate(paymentHash: hash) - } if rail == .ldk { ldkSendsInFlight[hash, default: 0] += 1 } @@ -2739,9 +2646,8 @@ extension LightningService { /// The rail's Lightning payments, none where the rail doesn't run; throws when the rail could not list them, runs /// here but isn't connected, or no sync has reached it yet, so a payment it may hold is never read as one it never - /// made. A refused send that may have reached Spark's operators reads pending until its invoice expires, unless - /// `includingRefusedSends` is false. - func channelFreeRailPayments(includingRefusedSends: Bool = true) async throws -> [ChannelFreeRailPayment] { + /// made. + func channelFreeRailPayments() async throws -> [ChannelFreeRailPayment] { // During an emergency exit Spark is off the rail but still lists the payments it made. if let rail = channelFreeRail ?? channelFreePaymentHistory { // A restored wallet fills its list on its first sync, so before a sync reaches Spark a missing send proves @@ -2753,7 +2659,6 @@ extension LightningService { let heldBefore = railSendHolds let unsettledBefore = await unsettledUncertainRailSends() let kept = unexpiredRailAttempts() - let refusedBefore = includingRefusedSends ? await unsettledRailSendRefusals() : [] 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) @@ -2787,14 +2692,7 @@ extension LightningService { let listed = Set((payments + unsettled + heldDuringRead).filter { $0.direction == .outbound }.map { $0.paymentHash.lowercased() }) let unlisted = kept.subtracting(listed).sorted() .map { ChannelFreeRailPayment(paymentHash: $0, direction: .outbound, status: .pending, preimage: nil) } - // Not over an earlier attempt's failure, which a transfer the refused send committed may still follow. - let pendingOrPaid = Set((payments.filter { $0.status != .failed } + unsettled + heldDuringRead + unlisted) - .filter { $0.direction == .outbound }.map { $0.paymentHash.lowercased() }) - // Also a send refused while the list was read, whose holds ended meanwhile. - let refusedDuringRead = includingRefusedSends ? await unsettledRailSendRefusals() : [] - let refused = refusedBefore.union(refusedDuringRead).subtracting(pendingOrPaid).sorted() - .map { ChannelFreeRailPayment(paymentHash: $0, direction: .outbound, status: .pending, preimage: nil) } - return payments + unsettled + heldDuringRead + unlisted + refused + return payments + unsettled + heldDuringRead + unlisted } if await channelFreeRailSupported() { throw ChannelFreeRailUnavailable() diff --git a/Bitkit/Services/PaykitPaymentProofService.swift b/Bitkit/Services/PaykitPaymentProofService.swift index 30e503aaa..06db47a1f 100644 --- a/Bitkit/Services/PaykitPaymentProofService.swift +++ b/Bitkit/Services/PaykitPaymentProofService.swift @@ -1385,10 +1385,8 @@ actor PaykitPaymentProofService { let underlyingError = (submissionError as? AppError)?.underlyingError ?? submissionError if underlyingError as? PaykitPaymentRequestError == .requestExpired { // The local deadline gate runs before submitting to the node. - } else if let refusal = underlyingError as? ChannelFreeRailSendRefused { - // Spark refused it before sending: not connected, not preparable, or over the fee limit. A refusal after it - // may have reached Spark's operators may still have sent it. - guard !refusal.mayHaveReachedSpark else { return false } + } else if underlyingError is ChannelFreeRailSendRefused { + // Spark refused it before sending: not connected, not preparable, or over the fee limit. } else if underlyingError is MoveToSparkError { // Any failed spending balance update happens before the invoice is paid, so nothing was sent. } else if let serviceError = underlyingError as? CustomServiceError { diff --git a/Bitkit/Utilities/QuickPayPaymentCoordinator.swift b/Bitkit/Utilities/QuickPayPaymentCoordinator.swift index f6251d237..0b410281d 100644 --- a/Bitkit/Utilities/QuickPayPaymentCoordinator.swift +++ b/Bitkit/Utilities/QuickPayPaymentCoordinator.swift @@ -201,10 +201,9 @@ final class QuickPayPaymentCoordinator { } static func isHardReject(_ error: Error) -> Bool { - // Spark refuses before anything leaves the wallet, unless the refusal came after the send may have reached its - // operators. - if let refusal = (error as? ChannelFreeRailSendRefused) ?? (error as? AppError)?.underlyingError as? ChannelFreeRailSendRefused { - return !refusal.mayHaveReachedSpark + // Spark refuses only before anything leaves the wallet. + if error is ChannelFreeRailSendRefused || (error as? AppError)?.underlyingError is ChannelFreeRailSendRefused { + return true } guard let nodeError = nodeError(from: error) else { return false diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 0f8a587e9..4ff339477 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1878,114 +1878,6 @@ extension ChannelFreeRailTests { XCTAssertTrue(payments.contains { $0.status == .pending }, "the retry read as A's failure") } - func testASparkSendRefusedAfterALeafFailureKeepsTheNodeOffUntilItExpires() async throws { - try await refuseASparkSendAfterALeafFailure() - rail.balanceSats = 0 - - // The SDK may have selected leaves again after a committed transfer, which can stay unlisted after a sync. - rail.syncedAfter = { $0 == nil } - await assertRefusedAfterASparkSend() - - rail.syncedAfter = { _ in true } - await assertRefusedAfterASparkSend() - - rail.listError = NSError(domain: "spark list", code: 1) - await assertRefusedAfterASparkSend() - } - - func testASparkSendRefusedAfterALeafFailureThatSparkListsPendingKeepsTheNodeOffWhileSparkCantList() async throws { - let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) - try await refuseASparkSendAfterALeafFailure() - rail.balanceSats = 0 - rail.syncedAfter = { _ in true } - rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .pending, preimage: nil)] - await assertRefusedAsDuplicate() - - // The transfer the refused send committed keeps its refusal, so a list Spark can't read still holds the node. - rail.payments = [] - rail.listError = NSError(domain: "spark list", code: 1) - await assertRefusedAfterASparkSend() - } - - func testANodeSendAdmittedAfterASparkSendWasRefusedAfterALeafFailureIsRefusedUntilTheInvoiceExpires() async throws { - let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) - let hash = String(invoice.paymentHash()) - let service = Bitkit.LightningService.shared - // The node send passed its checks before the Spark send was refused. - let mark = service.attemptMark - try await refuseASparkSendAfterALeafFailure() - - XCTAssertThrowsError(try service.admitSend(paymentHash: hash, on: .ldk, since: mark)) { - XCTAssertTrue(PrivatePaykitService.isDuplicatePaymentError($0), "\($0)") - } - - // Once the invoice expired, no node send can pay it. - service.now = { Date(timeIntervalSince1970: TimeInterval(invoice.secondsSinceEpoch() + invoice.expiryTimeSeconds())) } - XCTAssertNoThrow(try service.admitSend(paymentHash: hash, on: .ldk, since: service.attemptMark)) - service.endLdkSend(paymentHash: hash) - } - - func testASparkSendRefusedAfterALeafFailureReadsPendingOverAnEarlierFailureUntilASyncAfterItExpires() async throws { - let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) - let hash = String(invoice.paymentHash()) - try await refuseASparkSendAfterALeafFailure() - rail.payments = [Bitkit.ChannelFreeRailPayment(paymentHash: hash, direction: .outbound, status: .failed, preimage: nil)] - rail.syncedAfter = { _ in true } - - let held = try await Bitkit.LightningService.shared.channelFreeRailPayments() - XCTAssertEqual(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(held, paymentHash: hash)?.status, .pending) - - let expiresAt = invoice.secondsSinceEpoch() + invoice.expiryTimeSeconds() - Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: TimeInterval(expiresAt)) } - // A transfer committed before the expiry can settle after it, until a sync after the expiry shows it didn't. - rail.syncedAfter = { ($0 ?? 0) < expiresAt } - let expired = try await Bitkit.LightningService.shared.channelFreeRailPayments() - XCTAssertEqual(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(expired, paymentHash: hash)?.status, .pending) - - rail.syncedAfter = { _ in true } - let synced = try await Bitkit.LightningService.shared.channelFreeRailPayments() - XCTAssertEqual(Bitkit.ChannelFreeRailPayment.latestOutboundAttempt(synced, paymentHash: hash)?.status, .failed) - } - - func testAMoveToSparkForASendRefusedAfterALeafFailureIsRefusedUntilItExpires() async throws { - try await refuseASparkSendAfterALeafFailure() - rail.syncedAfter = { $0 == nil } - - do { - _ = try await Bitkit.LightningService.shared.hasSettledEarlierAttempt(bolt11: Self.invoice, sats: nil) - XCTFail("Expected the move to be refused") - } catch { - XCTAssertEqual((error as? Bitkit.ChannelFreeRailSendRefused)?.mayHaveReachedSpark, true, "\(error)") - } - } - - func testASparkRetryOfASendRefusedAfterALeafFailureGoesOutBeforeSparkSyncs() async throws { - try await refuseASparkSendAfterALeafFailure() - // Synced once, so Spark lists its payments, but not since the refusal. - rail.syncedAfter = { $0 == nil } - - _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) - - XCTAssertEqual(rail.sends, 1) - } - - /// Refuses a Spark send of `invoice`, before its expiry, after it may have reached Spark's operators. - private func refuseASparkSendAfterALeafFailure() async throws { - let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) - Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: TimeInterval(invoice.secondsSinceEpoch())) } - rail.balanceSats = 100_000 - var refusal = Bitkit.ChannelFreeRailSendRefused(reason: "leaves") - refusal.mayHaveReachedSpark = true - rail.refusalAfterSubmission = refusal - 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)") - } - rail.refusalAfterSubmission = nil - } - func testASparkSendCheckedAgainBeforeARetryGoesOut() async throws { rail.balanceSats = 100_000 rail.submissionChecks = 2 @@ -2138,17 +2030,6 @@ extension ChannelFreeRailTests { rail.sentBolt11 = nil } - private func assertRefusedAfterASparkSend(file: StaticString = #filePath, line: UInt = #line) async { - do { - _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) - XCTFail("Expected the send to be refused", file: file, line: line) - } catch { - let refusal = error as? Bitkit.ChannelFreeRailSendRefused - XCTAssertEqual(refusal?.mayHaveReachedSpark, true, "\(error)", file: file, line: line) - } - XCTAssertNil(rail.sentBolt11, file: file, line: line) - } - private func assertRefusedAsDuplicate(file: StaticString = #filePath, line: UInt = #line) async { do { _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) diff --git a/BitkitTests/PaykitPaymentProofServiceTests.swift b/BitkitTests/PaykitPaymentProofServiceTests.swift index 7881308c7..5552f93fa 100644 --- a/BitkitTests/PaykitPaymentProofServiceTests.swift +++ b/BitkitTests/PaykitPaymentProofServiceTests.swift @@ -1727,7 +1727,6 @@ final class PaykitPaymentProofServiceTests: XCTestCase { Bitkit.AppError(error: NodeError.PersistenceFailed(message: "io")), NodeError.DuplicatePayment(message: "pending"), NSError(domain: "payment", code: 1), - Bitkit.AppError(error: Self.refusalAfterReachingSpark), ] for error in errors { let record = try paymentRequestRecord() @@ -1769,13 +1768,6 @@ final class PaykitPaymentProofServiceTests: XCTestCase { } } - /// A Spark refusal after the send may have reached Spark's operators, which may still have sent it. - private static var refusalAfterReachingSpark: Bitkit.ChannelFreeRailSendRefused { - var refusal = Bitkit.ChannelFreeRailSendRefused(reason: "Spark could not select leaves") - refusal.mayHaveReachedSpark = true - return refusal - } - func testDefiniteLightningSubmissionFailureClearsProof() async throws { let errors: [Error] = [ PaykitPaymentRequestError.requestExpired, diff --git a/BitkitTests/QuickPayPaymentCoordinatorTests.swift b/BitkitTests/QuickPayPaymentCoordinatorTests.swift index c6fdf9b88..84c88208b 100644 --- a/BitkitTests/QuickPayPaymentCoordinatorTests.swift +++ b/BitkitTests/QuickPayPaymentCoordinatorTests.swift @@ -53,15 +53,6 @@ final class QuickPayPaymentCoordinatorTests: XCTestCase { XCTAssertFalse(QuickPayPaymentCoordinator.isHardReject(NodeError.DuplicatePayment(message: "dup"))) } - func testASparkRefusalAfterTheSendMayHaveReachedSparkIsNotHardReject() { - var refusal = Bitkit.ChannelFreeRailSendRefused(reason: "leaves") - XCTAssertTrue(QuickPayPaymentCoordinator.isHardReject(refusal)) - - refusal.mayHaveReachedSpark = true - XCTAssertFalse(QuickPayPaymentCoordinator.isHardReject(refusal)) - XCTAssertFalse(QuickPayPaymentCoordinator.isHardReject(Bitkit.AppError(error: refusal))) - } - func testInvalidInvoiceIsHardReject() { XCTAssertTrue(QuickPayPaymentCoordinator.isHardReject(NodeError.InvalidInvoice(message: "bad"))) } diff --git a/BitkitTests/SparkSendKeyTests.swift b/BitkitTests/SparkSendKeyTests.swift index 495d88e89..6dc121959 100644 --- a/BitkitTests/SparkSendKeyTests.swift +++ b/BitkitTests/SparkSendKeyTests.swift @@ -82,15 +82,16 @@ final class SparkSendKeyTests: XCTestCase { let fresh = Bitkit.SparkManager.bolt11SendFailure(shortBalance, isReusedKey: false) XCTAssertFalse(reused is Bitkit.ChannelFreeRailSendRefused, "\(reused)") - XCTAssertTrue((fresh as? Bitkit.ChannelFreeRailSendRefused)?.mayHaveReachedSpark == true, "\(fresh)") + XCTAssertTrue(fresh is Bitkit.ChannelFreeRailSendRefused, "\(fresh)") } - func testLeavesSparkCantSelectAreRefusedUnderANewKeyOnly() { + func testLeavesSparkCantSelectKeepTheSendInDoubtUnderAnyKey() { + // The SDK selects leaves again after an operator error, so the failure can follow a committed transfer. let reused = Bitkit.SparkManager.bolt11SendFailure(leafSelectionFailure, isReusedKey: true) let fresh = Bitkit.SparkManager.bolt11SendFailure(leafSelectionFailure, isReusedKey: false) XCTAssertFalse(reused is Bitkit.ChannelFreeRailSendRefused, "\(reused)") - XCTAssertTrue((fresh as? Bitkit.ChannelFreeRailSendRefused)?.mayHaveReachedSpark == true, "\(fresh)") + XCTAssertFalse(fresh is Bitkit.ChannelFreeRailSendRefused, "\(fresh)") } func testAFailedPaymentSparkReturnsIsRefused() { From ec69f991ffc0dbcaa91af9376669d7b6700d970d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 17:35:43 +0100 Subject: [PATCH 14/23] fix: end a held spark send at its invoice's expiry A send whose leaves Spark can't select stays in doubt under any key, and a short balance or expiry on a leaf retry reads as that leaf failure. The hold reports the payment failed once a sync after the invoice's expiry ends it, and a retry over Spark goes out at once under the send's derived key, which can't pay twice. Verified: ChannelFreeRailTests and SparkSendKeyTests pass on the simulator. --- Bitkit/Managers/SparkManager.swift | 20 ++++++-- Bitkit/Services/LightningService.swift | 36 +++++++++++++- BitkitTests/ChannelFreeRailTests.swift | 67 ++++++++++++++++++++++++++ BitkitTests/SparkSendKeyTests.swift | 17 +++++++ 4 files changed, 135 insertions(+), 5 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index d897740cc..4857b9583 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -652,6 +652,10 @@ final class SparkManager: ChannelFreeLightningRail { // MARK: ChannelFreeLightningRail + nonisolated func hasKeyedSend(paymentHash: String) -> Bool { + SparkSendAttempts.latest(paymentHash: paymentHash) != nil + } + nonisolated func receive(amountSats: UInt64?, description: String, expirySecs: UInt32) async throws -> String { let method = ReceivePaymentMethod.bolt11Invoice( description: description, @@ -773,6 +777,13 @@ final class SparkManager: ChannelFreeLightningRail { /// can hide the transfer that attempt committed, so the send stays in doubt until Spark settles it. Leaves Spark /// still can't select after its retries keep the send in doubt under any key, as the SDK selects them again after an /// operator error, so the failure can follow a transfer this send committed. + nonisolated static func isShortBalance(_ error: Error) -> Bool { + if case SdkError.InsufficientFunds = error { + return true + } + return false + } + nonisolated static func bolt11SendFailure(_ error: Error, isReusedKey: Bool) -> Error { if isReusedKey, case SdkError.InsufficientFunds = error { return error @@ -785,8 +796,9 @@ final class SparkManager: ChannelFreeLightningRail { /// Sends again under the same key while Spark can't select the leaves to spend, as right after a move to Spark lands. /// Spark selects them before anything reaches the operators, so a retry under the key can't pay twice. `canRetry` - /// is checked before each retry, which otherwise ends with the last failure. An invoice that expires meanwhile ends it - /// with the leaf failure, which may follow a committed transfer, so its expiry never reads as a send that never left. + /// is checked before each retry, which otherwise ends with the last failure. An invoice that expires or a short balance + /// on a retry ends it with the leaf failure, which may follow a committed transfer, so neither reads as a send that + /// never left. nonisolated static func sendRetryingLeafSelection( retryDelay: Duration = .seconds(2), canRetry: () -> Bool, @@ -797,7 +809,9 @@ final class SparkManager: ChannelFreeLightningRail { do { return try await send() } catch { - if retries > 0, expiredInvoiceRefusal(error) != nil { + // A failed try can have committed a transfer before Spark selected leaves again, so an expiry or a + // short balance on a retry, which would read as nothing sent, ends with the leaf failure instead. + if retries > 0, expiredInvoiceRefusal(error) != nil || Self.isShortBalance(error) { throw SdkError.SparkError("Failed to select leaves after all retries") } guard isLeafSelectionFailure(error), retries < leafSelectionRetries else { throw error } diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 465384034..b59981b7d 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -26,6 +26,8 @@ protocol ChannelFreeLightningRail: AnyObject { func lightningSendStatus(bolt11: String) async throws -> PaymentStatus? /// Whether this app would have paid `bolt11` by a direct Spark transfer, which `lightningSendStatus` can't see. func mayPayBySparkTransfer(bolt11: String, sats: UInt64?) async throws -> Bool + /// Whether this build sent the invoice with `paymentHash` under a derived key, so a retry under that key can't pay twice. + func hasKeyedSend(paymentHash: String) -> Bool } @MainActor @@ -1647,10 +1649,15 @@ class LightningService: NodeLifecycleService { if let payments = await readableRailPayments() { let live = keepRailAttempts(from: payments, since: mark) let payment = ChannelFreeRailPayment.latestOutboundAttempt(payments, paymentHash: paymentHash) - if let payment { + // A send in doubt under its derived key goes out again under that key over Spark, which can't pay twice: + // the operators return the transfer it committed, if any. + let isKeyedRetry = payment?.status != .succeeded && isKeyedRailSendInDoubt(paymentHash: paymentHash, sendsOverRail: sendsOverRail) + if let payment, !isKeyedRetry { statuses.append(payment.status) } - if payment == nil || payment?.status == .failed { + if isKeyedRetry { + Logger.info("Retrying '\(paymentHash)' over Spark under its earlier key", context: "LightningService") + } else if payment == nil || payment?.status == .failed { if live.contains(paymentHash.lowercased()) || isRailSendInFlight(paymentHash: paymentHash) { statuses.append(.pending) } else if await !railSyncedSinceUncertainSend(paymentHash: paymentHash) { @@ -1761,6 +1768,16 @@ class LightningService: NodeLifecycleService { } /// Nil while the rail's payments can't be read: listing them failed, or the rail runs here but isn't connected. + /// Whether a send of `paymentHash` this build made under a derived key is in doubt and none is in flight, so a send + /// over Spark may go out again under that key. + private func isKeyedRailSendInDoubt(paymentHash: String, sendsOverRail: Bool) -> Bool { + guard sendsOverRail, !isRailSendInFlight(paymentHash: paymentHash), + channelFreeRail?.hasKeyedSend(paymentHash: paymentHash) == true + else { return false } + let hash = paymentHash.lowercased() + return eventCallbackLock.withLock { uncertainRailSendFailedAt()[hash] != nil } + } + private func readableRailPayments() async -> [ChannelFreeRailPayment]? { try? await channelFreeRailPayments() } @@ -1934,6 +1951,10 @@ class LightningService: NodeLifecycleService { return false } endRailSendUncertainty(paymentHash: hash, startedAt: uncertain.startedAt) + // Reported as failed, so a send screen left on Pending resolves; a retry in flight reports its own outcome. + if !isRailSendInFlight(paymentHash: hash) { + deliverChannelFreeRailEvent(.paymentFailed(paymentId: hash, paymentHash: hash, reason: nil)) + } return true } @@ -2618,6 +2639,17 @@ extension LightningService { callback?(event) } + /// Passes `event` to the app without settling any hold, as for a send whose hold already ended. + private func deliverChannelFreeRailEvent(_ event: Event) { + let callback = eventCallbackLock.withLock { + if storedEventCallback == nil { + pendingChannelFreeRailEvents.append(event) + } + return storedEventCallback + } + callback?(event) + } + func noteAttempt(on rail: LightningPaymentRail, paymentHash: String) { eventCallbackLock.withLock { attemptRails[paymentHash.lowercased()] = rail } } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 4ff339477..471e5605f 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -693,6 +693,67 @@ extension ChannelFreeRailTests { await assertReachesTheNode() } + /// A Spark send whose leaves Spark still can't select after its retries, which may follow a committed transfer. + private func sendInDoubtAfterALeafFailure() async throws { + let expiresAt = try Self.invoiceExpiresAt() + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: expiresAt - 600) } + rail.balanceSats = 100_000 + rail.errorAfterSubmission = Bitkit.SparkManager.bolt11SendFailure( + SdkError.SparkError("Tree service error: generic error: Failed to select leaves after all retries"), + isReusedKey: false + ) + do { + _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + XCTFail("Expected the send to stay in doubt") + } catch { + XCTAssertFalse(error is Bitkit.ChannelFreeRailSendRefused, "\(error)") + } + rail.errorAfterSubmission = nil + } + + func testASparkSendInDoubtAfterALeafFailureEndsAtItsInvoicesExpiry() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + let previousRecord = service.railSendExpired + defer { service.railSendExpired = previousRecord } + final class Calls: @unchecked Sendable { var count = 0 } + let calls = Calls() + service.railSendExpired = { _ in + calls.count += 1 + return true + } + final class Failures: @unchecked Sendable { var hashes: [String] = [] } + let failures = Failures() + service.setEventCallback { event in + if case let .paymentFailed(_, paymentHash?, _) = event { + failures.hashes.append(paymentHash) + } + } + try await sendInDoubtAfterALeafFailure() + rail.syncedAfter = { _ in true } + + await service.endExpiredRailSendUncertainties() + XCTAssertEqual(calls.count, 0, "a transfer the send committed can still go out") + XCTAssertNotNil(service.railSendHolds[hash]) + + let expiresAt = try Self.invoiceExpiresAt() + service.now = { Date(timeIntervalSince1970: expiresAt) } + await service.endExpiredRailSendUncertainties() + + XCTAssertEqual(calls.count, 1) + XCTAssertNil(service.railSendHolds[hash]) + XCTAssertEqual(failures.hashes, [hash], "a send screen left on Pending never resolves") + } + + func testASparkRetryOfASendInDoubtAfterALeafFailureGoesOutUnderItsKey() async throws { + try await sendInDoubtAfterALeafFailure() + try rail.keyedSends.insert(String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()).lowercased()) + + _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + + XCTAssertEqual(rail.sends, 1) + } + func testAnUnknownSparkSendMissingAfterAFreshSyncIsHeldUntilItsInvoiceExpires() async throws { let expiresAt = try Self.invoiceExpiresAt() Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: expiresAt - 600) } @@ -2330,6 +2391,12 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { /// Whether the invoice carries a Spark address a Spark-preferring send pays directly. var paysBySparkTransfer: Result = .success(false) var sparkTransferChecks = 0 + /// The payment hashes sent under a derived key. + var keyedSends: Set = [] + + func hasKeyedSend(paymentHash: String) -> Bool { + keyedSends.contains(paymentHash.lowercased()) + } func receive(amountSats: UInt64?, description: String, expirySecs: UInt32) async throws -> String { "lnbcrt1fake" diff --git a/BitkitTests/SparkSendKeyTests.swift b/BitkitTests/SparkSendKeyTests.swift index 6dc121959..83b29465a 100644 --- a/BitkitTests/SparkSendKeyTests.swift +++ b/BitkitTests/SparkSendKeyTests.swift @@ -119,6 +119,23 @@ final class SparkSendKeyTests: XCTestCase { } } + func testAShortBalanceOnALeafRetryEndsWithTheLeafFailure() async { + var sends = 0 + + do { + _ = try await Bitkit.SparkManager.sendRetryingLeafSelection(retryDelay: .zero, canRetry: { true }) { + sends += 1 + if sends == 1 { + throw leafSelectionFailure + } + throw SdkError.InsufficientFunds(tokenIdentifier: nil) + } + XCTFail("Expected the send to fail") + } catch { + XCTAssertTrue(Bitkit.SparkManager.isLeafSelectionFailure(error), "\(error)") + } + } + func testASendRetriesWhileSparkCantSelectItsLeaves() async throws { var sends = 0 From f5463f1f2c77324945f4142d8f6b371ae4566220 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 18:36:54 +0100 Subject: [PATCH 15/23] fix: keep a spark send in doubt through a retry that never goes out A retry of a send in doubt that Spark refuses before it goes out reads as pending, as the earlier attempt may have paid, and an expiry under a reused key stays in doubt. The expiry reports a failure only when Spark lists none paid or pending, and a move to Spark for a send in doubt is refused as pending. Verified: ChannelFreeRailTests, SparkSendKeyTests and SendSheetLifecycleTests pass on the simulator. --- Bitkit/Managers/SparkManager.swift | 30 ++++++++------ Bitkit/Services/LightningService.swift | 45 ++++++++++++-------- BitkitTests/ChannelFreeRailTests.swift | 57 ++++++++++++++++++++++++-- BitkitTests/SparkSendKeyTests.swift | 11 +++++ 4 files changed, 111 insertions(+), 32 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 4857b9583..1296003c5 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -432,7 +432,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.railSendExpired = { [weak self] hash in await self?.recordExpiredSend(paymentHash: hash) ?? false } + LightningService.shared.railSendExpired = { [weak self] hash in await self?.recordExpiredSend(paymentHash: hash) } if !isExiting { LightningService.shared.channelFreeRail = self } @@ -772,11 +772,6 @@ final class SparkManager: ChannelFreeLightningRail { return !overflow && total <= balanceSats } - /// What a failure inside the BOLT11 `sendPayment` means for the caller. Spark picks the leaves to spend before the - /// operators see the key, so a short balance left nothing under a new key; under a key an earlier attempt used, it - /// can hide the transfer that attempt committed, so the send stays in doubt until Spark settles it. Leaves Spark - /// still can't select after its retries keep the send in doubt under any key, as the SDK selects them again after an - /// operator error, so the failure can follow a transfer this send committed. nonisolated static func isShortBalance(_ error: Error) -> Bool { if case SdkError.InsufficientFunds = error { return true @@ -784,8 +779,13 @@ final class SparkManager: ChannelFreeLightningRail { return false } + /// What a failure inside the BOLT11 `sendPayment` means for the caller. Spark picks the leaves to spend before the + /// operators see the key, so a short balance left nothing under a new key; under a key an earlier attempt used, it + /// can hide the transfer that attempt committed, so the send stays in doubt until Spark settles it. Leaves Spark + /// still can't select after its retries keep the send in doubt under any key, as the SDK selects them again after an + /// operator error, so the failure can follow a transfer this send committed. nonisolated static func bolt11SendFailure(_ error: Error, isReusedKey: Bool) -> Error { - if isReusedKey, case SdkError.InsufficientFunds = error { + if isReusedKey, isShortBalance(error) || expiredInvoiceRefusal(error) != nil { return error } if isLeafSelectionFailure(error) { @@ -1975,14 +1975,20 @@ final class SparkManager: ChannelFreeLightningRail { } /// 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 } + /// listed before it went out, or a failure of the stored pending send when Spark lists none. Returns the status saved, + /// nil when it wasn't. + private func recordExpiredSend(paymentHash: String) async -> LDKNode.PaymentStatus? { + guard let payments = try? await requireSdk().listPayments(request: ListPaymentsRequest()).payments else { return nil } let isEarlierAttempt = { LightningService.shared.isEarlierRailAttempt(paymentHash: $0, createdAt: $1) } if let own = Self.expiredSendAttempt(payments, paymentHash: paymentHash, isEarlierAttempt: isEarlierAttempt) { - return await recordActivity(own) + guard await recordActivity(own) else { return nil } + switch own.status { + case .completed: return .succeeded + case .pending: return .pending + case .failed: return .failed + } } - return await (try? CoreService.shared.activity.failPendingLightningSend(id: paymentHash)) != nil + return await (try? CoreService.shared.activity.failPendingLightningSend(id: paymentHash)) != nil ? .failed : nil } /// The latest of Spark's attempts of a send whose invoice expired, none when Spark lists only attempts before it. diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index b59981b7d..d9df069c9 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -226,8 +226,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 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)? + /// when listed, otherwise by failing the stored pending row. Returns the status saved, nil when the row wasn't. + var railSendExpired: ((String) async -> PaymentStatus?)? var onchainTransactionConfirmed: (@Sendable (String) async -> Void)? var onchainTransactionReceived: (@Sendable (String) async -> Void)? typealias OnchainActivityCompletion = @MainActor () async -> Void @@ -1245,6 +1245,10 @@ class LightningService: NodeLifecycleService { endRailSendUncertainty(paymentHash: paymentHash) releaseRailAttempt(paymentHash: paymentHash, unlessInFlight: false) } + // A retry of a send still in doubt that never went out leaves that send pending, not refused. + if let paymentHash, eventCallbackLock.withLock({ uncertainRailSendFailedAt()[paymentHash.lowercased()] != nil }) { + throw Self.pendingDuplicate(paymentHash: paymentHash) + } throw refusal } catch where isRefusedAtAdmission { // Nothing of this send left. Refused for a Spark send recorded since the checks, its caller gets that @@ -1614,7 +1618,8 @@ class LightningService: NodeLifecycleService { sats: UInt64?, invoiceCreatedAt: UInt64?, invoiceExpiresAt: Int?, - sendsOverRail: Bool = false + sendsOverRail: Bool = false, + retriesKeyedSend: Bool = true ) async throws -> PaymentHash? { guard let paymentHash else { return nil } var statuses: [PaymentStatus] = rails.contains(.channelFree) && isRailSendInFlight(paymentHash: paymentHash) ? [.pending] : [] @@ -1651,7 +1656,7 @@ class LightningService: NodeLifecycleService { let payment = ChannelFreeRailPayment.latestOutboundAttempt(payments, paymentHash: paymentHash) // A send in doubt under its derived key goes out again under that key over Spark, which can't pay twice: // the operators return the transfer it committed, if any. - let isKeyedRetry = payment?.status != .succeeded && isKeyedRailSendInDoubt(paymentHash: paymentHash, sendsOverRail: sendsOverRail) + let isKeyedRetry = payment?.status != .succeeded && isKeyedRailSendInDoubt(paymentHash: paymentHash, sendsOverRail: sendsOverRail && retriesKeyedSend) if let payment, !isKeyedRetry { statuses.append(payment.status) } @@ -1767,7 +1772,6 @@ class LightningService: NodeLifecycleService { Int(clamping: invoiceCreatedAt ?? 0) < restoredAt && invoiceExpiresAt.map { now < $0 } ?? true } - /// Nil while the rail's payments can't be read: listing them failed, or the rail runs here but isn't connected. /// Whether a send of `paymentHash` this build made under a derived key is in doubt and none is in flight, so a send /// over Spark may go out again under that key. private func isKeyedRailSendInDoubt(paymentHash: String, sendsOverRail: Bool) -> Bool { @@ -1778,6 +1782,7 @@ class LightningService: NodeLifecycleService { return eventCallbackLock.withLock { uncertainRailSendFailedAt()[hash] != nil } } + /// Nil while the rail's payments can't be read: listing them failed, or the rail runs here but isn't connected. private func readableRailPayments() async -> [ChannelFreeRailPayment]? { try? await channelFreeRailPayments() } @@ -1890,17 +1895,21 @@ class LightningService: NodeLifecycleService { /// 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) { + @discardableResult + private func endRailSendUncertainty(paymentHash: String, startedAt: Int) -> Bool { endRailSendUncertainty(paymentHash: paymentHash) { $0 == startedAt } } - private func endRailSendUncertainty(paymentHash: String, where isEnded: (Int) -> Bool) { + /// Returns whether it ended a hold. + @discardableResult + private func endRailSendUncertainty(paymentHash: String, where isEnded: (Int) -> Bool) -> Bool { let hash = paymentHash.lowercased() - eventCallbackLock.withLock { + return eventCallbackLock.withLock { var uncertain = uncertainRailSendFailedAt() - guard let startedAt = uncertain[hash], isEnded(startedAt) else { return } + guard let startedAt = uncertain[hash], isEnded(startedAt) else { return false } uncertain.removeValue(forKey: hash) railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) + return true } } @@ -1947,12 +1956,15 @@ class LightningService: NodeLifecycleService { 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, startedAt: uncertain.startedAt) - // Reported as failed, so a send screen left on Pending resolves; a retry in flight reports its own outcome. - if !isRailSendInFlight(paymentHash: hash) { + var status = PaymentStatus.failed + if let record = railSendExpired { + guard let recorded = await record(hash) else { return false } + status = recorded + } + let didEnd = endRailSendUncertainty(paymentHash: hash, startedAt: uncertain.startedAt) + // Reported as failed, so a send screen left on Pending resolves; a retry in flight reports its own outcome, and + // a send Spark lists paid or pending reports by Spark's own event. + if didEnd, status == .failed, !isRailSendInFlight(paymentHash: hash) { deliverChannelFreeRailEvent(.paymentFailed(paymentId: hash, paymentHash: hash, reason: nil)) } return true @@ -1978,7 +1990,8 @@ class LightningService: NodeLifecycleService { sats: sats, invoiceCreatedAt: invoice?.secondsSinceEpoch(), invoiceExpiresAt: expiresAt, - sendsOverRail: true + sendsOverRail: true, + retriesKeyedSend: false ) != nil } diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 471e5605f..ac69c5922 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -720,7 +720,7 @@ extension ChannelFreeRailTests { let calls = Calls() service.railSendExpired = { _ in calls.count += 1 - return true + return .failed } final class Failures: @unchecked Sendable { var hashes: [String] = [] } let failures = Failures() @@ -745,6 +745,55 @@ extension ChannelFreeRailTests { XCTAssertEqual(failures.hashes, [hash], "a send screen left on Pending never resolves") } + func testASparkSendInDoubtSparkListsPaidAtItsInvoicesExpiryReportsNoFailure() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + let previousRecord = service.railSendExpired + defer { service.railSendExpired = previousRecord } + service.railSendExpired = { _ in .succeeded } + final class Failures: @unchecked Sendable { var hashes: [String] = [] } + let failures = Failures() + service.setEventCallback { event in + if case let .paymentFailed(_, paymentHash?, _) = event { + failures.hashes.append(paymentHash) + } + } + try await sendInDoubtAfterALeafFailure() + rail.syncedAfter = { _ in true } + service.now = { try! Date(timeIntervalSince1970: Self.invoiceExpiresAt()) } + + await service.endExpiredRailSendUncertainties() + + XCTAssertNil(service.railSendHolds[hash]) + XCTAssertEqual(failures.hashes, [], "a paid send was reported failed") + } + + func testASparkRetryOfASendInDoubtRefusedBeforeItGoesOutStaysPending() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + try await sendInDoubtAfterALeafFailure() + rail.keyedSends.insert(hash.lowercased()) + rail.refusal = Bitkit.ChannelFreeRailSendRefused(reason: "short") + + do { + _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + XCTFail("Expected the retry to fail") + } catch { + XCTAssertFalse(error is Bitkit.ChannelFreeRailSendRefused, "a refusal releases the held send's proof: \(error)") + } + XCTAssertNotNil(Bitkit.LightningService.shared.railSendHolds[hash]) + } + + func testAMoveToSparkForASendInDoubtUnderItsKeyIsRefusedAsPending() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + try await sendInDoubtAfterALeafFailure() + rail.keyedSends.insert(hash.lowercased()) + + do { + _ = try await Bitkit.LightningService.shared.hasSettledEarlierAttempt(bolt11: Self.invoice, sats: nil) + XCTFail("Expected the move to be refused while the send is in doubt") + } catch {} + } + func testASparkRetryOfASendInDoubtAfterALeafFailureGoesOutUnderItsKey() async throws { try await sendInDoubtAfterALeafFailure() try rail.keyedSends.insert(String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()).lowercased()) @@ -1799,7 +1848,7 @@ extension ChannelFreeRailTests { service.emitChannelFreeRailEvent(.paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), paymentCreatedAt: Self.sparkNow()) service.now = { Date(timeIntervalSince1970: expiresAt + 5) } try? await sendOverSpark() - return true + return .failed } await service.endExpiredRailSendUncertainties() @@ -1980,7 +2029,7 @@ extension ChannelFreeRailTests { let calls = Calls() service.railSendExpired = { _ in calls.count += 1 - return true + return .failed } let expiresAt = try Self.invoiceExpiresAt() service.now = { Date(timeIntervalSince1970: expiresAt) } @@ -2029,7 +2078,7 @@ extension ChannelFreeRailTests { written.attempt = SparkManager.expiredSendAttempt( [Self.sparkPayment(hash: hash, status: .failed, timestamp: startedAt - 5)], paymentHash: hash ) { service.isEarlierRailAttempt(paymentHash: $0, createdAt: $1) } - return true + return .failed } let expiresAt = try Self.invoiceExpiresAt() service.now = { Date(timeIntervalSince1970: expiresAt) } diff --git a/BitkitTests/SparkSendKeyTests.swift b/BitkitTests/SparkSendKeyTests.swift index 83b29465a..0fabb9338 100644 --- a/BitkitTests/SparkSendKeyTests.swift +++ b/BitkitTests/SparkSendKeyTests.swift @@ -94,6 +94,17 @@ final class SparkSendKeyTests: XCTestCase { XCTAssertFalse(fresh is Bitkit.ChannelFreeRailSendRefused, "\(fresh)") } + func testAnExpiryUnderAReusedKeyKeepsTheSendInDoubt() { + // The attempt that used the key may have committed a transfer before the invoice expired. + let expired = SdkError.InvalidInput("invoice has expired") + + let reused = Bitkit.SparkManager.bolt11SendFailure(expired, isReusedKey: true) + let fresh = Bitkit.SparkManager.bolt11SendFailure(expired, isReusedKey: false) + + XCTAssertFalse(reused is Bitkit.ChannelFreeRailSendRefused, "\(reused)") + XCTAssertTrue(fresh is Bitkit.ChannelFreeRailSendRefused, "\(fresh)") + } + func testAFailedPaymentSparkReturnsIsRefused() { XCTAssertThrowsError(try Bitkit.SparkManager.checkSentPayment(.failed)) { XCTAssertTrue($0 is Bitkit.ChannelFreeRailSendRefused, "\($0)") From e280c95db354e686d3b2e30d7002d16c174b3bc2 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 19:24:36 +0100 Subject: [PATCH 16/23] fix: read any retry of a spark send in doubt that never left as pending A retry of a send in doubt stopped before it records its attempt, by its fee limit, a failed estimate or its caller's last check, leaves that send pending, as it may have paid. Verified: ChannelFreeRailTests and SparkSendKeyTests pass on the simulator; swiftformat lint passes. --- Bitkit/Services/LightningService.swift | 19 ++++++++++---- BitkitTests/ChannelFreeRailTests.swift | 35 ++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index d9df069c9..b38a8b41d 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1199,6 +1199,7 @@ class LightningService: NodeLifecycleService { feeSats = try await rail.estimateRoutingFees(bolt11: bolt11, amountSats: sats) } catch { Logger.warn("Spark fee estimate failed: \(error)", context: "LightningService") + try throwPendingIfInDoubt(paymentHash: paymentHash) throw error as? ChannelFreeRailSendRefused ?? ChannelFreeRailSendRefused( reason: t("wallet__payment_failed_description"), underlying: error @@ -1206,6 +1207,7 @@ class LightningService: NodeLifecycleService { } guard feeSats * 1000 <= maxFeeMsat else { Logger.info("Spark routing fee of \(feeSats) sats exceeds the limit of \(maxFeeMsat / 1000) sats", context: "LightningService") + try throwPendingIfInDoubt(paymentHash: paymentHash) throw ChannelFreeRailSendRefused(reason: t("wallet__max_possible_fee_rate")) } } @@ -1245,10 +1247,7 @@ class LightningService: NodeLifecycleService { endRailSendUncertainty(paymentHash: paymentHash) releaseRailAttempt(paymentHash: paymentHash, unlessInFlight: false) } - // A retry of a send still in doubt that never went out leaves that send pending, not refused. - if let paymentHash, eventCallbackLock.withLock({ uncertainRailSendFailedAt()[paymentHash.lowercased()] != nil }) { - throw Self.pendingDuplicate(paymentHash: paymentHash) - } + try throwPendingIfInDoubt(paymentHash: paymentHash) throw refusal } catch where isRefusedAtAdmission { // Nothing of this send left. Refused for a Spark send recorded since the checks, its caller gets that @@ -1265,6 +1264,8 @@ class LightningService: NodeLifecycleService { // failed before it recorded its attempt never reached Spark. if let paymentHash, didRecordAttempt { markRailSendUncertain(paymentHash: paymentHash, since: mark) + } else { + try throwPendingIfInDoubt(paymentHash: paymentHash) } throw error } @@ -1656,7 +1657,8 @@ class LightningService: NodeLifecycleService { let payment = ChannelFreeRailPayment.latestOutboundAttempt(payments, paymentHash: paymentHash) // A send in doubt under its derived key goes out again under that key over Spark, which can't pay twice: // the operators return the transfer it committed, if any. - let isKeyedRetry = payment?.status != .succeeded && isKeyedRailSendInDoubt(paymentHash: paymentHash, sendsOverRail: sendsOverRail && retriesKeyedSend) + let isKeyedRetry = payment?.status != .succeeded + && isKeyedRailSendInDoubt(paymentHash: paymentHash, sendsOverRail: sendsOverRail && retriesKeyedSend) if let payment, !isKeyedRetry { statuses.append(payment.status) } @@ -1995,6 +1997,13 @@ class LightningService: NodeLifecycleService { ) != nil } + /// A retry of a send still in doubt that never went out leaves that send pending, not failed, as it may have paid: + /// a failure would release its Paykit proof, allowance and QuickPay charge. + private func throwPendingIfInDoubt(paymentHash: String?) throws { + guard let paymentHash, eventCallbackLock.withLock({ uncertainRailSendFailedAt()[paymentHash.lowercased()] != nil }) else { return } + throw Self.pendingDuplicate(paymentHash: paymentHash) + } + 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 ac69c5922..bf1959aa0 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -783,6 +783,41 @@ extension ChannelFreeRailTests { XCTAssertNotNil(Bitkit.LightningService.shared.railSendHolds[hash]) } + func testASparkRetryOfASendInDoubtOverItsFeeLimitStaysPending() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + try await sendInDoubtAfterALeafFailure() + rail.keyedSends.insert(hash.lowercased()) + rail.routingFeeSats = 5 + let limit = RouteParametersConfig( + maxTotalRoutingFeeMsat: 1000, maxTotalCltvExpiryDelta: 1008, maxPathCount: 10, maxChannelSaturationPowerOfHalf: 2 + ) + + do { + _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice, params: limit) + XCTFail("Expected the retry to fail") + } catch { + XCTAssertFalse(error is Bitkit.ChannelFreeRailSendRefused, "a refusal releases the held send's proof: \(error)") + } + XCTAssertNotNil(Bitkit.LightningService.shared.railSendHolds[hash]) + } + + func testASparkRetryOfASendInDoubtStoppedBeforeSubmissionStaysPending() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + try await sendInDoubtAfterALeafFailure() + rail.keyedSends.insert(hash.lowercased()) + + do { + _ = try await Bitkit.LightningService.shared.send( + bolt11: Self.invoice, + beforeSubmission: { throw NSError(domain: "request", code: 1) } + ) + XCTFail("Expected the retry to fail") + } catch { + XCTAssertNotEqual((error as NSError).domain, "request", "a request error releases the held send's proof: \(error)") + } + XCTAssertNotNil(Bitkit.LightningService.shared.railSendHolds[hash]) + } + func testAMoveToSparkForASendInDoubtUnderItsKeyIsRefusedAsPending() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) try await sendInDoubtAfterALeafFailure() From 7313885b29b8e3b1b4e232a67398614af372a9c1 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 19:43:53 +0100 Subject: [PATCH 17/23] fix: settle a spark send in doubt before a new key's retry A retry of a send in doubt whose attempt Spark lists failed waits for that failure to settle the hold before it takes a new key, so the earlier attempt's failure is never read as the new attempt's. Verified: ChannelFreeRailTests and SparkSendKeyTests pass on the simulator; swiftformat lint passes. --- Bitkit/Managers/SparkManager.swift | 11 +++++++++++ BitkitTests/SparkSendKeyTests.swift | 7 +++++++ 2 files changed, 18 insertions(+) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 1296003c5..8f54c72a5 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -718,6 +718,12 @@ final class SparkManager: ChannelFreeLightningRail { let idempotencyKey = SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: attempt) let previousAttempt = SparkSendAttempts.latest(paymentHash: paymentHash) let isReusedKey = previousAttempt == attempt + // A send in doubt whose attempt Spark lists failed is settled by that failure first, so its hold can't be taken + // for this new attempt's. + let isInDoubt = LightningService.shared.railSendHolds[paymentHash.lowercased()] != nil + if Self.waitsForHold(isReusedKey: isReusedKey, previousAttempt: previousAttempt, isInDoubt: isInDoubt) { + throw ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description")) + } let (sum, overflows) = invoiceDetails.timestamp.addingReportingOverflow(invoiceDetails.expiry) let expiresAt = overflows ? UInt64.max : sum // An exit that started while the quote was prepared refuses it here, before its hash is recorded. @@ -752,6 +758,11 @@ final class SparkManager: ChannelFreeLightningRail { return invoiceDetails.paymentHash } + /// Whether a send must wait for the hold of the invoice's earlier attempt to settle before it takes a new key. + nonisolated static func waitsForHold(isReusedKey: Bool, previousAttempt: UInt32?, isInDoubt: Bool) -> Bool { + !isReusedKey && previousAttempt != nil && isInDoubt + } + /// A failed payment, as Spark returns under a key it already failed when its failed list couldn't be read to move /// past it, paid nothing, so the send is refused instead of read as submitted. nonisolated static func checkSentPayment(_ status: BreezSdkSpark.PaymentStatus) throws { diff --git a/BitkitTests/SparkSendKeyTests.swift b/BitkitTests/SparkSendKeyTests.swift index 0fabb9338..10d04d3fe 100644 --- a/BitkitTests/SparkSendKeyTests.swift +++ b/BitkitTests/SparkSendKeyTests.swift @@ -105,6 +105,13 @@ final class SparkSendKeyTests: XCTestCase { XCTAssertTrue(fresh is Bitkit.ChannelFreeRailSendRefused, "\(fresh)") } + func testANewKeyWaitsWhileTheEarlierAttemptIsInDoubt() { + XCTAssertTrue(Bitkit.SparkManager.waitsForHold(isReusedKey: false, previousAttempt: 0, isInDoubt: true)) + XCTAssertFalse(Bitkit.SparkManager.waitsForHold(isReusedKey: true, previousAttempt: 0, isInDoubt: true)) + XCTAssertFalse(Bitkit.SparkManager.waitsForHold(isReusedKey: false, previousAttempt: 0, isInDoubt: false)) + XCTAssertFalse(Bitkit.SparkManager.waitsForHold(isReusedKey: false, previousAttempt: nil, isInDoubt: true)) + } + func testAFailedPaymentSparkReturnsIsRefused() { XCTAssertThrowsError(try Bitkit.SparkManager.checkSentPayment(.failed)) { XCTAssertTrue($0 is Bitkit.ChannelFreeRailSendRefused, "\($0)") From 0883b1c220932b95a37de4bbaf02ed7ee134a72f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 25 Nov 2026 19:58:17 +0100 Subject: [PATCH 18/23] fix: record a paid attempt when a spark send in doubt expires An expired send in doubt records the invoice's paid attempt whenever Spark dated it, so a paid send never reports a failure, and a new key waits whenever the send is in doubt. Verified: ChannelFreeRailTests and SparkSendKeyTests pass on the simulator; swiftformat lint passes. --- Bitkit/Managers/SparkManager.swift | 10 ++++++---- BitkitTests/SparkSendKeyTests.swift | 7 +++---- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 8f54c72a5..d38c85008 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -721,7 +721,7 @@ final class SparkManager: ChannelFreeLightningRail { // A send in doubt whose attempt Spark lists failed is settled by that failure first, so its hold can't be taken // for this new attempt's. let isInDoubt = LightningService.shared.railSendHolds[paymentHash.lowercased()] != nil - if Self.waitsForHold(isReusedKey: isReusedKey, previousAttempt: previousAttempt, isInDoubt: isInDoubt) { + if Self.waitsForHold(isReusedKey: isReusedKey, isInDoubt: isInDoubt) { throw ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description")) } let (sum, overflows) = invoiceDetails.timestamp.addingReportingOverflow(invoiceDetails.expiry) @@ -759,8 +759,8 @@ final class SparkManager: ChannelFreeLightningRail { } /// Whether a send must wait for the hold of the invoice's earlier attempt to settle before it takes a new key. - nonisolated static func waitsForHold(isReusedKey: Bool, previousAttempt: UInt32?, isInDoubt: Bool) -> Bool { - !isReusedKey && previousAttempt != nil && isInDoubt + nonisolated static func waitsForHold(isReusedKey: Bool, isInDoubt: Bool) -> Bool { + !isReusedKey && isInDoubt } /// A failed payment, as Spark returns under a key it already failed when its failed list couldn't be read to move @@ -1991,7 +1991,9 @@ final class SparkManager: ChannelFreeLightningRail { private func recordExpiredSend(paymentHash: String) async -> LDKNode.PaymentStatus? { guard let payments = try? await requireSdk().listPayments(request: ListPaymentsRequest()).payments else { return nil } let isEarlierAttempt = { LightningService.shared.isEarlierRailAttempt(paymentHash: $0, createdAt: $1) } - if let own = Self.expiredSendAttempt(payments, paymentHash: paymentHash, isEarlierAttempt: isEarlierAttempt) { + // A paid attempt settles the invoice whenever Spark dated it. + let paid = Self.expiredSendAttempt(payments.filter { $0.status == .completed }, paymentHash: paymentHash) { _, _ in false } + if let own = paid ?? Self.expiredSendAttempt(payments, paymentHash: paymentHash, isEarlierAttempt: isEarlierAttempt) { guard await recordActivity(own) else { return nil } switch own.status { case .completed: return .succeeded diff --git a/BitkitTests/SparkSendKeyTests.swift b/BitkitTests/SparkSendKeyTests.swift index 10d04d3fe..b879bb6b8 100644 --- a/BitkitTests/SparkSendKeyTests.swift +++ b/BitkitTests/SparkSendKeyTests.swift @@ -106,10 +106,9 @@ final class SparkSendKeyTests: XCTestCase { } func testANewKeyWaitsWhileTheEarlierAttemptIsInDoubt() { - XCTAssertTrue(Bitkit.SparkManager.waitsForHold(isReusedKey: false, previousAttempt: 0, isInDoubt: true)) - XCTAssertFalse(Bitkit.SparkManager.waitsForHold(isReusedKey: true, previousAttempt: 0, isInDoubt: true)) - XCTAssertFalse(Bitkit.SparkManager.waitsForHold(isReusedKey: false, previousAttempt: 0, isInDoubt: false)) - XCTAssertFalse(Bitkit.SparkManager.waitsForHold(isReusedKey: false, previousAttempt: nil, isInDoubt: true)) + XCTAssertTrue(Bitkit.SparkManager.waitsForHold(isReusedKey: false, isInDoubt: true)) + XCTAssertFalse(Bitkit.SparkManager.waitsForHold(isReusedKey: true, isInDoubt: true)) + XCTAssertFalse(Bitkit.SparkManager.waitsForHold(isReusedKey: false, isInDoubt: false)) } func testAFailedPaymentSparkReturnsIsRefused() { From 62a7f096f9d15d300d62d457a596dfcfc01fc1e1 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 09:57:13 +0100 Subject: [PATCH 19/23] fix: keep a paid spark send paid at expiry A send Spark lists no attempt of at its invoice's expiry was read as failed whenever its stored row wasn't pending, a succeeded row too, so a success Spark published after the list was read could be reported as a failure. The stored row's status now decides: succeeded stays paid. A retry of an amountless invoice at another amount reused the held attempt's key, so Spark returned the first payment while the send showed the new amount. Each attempt now keeps its amount, and a same-key retry at another amount waits for the hold like a duplicate. Verified: ChannelFreeRailTests, SparkSendKeyTests and FailPendingLightningSendTests pass on the simulator; swiftformat lint passes. --- Bitkit/Managers/SparkManager.swift | 34 +++++++++++++++---- Bitkit/Services/CoreService.swift | 11 +++--- Bitkit/Services/SparkSendKey.swift | 23 ++++++++----- .../FailPendingLightningSendTests.swift | 8 ++++- BitkitTests/SparkSendKeyTests.swift | 33 ++++++++++++------ 5 files changed, 78 insertions(+), 31 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index d38c85008..971ee4cc5 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -717,11 +717,16 @@ final class SparkManager: ChannelFreeLightningRail { ) let idempotencyKey = SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: attempt) let previousAttempt = SparkSendAttempts.latest(paymentHash: paymentHash) + let previousAmountSats = SparkSendAttempts.latestAmountSats(paymentHash: paymentHash) let isReusedKey = previousAttempt == attempt // A send in doubt whose attempt Spark lists failed is settled by that failure first, so its hold can't be taken // for this new attempt's. let isInDoubt = LightningService.shared.railSendHolds[paymentHash.lowercased()] != nil - if Self.waitsForHold(isReusedKey: isReusedKey, isInDoubt: isInDoubt) { + if Self.waitsForHold( + isReusedKey: isReusedKey, + isInDoubt: isInDoubt, + changesAmount: previousAmountSats.map { $0 != amountSats } ?? false + ) { throw ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description")) } let (sum, overflows) = invoiceDetails.timestamp.addingReportingOverflow(invoiceDetails.expiry) @@ -733,7 +738,9 @@ final class SparkManager: ChannelFreeLightningRail { // A deadline that passed while the quote was prepared stops the payment here, before anything leaves. try beforeSubmission() // Kept once the send is admitted, so a send refused before it leaves keeps the earlier attempt. - SparkSendAttempts.set(paymentHash: paymentHash, attempt: attempt, expiresAt: expiresAt, now: Self.nowSecs()) + SparkSendAttempts.set( + paymentHash: paymentHash, attempt: attempt, amountSats: amountSats, expiresAt: expiresAt, now: Self.nowSecs() + ) do { return try await Self.sendRetryingLeafSelection(canRetry: { (try? beforeSubmission()) != nil }) { try await sdk.sendPayment(request: SendPaymentRequest( @@ -749,7 +756,9 @@ final class SparkManager: ChannelFreeLightningRail { } catch let refusal as ChannelFreeRailSendRefused { // A refused attempt never reached Spark's operators, so its key stays unused and a retry refuses the same way. if !isReusedKey { - SparkSendAttempts.restore(paymentHash: paymentHash, attempt: previousAttempt, expiresAt: expiresAt) + SparkSendAttempts.restore( + paymentHash: paymentHash, attempt: previousAttempt, amountSats: previousAmountSats, expiresAt: expiresAt + ) } throw refusal } @@ -758,9 +767,10 @@ final class SparkManager: ChannelFreeLightningRail { return invoiceDetails.paymentHash } - /// Whether a send must wait for the hold of the invoice's earlier attempt to settle before it takes a new key. - nonisolated static func waitsForHold(isReusedKey: Bool, isInDoubt: Bool) -> Bool { - !isReusedKey && isInDoubt + /// Whether a send must wait for the hold of the invoice's earlier attempt to settle: before it takes a new key, or + /// when it would reuse that attempt's key at another amount, as Spark would return the earlier payment for it. + nonisolated static func waitsForHold(isReusedKey: Bool, isInDoubt: Bool, changesAmount: Bool) -> Bool { + isReusedKey ? changesAmount : isInDoubt } /// A failed payment, as Spark returns under a key it already failed when its failed list couldn't be read to move @@ -2001,7 +2011,17 @@ final class SparkManager: ChannelFreeLightningRail { case .failed: return .failed } } - return await (try? CoreService.shared.activity.failPendingLightningSend(id: paymentHash)) != nil ? .failed : nil + do { + return try await Self.expiredSendStatus(stored: CoreService.shared.activity.failPendingLightningSend(id: paymentHash)) + } catch { + return nil + } + } + + /// The outcome of a send Spark lists no attempt of once its invoice expired, by its stored row: paid when it already + /// succeeded, as Spark's success can land after the list was read, and failed otherwise. + nonisolated static func expiredSendStatus(stored: PaymentState?) -> LDKNode.PaymentStatus { + stored == .succeeded ? .succeeded : .failed } /// The latest of Spark's attempts of a send whose invoice expired, none when Spark lists only attempts before it. diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 0129fa61f..a55ba0b4e 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1407,16 +1407,19 @@ 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 { + /// operation, so a change saved meanwhile isn't overwritten. Returns the send's status after it, nil when none is stored. + @discardableResult + func failPendingLightningSend(id: String) async throws -> PaymentState? { 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 } + activity.txType == .sent + else { return nil } + guard activity.status == .pending else { return activity.status } var failed = activity failed.status = .failed try updateActivity(activityId: id, activity: .lightning(failed)) self.activitiesChangedSubject.send() + return .failed } } diff --git a/Bitkit/Services/SparkSendKey.swift b/Bitkit/Services/SparkSendKey.swift index 02bc95890..aa09e31e2 100644 --- a/Bitkit/Services/SparkSendKey.swift +++ b/Bitkit/Services/SparkSendKey.swift @@ -40,6 +40,8 @@ enum SparkSendAttempts { private struct Attempt: Codable { let attempt: UInt32 let expiresAt: UInt64 + /// The amount the attempt sent; nil for one kept before amounts were. + var amountSats: UInt64? } /// The attempt whose key pays the invoice with `paymentHash`: the latest kept one, past each whose key is in @@ -58,22 +60,27 @@ enum SparkSendAttempts { lock.withLock { stored[paymentHash.lowercased()]?.attempt } } - /// Keeps `attempt` as the latest at the invoice with `paymentHash`, which expires at `expiresAt`, and drops the - /// attempts of invoices expired before `now`, both in epoch seconds. - static func set(paymentHash: String, attempt: UInt32, expiresAt: UInt64, now: UInt64) { + /// The amount the latest attempt at the invoice with `paymentHash` sent, nil when none was kept with one. + static func latestAmountSats(paymentHash: String) -> UInt64? { + lock.withLock { stored[paymentHash.lowercased()]?.amountSats } + } + + /// Keeps `attempt`, sending `amountSats`, as the latest at the invoice with `paymentHash`, which expires at + /// `expiresAt`, and drops the attempts of invoices expired before `now`, both in epoch seconds. + static func set(paymentHash: String, attempt: UInt32, amountSats: UInt64, expiresAt: UInt64, now: UInt64) { lock.withLock { var attempts = stored.filter { $0.value.expiresAt >= now } - attempts[paymentHash.lowercased()] = Attempt(attempt: attempt, expiresAt: expiresAt) + attempts[paymentHash.lowercased()] = Attempt(attempt: attempt, expiresAt: expiresAt, amountSats: amountSats) stored = attempts } } - /// Puts back `attempt`, the latest kept before a send whose key never reached Spark, or drops the invoice's entry - /// when it had none. - static func restore(paymentHash: String, attempt: UInt32?, expiresAt: UInt64) { + /// Puts back `attempt` and its `amountSats`, the latest kept before a send whose key never reached Spark, or drops + /// the invoice's entry when it had none. + static func restore(paymentHash: String, attempt: UInt32?, amountSats: UInt64?, expiresAt: UInt64) { lock.withLock { var attempts = stored - attempts[paymentHash.lowercased()] = attempt.map { Attempt(attempt: $0, expiresAt: expiresAt) } + attempts[paymentHash.lowercased()] = attempt.map { Attempt(attempt: $0, expiresAt: expiresAt, amountSats: amountSats) } stored = attempts } } diff --git a/BitkitTests/FailPendingLightningSendTests.swift b/BitkitTests/FailPendingLightningSendTests.swift index da301ad77..8f93ebaaf 100644 --- a/BitkitTests/FailPendingLightningSendTests.swift +++ b/BitkitTests/FailPendingLightningSendTests.swift @@ -37,9 +37,15 @@ final class FailPendingLightningSendTests: XCTestCase { ))) } + var returned: [String: PaymentState?] = [:] for row in rows { - try await activity.failPendingLightningSend(id: row.id) + returned[row.id] = try await activity.failPendingLightningSend(id: row.id) } + XCTAssertEqual(returned["paid-send"], .succeeded) + XCTAssertEqual(returned["pending-send"], .failed) + XCTAssertEqual(returned["pending-receive"], .some(nil)) + let missing = try await activity.failPendingLightningSend(id: "missing") + XCTAssertNil(missing) let expected: [String: PaymentState] = [ "pending-send": .failed, "paid-send": .succeeded, "failed-send": .failed, "pending-receive": .pending, diff --git a/BitkitTests/SparkSendKeyTests.swift b/BitkitTests/SparkSendKeyTests.swift index b879bb6b8..a1c6fd1f4 100644 --- a/BitkitTests/SparkSendKeyTests.swift +++ b/BitkitTests/SparkSendKeyTests.swift @@ -52,7 +52,7 @@ final class SparkSendKeyTests: XCTestCase { func testARetryReusesItsAttemptsKeyUntilSparkListsThatAttemptFailed() { let secret = SparkSendKey.secret(seed: seed) - SparkSendAttempts.set(paymentHash: paymentHash, attempt: 1, expiresAt: 2000, now: 1000) + SparkSendAttempts.set(paymentHash: paymentHash, attempt: 1, amountSats: 1000, expiresAt: 2000, now: 1000) let firstFailed: Set = [SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: 0)] XCTAssertEqual(SparkSendAttempts.next(paymentHash: paymentHash, secret: secret, failedIds: firstFailed), 1) @@ -60,7 +60,7 @@ final class SparkSendKeyTests: XCTestCase { func testARetryTakesTheNextKeyOnceSparkListsItsAttemptFailed() { let secret = SparkSendKey.secret(seed: seed) - SparkSendAttempts.set(paymentHash: paymentHash, attempt: 0, expiresAt: 2000, now: 1000) + SparkSendAttempts.set(paymentHash: paymentHash, attempt: 0, amountSats: 1000, expiresAt: 2000, now: 1000) let failed = Set([0, 1].map { SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: $0) }) XCTAssertEqual(SparkSendAttempts.next(paymentHash: paymentHash, secret: secret, failedIds: failed), 2) @@ -68,8 +68,8 @@ final class SparkSendKeyTests: XCTestCase { func testAnExpiredInvoicesAttemptIsDropped() { let secret = SparkSendKey.secret(seed: seed) - SparkSendAttempts.set(paymentHash: paymentHash, attempt: 3, expiresAt: 1500, now: 1000) - SparkSendAttempts.set(paymentHash: String(repeating: "ab", count: 32), attempt: 0, expiresAt: 3000, now: 2000) + SparkSendAttempts.set(paymentHash: paymentHash, attempt: 3, amountSats: 1000, expiresAt: 1500, now: 1000) + SparkSendAttempts.set(paymentHash: String(repeating: "ab", count: 32), attempt: 0, amountSats: 1000, expiresAt: 3000, now: 2000) XCTAssertEqual(SparkSendAttempts.next(paymentHash: paymentHash, secret: secret, failedIds: []), 0) } @@ -106,9 +106,19 @@ final class SparkSendKeyTests: XCTestCase { } func testANewKeyWaitsWhileTheEarlierAttemptIsInDoubt() { - XCTAssertTrue(Bitkit.SparkManager.waitsForHold(isReusedKey: false, isInDoubt: true)) - XCTAssertFalse(Bitkit.SparkManager.waitsForHold(isReusedKey: true, isInDoubt: true)) - XCTAssertFalse(Bitkit.SparkManager.waitsForHold(isReusedKey: false, isInDoubt: false)) + XCTAssertTrue(Bitkit.SparkManager.waitsForHold(isReusedKey: false, isInDoubt: true, changesAmount: false)) + XCTAssertFalse(Bitkit.SparkManager.waitsForHold(isReusedKey: true, isInDoubt: true, changesAmount: false)) + XCTAssertFalse(Bitkit.SparkManager.waitsForHold(isReusedKey: false, isInDoubt: false, changesAmount: false)) + } + + func testAReusedKeyAtAnotherAmountWaits() { + XCTAssertTrue(Bitkit.SparkManager.waitsForHold(isReusedKey: true, isInDoubt: true, changesAmount: true)) + } + + func testAnExpiredSendAlreadyPaidStaysPaid() { + XCTAssertEqual(Bitkit.SparkManager.expiredSendStatus(stored: .succeeded), .succeeded) + XCTAssertEqual(Bitkit.SparkManager.expiredSendStatus(stored: .failed), .failed) + XCTAssertEqual(Bitkit.SparkManager.expiredSendStatus(stored: nil), .failed) } func testAFailedPaymentSparkReturnsIsRefused() { @@ -212,13 +222,14 @@ final class SparkSendKeyTests: XCTestCase { } func testARefusedAttemptGivesBackTheEarlierOne() { - SparkSendAttempts.set(paymentHash: paymentHash, attempt: 1, expiresAt: 2000, now: 1000) - SparkSendAttempts.set(paymentHash: paymentHash, attempt: 2, expiresAt: 2000, now: 1000) + SparkSendAttempts.set(paymentHash: paymentHash, attempt: 1, amountSats: 1000, expiresAt: 2000, now: 1000) + SparkSendAttempts.set(paymentHash: paymentHash, attempt: 2, amountSats: 2000, expiresAt: 2000, now: 1000) - SparkSendAttempts.restore(paymentHash: paymentHash, attempt: 1, expiresAt: 2000) + SparkSendAttempts.restore(paymentHash: paymentHash, attempt: 1, amountSats: 1000, expiresAt: 2000) XCTAssertEqual(SparkSendAttempts.latest(paymentHash: paymentHash), 1) + XCTAssertEqual(SparkSendAttempts.latestAmountSats(paymentHash: paymentHash), 1000) - SparkSendAttempts.restore(paymentHash: paymentHash, attempt: nil, expiresAt: 2000) + SparkSendAttempts.restore(paymentHash: paymentHash, attempt: nil, amountSats: nil, expiresAt: 2000) XCTAssertNil(SparkSendAttempts.latest(paymentHash: paymentHash)) } From c5ea2dbc86bb715253f71a5a17394ac5373079f3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 10:14:53 +0100 Subject: [PATCH 20/23] fix: let a pending spark attempt decide an expired send At expiry a send's pending attempt could lose to a newer failed attempt or to the filter for attempts listed before the send, so a send Spark still ran was failed. A paid attempt, then a pending one, now decides it. A failed attempt's outcome also rereads the stored row, so a success saved since the list was read stays paid. Verified: ChannelFreeRailTests, SparkSendKeyTests and FailPendingLightningSendTests pass on the simulator; swiftformat lint passes. --- Bitkit/Managers/SparkManager.swift | 27 ++++++++++++++++++++++---- BitkitTests/ChannelFreeRailTests.swift | 10 ++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index 971ee4cc5..ff36d2f07 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -2001,14 +2001,18 @@ final class SparkManager: ChannelFreeLightningRail { private func recordExpiredSend(paymentHash: String) async -> LDKNode.PaymentStatus? { guard let payments = try? await requireSdk().listPayments(request: ListPaymentsRequest()).payments else { return nil } let isEarlierAttempt = { LightningService.shared.isEarlierRailAttempt(paymentHash: $0, createdAt: $1) } - // A paid attempt settles the invoice whenever Spark dated it. - let paid = Self.expiredSendAttempt(payments.filter { $0.status == .completed }, paymentHash: paymentHash) { _, _ in false } - if let own = paid ?? Self.expiredSendAttempt(payments, paymentHash: paymentHash, isEarlierAttempt: isEarlierAttempt) { + if let own = Self.expiredSendDecidingAttempt(payments, paymentHash: paymentHash, isEarlierAttempt: isEarlierAttempt) { guard await recordActivity(own) else { return nil } switch own.status { case .completed: return .succeeded case .pending: return .pending - case .failed: return .failed + case .failed: + // A success saved since the list was read keeps its row, and stays paid. + do { + return try await Self.expiredSendStatus(stored: CoreService.shared.activity.failPendingLightningSend(id: paymentHash)) + } catch { + return nil + } } } do { @@ -2024,6 +2028,21 @@ final class SparkManager: ChannelFreeLightningRail { stored == .succeeded ? .succeeded : .failed } + /// The attempt that decides a send whose invoice expired: a paid one, then a pending one, whenever Spark dated them, + /// as either can still settle the invoice, else the latest attempt not listed before the send went out. + nonisolated static func expiredSendDecidingAttempt( + _ payments: [Payment], + paymentHash: String, + isEarlierAttempt: (_ hash: String, _ createdAt: UInt64) -> Bool + ) -> Payment? { + for status in [BreezSdkSpark.PaymentStatus.completed, .pending] { + if let live = expiredSendAttempt(payments.filter { $0.status == status }, paymentHash: paymentHash, isEarlierAttempt: { _, _ in false }) { + return live + } + } + return expiredSendAttempt(payments, paymentHash: paymentHash, isEarlierAttempt: isEarlierAttempt) + } + /// 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], diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index bf1959aa0..b21e7af3e 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -2128,6 +2128,16 @@ extension ChannelFreeRailTests { ) } + func testAnExpiredSendSparkStillListsPendingIsDecidedByThatAttempt() { + let hash = String(repeating: "cd", count: 32) + let pending = Self.sparkPayment(hash: hash, status: .pending, timestamp: 100) + let failed = Self.sparkPayment(hash: hash, status: .failed, timestamp: 200) + + let deciding = SparkManager.expiredSendDecidingAttempt([pending, failed], paymentHash: hash) { _, _ in true } + + XCTAssertEqual(deciding?.status, .pending) + } + func testAnEarlierFailureWhileARetryEntersSparksSendCallStaysOffItsScreen() async throws { let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) let hash = String(invoice.paymentHash()) From ac556adfcc67b77629c39c35f9b49b17b12cef34 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 11:15:23 +0100 Subject: [PATCH 21/23] fix: keep a spark hold at expiry while its retry is in flight At its invoice's expiry a send in doubt ended its hold and failed its row even while a retry under its key was in flight, so a retry refused before it went out left the send's waiters without an outcome. The hold now stays until that retry ends, and a later sync settles it. Verified: ChannelFreeRailTests, SparkSendKeyTests and FailPendingLightningSendTests pass on the simulator; swiftformat lint passes. --- Bitkit/Services/LightningService.swift | 2 ++ BitkitTests/ChannelFreeRailTests.swift | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index b38a8b41d..35413f08d 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1957,6 +1957,8 @@ class LightningService: NodeLifecycleService { guard let rail = channelFreeRail ?? channelFreePaymentHistory, await rail.hasSynced(after: UInt64(max(uncertain.startedAt, expiresAt))) else { return false } + // A retry in flight under the send's key settles it by its own outcome, or leaves the hold to a later sync. + guard !isRailSendInFlight(paymentHash: hash) else { return false } // Its Activity row is written first, so a stop in between finds the send held and writes it again. var status = PaymentStatus.failed if let record = railSendExpired { diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index b21e7af3e..e907e1030 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -768,6 +768,29 @@ extension ChannelFreeRailTests { XCTAssertEqual(failures.hashes, [], "a paid send was reported failed") } + func testASparkSendInDoubtKeepsItsHoldAtExpiryWhileARetryIsInFlight() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + let previousRecord = service.railSendExpired + defer { service.railSendExpired = previousRecord } + final class Calls: @unchecked Sendable { var count = 0 } + let calls = Calls() + service.railSendExpired = { _ in + calls.count += 1 + return .failed + } + try await sendInDoubtAfterALeafFailure() + rail.syncedAfter = { _ in true } + service.now = { try! Date(timeIntervalSince1970: Self.invoiceExpiresAt()) } + XCTAssertTrue(service.beginRailSend(paymentHash: hash)) + defer { service.endRailSend(paymentHash: hash) } + + await service.endExpiredRailSendUncertainties() + + XCTAssertEqual(calls.count, 0, "the send's row was failed under its retry") + XCTAssertNotNil(service.railSendHolds[hash], "the hold ended under its retry") + } + func testASparkRetryOfASendInDoubtRefusedBeforeItGoesOutStaysPending() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) try await sendInDoubtAfterALeafFailure() From f758f5dfa6fead17cc78db59051a39ea64e70f04 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 11:34:02 +0100 Subject: [PATCH 22/23] fix: keep a spark hold when a retry starts as its expiry is recorded A retry under the send's key that started while the expired send's row was written could still lose its hold, and one that ended meanwhile was reported failed. The hold now ends only when no retry is in flight or started since the check, judged under the lock that starts retries. Verified: ChannelFreeRailTests, SparkSendKeyTests and FailPendingLightningSendTests pass on the simulator; swiftformat lint passes. --- Bitkit/Services/LightningService.swift | 19 ++++++++++++++---- BitkitTests/ChannelFreeRailTests.swift | 27 ++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 35413f08d..4a164f923 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -210,6 +210,8 @@ 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 = [] + /// How many rail sends of each invoice started, so a check can tell one started since it read. + private var railSendStarts: [String: Int] = [:] /// 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] = [:] @@ -1957,15 +1959,19 @@ class LightningService: NodeLifecycleService { guard let rail = channelFreeRail ?? channelFreePaymentHistory, await rail.hasSynced(after: UInt64(max(uncertain.startedAt, expiresAt))) else { return false } - // A retry in flight under the send's key settles it by its own outcome, or leaves the hold to a later sync. - guard !isRailSendInFlight(paymentHash: hash) else { return false } + // A retry under the send's key, in flight or started since, settles it by its own outcome, or leaves the hold to + // a later sync. + let starts = eventCallbackLock.withLock { railSendsInFlight.contains(hash) ? nil : railSendStarts[hash] ?? 0 } + guard let starts else { return false } // Its Activity row is written first, so a stop in between finds the send held and writes it again. var status = PaymentStatus.failed if let record = railSendExpired { guard let recorded = await record(hash) else { return false } status = recorded } - let didEnd = endRailSendUncertainty(paymentHash: hash, startedAt: uncertain.startedAt) + let didEnd = endRailSendUncertainty(paymentHash: hash) { + $0 == uncertain.startedAt && !railSendsInFlight.contains(hash) && railSendStarts[hash] ?? 0 == starts + } // Reported as failed, so a send screen left on Pending resolves; a retry in flight reports its own outcome, and // a send Spark lists paid or pending reports by Spark's own event. if didEnd, status == .failed, !isRailSendInFlight(paymentHash: hash) { @@ -2012,7 +2018,12 @@ class LightningService: NodeLifecycleService { func beginRailSend(paymentHash: String?) -> Bool { guard let paymentHash else { return true } - return eventCallbackLock.withLock { railSendsInFlight.insert(paymentHash.lowercased()).inserted } + let hash = paymentHash.lowercased() + return eventCallbackLock.withLock { + guard railSendsInFlight.insert(hash).inserted else { return false } + railSendStarts[hash, default: 0] += 1 + return true + } } /// The last check before a send leaves on `rail`, under the same lock that marks the other rail's sends in flight, diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index e907e1030..742ca1108 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -791,6 +791,33 @@ extension ChannelFreeRailTests { XCTAssertNotNil(service.railSendHolds[hash], "the hold ended under its retry") } + func testASparkSendInDoubtKeepsItsHoldWhenARetryStartsAsItsExpiryIsRecorded() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + let previousRecord = service.railSendExpired + defer { service.railSendExpired = previousRecord } + service.railSendExpired = { hash in + XCTAssertTrue(service.beginRailSend(paymentHash: hash)) + service.endRailSend(paymentHash: hash) + return .failed + } + final class Failures: @unchecked Sendable { var hashes: [String] = [] } + let failures = Failures() + service.setEventCallback { event in + if case let .paymentFailed(_, paymentHash?, _) = event { + failures.hashes.append(paymentHash) + } + } + try await sendInDoubtAfterALeafFailure() + rail.syncedAfter = { _ in true } + service.now = { try! Date(timeIntervalSince1970: Self.invoiceExpiresAt()) } + + await service.endExpiredRailSendUncertainties() + + XCTAssertNotNil(service.railSendHolds[hash], "the hold ended under the retry") + XCTAssertEqual(failures.hashes, [], "the retry was reported failed") + } + func testASparkRetryOfASendInDoubtRefusedBeforeItGoesOutStaysPending() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) try await sendInDoubtAfterALeafFailure() From 3c465d3515a543c7d0798ae53792954d91d42122 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 26 Nov 2026 12:38:50 +0100 Subject: [PATCH 23/23] fix: read a spark send held for its retry as pending The expiry check reported a send settled even when it kept the hold for a retry, so a list read right after showed no pending send while the invoice was still held. It now reports settled only once the hold is gone. Verified: ChannelFreeRailTests, SparkSendKeyTests and FailPendingLightningSendTests pass on the simulator; swiftformat lint passes. --- Bitkit/Services/LightningService.swift | 3 ++- BitkitTests/ChannelFreeRailTests.swift | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 4a164f923..53f974d3b 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1977,7 +1977,8 @@ class LightningService: NodeLifecycleService { if didEnd, status == .failed, !isRailSendInFlight(paymentHash: hash) { deliverChannelFreeRailEvent(.paymentFailed(paymentId: hash, paymentHash: hash, reason: nil)) } - return true + // A hold kept for a retry, or a retry's own, still holds the invoice. + return didEnd || eventCallbackLock.withLock { uncertainRailSendFailedAt()[hash] == nil } } /// Ends the sends Spark never settled whose invoice expired since, once a sync after the grace reached Spark. diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 742ca1108..637155ce5 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -816,6 +816,8 @@ extension ChannelFreeRailTests { XCTAssertNotNil(service.railSendHolds[hash], "the hold ended under the retry") XCTAssertEqual(failures.hashes, [], "the retry was reported failed") + let payments = try await service.channelFreeRailPayments().filter { $0.paymentHash == hash } + XCTAssertTrue(payments.contains { $0.status == .pending }, "the held send read as settled") } func testASparkRetryOfASendInDoubtRefusedBeforeItGoesOutStaysPending() async throws {