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
2 changes: 1 addition & 1 deletion Bitkit.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -1295,7 +1295,7 @@
repositoryURL = "https://github.com/synonymdev/ldk-node";
requirement = {
kind = exactVersion;
version = "0.7.0-rc.81";
version = "0.7.0-rc.82";
};
};
96DEA0382DE8BBA1009932BF /* XCRemoteSwiftPackageReference "bitkit-core" */ = {
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

91 changes: 76 additions & 15 deletions Bitkit/Services/LightningService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,10 @@ class LightningService: NodeLifecycleService {

private let restartLock = NSLock()
private var lastRestart: Task<Void, Error>?
/// Counts the stops callers asked for, so a recovery start can tell that one came in after it began.
private var requestedStops = 0
/// Starts while a stopped node's VSS writes keep the store busy; each build waits up to 60 s for them.
static let busyStoreStartAttempts = 5

private let eventLoopLock = NSLock()
/// The current event loop and the node it serves, so only that node's lifecycle can cancel it.
Expand Down Expand Up @@ -435,42 +439,56 @@ class LightningService: NodeLifecycleService {
// Stop the current node if it exists, ignore errors if already stopped
if let node {
do {
try await stop()
try await stopNode()
} catch {
Logger.debug("Node was already stopped or failed to stop: \(error)")
// Clear the node reference anyway
await releaseAfterFailedStop(of: node)
}
}
let stopsBefore = restartLock.withLock { requestedStops }

// Restart the node with the current configuration
try await Self.applyConfigChange(
stopRequested: { self.restartLock.withLock { self.requestedStops != stopsBefore } },
start: {
try await self.setup(walletIndex: self.currentWalletIndex, electrumServerUrl: electrumServerUrl, rgsServerUrl: rgsServerUrl)
try await self.start()
},
recover: { try await self.restartWithPreviousConfig(stopsBefore: stopsBefore) }
)
}

/// Starts the node with a changed config, retrying while the store is busy with the stopped node's VSS writes, which have
/// nothing to do with the new config. Any other failure, or a busy store past every attempt, runs `recover` and rethrows.
static func applyConfigChange(
stopRequested: () -> Bool,
start: () async throws -> Void,
recover: () async throws -> Void
) async throws {
do {
try await setup(walletIndex: currentWalletIndex, electrumServerUrl: electrumServerUrl, rgsServerUrl: rgsServerUrl)
try await start()
Logger.info("Node restarted successfully")
try await startRetryingBusyStore(stopRequested: stopRequested, start: start)
Logger.info("Node restarted successfully", context: "LightningService")
} catch {
Logger.warn("Failed ldk-node config change, attempting recovery…")
// Attempt to restart with previous config
Logger.warn("Failed ldk-node config change, attempting recovery…", context: "LightningService")
// If recovery fails, log it but still throw the original error
do {
try await restartWithPreviousConfig()
try await recover()
} catch {
Logger.error("Recovery attempt also failed: \(error)")
Logger.error("Recovery attempt also failed: \(error)", context: "LightningService")
}
// Always re-throw the original error that caused the restart failure
throw error
}
}

/// Restarts the node with the previous stored configuration (recovery method)
/// This is called when a config change fails to restore the node to a working state
private func restartWithPreviousConfig() async throws {
private func restartWithPreviousConfig(stopsBefore: Int) async throws {
Logger.debug("Stopping node for recovery attempt")

// Stop the current node if it exists
if let node {
do {
try await stop()
try await stopNode()
} catch {
Logger.error("Failed to stop node during recovery: \(error)")
await releaseAfterFailedStop(of: node)
Expand All @@ -480,16 +498,53 @@ class LightningService: NodeLifecycleService {
Logger.debug("Starting node with previous config for recovery")

do {
// Restart with nil URLs to use stored/default configuration
try await setup(walletIndex: currentWalletIndex, electrumServerUrl: nil, rgsServerUrl: nil)
try await start()
// The stopped node's VSS writes can keep retrying for minutes, past one build's wait for them.
try await Self.startRetryingBusyStore(stopRequested: { self.restartLock.withLock { self.requestedStops != stopsBefore } }) {
// Restart with nil URLs to use stored/default configuration
try await self.setup(walletIndex: self.currentWalletIndex, electrumServerUrl: nil, rgsServerUrl: nil)
try await self.start()
}
Logger.debug("Successfully started node with previous config")
} catch {
Logger.error("Failed starting node with previous config: \(error)")
throw error
}
}

/// Runs `start` again while it fails because the store is still busy with a stopped node's VSS writes, up to
/// `busyStoreStartAttempts` times. A stop requested meanwhile wins: no further start runs.
static func startRetryingBusyStore(
attempts: Int = busyStoreStartAttempts,
stopRequested: () -> Bool,
start: () async throws -> Void
) async throws {
var attempt = 0
while true {
guard !stopRequested() else {
Logger.info("Skipped node start because a stop was requested", context: "LightningService")
throw AppError(serviceError: .nodeNotSetup)
}
attempt += 1
if attempt > 1 {
Logger.warn("Retrying node start on a busy store '\(attempt)/\(attempts)'", context: "LightningService")
}
do {
try await start()
return
} catch where isKvStoreSetupFailure(error) && attempt < attempts {
continue
}
}
}

static func isKvStoreSetupFailure(_ error: Error) -> Bool {
let underlying = (error as? AppError)?.underlyingError ?? error
if case BuildError.KvStoreSetupFailed = underlying {
return true
}
return false
}

/// Pass onEvent when being used in the background to listen for payments, channels, closes, etc
/// - Parameter onEvent: Triggered on any LDK node event
func start(onEvent: ((Event) -> Void)? = nil) async throws {
Expand Down Expand Up @@ -550,6 +605,12 @@ class LightningService: NodeLifecycleService {
}

func stop(clearEventCallback: Bool = false) async throws {
restartLock.withLock { requestedStops += 1 }
try await stopNode(clearEventCallback: clearEventCallback)
}

/// Stops the node without counting as a requested stop, for the restart and its recovery.
private func stopNode(clearEventCallback: Bool = false) async throws {
guard let node else {
Logger.warn("Node not started, nothing to stop")
return
Expand Down
99 changes: 99 additions & 0 deletions BitkitTests/LightningServiceTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,103 @@ final class LightningServiceTests: XCTestCase {
release.continuation.finish()
await task.value
}

// Regression: a stopped node's VSS writes can keep retrying past one build's wait for them, so the recovery start
// retries while the build fails on the busy store instead of leaving the node offline.
func testRecoveryStartRetriesWhileTheVssStoreIsBusy() async throws {
let busy = Bitkit.AppError(error: BuildError.KvStoreSetupFailed(message: "in flight"))
var attempts = 0
try await Bitkit.LightningService.startRetryingBusyStore(stopRequested: { false }) {
attempts += 1
if attempts < 3 {
throw busy
}
}
XCTAssertEqual(attempts, 3)
}

func testRecoveryStartGivesUpAfterItsAttempts() async {
var attempts = 0
do {
try await Bitkit.LightningService.startRetryingBusyStore(stopRequested: { false }) {
attempts += 1
throw Bitkit.AppError(error: BuildError.KvStoreSetupFailed(message: "in flight"))
}
XCTFail("expected the last failure")
} catch {}
XCTAssertEqual(attempts, Bitkit.LightningService.busyStoreStartAttempts)
}

func testRecoveryStartDoesNotRetryOtherFailures() async {
var attempts = 0
do {
try await Bitkit.LightningService.startRetryingBusyStore(stopRequested: { false }) {
attempts += 1
throw Bitkit.AppError(error: BuildError.WalletSetupFailed(message: ""))
}
XCTFail("expected the failure")
} catch {}
XCTAssertEqual(attempts, 1)
}

// Regression: a stop requested while the recovery runs wins over its retry.
func testRecoveryStartDoesNotRetryOverARequestedStop() async {
var attempts = 0
var stopRequested = false
do {
try await Bitkit.LightningService.startRetryingBusyStore(stopRequested: { stopRequested }) {
attempts += 1
stopRequested = true
throw Bitkit.AppError(error: BuildError.KvStoreSetupFailed(message: "in flight"))
}
XCTFail("expected the skipped start to fail")
} catch {}
XCTAssertEqual(attempts, 1)
}

func testRecoveryStartDoesNotStartOverAStopRequestedBeforeIt() async {
var attempts = 0
do {
try await Bitkit.LightningService.startRetryingBusyStore(stopRequested: { true }) { attempts += 1 }
XCTFail("expected the skipped start to fail")
} catch {}
XCTAssertEqual(attempts, 0)
}

// Regression: a busy store has nothing to do with the requested Electrum or RGS server, so the change retries it
// instead of falling back to the previous config.
func testConfigChangeRetriesItsOwnStartWhileTheVssStoreIsBusy() async throws {
var attempts = 0
var recovered = false
try await Bitkit.LightningService.applyConfigChange(
stopRequested: { false },
start: {
attempts += 1
if attempts < 2 {
throw Bitkit.AppError(error: BuildError.KvStoreSetupFailed(message: "in flight"))
}
},
recover: { recovered = true }
)
XCTAssertEqual(attempts, 2)
XCTAssertFalse(recovered)
}

func testConfigChangeRecoversAfterAnotherFailure() async {
var attempts = 0
var recovered = false
do {
try await Bitkit.LightningService.applyConfigChange(
stopRequested: { false },
start: {
attempts += 1
throw Bitkit.AppError(error: BuildError.WalletSetupFailed(message: ""))
},
recover: { recovered = true }
)
XCTFail("expected the change to fail")
} catch {}
XCTAssertEqual(attempts, 1)
XCTAssertTrue(recovered)
}
}
1 change: 1 addition & 0 deletions changelog.d/next/1520.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed a rare case where restarting the Lightning node could overwrite its newer backed-up state with older data.
Loading