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
60 changes: 41 additions & 19 deletions Bitkit/Services/LightningService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1132,6 +1132,7 @@ class LightningService: NodeLifecycleService {
}
}
var isRefusedAtAdmission = false
var didRecordAttempt = false
do {
return try await rail.send(
bolt11: bolt11,
Expand All @@ -1149,6 +1150,7 @@ class LightningService: NodeLifecycleService {
// Noted once admitted, so a refused attempt never takes the place of the one that went out.
self?.noteAttempt(on: .channelFree, bolt11: bolt11)
self?.recordRailAttempt(paymentHash: paymentHash, expiresAt: expiresAt)
didRecordAttempt = true
// Kept until Spark settles the attempt, so no retry of the invoice starts meanwhile, also after a
// relaunch.
if let paymentHash {
Expand All @@ -1157,8 +1159,9 @@ class LightningService: NodeLifecycleService {
}
)
} catch let refusal as ChannelFreeRailSendRefused {
// Nothing left the wallet, and the checks above leave no earlier live attempt under this hash.
if let paymentHash {
// Nothing left the wallet. Refused before submission, this send recorded nothing, so another send's
// attempt and hold of the invoice stay.
if let paymentHash, didRecordAttempt {
endRailSendUncertainty(paymentHash: paymentHash)
releaseRailAttempt(paymentHash: paymentHash, unlessInFlight: false)
}
Expand All @@ -1174,8 +1177,9 @@ class LightningService: NodeLifecycleService {
guard let paid = try await settledRecordedRailSend(paymentHash: paymentHash, since: mark) else { throw error }
return paid
} catch {
// A send that failed once submitted may still go out, so its outcome waits for a later sync.
if let paymentHash {
// A send that failed once submitted may still go out, so its outcome waits for a later sync. One that
// failed before it recorded its attempt never reached Spark.
if let paymentHash, didRecordAttempt {
markRailSendUncertain(paymentHash: paymentHash, since: mark)
}
throw error
Expand Down Expand Up @@ -1386,8 +1390,13 @@ class LightningService: NodeLifecycleService {
eventCallbackLock.withLock { AttemptMark(records: attemptRecords, railInFlight: railSendsInFlight, ldkInFlight: ldkSendsInFlight) }
}

private func releaseLdkAttempt(paymentHash: String) {
eventCallbackLock.withLock { removeAttempt(paymentHash: paymentHash.lowercased(), key: Self.ldkAttemptsKey) }
/// Skipped when a node send of the invoice is in flight, or was recorded since `mark`, as that send holds it again.
private func releaseLdkAttempt(paymentHash: String, since mark: AttemptMark) {
let hash = paymentHash.lowercased()
eventCallbackLock.withLock {
guard !attemptsLive(since: mark, key: Self.ldkAttemptsKey).contains(hash) else { return }
removeAttempt(paymentHash: hash, key: Self.ldkAttemptsKey)
}
}

/// Callers hold `eventCallbackLock`.
Expand Down Expand Up @@ -1450,11 +1459,11 @@ class LightningService: NodeLifecycleService {
/// The node's payments, after keeping its attempts from them, with the hashes still holding Spark (`live`); nil
/// while the node can't list them.
@discardableResult
private func listNodePaymentsKeepingAttempts() async -> (payments: [PaymentDetails], live: Set<String>)? {
private func listNodePaymentsKeepingAttempts() async -> (payments: [PaymentDetails], live: Set<String>, mark: AttemptMark)? {
let mark = attemptMark
guard let payments = await nodePayments() else { return nil }
let live = keepLdkAttempts(from: payments, since: mark)
return (payments, live)
return (payments, live, mark)
}

/// Keeps the hashes of the node's pending and paid outbound payments, once, so those made before hashes were kept
Expand Down Expand Up @@ -1523,7 +1532,7 @@ class LightningService: NodeLifecycleService {
guard let paymentHash else { return nil }
var statuses: [PaymentStatus] = rails.contains(.channelFree) && isRailSendInFlight(paymentHash: paymentHash) ? [.pending] : []
if rails.contains(.ldk) {
if let (payments, live) = await listNodePaymentsKeepingAttempts() {
if let (payments, live, mark) = await listNodePaymentsKeepingAttempts() {
let payment = payments.first {
$0.direction == .outbound && $0.id.caseInsensitiveCompare(paymentHash) == .orderedSame
}
Expand All @@ -1535,7 +1544,7 @@ class LightningService: NodeLifecycleService {
if live.contains(paymentHash.lowercased()) {
statuses.append(.pending)
} else {
releaseLdkAttempt(paymentHash: paymentHash)
releaseLdkAttempt(paymentHash: paymentHash, since: mark)
}
}
} else if hasAttempt(paymentHash: paymentHash, key: Self.ldkAttemptsKey) {
Expand Down Expand Up @@ -1563,7 +1572,8 @@ class LightningService: NodeLifecycleService {
Logger.info("Held '\(paymentHash)' until Spark syncs after its unknown send", context: "LightningService")
statuses.append(.pending)
} else {
releaseRailAttempt(paymentHash: paymentHash)
// A retry recorded while Spark synced keeps its attempt.
releaseRailAttempt(paymentHash: paymentHash, since: mark)
if !isPaidOverTheNode {
try await refuseUnverifiedRestoredInvoice(
paymentHash: paymentHash, bolt11: bolt11, sats: sats,
Expand Down Expand Up @@ -1819,8 +1829,8 @@ class LightningService: NodeLifecycleService {
}
}

/// True unless the hash's last rail send failed after it was submitted and may still go out: no sync has reached the
/// rail since, or its invoice hasn't expired.
/// True unless the hash's last rail send failed after it was submitted and may still go out: its invoice hasn't
/// expired, or no sync has reached the rail since it did.
private func railSyncedSinceUncertainSend(paymentHash: String) async -> Bool {
let hash = paymentHash.lowercased()
let uncertain = eventCallbackLock.withLock {
Expand All @@ -1831,7 +1841,7 @@ class LightningService: NodeLifecycleService {
// can still fail to resume it, so only an expired invoice shows a missing send will never go out.
guard let expiresAt = uncertain.expiresAt, Int(now().timeIntervalSince1970) >= expiresAt else { return false }
// During an exit Spark no longer sends but still syncs its history, which settles the send the same way.
guard let rail = channelFreeRail ?? channelFreePaymentHistory, await rail.hasSynced(after: UInt64(uncertain.startedAt)) else {
guard let rail = channelFreeRail ?? channelFreePaymentHistory, await rail.hasSynced(after: UInt64(max(uncertain.startedAt, expiresAt))) else {
return false
}
// Its Activity row is written first, so a stop in between finds the send held and writes it again.
Expand Down Expand Up @@ -2538,20 +2548,32 @@ extension LightningService {
// A restored wallet fills its list on its first sync, so before a sync reaches Spark a missing send proves
// nothing.
guard await rail.hasSynced(after: nil) else { throw ChannelFreeRailUnavailable() }
// Read before the listing, so a sync that ends while it is read can't settle a send the listing predates.
// Read before the listing, so a sync that ends while it is read can't settle a send the listing predates,
// and a hold taken meanwhile reads as taken during the read.
let mark = attemptMark
let heldBefore = railSendHolds
let unsettledBefore = await unsettledUncertainRailSends()
let kept = unexpiredRailAttempts()
let heldBefore = railSendHolds
let payments = try await rail.lightningPayments()
// A send Spark lists a settled attempt of is no longer held; the others read pending until then.
settleListedRailSends(payments, heldBefore: heldBefore)
let stillUnsettled = eventCallbackLock.withLock { Set(uncertainRailSendFailedAt().keys) }
let holdsAfter = eventCallbackLock.withLock { uncertainRailSendFailedAt() }
let stillUnsettled = Set(holdsAfter.keys)
// A hold that ended during the read without its result in the list (a success Spark lists later) stays
// pending, so it never reads as an earlier attempt's failure.
let unsettled = unsettledBefore.filter {
stillUnsettled.contains($0.paymentHash)
|| !Self.listsResult(payments, paymentHash: $0.paymentHash, startedAt: heldBefore[$0.paymentHash])
}
// A retry in flight during the read, or that took a hold or recorded its attempt meanwhile, is one this list
// predates, so it reads pending until a later list shows its result, also when it already ended.
let unsettledHashes = Set(unsettled.map { $0.paymentHash.lowercased() })
let recordedDuringRead = eventCallbackLock.withLock { attemptsLive(since: mark, key: Self.railAttemptsKey) }
let paidHashes = Set(payments.filter { $0.direction == .outbound && $0.status == .succeeded }.map { $0.paymentHash.lowercased() })
let heldDuringRead = Set(holdsAfter.filter { heldBefore[$0.key] != $0.value }.keys)
.union(recordedDuringRead.subtracting(paidHashes))
.subtracting(unsettledHashes).sorted()
.map { ChannelFreeRailPayment(paymentHash: $0, direction: .outbound, status: .pending, preimage: nil) }
if let since = sparkHistoryUnseededSince, await rail.hasSynced(after: UInt64(clamping: since)) {
// Kept, so after a relaunch the sends Spark listed hold the node until Spark syncs again.
let seeded = payments.filter { $0.direction == .outbound && $0.status != .failed }.map { $0.paymentHash.lowercased() }
Expand All @@ -2562,10 +2584,10 @@ extension LightningService {
}
clearSparkHistoryUnseeded()
}
let listed = Set((payments + unsettled).filter { $0.direction == .outbound }.map { $0.paymentHash.lowercased() })
let listed = Set((payments + unsettled + heldDuringRead).filter { $0.direction == .outbound }.map { $0.paymentHash.lowercased() })
let unlisted = kept.subtracting(listed).sorted()
.map { ChannelFreeRailPayment(paymentHash: $0, direction: .outbound, status: .pending, preimage: nil) }
return payments + unsettled + unlisted
return payments + unsettled + heldDuringRead + unlisted
}
if await channelFreeRailSupported() {
throw ChannelFreeRailUnavailable()
Expand Down
127 changes: 125 additions & 2 deletions BitkitTests/ChannelFreeRailTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -862,6 +862,11 @@ extension ChannelFreeRailTests {
rail.balanceSats = 0

await assertReachesTheNode()

// The listed failure released the hold, so a retry still reaches the node once Spark's history can't be read.
rail.listError = NSError(domain: "spark", code: 1)

await assertReachesTheNode()
}

/// Keeps only what the service stores across launches: the rail's kept keys survive, everything in memory goes.
Expand Down Expand Up @@ -1704,12 +1709,13 @@ extension ChannelFreeRailTests {
defer { service.railSendExpired = previousRecord }
let expiresAt = try Self.invoiceExpiresAt()
service.now = { Date(timeIntervalSince1970: expiresAt) }
// Spark's last sync came before the retry, so only a lost hold lets the invoice go out again.
rail.syncedAfter = { seconds in seconds.map { $0 < UInt64(expiresAt) } ?? true }
// Spark's last sync came after the expiry but before the retry, so only a lost hold lets the invoice go out again.
rail.syncedAfter = { seconds in seconds.map { $0 <= UInt64(expiresAt) } ?? true }
// While the expired send's row is written, its own failure ends it and a retry of the invoice goes to Spark.
service.railSendExpired = { [self] _ in
service.railSendExpired = nil
service.emitChannelFreeRailEvent(.paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), paymentCreatedAt: Self.sparkNow())
service.now = { Date(timeIntervalSince1970: expiresAt + 5) }
try? await sendOverSpark()
return true
}
Expand Down Expand Up @@ -1806,6 +1812,120 @@ extension ChannelFreeRailTests {
XCTAssertTrue(payments.contains { $0.status == .pending }, "the retry read as A's failure")
}

func testARetryHeldWhileSparksListIsReadReadsPending() async throws {
let (hash, startedAt) = try await sendARetryFiveSecondsAfterAFailedAttempt()
let service = Bitkit.LightningService.shared
// No hold before the read; a retry takes one while Spark's list, showing only A's failure, is read.
service.railAttemptsStore.set([String: Int](), forKey: Self.uncertainRailSendsKey)
rail.onList = {
service.railAttemptsStore.set([hash: Int(startedAt) + 30], forKey: Self.uncertainRailSendsKey)
}

let payments = try await service.channelFreeRailPayments().filter { $0.paymentHash == hash }

XCTAssertTrue(payments.contains { $0.status == .pending }, "the retry held during the read read as A's failure")
}

func testARetryThatStartsAndEndsWhileSparksListIsReadReadsPending() async throws {
let (hash, _) = try await sendARetryFiveSecondsAfterAFailedAttempt()
let service = Bitkit.LightningService.shared
// No hold before the read; a retry records its attempt and its success ends its hold while the list, showing
// only A's failure, is read.
service.railAttemptsStore.set([String: Int](), forKey: Self.uncertainRailSendsKey)
rail.onList = {
service.recordRailAttempt(paymentHash: hash)
}

let payments = try await service.channelFreeRailPayments().filter { $0.paymentHash == hash }

XCTAssertTrue(payments.contains { $0.status == .pending }, "the retry read as A's failure")
}

func testARetryInFlightWhenSparksListIsReadReadsPendingAfterItEnds() async throws {
let (hash, _) = try await sendARetryFiveSecondsAfterAFailedAttempt()
let service = Bitkit.LightningService.shared
// No hold before the read; a retry in flight when it starts ends while the list, showing only A's failure, is read.
service.railAttemptsStore.set([String: Int](), forKey: Self.uncertainRailSendsKey)
XCTAssertTrue(service.beginRailSend(paymentHash: hash))
defer { service.endRailSend(paymentHash: hash) }
rail.onList = {
service.endRailSend(paymentHash: hash)
}

let payments = try await service.channelFreeRailPayments().filter { $0.paymentHash == hash }

XCTAssertTrue(payments.contains { $0.status == .pending }, "the retry read as A's failure")
}

func testASparkSendFailingBeforeItRecordsItsAttemptTakesNoHold() async throws {
let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash())
let service = Bitkit.LightningService.shared
rail.balanceSats = 100_000
// Another send records its attempt after this one's checks; this one's own check then fails before submission.
final class Entered: @unchecked Sendable { var value = false }
let entered = Entered()
rail.onSend = {
entered.value = true
service.recordRailAttempt(paymentHash: hash)
}

do {
_ = try await service.send(bolt11: Self.invoice, beforeSubmission: { throw NSError(domain: "request", code: 1) })
XCTFail("Expected the send's own check to fail")
} catch {
XCTAssertEqual((error as NSError).domain, "request", "\(error)")
}

XCTAssertTrue(entered.value, "the send never reached Spark's send call")
XCTAssertNil(service.railSendHolds[hash], "a send that never reached Spark took a hold")
}

func testAnExpiredSendStaysHeldUntilASyncAfterItsExpiry() async throws {
let (hash, _) = try await sendARetryFiveSecondsAfterAFailedAttempt()
let service = Bitkit.LightningService.shared
let previousRecord = service.railSendExpired
defer { service.railSendExpired = previousRecord }
final class Calls: @unchecked Sendable { var count = 0 }
let calls = Calls()
service.railSendExpired = { _ in
calls.count += 1
return true
}
let expiresAt = try Self.invoiceExpiresAt()
service.now = { Date(timeIntervalSince1970: expiresAt) }
// Spark's last sync came after the send, but before its invoice expired.
rail.syncedAfter = { ($0 ?? 0) < UInt64(expiresAt) }

await service.endExpiredRailSendUncertainties()

XCTAssertEqual(calls.count, 0, "a sync before the expiry settled the send")
XCTAssertNotNil(service.railSendHolds[hash])

rail.syncedAfter = { _ in true }
await service.endExpiredRailSendUncertainties()

XCTAssertEqual(calls.count, 1)
XCTAssertNil(service.railSendHolds[hash])
}

func testASparkSendRefusedBeforeSubmissionKeepsAnotherSendsAttemptAndHold() async throws {
let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash())
let service = Bitkit.LightningService.shared
rail.balanceSats = 100_000
// Send A of the invoice went out and returned after this send's checks, then Spark refuses this one before
// submission, as A spent the balance.
rail.onSend = {
service.railAttemptsStore.set([hash], forKey: Self.railAttemptsKey)
service.railAttemptsStore.set([hash: 1000], forKey: Self.uncertainRailSendsKey)
}
rail.refusal = Bitkit.ChannelFreeRailSendRefused(reason: "insufficient balance")

_ = try? await service.send(bolt11: Self.invoice)

XCTAssertEqual(service.railAttemptsStore.stringArray(forKey: Self.railAttemptsKey), [hash], "A's attempt was released")
XCTAssertNotNil(service.railSendHolds[hash], "A's hold was ended")
}

func testAnExpiredRetryFailsItsOwnRowWhenSparkListsOnlyTheFailureFiveSecondsBeforeIt() async throws {
let (hash, startedAt) = try await sendARetryFiveSecondsAfterAFailedAttempt()
let service = Bitkit.LightningService.shared
Expand Down Expand Up @@ -2162,6 +2282,8 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail {
var refusalAfterSubmission: Bitkit.ChannelFreeRailSendRefused?
/// Runs while a listing is read, before it returns `payments`.
var onList: (() -> Void)?
/// Runs as a send enters Spark, before `refusal`.
var onSend: (() -> Void)?
/// Runs as a send is about to be submitted, before `beforeSubmission`.
var beforeSubmit: (() -> Void)?
/// Thrown after the send was submitted, as when the connection drops inside Spark's send.
Expand All @@ -2182,6 +2304,7 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail {
}

func send(bolt11: String, sats: UInt64?, maxFeeSats: UInt64?, beforeSubmission: @escaping () throws -> Void) async throws -> PaymentHash {
onSend?()
if let refusal {
throw refusal
}
Expand Down
Loading
Loading