Skip to content
Open
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
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -604,3 +604,4 @@ suspend fun getData(): Result<Data> = withContext(Dispatchers.IO) {
- Use `WakeRepo` to register with the wake gateway, and `WakeWorker` with `WakeInbox` to handle the wakes received via cloud messages; add a topic's handler to `WakeHandlers`
- Use `*Services` to wrap rust library code exposed via bindings
- Use CQRS pattern of Command + Handler like it's done in the `NotifyPaymentReceived` + `NotifyPaymentReceivedHandler` setup
- Run background work that uses the network and must not stop when the user closes the app (loading the Paykit Server accounts after node start, a Spark exit) in a WorkManager `CoroutineWorker` (`@HiltWorker`), queued as unique work with a network constraint, never in a coroutine on a ViewModel, repository or app scope; see `WatchOnlyAccountsWorker` and `SparkExitWorker`
18 changes: 14 additions & 4 deletions app/src/main/java/to/bitkit/repositories/LightningRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ class LightningRepo @Inject constructor(
private val urlValidator: UrlValidator,
private val electrumProbeService: ElectrumProbeService,
private val sparkRepo: SparkRepo,
private val watchOnlyAccountsWork: WatchOnlyAccountsWork,
) : OnchainReleasing {
private val _lightningState = MutableStateFlow(LightningState())
val lightningState = _lightningState.asStateFlow()
Expand Down Expand Up @@ -537,16 +538,15 @@ class LightningRepo @Inject constructor(

if (lightningService.status?.isRunning == true) {
Logger.info("LDK node already running", context = TAG)
runSuspendCatching { lightningService.reconcileWatchOnlyAccounts() }
.onFailure {
Logger.warn("Failed to reconcile Paykit Server accounts during startup", it, context = TAG)
}
return@withLock adoptRunningNode()
}

lightningService.start(timeout, ::onEvent)

_lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) }
// Queued as soon as the node runs, so no later step that fails or is cancelled leaves the
// accounts unloaded.
queueWatchOnlyAccountsLoad()
listPaymentsKeepingSendHashes()

// Initial state sync
Expand Down Expand Up @@ -663,12 +663,22 @@ class LightningRepo @Inject constructor(

private suspend fun adoptRunningNode(): Result<Unit> {
_lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) }
queueWatchOnlyAccountsLoad()
scheduleOrdinaryFollowupRetry()
return lightningService.startEventListener(::onEvent).onFailure {
Logger.warn("Failed to start event listener", it, context = TAG)
}
}

/** Queues the load of the Paykit Server accounts, which the node is built without, when the wallet tracks any. */
private suspend fun queueWatchOnlyAccountsLoad() {
// On a failed read the worker is queued anyway; it does nothing when no account is tracked.
val hasTracked = runSuspendCatching { lightningService.hasTrackedWatchOnlyAccounts() }
.onFailure { Logger.warn("Failed to read tracked Paykit Server accounts", it, context = TAG) }
.getOrDefault(true)
if (hasTracked) watchOnlyAccountsWork.schedule()
}

private suspend fun releaseUnsavedConfigNode() {
runSuspendCatching { lightningService.stop() }
.onFailure { Logger.warn("Failed to release node built with an unsaved config", it, context = TAG) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,7 @@ class WatchOnlyAccountRepo @Inject constructor(

/**
* Applies [enabled] to the running node. Without a node (stopped, or being rebuilt after the app returned to the
* foreground) only the store changes: the next build loads tracked accounts from it, and
* [LightningService.reconcileWatchOnlyAccounts] on start adds or removes any account the build missed.
* foreground) only the store changes: [WatchOnlyAccountsWorker] loads the tracked accounts after the next start.
*
* The node is checked before queueing because a rebuild holds the LDK queue for the whole build while the node is
* still null; checking only inside the queue would make the approval wait for the build.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package to.bitkit.repositories

import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import dagger.hilt.android.qualifiers.ApplicationContext
import to.bitkit.ext.runSuspendCatching
import to.bitkit.services.LightningService
import to.bitkit.services.isRejectedPaykitServerAccount
import to.bitkit.utils.Logger
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.time.Duration.Companion.seconds
import kotlin.time.toJavaDuration

/**
* Queues [WatchOnlyAccountsWorker] after each node start. The node is built without the Paykit Server accounts, so its
* start does not grow with their number; a worker loads them, which WorkManager keeps when the app closes.
*/
@Singleton
class WatchOnlyAccountsWork @Inject constructor(
@ApplicationContext private val context: Context,
) {
companion object {
const val WORK_NAME = "watch-only-accounts-load"
private val RETRY_DELAY = 15.seconds
}

fun schedule() {
// A new start replaces the work of the node before it, which waits in backoff or loads into a stopped node.
WorkManager.getInstance(context).enqueueUniqueWork(WORK_NAME, ExistingWorkPolicy.REPLACE, request())
}

internal fun request() = OneTimeWorkRequestBuilder<WatchOnlyAccountsWorker>()
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
// A transient failure (VSS, Electrum) retries soon after it clears, not after an exponential backoff.
.setBackoffCriteria(BackoffPolicy.LINEAR, RETRY_DELAY.toJavaDuration())
.build()
}

/** Loads the Paykit Server accounts into the running node, then syncs the wallet so their funds and activity show. */
@HiltWorker
class WatchOnlyAccountsWorker @AssistedInject constructor(
@Assisted appContext: Context,
@Assisted workerParams: WorkerParameters,
private val lightningService: LightningService,
private val walletRepo: WalletRepo,
) : CoroutineWorker(appContext, workerParams) {
companion object {
private const val TAG = "WatchOnlyAccountsWorker"
}

override suspend fun doWork(): Result {
// The next start queues this work again.
if (lightningService.status?.isRunning != true) {
Logger.info("Skipped loading Paykit Server accounts: node not running", context = TAG)
return Result.success()
Comment thread
ovitrif marked this conversation as resolved.
Resolved
Comment thread
ovitrif marked this conversation as resolved.
Resolved
}
// The service logs each account that fails to load.
val result = runSuspendCatching { lightningService.reconcileWatchOnlyAccounts(syncAfterReconcile = false) }
val failure = result.exceptionOrNull()
when {
failure != null && !failure.isRejectedPaykitServerAccount() -> {
Logger.info("Retrying Paykit Server accounts that failed to load", context = TAG)
return Result.retry()
}
failure != null -> Logger.info("Skipped Paykit Server accounts the node rejects", context = TAG)
result.getOrNull() != true -> {
Logger.info("Skipped loading Paykit Server accounts: node stopped", context = TAG)
return Result.success()
}
else -> Logger.info("Loaded Paykit Server accounts", context = TAG)
}
walletRepo.syncNodeAndWallet().onFailure {
Logger.warn("Failed to sync wallet after loading Paykit Server accounts", it, context = TAG)
}
Comment thread
ovitrif marked this conversation as resolved.
Resolved
return Result.success()
}
}
Loading