diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 17b271bee6..84aba06367 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -108,6 +108,7 @@ import to.bitkit.services.NetworkGraphInfo import to.bitkit.services.NodeEventHandler import to.bitkit.services.SparkError import to.bitkit.utils.AppError +import to.bitkit.utils.LdkError import to.bitkit.utils.Logger import to.bitkit.utils.ServiceError import to.bitkit.utils.UrlValidator @@ -1297,7 +1298,22 @@ class LightningRepo @Inject constructor( Logger.debug("Starting node with previous config for recovery", context = TAG) - start(shouldRetry = false).onSuccess { + var result: Result + var attempt = 0 + // The stopped node's VSS writes can keep retrying for minutes, past one build's wait for them. + do { + // A stop requested since the app went to the background wins over recovery. + if (pendingStopJob.get() != null) { + Logger.info("Skipped recovery start because a stop was requested", context = TAG) + return@withContext Result.failure(NodeStartYieldedToStopError(null)) + } + attempt++ + if (attempt > 1) { + Logger.warn("Retrying recovery start '$attempt/$RECOVERY_START_ATTEMPTS'", context = TAG) + } + result = startNode(shouldRetry = false, shouldCancelPendingStop = false) + } while (result.exceptionOrNull().isKvStoreSetupFailure() && attempt < RECOVERY_START_ATTEMPTS) + result.onSuccess { Logger.debug("Successfully started node with previous config", context = TAG) }.onFailure { Logger.error("Failed starting node with previous config", it, context = TAG) @@ -3264,6 +3280,9 @@ class LightningRepo @Inject constructor( private const val SYNC_RETRY_DELAY_MS = 15_000L private const val MSATS_PER_SAT = 1_000uL + /** Recovery starts while a stopped node's VSS writes keep the store busy; each build waits up to 60 s. */ + private const val RECOVERY_START_ATTEMPTS = 5 + /** LDK's default routing fee limit is 1% of the amount, this divisor, plus [DEFAULT_ROUTING_FEE_BASE_MSAT]. */ private const val DEFAULT_ROUTING_FEE_DIVISOR = 100uL @@ -3488,3 +3507,6 @@ sealed interface EarlierSend { /** Spark invoices hold whole sats, so an exact msat amount the channels can't receive has nowhere to go. */ class SubSatAmountUnsupportedError(amountMsats: ULong) : AppError("Spark can only receive whole sats, not '$amountMsats' msat, and the channels can't receive it") + +private fun Throwable?.isKvStoreSetupFailure() = + generateSequence(this) { it.cause }.any { (it as? LdkError)?.isKvStoreSetupFailed == true } diff --git a/app/src/main/java/to/bitkit/services/LightningService.kt b/app/src/main/java/to/bitkit/services/LightningService.kt index 9b639c2f48..03bb0313bc 100644 --- a/app/src/main/java/to/bitkit/services/LightningService.kt +++ b/app/src/main/java/to/bitkit/services/LightningService.kt @@ -575,14 +575,15 @@ class LightningService internal constructor( } // A stop can leave tasks detached, e.g. a VSS write that keeps retrying. ldk-node keeps their runtime // alive until they end, but the release returns before that, so a rebuilt node could run while the old - // node's work still writes. In the background, kill the process instead; a cold start restores - // everything. In the foreground, release as before. - if (monitor.hasDetachedWork && isAppInBackground() && exitBeforeRuntimeShutdown()) return@withContext + // node's work still runs. Building the next node waits up to 60 s for the old node's VSS writes in + // flight and drops any it starts later. In the background, kill the process instead; a cold start + // restores everything. In the foreground, release as before. + if (monitor.hasDetachedWork && isAppInBackground() && exitBeforeDetachedWorkOverlaps()) return@withContext releaseHandle(node) Logger.info("Node stopped", context = TAG) } - private suspend fun exitBeforeRuntimeShutdown(): Boolean { + private suspend fun exitBeforeDetachedWorkOverlaps(): Boolean { Logger.warn("Exiting process: node stop left ldk_node tasks detached while in background", context = TAG) delay(EXIT_LOG_FLUSH_DELAY) if (!isAppInBackground()) { @@ -597,11 +598,12 @@ class LightningService internal constructor( * Releases the rust handle instead of leaving it to the GC finalizer, keeping it off the * single-threaded LDK queue and off the lifecycle critical path. * - * `free_node` only returns once the node's background tasks drain, which takes tens of seconds - * when a failed start left them wedged, so the wait is bounded and the release is joined rather - * than run inline: cancelling a blocking FFI call does nothing, but abandoning the join lets the - * caller continue while the release finishes on its own. [awaitNodeRelease] gates the next - * rebuild or destructive storage work on the same job so native lifetimes never overlap. + * `free_node` waits a bounded time for the node's background tasks to drain, which can take tens + * of seconds when a failed start left them wedged, so the wait here is bounded too and the release + * is joined rather than run inline: cancelling a blocking FFI call does nothing, but abandoning the + * join lets the caller continue while the release finishes on its own. [awaitNodeRelease] gates + * the next rebuild or destructive storage work on the same job. After a timed-out stop, `free_node` + * can return while detached work of the old node still runs. */ private suspend fun releaseHandle(node: Node) { val release = launch(ioDispatcher) { @@ -616,10 +618,10 @@ class LightningService internal constructor( } /** - * Blocks until the previous node's release ([releaseHandle] / `free_node`) has finished, so a - * rebuild or destructive storage operation never overlaps the old node's native lifetime. The - * wait is bounded: a stuck free_node throws rather than proceeding (which would overlap) or - * blocking forever (which would brick every future rebuild). + * Blocks until the previous node's release ([releaseHandle] / `free_node`) has returned. It does + * not wait for the old node's detached work, which can still run after a timed-out stop. The wait + * is bounded: a stuck free_node throws rather than proceeding or blocking forever (which would + * brick every future rebuild). */ suspend fun awaitNodeRelease(timeout: Duration = NODE_RELEASE_GATE_TIMEOUT) { val release = releaseJob ?: return diff --git a/app/src/main/java/to/bitkit/utils/Errors.kt b/app/src/main/java/to/bitkit/utils/Errors.kt index 4eb6a2c26b..e722f97e8d 100644 --- a/app/src/main/java/to/bitkit/utils/Errors.kt +++ b/app/src/main/java/to/bitkit/utils/Errors.kt @@ -34,12 +34,13 @@ class LdkError(private val inner: LdkException) : AppError("Unknown LDK error.") override val message get() = inner.message ?: super.message val compactType get() = inner.compactType + val isKvStoreSetupFailed get() = (inner as? LdkException.Build)?.exception is BuildException.KvStoreSetupFailed sealed interface LdkException { val message: String? val compactType: String? - class Build(exception: BuildException) : LdkException { + class Build(val exception: BuildException) : LdkException { override val compactType = exception::class.simpleName override val message = when (exception) { is BuildException.InvalidChannelMonitor -> "Invalid channel monitor." diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 625724b33f..1432a1f9f6 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -39,6 +39,7 @@ import org.junit.Before import org.junit.Test import org.lightningdevkit.ldknode.AddressTypeBalance import org.lightningdevkit.ldknode.BalanceDetails +import org.lightningdevkit.ldknode.BuildException import org.lightningdevkit.ldknode.ChannelDataMigration import org.lightningdevkit.ldknode.ChannelDetails import org.lightningdevkit.ldknode.Event @@ -115,6 +116,7 @@ import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertIs +import kotlin.test.assertNotEquals import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue @@ -4538,6 +4540,79 @@ class LightningRepoTest : BaseUnitTest() { testScheduler.advanceUntilIdle() } + // 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. + @Test + fun `restartWithElectrumServer recovery retries while the vss store is busy`() = test { + startNodeForTesting() + val badUrl = "ssl://10.0.2.2:60001" + whenever(lightningService.node).thenReturn(null) + whenever(lightningService.stop()).thenReturn(Unit) + val busy = AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + whenever { lightningService.setup(any(), eq(badUrl), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { throw busy } + var recoveryAttempts = 0 + whenever { lightningService.setup(any(), isNull(), isNull(), anyOrNull()) } + .doSuspendableAnswer { + recoveryAttempts++ + if (recoveryAttempts < 3) throw busy + } + + assertTrue(sut.restartWithElectrumServer(badUrl).isFailure) + testScheduler.advanceUntilIdle() + + assertEquals(3, recoveryAttempts) + assertEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + + // Regression: a stop requested while the app went to the background wins over the recovery retry, + // which would otherwise cancel it and leave the node running with background payments off. + @Test + fun `restartWithElectrumServer recovery does not retry over a requested stop`() = test { + startNodeForTesting() + val badUrl = "ssl://10.0.2.2:60001" + whenever(lightningService.node).thenReturn(null) + whenever(lightningService.stop()).thenReturn(Unit) + val busy = AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + whenever { lightningService.setup(any(), eq(badUrl), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { throw busy } + var recoveryAttempts = 0 + whenever { lightningService.setup(any(), isNull(), isNull(), anyOrNull()) } + .doSuspendableAnswer { + recoveryAttempts++ + sut.stopDebounced() + throw busy + } + + assertTrue(sut.restartWithElectrumServer(badUrl).isFailure) + testScheduler.advanceUntilIdle() + + assertEquals(1, recoveryAttempts) + assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + + // Regression: a stop requested during the failed change's build is kept by recovery, whose first + // start would otherwise cancel it before any retry could see it. + @Test + fun `restartWithElectrumServer recovery does not start over a stop requested before it`() = test { + startNodeForTesting() + val badUrl = "ssl://10.0.2.2:60001" + whenever(lightningService.node).thenReturn(null) + whenever(lightningService.stop()).thenReturn(Unit) + val busy = AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + whenever { lightningService.setup(any(), eq(badUrl), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { + sut.stopDebounced() + throw busy + } + + assertTrue(sut.restartWithElectrumServer(badUrl).isFailure) + testScheduler.advanceUntilIdle() + + verify(lightningService, never()).setup(any(), isNull(), isNull(), anyOrNull()) + assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + // Regression: a server that cannot work is rejected by the probe before the node is touched. // Tearing the node down for one is what leaves its electrum tasks wedged, so that a later // free_node blocks for tens of seconds instead of milliseconds. diff --git a/changelog.d/next/2004.fixed.md b/changelog.d/next/2004.fixed.md new file mode 100644 index 0000000000..45ee7f9fe7 --- /dev/null +++ b/changelog.d/next/2004.fixed.md @@ -0,0 +1 @@ +Fixed a rare case where restarting the Lightning node could overwrite its newer backed-up state with older data. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index bf4e7b28fb..d3d9efc7d1 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.81" } +ldk-node-android = { module = "com.synonym:ldk-node-android", version = "0.7.0-rc.82" } 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 ec844f9130..a618f3c14f 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -4417,6 +4417,17 @@ + + + + + + + + + + +