diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 8c0664faf..8fde8d758 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -169,8 +169,9 @@ class LightningService: NodeLifecycleService { private var attemptRecords = 0 /// Per store key, the `attemptRecords` count at each hash's latest record. private var attemptRecordedAt: [String: [String: Int]] = [:] - /// Node sends under way, so a listing that shows only an earlier failed attempt doesn't drop their hash. - private var ldkSendsInFlight: Set = [] + /// Node sends under way, counted per hash, so a listing that shows only an earlier failed attempt doesn't drop their + /// hash, and one send ending leaves a repeat send of the invoice in flight. + private var ldkSendsInFlight: [String: Int] = [:] weak var channelFreeRail: ChannelFreeLightningRail? /// The rail whose payments the duplicate-payment check reads, kept while an emergency exit takes Spark off /// Lightning: an invoice Spark paid or is paying is never paid again over a channel. @@ -1194,12 +1195,19 @@ class LightningService: NodeLifecycleService { Logger.info("Paying bolt11: \(bolt11)") let sendKey = paymentHash?.lowercased() - defer { endLdkSend(paymentHash: sendKey) } + // Only an admitted send is counted in flight, so a refused one must not end another's. + var isAdmitted = false + defer { + if isAdmitted { + endLdkSend(paymentHash: sendKey) + } + } do { return try await Self.submitPayment(beforeSubmission: { [weak self] in try beforeSubmission() guard let self else { return } try admitSend(paymentHash: sendKey, on: .ldk, since: mark) + isAdmitted = true noteAttempt(on: .ldk, bolt11: bolt11) recordLdkAttempt(paymentHash: paymentHash, expiresAt: expiresAt) }) { @@ -1379,7 +1387,7 @@ class LightningService: NodeLifecycleService { /// The attempts recorded so far and the sends in flight, read before a listing so a trim or release from it skips /// the retries recorded since, and the ones in flight then that ended while it was read. var attemptMark: AttemptMark { - eventCallbackLock.withLock { AttemptMark(records: attemptRecords, railInFlight: railSendsInFlight, ldkInFlight: ldkSendsInFlight) } + eventCallbackLock.withLock { AttemptMark(records: attemptRecords, railInFlight: railSendsInFlight, ldkInFlight: Set(ldkSendsInFlight.keys)) } } private func releaseLdkAttempt(paymentHash: String) { @@ -1408,7 +1416,7 @@ class LightningService: NodeLifecycleService { /// The hashes under `key` that may still be pending since `mark`: in flight now or then, or recorded after it. /// Callers hold `eventCallbackLock`. private func attemptsLive(since mark: AttemptMark, key: String) -> Set { - let inFlight = key == Self.railAttemptsKey ? railSendsInFlight.union(mark.railInFlight) : ldkSendsInFlight.union(mark.ldkInFlight) + let inFlight = key == Self.railAttemptsKey ? railSendsInFlight.union(mark.railInFlight) : mark.ldkInFlight.union(ldkSendsInFlight.keys) return inFlight.union(attemptsRecorded(since: mark.records, key: key)) } @@ -1724,7 +1732,7 @@ class LightningService: NodeLifecycleService { func admitSend(paymentHash: String?, on rail: LightningPaymentRail, since mark: AttemptMark) throws { guard let hash = paymentHash?.lowercased() else { return } try eventCallbackLock.withLock { - let otherInFlight = rail == .ldk ? railSendsInFlight : ldkSendsInFlight + let otherInFlight = rail == .ldk ? railSendsInFlight : Set(ldkSendsInFlight.keys) let otherKey = rail == .ldk ? Self.railAttemptsKey : Self.ldkAttemptsKey if otherInFlight.contains(hash) || attemptsRecorded(since: mark.records, key: otherKey).contains(hash) { Logger.warn("Refused paying '\(hash)', the other rail sent it meanwhile", context: "LightningService") @@ -1735,7 +1743,7 @@ class LightningService: NodeLifecycleService { throw Self.pendingDuplicate(paymentHash: hash) } if rail == .ldk { - ldkSendsInFlight.insert(hash) + ldkSendsInFlight[hash, default: 0] += 1 } } } @@ -1769,19 +1777,23 @@ class LightningService: NodeLifecycleService { /// Whether a send of `hash` is in flight on either rail, or the node recorded one since `mark`. private func isSendLive(paymentHash hash: String, since mark: AttemptMark) -> Bool { eventCallbackLock.withLock { - railSendsInFlight.contains(hash) || ldkSendsInFlight.contains(hash) + railSendsInFlight.contains(hash) || ldkSendsInFlight[hash] != nil || attemptsRecorded(since: mark.records, key: Self.ldkAttemptsKey).contains(hash) } } func beginLdkSend(paymentHash: String?) { guard let paymentHash else { return } - _ = eventCallbackLock.withLock { ldkSendsInFlight.insert(paymentHash.lowercased()) } + eventCallbackLock.withLock { ldkSendsInFlight[paymentHash.lowercased(), default: 0] += 1 } } func endLdkSend(paymentHash: String?) { guard let paymentHash else { return } - _ = eventCallbackLock.withLock { ldkSendsInFlight.remove(paymentHash.lowercased()) } + let hash = paymentHash.lowercased() + eventCallbackLock.withLock { + guard let count = ldkSendsInFlight[hash] else { return } + ldkSendsInFlight[hash] = count > 1 ? count - 1 : nil + } } func endRailSend(paymentHash: String?) { diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 56f222a97..b8bcb9209 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -478,6 +478,19 @@ extension ChannelFreeRailTests { await assertRefusedAsDuplicate() } + func testANodeSendEndingLeavesARepeatNodeSendOfTheInvoiceInFlight() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + // Two node sends of the invoice are under way; one returns while the other is still queued. + service.beginLdkSend(paymentHash: hash) + service.beginLdkSend(paymentHash: hash) + service.endLdkSend(paymentHash: hash) + defer { service.endLdkSend(paymentHash: hash) } + rail.balanceSats = 100_000 + + await assertRefusedAsDuplicate() + } + func testASparkAttemptRefusedAtAdmissionKeepsTheNodeAttemptAsTheLatest() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared diff --git a/changelog.d/next/1405.fixed.md b/changelog.d/next/1405.fixed.md new file mode 100644 index 000000000..abf5bfff7 --- /dev/null +++ b/changelog.d/next/1405.fixed.md @@ -0,0 +1 @@ +A Lightning invoice sent twice at once can no longer be paid a second time over Spark later.