Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 22 additions & 10 deletions Bitkit/Services/LightningService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = []
/// 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.
Expand Down Expand Up @@ -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)
}) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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<String> {
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))
}

Expand Down Expand Up @@ -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")
Expand All @@ -1735,7 +1743,7 @@ class LightningService: NodeLifecycleService {
throw Self.pendingDuplicate(paymentHash: hash)
}
if rail == .ldk {
ldkSendsInFlight.insert(hash)
ldkSendsInFlight[hash, default: 0] += 1
}
}
}
Expand Down Expand Up @@ -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?) {
Expand Down
13 changes: 13 additions & 0 deletions BitkitTests/ChannelFreeRailTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions changelog.d/next/1405.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A Lightning invoice sent twice at once can no longer be paid a second time over Spark later.
Loading