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/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 2bc317630..0390f7c5e 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 @@ -106,7 +107,14 @@ protocol NodeLifecycleService: AnyObject { class LightningService: NodeLifecycleService { private static let watchOnlyAccountHighestPreRevealedAddressIndex: UInt32 = 999 - private var configuredNode: (node: Node, electrumServerUrl: String)? + private var configuredNode: (node: Node, electrumServerUrl: String)? { + didSet { + if configuredNode?.node !== oldValue?.node { + cancelEventLoop() + } + } + } + private var node: Node? { setupLock.withLock { configuredNode?.node } } @@ -119,6 +127,29 @@ 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. + /// Returns false when another node replaced it. + @discardableResult + private func release(_ node: Node) -> Bool { + setupLock.withLock { + 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. + 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) + 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. @@ -324,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 @@ -401,8 +446,16 @@ 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 { + // A node that is already running keeps the loop started above. + if !Self.isAlreadyRunning(error) { + cancelEventLoop() + } + throw error } #if !BITKIT_NOTIFICATION_EXTENSION @@ -436,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 { @@ -451,7 +507,13 @@ class LightningService: NodeLifecycleService { try await ServiceQueue.background(.ldk) { try Self.stopReleasingFinishedNode(node.stop) } - releaseNode() + // 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 = takeEventLoopToStop(), await !Self.waitForEnd(of: eventLoop, timeout: Self.eventLoopStopTimeout) { + Logger.warn("Event loop of the stopped node did not end in time", context: "LightningService") + } + clearStoppedEventLoop() + wasReplaced = !release(node) if clearEventCallback { self.clearEventCallback() @@ -2433,15 +2495,26 @@ 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() } + 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) + continue + } do { try node.eventHandled() @@ -2644,6 +2717,67 @@ 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 { + 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) + } + } + let timer = Task { + try? await Task.sleep(for: timeout) + resume(false) + } + Task { + await task.value + timer.cancel() + resume(true) + } + } + } + + /// 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 11cdbe9ac..2a5ea79e0 100644 --- a/BitkitTests/LightningServiceTests.swift +++ b/BitkitTests/LightningServiceTests.swift @@ -21,4 +21,28 @@ final class LightningServiceTests: XCTestCase { func testStopKeepsANodeWhoseStopFailedOtherwise() { 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)) + 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 + } } 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. 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.