From 45ff9d453e7f7fd206b3a7bab986a41fd76f413f Mon Sep 17 00:00:00 2001 From: ovitrif Date: Mon, 23 Nov 2026 13:12:26 +0100 Subject: [PATCH 1/7] fix: stop the native abort when the node stops with stuck work Takes ldk-node 0.7.0-rc.81, which keeps the runtime alive until detached work ends. Verified: none (unit suite runs next on m1a) --- Bitkit.xcodeproj/project.pbxproj | 2 +- .../project.xcworkspace/xcshareddata/swiftpm/Package.resolved | 4 ++-- changelog.d/next/1393.fixed.md | 1 + 3 files changed, 4 insertions(+), 3 deletions(-) create mode 100644 changelog.d/next/1393.fixed.md diff --git a/Bitkit.xcodeproj/project.pbxproj b/Bitkit.xcodeproj/project.pbxproj index 8b60f615c..ae80d4f6b 100644 --- a/Bitkit.xcodeproj/project.pbxproj +++ b/Bitkit.xcodeproj/project.pbxproj @@ -1295,7 +1295,7 @@ repositoryURL = "https://github.com/synonymdev/ldk-node"; requirement = { kind = exactVersion; - version = "0.7.0-rc.80"; + version = "0.7.0-rc.81"; }; }; 96DEA0382DE8BBA1009932BF /* XCRemoteSwiftPackageReference "bitkit-core" */ = { diff --git a/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 1b6b5c2ba..879f7e42c 100644 --- a/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -24,8 +24,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/synonymdev/ldk-node", "state" : { - "revision" : "b6335ecd86e9e9dc4e824dcb4b6065273572ca9d", - "version" : "0.7.0-rc.80" + "revision" : "366d56ef3c735406146ed12a34aba291776d29f6", + "version" : "0.7.0-rc.81" } }, { diff --git a/changelog.d/next/1393.fixed.md b/changelog.d/next/1393.fixed.md new file mode 100644 index 000000000..55ec0597c --- /dev/null +++ b/changelog.d/next/1393.fixed.md @@ -0,0 +1 @@ +Fixed a rare crash when the Lightning node stops while background work is still running. From 86131400ed9be90f7dd7c992e51f6da1404c8a3b Mon Sep 17 00:00:00 2001 From: ovitrif Date: Mon, 23 Nov 2026 14:01:03 +0100 Subject: [PATCH 2/7] fix: release the old node on each restart The event loop awaited nextEventAsync(), which cannot be cancelled and never returns once its node stops, so every restart kept the stopped node, its runtime and a loop alive. Poll nextEvent() in a stored task that is cancelled when the node changes, is cleared or fails to start, and that ends once its node is no longer current. Verified: none (unit suite runs next on m1a) --- Bitkit/Services/LightningService.swift | 50 ++++++++++++++++++++------ changelog.d/next/1276.fixed.md | 1 + 2 files changed, 41 insertions(+), 10 deletions(-) create mode 100644 changelog.d/next/1276.fixed.md diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index e7df577f0..443628e74 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -106,7 +106,17 @@ protocol NodeLifecycleService: AnyObject { class LightningService: NodeLifecycleService { private static let watchOnlyAccountHighestPreRevealedAddressIndex: UInt32 = 999 - private var node: Node? + private var node: Node? { + didSet { + if node !== oldValue { + cancelEventLoop() + } + } + } + + private let eventLoopLock = NSLock() + private var eventLoopTask: Task? + private static let eventPollInterval: Duration = .milliseconds(100) private let beforeNodeStopLock = NSLock() private var beforeNodeStopAction: (() async -> Void)? /// Runs before the node stops, while its wallet can still release what was prepared on it. @@ -388,8 +398,13 @@ class LightningService: NodeLifecycleService { listenForEvents(onEvent: eventCallbackLock.withLock { storedEventCallback }) Logger.debug("Starting node...") - try await ServiceQueue.background(.ldk) { - try node.start() + do { + try await ServiceQueue.background(.ldk) { + try node.start() + } + } catch { + cancelEventLoop() + throw error } #if !BITKIT_NOTIFICATION_EXTENSION @@ -2420,15 +2435,23 @@ extension LightningService { await completion?() } + /// Polls instead of awaiting `nextEventAsync()`: that call cannot be cancelled and never returns once its node stops, so it would keep + /// the stopped node, its runtime and this loop alive. The loop ends once `node` is no longer the current node. func listenForEvents(onEvent: ((Event) -> Void)? = nil) { - Task { - while true { - guard let node = self.node else { - Logger.error("LDK node not started") - return - } + guard let node else { + Logger.error("LDK node not started") + return + } - let event = await node.nextEventAsync() + eventLoopLock.lock() + defer { eventLoopLock.unlock() } + eventLoopTask?.cancel() + eventLoopTask = Task { + while !Task.isCancelled, self.node === node { + guard let event = node.nextEvent() else { + try? await Task.sleep(for: Self.eventPollInterval) + continue + } do { try node.eventHandled() @@ -2631,6 +2654,13 @@ extension LightningService { } } + private func cancelEventLoop() { + eventLoopLock.withLock { + eventLoopTask?.cancel() + eventLoopTask = nil + } + } + private func registerClosedChannel( channel: ChannelDetails, reason: String diff --git a/changelog.d/next/1276.fixed.md b/changelog.d/next/1276.fixed.md new file mode 100644 index 000000000..a83b0987c --- /dev/null +++ b/changelog.d/next/1276.fixed.md @@ -0,0 +1 @@ +Fixed each Lightning node restart leaving the previous node running in the background. From 7a75ac7245d8c143e0359f086b84d1599cd1b39e Mon Sep 17 00:00:00 2001 From: ovitrif Date: Mon, 23 Nov 2026 15:35:56 +0100 Subject: [PATCH 3/7] fix: keep events flowing across node starts and stops - start() cancelled the event loop on any failure of node.start(), including AlreadyRunning, which left a node that keeps running without one. It now keeps the loop then. - stop() returned while the cancelled loop could still be handling an event of the stopped node, so the next node could load a queue that still held it and deliver it again. stop() now waits up to 5 s for the loop to end. Verified: swiftformat --lint; build and unit suite run next. --- Bitkit/Services/LightningService.swift | 47 +++++++++++++++++++++++-- BitkitTests/LightningServiceTests.swift | 17 +++++++++ 2 files changed, 61 insertions(+), 3 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 443628e74..7c1177cc1 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -2,6 +2,7 @@ import BitkitCore import Combine import Foundation import LDKNode +import os // TODO: catch all errors and pass a readable error message to the UI @@ -117,6 +118,8 @@ class LightningService: NodeLifecycleService { private let eventLoopLock = NSLock() private var eventLoopTask: Task? private static let eventPollInterval: Duration = .milliseconds(100) + // Bounds the wait for the loop's last iteration, as `eventHandled()` can block on a stuck VSS write. + private static let eventLoopStopTimeout: Duration = .seconds(5) private let beforeNodeStopLock = NSLock() private var beforeNodeStopAction: (() async -> Void)? /// Runs before the node stops, while its wallet can still release what was prepared on it. @@ -403,7 +406,13 @@ class LightningService: NodeLifecycleService { try node.start() } } catch { - cancelEventLoop() + switch error { + case NodeError.AlreadyRunning: + // The node keeps running, so it keeps the loop started above. + break + default: + cancelEventLoop() + } throw error } @@ -453,7 +462,12 @@ class LightningService: NodeLifecycleService { try await ServiceQueue.background(.ldk) { try Self.stopReleasingFinishedNode(node.stop) } + let eventLoop = cancelEventLoop() self.node = nil + // An event the loop took is handled, and its removal from the queue persisted, before the next node loads that queue. + if let eventLoop, await !Self.waitForEnd(of: eventLoop, timeout: Self.eventLoopStopTimeout) { + Logger.warn("Event loop of the stopped node did not end in time", context: "LightningService") + } if clearEventCallback { self.clearEventCallback() @@ -2654,10 +2668,37 @@ extension LightningService { } } - private func cancelEventLoop() { + @discardableResult + private func cancelEventLoop() -> Task? { eventLoopLock.withLock { - eventLoopTask?.cancel() + let task = eventLoopTask + task?.cancel() eventLoopTask = nil + return task + } + } + + /// Returns whether `task` ended within `timeout`. + static func waitForEnd(of task: Task, timeout: Duration) async -> Bool { + let resumed = OSAllocatedUnfairLock(initialState: false) + return await withCheckedContinuation { continuation in + let resume = { (ended: Bool) in + let first = resumed.withLock { resumed in + defer { resumed = true } + return !resumed + } + if first { + continuation.resume(returning: ended) + } + } + Task { + await task.value + resume(true) + } + Task { + try? await Task.sleep(for: timeout) + resume(false) + } } } diff --git a/BitkitTests/LightningServiceTests.swift b/BitkitTests/LightningServiceTests.swift index 11cdbe9ac..51ef7b325 100644 --- a/BitkitTests/LightningServiceTests.swift +++ b/BitkitTests/LightningServiceTests.swift @@ -21,4 +21,21 @@ final class LightningServiceTests: XCTestCase { func testStopKeepsANodeWhoseStopFailedOtherwise() { XCTAssertThrowsError(try Bitkit.LightningService.stopReleasingFinishedNode { throw NodeError.ConnectionFailed(message: "") }) } + + func testWaitForEndReturnsOnceTheTaskEnds() async { + let task = Task { try? await Task.sleep(for: .milliseconds(50)) } + let ended = await Bitkit.LightningService.waitForEnd(of: task, timeout: .seconds(10)) + XCTAssertTrue(ended) + } + + func testWaitForEndGivesUpOnATaskThatDoesNotEnd() async { + let release = AsyncStream.makeStream() + let task = Task { + for await _ in release.stream {} + } + let ended = await Bitkit.LightningService.waitForEnd(of: task, timeout: .milliseconds(50)) + XCTAssertFalse(ended) + release.continuation.finish() + await task.value + } } From 787467cb2811d133dcd172d609a546b7d388ac9f Mon Sep 17 00:00:00 2001 From: ovitrif Date: Mon, 23 Nov 2026 16:33:52 +0100 Subject: [PATCH 4/7] fix: keep the running loop when a start finds the node running ServiceQueue wraps the error of node.start() in AppError, so the AlreadyRunning check never matched and a redundant start still cancelled the running node's loop. A new loop now also waits for the one it replaces, so both never handle the same event, and stop() clears the node only after its loop ended. Verified: swiftformat --lint --- Bitkit/Services/LightningService.swift | 40 ++++++++++++++++--------- BitkitTests/LightningServiceTests.swift | 7 +++++ 2 files changed, 33 insertions(+), 14 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 7c1177cc1..94686ce29 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -406,11 +406,8 @@ class LightningService: NodeLifecycleService { try node.start() } } catch { - switch error { - case NodeError.AlreadyRunning: - // The node keeps running, so it keeps the loop started above. - break - default: + // A node that is already running keeps the loop started above. + if !Self.isAlreadyRunning(error) { cancelEventLoop() } throw error @@ -462,12 +459,12 @@ class LightningService: NodeLifecycleService { try await ServiceQueue.background(.ldk) { try Self.stopReleasingFinishedNode(node.stop) } - let eventLoop = cancelEventLoop() - self.node = nil - // An event the loop took is handled, and its removal from the queue persisted, before the next node loads that queue. - if let eventLoop, await !Self.waitForEnd(of: eventLoop, timeout: Self.eventLoopStopTimeout) { + // An event the loop took is handled, and its removal from the queue persisted, before the node is cleared and a next node + // can load that queue. + if let eventLoop = cancelEventLoop(), await !Self.waitForEnd(of: eventLoop, timeout: Self.eventLoopStopTimeout) { Logger.warn("Event loop of the stopped node did not end in time", context: "LightningService") } + self.node = nil if clearEventCallback { self.clearEventCallback() @@ -2459,8 +2456,11 @@ extension LightningService { eventLoopLock.lock() defer { eventLoopLock.unlock() } - eventLoopTask?.cancel() + let previousLoop = eventLoopTask + previousLoop?.cancel() eventLoopTask = Task { + // The previous loop finishes the event it took first, so both never handle the same event. + await previousLoop?.value while !Task.isCancelled, self.node === node { guard let event = node.nextEvent() else { try? await Task.sleep(for: Self.eventPollInterval) @@ -2691,17 +2691,29 @@ extension LightningService { continuation.resume(returning: ended) } } + let timer = Task { + try? await Task.sleep(for: timeout) + resume(false) + } Task { await task.value + timer.cancel() resume(true) } - Task { - try? await Task.sleep(for: timeout) - resume(false) - } } } + /// Whether `error` from `node.start()`, possibly wrapped by `ServiceQueue`, says the node is already running. + static func isAlreadyRunning(_ error: Error) -> Bool { + guard let nodeError = ((error as? AppError)?.underlyingError ?? error) as? NodeError else { + return false + } + if case .AlreadyRunning = nodeError { + return true + } + return false + } + private func registerClosedChannel( channel: ChannelDetails, reason: String diff --git a/BitkitTests/LightningServiceTests.swift b/BitkitTests/LightningServiceTests.swift index 51ef7b325..2a5ea79e0 100644 --- a/BitkitTests/LightningServiceTests.swift +++ b/BitkitTests/LightningServiceTests.swift @@ -22,6 +22,13 @@ final class LightningServiceTests: XCTestCase { XCTAssertThrowsError(try Bitkit.LightningService.stopReleasingFinishedNode { throw NodeError.ConnectionFailed(message: "") }) } + func testAStartFailingBecauseTheNodeRunsIsRecognizedThroughTheQueueWrapper() { + let alreadyRunning = NodeError.AlreadyRunning(message: "") + XCTAssertTrue(Bitkit.LightningService.isAlreadyRunning(alreadyRunning)) + XCTAssertTrue(Bitkit.LightningService.isAlreadyRunning(Bitkit.AppError(error: alreadyRunning))) + XCTAssertFalse(Bitkit.LightningService.isAlreadyRunning(Bitkit.AppError(error: NodeError.ConnectionFailed(message: "")))) + } + func testWaitForEndReturnsOnceTheTaskEnds() async { let task = Task { try? await Task.sleep(for: .milliseconds(50)) } let ended = await Bitkit.LightningService.waitForEnd(of: task, timeout: .seconds(10)) From 58130ccb83922b8ee50d197e22452f4819622190 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 09:24:11 +0100 Subject: [PATCH 5/7] style: doc comment on the event loop stop timeout Verified: swiftformat --lint . (0 files need formatting); comment-only change --- Bitkit/Services/LightningService.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 8537d9f96..861f775cd 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -130,7 +130,7 @@ class LightningService: NodeLifecycleService { private let eventLoopLock = NSLock() private var eventLoopTask: Task? private static let eventPollInterval: Duration = .milliseconds(100) - // Bounds the wait for the loop's last iteration, as `eventHandled()` can block on a stuck VSS write. + /// Bounds the wait for the loop's last iteration, as `eventHandled()` can block on a stuck VSS write. private static let eventLoopStopTimeout: Duration = .seconds(5) private let beforeNodeStopLock = NSLock() From c3f47e988859d94861beb5f3c5985cb09e7d5b1c Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 10:13:47 +0100 Subject: [PATCH 6/7] fix: keep a late stop from clearing the restarted node A second stop of the same node waits for the event loop the first stop took, and a stop releases the node only while it is still the configured one. Verified: iOS unit suite on simulator (all pass except BackupServiceTests.testAutomaticBackupRetriesContentionAndChangesDuringUpload, which then passed 3 of 3 alone); swiftformat --lint --- Bitkit/Services/LightningService.swift | 31 ++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 861f775cd..9da8a9281 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -127,8 +127,19 @@ class LightningService: NodeLifecycleService { setupLock.withLock { configuredNode = nil } } + /// Releases `node` only while it is still the configured one, so a stop that finishes late cannot clear its replacement. + private func release(_ node: Node) { + setupLock.withLock { + if configuredNode?.node === node { + configuredNode = nil + } + } + } + private let eventLoopLock = NSLock() private var eventLoopTask: Task? + /// The loop a stop cancelled, so a concurrent stop of the same node waits for it too. + private var stoppedEventLoopTask: Task? private static let eventPollInterval: Duration = .milliseconds(100) /// Bounds the wait for the loop's last iteration, as `eventHandled()` can block on a stuck VSS write. private static let eventLoopStopTimeout: Duration = .seconds(5) @@ -475,10 +486,11 @@ class LightningService: NodeLifecycleService { } // An event the loop took is handled, and its removal from the queue persisted, before the node is cleared and a next node // can load that queue. - if let eventLoop = cancelEventLoop(), await !Self.waitForEnd(of: eventLoop, timeout: Self.eventLoopStopTimeout) { + if let eventLoop = takeEventLoopToStop(), await !Self.waitForEnd(of: eventLoop, timeout: Self.eventLoopStopTimeout) { Logger.warn("Event loop of the stopped node did not end in time", context: "LightningService") } - releaseNode() + clearStoppedEventLoop() + release(node) if clearEventCallback { self.clearEventCallback() @@ -2682,6 +2694,21 @@ extension LightningService { } } + private func takeEventLoopToStop() -> Task? { + eventLoopLock.withLock { + if let task = eventLoopTask { + task.cancel() + eventLoopTask = nil + stoppedEventLoopTask = task + } + return stoppedEventLoopTask + } + } + + private func clearStoppedEventLoop() { + eventLoopLock.withLock { stoppedEventLoopTask = nil } + } + @discardableResult private func cancelEventLoop() -> Task? { eventLoopLock.withLock { From 9d68d56f818df4e823d8f793617bfbae91e2b1e9 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 15:42:22 +0100 Subject: [PATCH 7/7] fix: keep overlapping restarts from unlocking the new node Restarts run one after another, so Reset during Electrum Connect waits for Connect's node and saves the server the running node uses. A stop whose node was already replaced leaves the lightning lock to the replacement. Verified: iOS unit suite on simulator; swiftformat --lint --- Bitkit/Services/LightningService.swift | 37 +++++++++++++++++++++----- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 9da8a9281..0390f7c5e 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -128,14 +128,20 @@ class LightningService: NodeLifecycleService { } /// Releases `node` only while it is still the configured one, so a stop that finishes late cannot clear its replacement. - private func release(_ node: Node) { + /// Returns false when another node replaced it. + @discardableResult + private func release(_ node: Node) -> Bool { setupLock.withLock { - if configuredNode?.node === node { - configuredNode = nil - } + guard let configured = configuredNode?.node else { return true } + guard configured === node else { return false } + configuredNode = nil + return true } } + private let restartLock = NSLock() + private var lastRestart: Task? + private let eventLoopLock = NSLock() private var eventLoopTask: Task? /// The loop a stop cancelled, so a concurrent stop of the same node waits for it too. @@ -349,7 +355,21 @@ class LightningService: NodeLifecycleService { passphrase = nil } + /// Runs after any restart already in progress, so overlapping restarts cannot stop or replace each other's node midway. func restart(electrumServerUrl: String? = nil, rgsServerUrl: String? = nil) async throws { + let restart: Task = restartLock.withLock { + let previous = lastRestart + let restart = Task { + _ = await previous?.result + try await self.restartNode(electrumServerUrl: electrumServerUrl, rgsServerUrl: rgsServerUrl) + } + lastRestart = restart + return restart + } + try await restart.value + } + + private func restartNode(electrumServerUrl: String?, rgsServerUrl: String?) async throws { Logger.info("Restarting node with current configuration") // Stop the current node if it exists, ignore errors if already stopped @@ -469,9 +489,12 @@ class LightningService: NodeLifecycleService { } func stop(clearEventCallback: Bool = false) async throws { + var wasReplaced = false defer { - // Always try to unlock, even if stopping fails - try? StateLocker.unlock(.lightning) + // Always try to unlock, even if stopping fails, unless a replacement node holds the lock by now + if !wasReplaced { + try? StateLocker.unlock(.lightning) + } } guard let node else { @@ -490,7 +513,7 @@ class LightningService: NodeLifecycleService { Logger.warn("Event loop of the stopped node did not end in time", context: "LightningService") } clearStoppedEventLoop() - release(node) + wasReplaced = !release(node) if clearEventCallback { self.clearEventCallback()