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
24 changes: 23 additions & 1 deletion app/src/main/java/to/bitkit/repositories/LightningRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<Unit>
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.
Comment thread
ovitrif marked this conversation as resolved.
Resolved
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)
}
Comment thread
ovitrif marked this conversation as resolved.
Resolved
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)
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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 }
28 changes: 15 additions & 13 deletions app/src/main/java/to/bitkit/services/LightningService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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()) {
Expand All @@ -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) {
Expand All @@ -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
Expand Down
3 changes: 2 additions & 1 deletion app/src/main/java/to/bitkit/utils/Errors.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand Down
75 changes: 75 additions & 0 deletions app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions changelog.d/next/2004.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.
2 changes: 1 addition & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Comment thread
ovitrif marked this conversation as resolved.
Resolved
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" }
Expand Down
11 changes: 11 additions & 0 deletions gradle/verification-metadata.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4417,6 +4417,17 @@
<sha256 value="eab2c77701542ee43ad631d5796ef63cbc4661f861ef25a35f7336e475c6936f" origin="Generated by Gradle"/>
</artifact>
</component>
<component group="com.synonym" name="ldk-node-android" version="0.7.0-rc.82">
<artifact name="ldk-node-android-0.7.0-rc.82-native-debug-symbols.zip">
<sha256 value="7a36d26068c1de5b5140be84905b06b43a659124f545d3ecc142e7ddc68d4a25" origin="Generated by Gradle"/>
</artifact>
<artifact name="ldk-node-android-0.7.0-rc.82.aar">
<sha256 value="7ab6badfb8c5881e2e3b0d66b780f040468db7acd98d19c8e781fbfd0ae630e5" origin="Generated by Gradle"/>
</artifact>
<artifact name="ldk-node-android-0.7.0-rc.82.module">
<sha256 value="b1d771c897fd219159a7128183212c3609903428691dc00800e64920cfe6db0b" origin="Generated by Gradle"/>
</artifact>
</component>
<component group="com.synonym" name="paykit-android" version="0.1.1-rc8">
<artifact name="paykit-android-0.1.1-rc8-native-debug-symbols.zip">
<sha256 value="a876e5ca61b8c2bac6166460906e561090f5f1f39995d751fbe9c8cc99b18a1e" origin="Generated by Gradle"/>
Expand Down