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
45 changes: 45 additions & 0 deletions app/src/main/java/to/bitkit/repositories/LightningRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,8 @@ class LightningRepo @Inject constructor(
return@collect
}

if (restartStoppedNode()) return@collect

if (_lightningState.value.nodeLifecycleState.isRunning()) {
scheduleOrdinaryFollowupRetry()
}
Expand Down Expand Up @@ -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)
Expand All @@ -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.
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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<Unit> {
_lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) }
scheduleOrdinaryFollowupRetry()
Expand Down
23 changes: 22 additions & 1 deletion app/src/main/java/to/bitkit/services/LightningService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -360,6 +364,7 @@ class LightningService internal constructor(
)
currentWalletIndex = walletIndex
runtimeMonitor = monitor
isStartTried = false
node = builtNode

Logger.info("LDK node setup", context = TAG)
Expand Down Expand Up @@ -528,6 +533,8 @@ class LightningService internal constructor(
Env.activeElectrumServerUrl.update { chainElectrumUrl }
} catch (e: NodeException) {
throw LdkError(e)
} finally {
isStartTried = true
}
}

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}
}
Expand Down Expand Up @@ -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<PeerDetails>? get() = node?.listPeers()
val channels: List<ChannelDetails>? get() = node?.listChannels()
Expand Down
129 changes: 128 additions & 1 deletion app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ class LightningRepoTest : BaseUnitTest() {
private val onchainSendAttemptStore = mock<OnchainSendAttemptStore>()
private val lnurlService = mock<LnurlService>()
private val connectivityRepo = mock<ConnectivityRepo>()
private val isOnline = MutableStateFlow(ConnectivityState.CONNECTED)
private val vssBackupClientLdk = mock<VssBackupClientLdk>()
private val electrumProbeService = mock<ElectrumProbeService>()
private val urlValidator = UrlValidator { Result.success(Unit) }
Expand All @@ -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(
Expand Down Expand Up @@ -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<Unit>()
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<Node>() 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<Node>() 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()
Expand Down
81 changes: 81 additions & 0 deletions app/src/test/java/to/bitkit/services/LightningServiceTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<NodeStatus> { 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<NodeStatus> { 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<NodeStatus> { 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<NodeStatus> { 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,
Expand Down
1 change: 1 addition & 0 deletions changelog.d/next/2197.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed the Lightning node staying offline after an internal error until the app was closed and reopened.
Loading