diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 1d3acb5bdf..5fb4ad25c7 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -249,6 +249,8 @@ class LightningRepo @Inject constructor( return@collect } + if (restartStoppedNode()) return@collect + if (_lightningState.value.nodeLifecycleState.isRunning()) { scheduleOrdinaryFollowupRetry() } @@ -285,6 +287,7 @@ class LightningRepo @Inject constructor( } delay(SYNC_RETRY_DELAY_MS) + if (restartStoppedNode()) return@launch Logger.info("Retrying sync after failure", context = TAG) sync().onSuccess { Logger.info("Sync retry succeeded", context = TAG) @@ -296,6 +299,42 @@ class LightningRepo @Inject constructor( syncRetryJob.set(job) } + /** + * Replaces a node that stopped itself, which ldk-node does after a panic: the lifecycle still reads as running. + * + * @return true when the node had stopped and a new start was launched + */ + private fun restartStoppedNode(): Boolean { + // Read before the checks, so a stop that lands after them wins over this start. + val stops = stopRequestCount.get() + // A pending background stop takes care of the node. + if (pendingStopJob.get()?.isActive == true) return false + if (!_lightningState.value.nodeLifecycleState.isRunning() || !lightningService.hasStoppedNode) return false + // Counted before launching, so neither a start in flight nor a second trigger gets another start. + if (!pendingStartCount.compareAndSet(expect = 0, update = 1)) return false + + Logger.warn("LDK node stopped itself, restarting it", context = TAG) + scope.launch { + var attempt = 0 + // The stopped node's VSS writes can keep retrying for minutes, past one build's wait for them. + do { + attempt++ + if (attempt > 1) { + if (pendingStopJob.get()?.isActive == true || stopRequestCount.get() != stops) break + Logger.warn("Retrying stopped node restart '$attempt/$BUSY_STORE_START_ATTEMPTS'", context = TAG) + } + val result = startNode( + walletIndex = lightningService.currentWalletIndex, + // A retry would cancel a pending background stop. + shouldRetry = false, + shouldCancelPendingStop = false, + stopRequestsSeen = stops, + ) + } while (result.exceptionOrNull().isKvStoreSetupFailure() && attempt < BUSY_STORE_START_ATTEMPTS) + }.invokeOnCompletion { pendingStartCount.update { it - 1 } } + return true + } + /** * Executes the provided operation only if the node is running. * If the node is not running, waits for it to be running for a specified timeout. @@ -448,6 +487,7 @@ class LightningRepo @Inject constructor( Logger.info("Skipped start because a stop was requested", context = TAG) return@withLock Result.failure(NodeStartYieldedToStopError(null)) } + dropStoppedNode() initialLifecycleState = _lightningState.value.nodeLifecycleState if (initialLifecycleState.isRunningOrStarting()) { return@withLock skipStartForRunningNode( @@ -612,6 +652,11 @@ class LightningRepo @Inject constructor( result } + // A node that panicked stopped itself and refuses to start again, so drop it and build a new one. + private suspend fun dropStoppedNode() { + if (lightningService.hasStoppedNode) stopLocked() + } + private suspend fun adoptRunningNode(): Result { _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) } scheduleOrdinaryFollowupRetry() diff --git a/app/src/main/java/to/bitkit/services/LightningService.kt b/app/src/main/java/to/bitkit/services/LightningService.kt index 26f5eabc54..a6d262963a 100644 --- a/app/src/main/java/to/bitkit/services/LightningService.kt +++ b/app/src/main/java/to/bitkit/services/LightningService.kt @@ -312,6 +312,10 @@ class LightningService internal constructor( @Volatile var node: Node? = null + /** Whether a start was tried on [node], which one that is only built has not had. */ + @Volatile + private var isStartTried = false + @Volatile var currentWalletIndex: Int = 0 private set @@ -360,6 +364,7 @@ class LightningService internal constructor( ) currentWalletIndex = walletIndex runtimeMonitor = monitor + isStartTried = false node = builtNode Logger.info("LDK node setup", context = TAG) @@ -528,6 +533,8 @@ class LightningService internal constructor( Env.activeElectrumServerUrl.update { chainElectrumUrl } } catch (e: NodeException) { throw LdkError(e) + } finally { + isStartTried = true } } @@ -649,6 +656,8 @@ class LightningService internal constructor( val monitor = runtimeMonitor Logger.debug("Stopping node…", context = TAG) + // A node the app stops is not one that stopped itself. + isStartTried = false ServiceQueue.LDK.background(ldkQueue) { runSuspendCatching { node.stop() } .onFailure { @@ -1643,7 +1652,16 @@ class LightningService internal constructor( Logger.debug("LDK event fired: ${jsonLogOf(event)}", context = TAG) runCatching { node.eventHandled() } .onSuccess { Logger.verbose("LDK eventHandled: '$event'", context = TAG) } - .onFailure { Logger.verbose("LDK eventHandled error: '$event'", it, context = TAG) } + .onFailure { + Logger.verbose("LDK eventHandled error: '$event'", it, context = TAG) + // A node that panicked refuses the event, which stays first in the queue and would come back at + // once, so leave it for the next node. A running node whose write failed has removed it, and an + // equal event may follow. + if (node.nextEvent() == event && !node.status().isRunning) { + Logger.warn("Event listener stopping: node refused a handled event", it, context = TAG) + return@withContext + } + } onEvent?.invoke(event) } } @@ -1702,6 +1720,9 @@ class LightningService internal constructor( val nodeId: String? get() = node?.nodeId() val balances: BalanceDetails? get() = node?.listBalances() val status: NodeStatus? get() = node?.status() + + /** A node a start was tried on that is not running: ldk-node stops one after a panic, and it cannot start again. */ + val hasStoppedNode: Boolean get() = isStartTried && status?.isRunning == false val config: Config? get() = node?.config() val peers: List? get() = node?.listPeers() val channels: List? get() = node?.listChannels() diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index e5d00c5ddd..e8621c1234 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -163,6 +163,7 @@ class LightningRepoTest : BaseUnitTest() { private val onchainSendAttemptStore = mock() private val lnurlService = mock() private val connectivityRepo = mock() + private val isOnline = MutableStateFlow(ConnectivityState.CONNECTED) private val vssBackupClientLdk = mock() private val electrumProbeService = mock() private val urlValidator = UrlValidator { Result.success(Unit) } @@ -180,7 +181,7 @@ class LightningRepoTest : BaseUnitTest() { whenever(lightningService.start(anyOrNull(), any())).thenReturn(Unit) whenever { electrumProbeService.probe(any(), any()) }.thenReturn(Result.success(Unit)) whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) - whenever(connectivityRepo.isOnline).thenReturn(MutableStateFlow(ConnectivityState.CONNECTED)) + whenever(connectivityRepo.isOnline).thenReturn(isOnline) whenever(settingsStore.data).thenReturn(flowOf(SettingsData())) whenever(lightningService.aresRequiredPeersInNetworkGraph()).thenReturn(true) sut = LightningRepo( @@ -636,6 +637,132 @@ class LightningRepoTest : BaseUnitTest() { verify(cacheStore, never()).invalidateReceiveOnchainAddress(any()) } + @Test + fun `start drops a node that stopped itself`() = test { + startNodeForTesting() + stubStoppedNode() + + sut.start(shouldRetry = false) + + verifyBlocking(lightningService) { stop() } + verifyBlocking(lightningService, times(2)) { start(anyOrNull(), any()) } + } + + @Test + fun `sync retry restarts a node that stopped itself`() = test { + startNodeForTesting() + stubStoppedNode() + var isSyncFailing = true + whenever(lightningService.sync()).doSuspendableAnswer { check(!isSyncFailing) { "node not running" } } + + sut.sync() + isSyncFailing = false + testScheduler.advanceTimeBy(16.seconds) + testScheduler.runCurrent() + + verifyBlocking(lightningService) { stop() } + verifyBlocking(lightningService, times(2)) { start(anyOrNull(), any()) } + } + + @Test + fun `a returning network restarts a node that stopped itself`() = test { + startNodeForTesting() + isOnline.value = ConnectivityState.DISCONNECTED + stubStoppedNode() + + isOnline.value = ConnectivityState.CONNECTED + testScheduler.runCurrent() + + verifyBlocking(lightningService) { stop() } + verifyBlocking(lightningService, times(2)) { start(anyOrNull(), any()) } + } + + @Test + fun `a second trigger does not restart a stopped node while a restart is in flight`() = test { + startNodeForTesting() + val startGate = CompletableDeferred() + whenever(lightningService.start(anyOrNull(), any())).doSuspendableAnswer { startGate.await() } + whenever(lightningService.hasStoppedNode).thenReturn(true) + + repeat(2) { + isOnline.value = ConnectivityState.DISCONNECTED + testScheduler.runCurrent() + isOnline.value = ConnectivityState.CONNECTED + testScheduler.runCurrent() + } + startGate.complete(Unit) + testScheduler.runCurrent() + + verifyBlocking(lightningService, times(2)) { start(anyOrNull(), any()) } + } + + @Test + fun `a pending background stop wins over restarting a stopped node`() = test { + startNodeForTesting() + isOnline.value = ConnectivityState.DISCONNECTED + stubStoppedNode() + + sut.stopDebounced() + isOnline.value = ConnectivityState.CONNECTED + testScheduler.runCurrent() + + verifyBlocking(lightningService, times(1)) { start(anyOrNull(), any()) } + sut.cancelPendingStop() + } + + @Test + fun `restarting a stopped node retries while the store is busy`() = test { + startNodeForTesting() + isOnline.value = ConnectivityState.DISCONNECTED + var hasNode = true + var hasStoppedNode = true + whenever(lightningService.node).thenAnswer { if (hasNode) mock() else null } + whenever(lightningService.hasStoppedNode).thenAnswer { hasStoppedNode } + whenever(lightningService.stop()).doSuspendableAnswer { + hasNode = false + hasStoppedNode = false + } + var setups = 0 + whenever { lightningService.setup(any(), anyOrNull(), anyOrNull(), anyOrNull()) }.doSuspendableAnswer { + if (setups++ == 0) throw AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + hasNode = true + } + + isOnline.value = ConnectivityState.CONNECTED + testScheduler.runCurrent() + + assertEquals(2, setups) + assertEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + + @Test + fun `a background stop ends the busy store retries of a stopped node restart`() = test { + startNodeForTesting() + isOnline.value = ConnectivityState.DISCONNECTED + var hasNode = true + whenever(lightningService.node).thenAnswer { if (hasNode) mock() else null } + whenever(lightningService.hasStoppedNode).thenAnswer { hasNode } + whenever(lightningService.stop()).doSuspendableAnswer { hasNode = false } + var setups = 0 + whenever { lightningService.setup(any(), anyOrNull(), anyOrNull(), anyOrNull()) }.doSuspendableAnswer { + setups++ + sut.stopDebounced() + throw AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + } + + isOnline.value = ConnectivityState.CONNECTED + testScheduler.runCurrent() + + assertEquals(1, setups) + sut.cancelPendingStop() + } + + private suspend fun stubStoppedNode() { + var hasStoppedNode = true + whenever(lightningService.hasStoppedNode).thenAnswer { hasStoppedNode } + whenever(lightningService.stop()).doSuspendableAnswer { hasStoppedNode = false } + } + @Test fun `start reconciles watch-only accounts when the underlying node is already running`() = test { sut.setInitNodeLifecycleState() diff --git a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt index ce53236cad..6957ef60b7 100644 --- a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt @@ -57,6 +57,7 @@ import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doNothing +import org.mockito.kotlin.doReturn import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.doThrow import org.mockito.kotlin.eq @@ -877,6 +878,86 @@ class LightningServiceTest : BaseUnitTest() { verify(newNode, never()).nextEventAsync() } + @Test + fun `listener stops without delivering an event the node refuses to mark handled`() = test { + val event = Event.PaymentSuccessful(null, "hash", null, null) + whenever(node.nextEventAsync()).thenReturn(event) + whenever(node.nextEvent()).thenReturn(event) + whenever(node.eventHandled()).thenThrow(IllegalStateException("refused")) + val status = mock { on { isRunning } doReturn false } + whenever(node.status()).thenReturn(status) + var delivered = 0 + + sut.startEventListener { delivered++ } + testScheduler.advanceUntilIdle() + + assertEquals(0, delivered) + verify(node, times(1)).nextEventAsync() + } + + @Test + fun `listener delivers an event that left the queue although marking it handled failed`() = test { + val event = Event.PaymentSuccessful(null, "hash", null, null) + var polls = 0 + whenever(node.nextEventAsync()).doSuspendableAnswer { + if (polls++ == 0) event else awaitCancellation() + } + whenever(node.eventHandled()).thenThrow(IllegalStateException("persistence failed")) + var delivered = 0 + + sut.startEventListener { delivered++ } + testScheduler.advanceUntilIdle() + + assertEquals(1, delivered) + sut.stop() + } + + @Test + fun `listener keeps running when an equal event follows a failed write on a running node`() = test { + val event = Event.PaymentSuccessful(null, "hash", null, null) + var polls = 0 + whenever(node.nextEventAsync()).doSuspendableAnswer { + if (polls++ == 0) event else awaitCancellation() + } + whenever(node.nextEvent()).thenReturn(event) + whenever(node.eventHandled()).thenThrow(IllegalStateException("persistence failed")) + val status = mock { on { isRunning } doReturn true } + whenever(node.status()).thenReturn(status) + var delivered = 0 + + sut.startEventListener { delivered++ } + testScheduler.advanceUntilIdle() + + assertEquals(1, delivered) + assertEquals(2, polls) + sut.stop() + } + + @Test + fun `a node counts as stopped only once a start was tried on it`() = test { + val status = mock { on { isRunning } doReturn false } + whenever(node.status()).thenReturn(status) + val wasStoppedBeforeStart = sut.hasStoppedNode + + sut.start() + + assertEquals(false, wasStoppedBeforeStart) + assertEquals(true, sut.hasStoppedNode) + } + + @Test + fun `a node the app is stopping does not count as stopped by itself`() = test { + val status = mock { on { isRunning } doReturn false } + whenever(node.status()).thenReturn(status) + sut.start() + var wasStoppedDuringStop: Boolean? = null + whenever(node.stop()).thenAnswer { wasStoppedDuringStop = sut.hasStoppedNode } + + sut.stop() + + assertEquals(false, wasStoppedDuringStop) + } + private class GateFixture( scope: CoroutineScope, val gated: LightningService, diff --git a/changelog.d/next/2197.fixed.md b/changelog.d/next/2197.fixed.md new file mode 100644 index 0000000000..7e5d0cba02 --- /dev/null +++ b/changelog.d/next/2197.fixed.md @@ -0,0 +1 @@ +Fixed the Lightning node staying offline after an internal error until the app was closed and reopened. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index e7efb21c44..a900e08477 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -69,7 +69,7 @@ ktor-client-logging = { module = "io.ktor:ktor-client-logging", version.ref = "k ktor-client-mock = { module = "io.ktor:ktor-client-mock", version.ref = "ktor" } ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" } ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" } -ldk-node-android = { module = "com.synonym:ldk-node-android", version = "0.7.0-rc.83" } +ldk-node-android = { module = "com.synonym:ldk-node-android", version = "0.7.0-rc.84" } lifecycle-process = { group = "androidx.lifecycle", name = "lifecycle-process", version.ref = "lifecycle" } lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" } lifecycle-runtime-ktx = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "lifecycle" } diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index af52336ec6..8c403f28b6 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -4439,6 +4439,17 @@ + + + + + + + + + + +