From b399f25763686c7c7a5c5b3ab993b63089840628 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 16:50:46 +0100 Subject: [PATCH 1/4] perf: load watch-only accounts after node start Build the node without the Paykit Server accounts, each of which added about 2 s to the build, and load them into the running node from a WorkManager worker queued after every start that tracks accounts, so the load survives the app closing. - Reconcile unloads and completes pending removals in one lock hold, then loads each account in its own LDK queue hop and lock hold, re-checking tracking before each load. - Wallet sync no longer reconciles accounts; the worker retries a transient failure with WorkManager backoff instead of the in-process retry loop. Verified: ./gradlew testDevDebugUnitTest detekt --- .../to/bitkit/repositories/LightningRepo.kt | 14 +- .../repositories/WatchOnlyAccountRepo.kt | 3 +- .../repositories/WatchOnlyAccountsWorker.kt | 92 +++++++ .../to/bitkit/services/LightningService.kt | 228 +++++++----------- .../main/java/to/bitkit/ui/Notifications.kt | 1 + .../bitkit/repositories/LightningRepoTest.kt | 49 ++-- ...atchOnlyAccountLifecycleCoordinatorTest.kt | 3 +- .../WatchOnlyAccountsWorkerTest.kt | 88 +++++++ .../bitkit/services/LightningServiceTest.kt | 175 +++----------- changelog.d/next/2238.changed.md | 1 + 10 files changed, 341 insertions(+), 313 deletions(-) create mode 100644 app/src/main/java/to/bitkit/repositories/WatchOnlyAccountsWorker.kt create mode 100644 app/src/test/java/to/bitkit/repositories/WatchOnlyAccountsWorkerTest.kt create mode 100644 changelog.d/next/2238.changed.md diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index aa4408f4f9..921aafc770 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -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() @@ -537,14 +538,11 @@ 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) + queueWatchOnlyAccountsLoad() _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) } listPaymentsKeepingSendHashes() @@ -663,12 +661,20 @@ class LightningRepo @Inject constructor( private suspend fun adoptRunningNode(): Result { _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() { + runSuspendCatching { lightningService.hasTrackedWatchOnlyAccounts() } + .onFailure { Logger.warn("Failed to read tracked Paykit Server accounts", it, context = TAG) } + .onSuccess { if (it) watchOnlyAccountsWork.schedule() } + } + private suspend fun releaseUnsavedConfigNode() { runSuspendCatching { lightningService.stop() } .onFailure { Logger.warn("Failed to release node built with an unsaved config", it, context = TAG) } diff --git a/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt index 83f26930f1..5b1df1c0e5 100644 --- a/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt @@ -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. diff --git a/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountsWorker.kt b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountsWorker.kt new file mode 100644 index 0000000000..75f0bd462d --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountsWorker.kt @@ -0,0 +1,92 @@ +package to.bitkit.repositories + +import android.content.Context +import androidx.hilt.work.HiltWorker +import androidx.work.Constraints +import androidx.work.CoroutineWorker +import androidx.work.ExistingWorkPolicy +import androidx.work.ForegroundInfo +import androidx.work.NetworkType +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.OutOfQuotaPolicy +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.R +import to.bitkit.androidServices.LightningNodeService.Companion.CHANNEL_ID_NODE +import to.bitkit.ext.runSuspendCatching +import to.bitkit.services.LightningService +import to.bitkit.services.isRejectedPaykitServerAccount +import to.bitkit.ui.ID_NOTIFICATION_WATCH_ONLY_ACCOUNTS +import to.bitkit.ui.notificationBuilder +import to.bitkit.utils.Logger +import javax.inject.Inject +import javax.inject.Singleton + +/** + * 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" + } + + fun schedule() { + val request = OneTimeWorkRequestBuilder() + .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()) + .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST) + .build() + // 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) + } +} + +/** 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() + } + val failure = runSuspendCatching { lightningService.reconcileWatchOnlyAccounts(syncAfterReconcile = false) } + .exceptionOrNull() + if (failure != null && !failure.isRejectedPaykitServerAccount()) { + Logger.warn("Failed to load Paykit Server accounts, retrying", failure, context = TAG) + return Result.retry() + } + if (failure != null) { + Logger.warn("Skipped Paykit Server accounts the node rejects", failure, context = TAG) + } 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) + } + return Result.success() + } + + override suspend fun getForegroundInfo(): ForegroundInfo = ForegroundInfo( + ID_NOTIFICATION_WATCH_ONLY_ACCOUNTS, + applicationContext.notificationBuilder(channelId = CHANNEL_ID_NODE) + .setContentTitle(applicationContext.getString(R.string.app_name)) + .setContentText(applicationContext.getString(R.string.notification__service__body)) + .build(), + ) +} diff --git a/app/src/main/java/to/bitkit/services/LightningService.kt b/app/src/main/java/to/bitkit/services/LightningService.kt index f83c2fd50e..5e7f98d6e2 100644 --- a/app/src/main/java/to/bitkit/services/LightningService.kt +++ b/app/src/main/java/to/bitkit/services/LightningService.kt @@ -126,11 +126,13 @@ private class EventListenerContext : AbstractCoroutineContextElement(Key) { /** * Builds the node config. LSP peers are not trusted for zero-conf channels or to broadcast our force * closes: Blocktank no longer serves channels, so our node must broadcast and fee-bump its own closes. + * + * It loads no Paykit Server account: each adds about 2 s to the build, so `WatchOnlyAccountsWorker` loads them into + * the running node instead. */ internal fun nodeConfig( base: Config, storageDirPath: String, - onchainWalletAccounts: List, ): Config = base.copy( storageDirPath = storageDirPath, network = Env.network, @@ -141,7 +143,7 @@ internal fun nodeConfig( ), probingLiquidityLimitMultiplier = 1uL, includeUntrustedPendingInSpendable = true, - onchainWalletAccounts = onchainWalletAccounts, + onchainWalletAccounts = emptyList(), ) /** Returns the stored peers with no channel and no claimable balance, or none while any sweep is pending. */ @@ -190,30 +192,6 @@ internal fun enabledOnchainWalletAccountConfigs( ) } -/** - * Builds with [config], and when ldk-node rejects a configured Paykit Server account (its xpub does not match the - * seed, which fails the whole build) builds again without those accounts, so the wallet still starts. The reconcile on - * start then adds each account the node accepts. - */ -internal suspend fun buildAcceptingPaykitServerAccounts(config: Config, build: suspend (Config) -> Node): Node = - try { - build(config) - } catch (e: BuildException.InvalidSeedBytes) { - if (config.onchainWalletAccounts.isEmpty()) throw LdkError(e) - Logger.error( - "Node rejected Paykit Server accounts at build, building without them", - e, - context = "LightningService", - ) - try { - build(config.copy(onchainWalletAccounts = emptyList())) - } catch (retryError: BuildException) { - throw LdkError(retryError) - } - } catch (e: BuildException) { - throw LdkError(e) - } - /** Whether ldk-node rejected a Paykit Server account's xpub for this seed, which no retry can fix. */ internal fun Throwable.isRejectedPaykitServerAccount(): Boolean = generateSequence(this) { it.cause }.any { it is NodeException.InvalidSeedBytes } @@ -253,7 +231,6 @@ class LightningService internal constructor( companion object { private const val TAG = "LightningService" private const val RELEASE_FEE_ATTEMPTS = 4 - private val WATCH_ONLY_RECONCILE_RETRY_DELAY = 15.seconds /** A small fixed payment to a new wallet address; the rest returns as change, which pays the fee. */ private const val RELEASE_AMOUNT_SATS = 1_000uL @@ -341,10 +318,6 @@ class LightningService internal constructor( @VisibleForTesting internal var chainElectrumUrl: String? = null - @Volatile - private var watchOnlyReconcileRetryJob: Job? = null - private val watchOnlyReconcileRetryLock = Any() - // Release of the previous node's rust handle (free_node). Rebuild and destructive storage work // wait on this so a new node never touches storage the old one is still draining. @Volatile @@ -384,11 +357,7 @@ class LightningService internal constructor( private suspend fun config(walletIndex: Int): Config { val dirPath = Env.ldkStoragePath(walletIndex) - return nodeConfig( - base = defaultConfig(), - storageDirPath = dirPath, - onchainWalletAccounts = enabledOnchainWalletAccountConfigs(watchOnlyAccountStore.load(), walletIndex), - ) + return nodeConfig(base = defaultConfig(), storageDirPath = dirPath) } @Suppress("ForbiddenComment") @@ -400,8 +369,10 @@ class LightningService internal constructor( runtimeMonitor: NodeRuntimeMonitor, channelMigration: ChannelDataMigration? = null, ): Node = ServiceQueue.LDK.background(ldkQueue) { - buildAcceptingPaykitServerAccounts(config) { - buildNode(walletIndex, customServerUrl, customRgsServerUrl, it, runtimeMonitor, channelMigration) + try { + buildNode(walletIndex, customServerUrl, customRgsServerUrl, config, runtimeMonitor, channelMigration) + } catch (e: BuildException) { + throw LdkError(e) } } @@ -549,8 +520,6 @@ class LightningService internal constructor( } } - reconcileWatchOnlyAccountsBestEffort() - // start event listener after node started onEvent?.let { eventHandler -> shouldListenForEvents = true @@ -573,85 +542,97 @@ class LightningService internal constructor( Logger.info("Node started", context = TAG) } - // No wallet sync here: it holds the watch-only lock and the LDK queue for the whole Electrum round trip, which - // delays the node start and any Pubky auth approval waiting on that lock. The initial sync after start covers it. - private suspend fun reconcileWatchOnlyAccountsBestEffort() { - runSuspendCatching { - reconcileWatchOnlyAccounts(syncAfterReconcile = false) - }.onFailure { error -> - Logger.error("Failed to reconcile Paykit Server accounts during startup", error, context = TAG) + /** + * Loads the current wallet's Paykit Server accounts into the running node and unloads the ones it no longer wants. + * Each account loads in its own LDK queue hop and lock hold: one takes about 2 s, and sends and Pubky auth + * approvals must not wait behind all of them. + */ + suspend fun reconcileWatchOnlyAccounts(syncAfterReconcile: Boolean = true) { + val node = node ?: return + val configs = watchOnlyAccountLifecycleCoordinator.withLock { unloadUnwantedWatchOnlyAccounts(node) } ?: return + + // One account the node rejects must not keep the others from loading. A transient failure is rethrown ahead of + // a rejected xpub so the caller retries it. + val failures = configs.mapNotNull { config -> + runSuspendCatching { loadWatchOnlyAccount(node, config) }.exceptionOrNull()?.also { + Logger.error("Failed to load Paykit Server account '${config.accountIndex}'", it, context = TAG) + } } - } + val retryable = failures.firstOrNull { !it.isRejectedPaykitServerAccount() } + (retryable ?: failures.firstOrNull())?.let { throw it } - suspend fun reconcileWatchOnlyAccounts(syncAfterReconcile: Boolean = true) { - watchOnlyAccountLifecycleCoordinator.withLock { - val node = node ?: return@withLock - val reconciliationState = watchOnlyAccountStore.loadReconciliationState() - val walletRecords = reconciliationState.accounts.filter { it.walletIndex == currentWalletIndex } - val accountsPendingRemoval = reconciliationState.accountsPendingRemoval.filter { - it.walletIndex == currentWalletIndex + if (syncAfterReconcile && configs.isNotEmpty()) { + ServiceQueue.LDK.background(ldkQueue) { + if (this@LightningService.node === node && node.status().isRunning) node.syncWallets() } - val desiredConfigs = enabledOnchainWalletAccountConfigs(walletRecords, currentWalletIndex) - - val reconciled = ServiceQueue.LDK.background(ldkQueue) { - // The node may have been stopped and released while this waited for the queue. - if (this@LightningService.node !== node) return@background false - val trackedAccounts = node.listOnchainWalletAccounts() - val managedKeys = (walletRecords + accountsPendingRemoval).mapNotNull { record -> - when (record.addressType) { - WATCH_ONLY_ACCOUNT_NATIVE_SEGWIT_ADDRESS_TYPE -> - accountKey(LdkAddressType.NATIVE_SEGWIT, record.accountIndex.toUInt()) - else -> null - } - }.toSet() - val desiredKeys = desiredConfigs.map { accountKey(it.addressType, it.accountIndex) }.toSet() + } + } - trackedAccounts.forEach { trackedAccount -> - val key = accountKey(trackedAccount.addressType, trackedAccount.accountIndex) - if (key in managedKeys && key !in desiredKeys) { - node.removeOnchainWalletAccount(trackedAccount.addressType, trackedAccount.accountIndex) - } - } + /** Whether the current wallet tracks any Paykit Server account, which the node loads after start. */ + suspend fun hasTrackedWatchOnlyAccounts(): Boolean = + enabledOnchainWalletAccountConfigs(watchOnlyAccountStore.load(), currentWalletIndex).isNotEmpty() - // One account the node rejects must not keep the others from loading. A transient failure is rethrown - // ahead of a rejected xpub so the caller retries it. - val failures = desiredConfigs.mapNotNull { config -> - runSuspendCatching { - val isTracked = trackedAccounts.any { - it.addressType == config.addressType && it.accountIndex == config.accountIndex - } - if (!isTracked) { - node.addOnchainWalletAccount(config.addressType, config.accountIndex, config.xpub) - } - node.onchainPayment().revealReceiveAddressesToAccount( - config.addressType, - config.accountIndex, - WATCH_ONLY_ACCOUNT_HIGHEST_PRE_REVEALED_ADDRESS_INDEX.toUInt(), - ) - }.exceptionOrNull()?.also { - Logger.error("Failed to load Paykit Server account ${config.accountIndex}", it, context = TAG) - } + /** + * Unloads the accounts the store no longer wants and completes their pending removal in the same lock hold, so a + * restore that queues new removals while accounts load is not cleared. Returns the accounts to load. + */ + private suspend fun unloadUnwantedWatchOnlyAccounts(node: Node): List? { + val walletIndex = currentWalletIndex + val reconciliationState = watchOnlyAccountStore.loadReconciliationState() + val walletRecords = reconciliationState.accounts.filter { it.walletIndex == walletIndex } + val accountsPendingRemoval = reconciliationState.accountsPendingRemoval.filter { it.walletIndex == walletIndex } + val desiredConfigs = enabledOnchainWalletAccountConfigs(walletRecords, walletIndex) + + val unloaded = ServiceQueue.LDK.background(ldkQueue) { + // The node may have been stopped and released while this waited for the queue. + if (this@LightningService.node !== node) return@background false + val managedKeys = (walletRecords + accountsPendingRemoval).mapNotNull { record -> + when (record.addressType) { + WATCH_ONLY_ACCOUNT_NATIVE_SEGWIT_ADDRESS_TYPE -> + accountKey(LdkAddressType.NATIVE_SEGWIT, record.accountIndex.toUInt()) + else -> null } - val retryable = failures.firstOrNull { !it.isRejectedPaykitServerAccount() } - (retryable ?: failures.firstOrNull())?.let { throw it } - - if (syncAfterReconcile && desiredConfigs.isNotEmpty() && node.status().isRunning) { - node.syncWallets() + }.toSet() + val desiredKeys = desiredConfigs.map { accountKey(it.addressType, it.accountIndex) }.toSet() + node.listOnchainWalletAccounts().forEach { trackedAccount -> + val key = accountKey(trackedAccount.addressType, trackedAccount.accountIndex) + if (key in managedKeys && key !in desiredKeys) { + node.removeOnchainWalletAccount(trackedAccount.addressType, trackedAccount.accountIndex) } - true - } - if (reconciled && accountsPendingRemoval.isNotEmpty()) { - watchOnlyAccountStore.completeReconciliation(currentWalletIndex) } + true } + if (!unloaded) return null + if (accountsPendingRemoval.isNotEmpty()) watchOnlyAccountStore.completeReconciliation(walletIndex) + return desiredConfigs } + private suspend fun loadWatchOnlyAccount(node: Node, config: OnchainWalletAccountConfig) = + watchOnlyAccountLifecycleCoordinator.withLock { + // Tracking may have been turned off while the accounts before this one loaded. + val records = watchOnlyAccountStore.loadReconciliationState().accounts + if (config !in enabledOnchainWalletAccountConfigs(records, currentWalletIndex)) return@withLock + ServiceQueue.LDK.background(ldkQueue) { + if (this@LightningService.node !== node) return@background + val isTracked = node.listOnchainWalletAccounts().any { + it.addressType == config.addressType && it.accountIndex == config.accountIndex + } + if (!isTracked) { + node.addOnchainWalletAccount(config.addressType, config.accountIndex, config.xpub) + } + node.onchainPayment().revealReceiveAddressesToAccount( + config.addressType, + config.accountIndex, + WATCH_ONLY_ACCOUNT_HIGHEST_PRE_REVEALED_ADDRESS_INDEX.toUInt(), + ) + } + } + // Teardown must not be abandoned midway: a cancelled caller would leave the rust node alive and // let the GC free it later on the finalizer thread, racing the next node. This covers the whole // body, including the listener join, so cancellation during listener cleanup cannot skip it. suspend fun stop() = withContext(NonCancellable) { Env.activeElectrumServerUrl.update { null } - watchOnlyReconcileRetryJob?.cancelAndJoin() shouldListenForEvents = false // A stop requested from inside an event handler runs on the listener job itself; joining it // here would deadlock, so let the loop exit on shouldListenForEvents instead. @@ -806,12 +787,6 @@ class LightningService internal constructor( suspend fun sync() { val node = this.node ?: throw ServiceError.NodeNotSetup() - // A Paykit Server account that fails to load must not fail the wallet sync: sends are gated on it. A transient - // failure is retried on its own schedule; an xpub the node rejects (`InvalidSeedBytes`) stays rejected. - val reconcileFailure = runSuspendCatching { reconcileWatchOnlyAccounts(syncAfterReconcile = false) } - .onFailure { Logger.error("Failed to reconcile Paykit Server accounts before sync", it, context = TAG) } - .exceptionOrNull() - Logger.verbose("Syncing LDK…", context = TAG) ServiceQueue.LDK.background(ldkQueue) { node.syncWallets() @@ -820,41 +795,6 @@ class LightningService internal constructor( _syncStatusChanged.tryEmit(Unit) Logger.debug("LDK synced", context = TAG) - if (reconcileFailure != null && !reconcileFailure.isRejectedPaykitServerAccount()) { - scheduleWatchOnlyReconcileRetry() - } - } - - /** Retries loading Paykit Server accounts until they load, the node stops, or the node rejects one for good. */ - private fun scheduleWatchOnlyReconcileRetry() { - synchronized(watchOnlyReconcileRetryLock) { - if (watchOnlyReconcileRetryJob?.isActive == true) return - watchOnlyReconcileRetryJob = launch { retryWatchOnlyReconcile() } - } - } - - private suspend fun retryWatchOnlyReconcile() { - var retry = true - while (retry && currentCoroutineContext().isActive && node != null) { - delay(WATCH_ONLY_RECONCILE_RETRY_DELAY) - val failure = runSuspendCatching { reconcileWatchOnlyAccounts(syncAfterReconcile = false) } - .exceptionOrNull() - if (failure == null) { - syncWalletsAfterAccountsLoad() - } else { - Logger.warn("Paykit Server account reconcile retry failed", failure, context = TAG) - } - retry = failure != null && !failure.isRejectedPaykitServerAccount() - } - } - - // Outside the watch-only lock, as in sync(): an Electrum round trip must not delay Pubky auth. A failure here is - // a wallet sync failure, which the regular sync retries. - private suspend fun syncWalletsAfterAccountsLoad() { - runSuspendCatching { - ServiceQueue.LDK.background(ldkQueue) { this@LightningService.node?.syncWallets() } - _syncStatusChanged.tryEmit(Unit) - }.onFailure { Logger.warn("Wallet sync after loading Paykit Server accounts failed", it, context = TAG) } } suspend fun sign(message: String): String { diff --git a/app/src/main/java/to/bitkit/ui/Notifications.kt b/app/src/main/java/to/bitkit/ui/Notifications.kt index 36a26faf62..b762cf854b 100644 --- a/app/src/main/java/to/bitkit/ui/Notifications.kt +++ b/app/src/main/java/to/bitkit/ui/Notifications.kt @@ -27,6 +27,7 @@ import kotlin.random.Random const val ID_NOTIFICATION_SKIPPED = -1 const val ID_NOTIFICATION_NODE = 1 const val ID_NOTIFICATION_WAKE = 2 +const val ID_NOTIFICATION_WATCH_ONLY_ACCOUNTS = 3 const val EXTRA_PAYKIT_SUBSCRIPTION_PAYMENT_DUE = "paykit_subscription_payment_due" const val EXTRA_PAYKIT_PAYER_IDENTITY = "paykit_payer_identity" const val EXTRA_PAYKIT_PAYMENT_REQUEST_ID = "paykit_payment_request_id" diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index a0aa9ec43e..f7ee66eca2 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -167,6 +167,7 @@ class LightningRepoTest : BaseUnitTest() { private val isOnline = MutableStateFlow(ConnectivityState.CONNECTED) private val vssBackupClientLdk = mock() private val electrumProbeService = mock() + private val watchOnlyAccountsWork = mock() private val urlValidator = UrlValidator { Result.success(Unit) } private val probePaymentA = "probe-payment-a" private val probePaymentB = "probe-payment-b" @@ -180,6 +181,7 @@ class LightningRepoTest : BaseUnitTest() { whenever(lightningService.setup(any(), anyOrNull(), anyOrNull(), anyOrNull())) .thenReturn(Unit) whenever(lightningService.start(anyOrNull(), any())).thenReturn(Unit) + whenever(lightningService.hasTrackedWatchOnlyAccounts()).thenReturn(false) whenever { electrumProbeService.probe(any(), any()) }.thenReturn(Result.success(Unit)) whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) whenever(connectivityRepo.isOnline).thenReturn(isOnline) @@ -200,6 +202,7 @@ class LightningRepoTest : BaseUnitTest() { urlValidator = urlValidator, electrumProbeService = electrumProbeService, sparkRepo = sparkRepo, + watchOnlyAccountsWork = watchOnlyAccountsWork, ) } @@ -789,40 +792,48 @@ class LightningRepoTest : BaseUnitTest() { } @Test - fun `start reconciles watch-only accounts when the underlying node is already running`() = test { + fun `start queues the paykit server account load after starting the node`() = test { sut.setInitNodeLifecycleState() - val node = mock() - val status = mock() - whenever(lightningService.node).thenReturn(node) - whenever(lightningService.status).thenReturn(status) - whenever(status.isRunning).thenReturn(true) - whenever { lightningService.startEventListener(any()) }.thenReturn(Result.success(Unit)) + whenever(lightningService.hasTrackedWatchOnlyAccounts()).thenReturn(true) + whenever(lightningService.node).thenReturn(mock()) + whenever(coreService.blocktank).thenReturn(mock()) - val result = sut.start(shouldRetry = false) + val result = sut.start() assertTrue(result.isSuccess) - assertEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) - verifyBlocking(lightningService) { reconcileWatchOnlyAccounts() } - verifyBlocking(lightningService, never()) { start(anyOrNull(), any()) } + verify(watchOnlyAccountsWork).schedule() + verifyBlocking(lightningService, never()) { reconcileWatchOnlyAccounts(any()) } + } + + @Test + fun `start queues no paykit server account load when the wallet tracks none`() = test { + sut.setInitNodeLifecycleState() + whenever(lightningService.hasTrackedWatchOnlyAccounts()).thenReturn(false) + whenever(lightningService.node).thenReturn(mock()) + whenever(coreService.blocktank).thenReturn(mock()) + + val result = sut.start() + + assertTrue(result.isSuccess) + verify(watchOnlyAccountsWork, never()).schedule() } @Test - fun `start remains running when watch-only reconciliation fails for an already running node`() = test { + fun `start queues the paykit server account load when the node is already running`() = test { sut.setInitNodeLifecycleState() + whenever(lightningService.hasTrackedWatchOnlyAccounts()).thenReturn(true) val node = mock() val status = mock() whenever(lightningService.node).thenReturn(node) whenever(lightningService.status).thenReturn(status) whenever(status.isRunning).thenReturn(true) - whenever { lightningService.reconcileWatchOnlyAccounts() } - .thenThrow(IllegalStateException("reconciliation failed")) whenever { lightningService.startEventListener(any()) }.thenReturn(Result.success(Unit)) val result = sut.start(shouldRetry = false) assertTrue(result.isSuccess) assertEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) - verifyBlocking(lightningService) { reconcileWatchOnlyAccounts() } + verify(watchOnlyAccountsWork).schedule() verifyBlocking(lightningService, never()) { start(anyOrNull(), any()) } } @@ -2801,6 +2812,7 @@ class LightningRepoTest : BaseUnitTest() { urlValidator = urlValidator, electrumProbeService = electrumProbeService, sparkRepo = sparkRepo, + watchOnlyAccountsWork = watchOnlyAccountsWork, ) @Test @@ -2921,6 +2933,7 @@ class LightningRepoTest : BaseUnitTest() { urlValidator = urlValidator, electrumProbeService = electrumProbeService, sparkRepo = spark, + watchOnlyAccountsWork = watchOnlyAccountsWork, ) startNodeForTesting() val first = async { spark.payInvoice("bolt11", 1_000uL) } @@ -4191,6 +4204,7 @@ class LightningRepoTest : BaseUnitTest() { urlValidator = urlValidator, electrumProbeService = electrumProbeService, sparkRepo = sparkRepo, + watchOnlyAccountsWork = watchOnlyAccountsWork, ) whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) whenever(coreService.activity).thenReturn(mock()) @@ -4651,6 +4665,7 @@ class LightningRepoTest : BaseUnitTest() { urlValidator = urlValidator, electrumProbeService = electrumProbeService, sparkRepo = sparkRepo, + watchOnlyAccountsWork = watchOnlyAccountsWork, ) whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) val activityService = mock() @@ -5053,6 +5068,7 @@ class LightningRepoTest : BaseUnitTest() { vssBackupClientLdk = vssBackupClientLdk, urlValidator = urlValidator, electrumProbeService = electrumProbeService, sparkRepo = sparkRepo, + watchOnlyAccountsWork = watchOnlyAccountsWork, ) whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) val activityService = mock() @@ -5124,6 +5140,7 @@ class LightningRepoTest : BaseUnitTest() { vssBackupClientLdk = vssBackupClientLdk, urlValidator = urlValidator, electrumProbeService = electrumProbeService, sparkRepo = sparkRepo, + watchOnlyAccountsWork = watchOnlyAccountsWork, ) whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) val activityService = mock() @@ -5206,6 +5223,7 @@ class LightningRepoTest : BaseUnitTest() { vssBackupClientLdk = vssBackupClientLdk, urlValidator = urlValidator, electrumProbeService = electrumProbeService, sparkRepo = sparkRepo, + watchOnlyAccountsWork = watchOnlyAccountsWork, ) whenever(settingsStore.data).thenReturn(flowOf(SettingsData(coinSelectAuto = false))) val activityService = mock() @@ -6270,6 +6288,7 @@ class LightningRepoTest : BaseUnitTest() { urlValidator = failingValidator, electrumProbeService = electrumProbeService, sparkRepo = sparkRepo, + watchOnlyAccountsWork = watchOnlyAccountsWork, ) sutWithFailingValidator.setInitNodeLifecycleState() whenever(lightningService.node).thenReturn(mock()) diff --git a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountLifecycleCoordinatorTest.kt b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountLifecycleCoordinatorTest.kt index 305f46686e..9ff5c6f3d1 100644 --- a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountLifecycleCoordinatorTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountLifecycleCoordinatorTest.kt @@ -100,7 +100,8 @@ class WatchOnlyAccountLifecycleCoordinatorTest : BaseUnitTest() { assertTrue(tracked.get()) assertTrue(storedAccounts.single().isTrackingEnabled) assertEquals(WatchOnlyAccountSetupState.Authorizing, storedAccounts.single().setupState) - assertEquals(2, loadCount.get()) + // The authorization's read, the reconciliation's plan, and its check before loading the account. + assertEquals(3, loadCount.get()) verify(node, never()).removeOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u) } diff --git a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountsWorkerTest.kt b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountsWorkerTest.kt new file mode 100644 index 0000000000..1de3365432 --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountsWorkerTest.kt @@ -0,0 +1,88 @@ +package to.bitkit.repositories + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import androidx.work.ListenableWorker +import androidx.work.WorkerParameters +import org.junit.Test +import org.junit.runner.RunWith +import org.lightningdevkit.ldknode.NodeException +import org.lightningdevkit.ldknode.NodeStatus +import org.mockito.kotlin.any +import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verifyBlocking +import org.mockito.kotlin.whenever +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import to.bitkit.services.LightningService +import to.bitkit.test.BaseUnitTest +import kotlin.test.assertEquals + +@Config(sdk = [34]) +@RunWith(RobolectricTestRunner::class) +class WatchOnlyAccountsWorkerTest : BaseUnitTest() { + private val context = ApplicationProvider.getApplicationContext() + private val lightningService = mock() + private val walletRepo = mock() + + @Test + fun `loads the accounts and syncs the wallet`() = test { + stubNodeRunning(true) + whenever(walletRepo.syncNodeAndWallet(any())).thenReturn(Result.success(Unit)) + + val result = worker().doWork() + + assertEquals(ListenableWorker.Result.success(), result) + verifyBlocking(lightningService) { reconcileWatchOnlyAccounts(syncAfterReconcile = false) } + verifyBlocking(walletRepo) { syncNodeAndWallet(any()) } + } + + @Test + fun `leaves the load to the next start when the node is not running`() = test { + stubNodeRunning(false) + + val result = worker().doWork() + + assertEquals(ListenableWorker.Result.success(), result) + verifyBlocking(lightningService, never()) { reconcileWatchOnlyAccounts(any()) } + } + + @Test + fun `retries a transient load failure`() = test { + stubNodeRunning(true) + whenever(lightningService.reconcileWatchOnlyAccounts(syncAfterReconcile = false)) + .doSuspendableAnswer { throw NodeException.PersistenceFailed("vss write failed") } + + val result = worker().doWork() + + assertEquals(ListenableWorker.Result.retry(), result) + verifyBlocking(walletRepo, never()) { syncNodeAndWallet(any()) } + } + + @Test + fun `does not retry an account the node rejects`() = test { + stubNodeRunning(true) + whenever(lightningService.reconcileWatchOnlyAccounts(syncAfterReconcile = false)) + .doSuspendableAnswer { throw NodeException.InvalidSeedBytes("xpub mismatch") } + whenever(walletRepo.syncNodeAndWallet(any())).thenReturn(Result.success(Unit)) + + val result = worker().doWork() + + assertEquals(ListenableWorker.Result.success(), result) + } + + private fun stubNodeRunning(isRunning: Boolean) { + val status = mock() + whenever(status.isRunning).thenReturn(isRunning) + whenever(lightningService.status).thenReturn(status) + } + + private fun worker() = WatchOnlyAccountsWorker( + appContext = context, + workerParams = mock(), + lightningService = lightningService, + walletRepo = walletRepo, + ) +} diff --git a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt index dc994b87a1..9bd8eadfba 100644 --- a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt @@ -14,11 +14,9 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.StandardTestDispatcher -import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout -import kotlinx.coroutines.withTimeoutOrNull import kotlinx.serialization.json.Json import org.junit.Before import org.junit.Rule @@ -28,7 +26,6 @@ import org.lightningdevkit.ldknode.AddressInfo import org.lightningdevkit.ldknode.AddressType import org.lightningdevkit.ldknode.AnchorChannelsConfig import org.lightningdevkit.ldknode.BalanceSource -import org.lightningdevkit.ldknode.BuildException import org.lightningdevkit.ldknode.Config import org.lightningdevkit.ldknode.ConfirmationStatus import org.lightningdevkit.ldknode.Event @@ -95,7 +92,6 @@ import to.bitkit.repositories.PreparedOnchainSend import to.bitkit.repositories.PreparedOnchainSendRefused import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError -import to.bitkit.utils.LdkError import to.bitkit.utils.LoggerLdk import to.bitkit.utils.ServiceError import java.io.File @@ -106,11 +102,9 @@ import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNull -import kotlin.test.assertSame import kotlin.test.assertTrue import kotlin.time.Clock import kotlin.time.Duration.Companion.milliseconds -import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant import com.synonym.bitkitcore.AddressType as BitkitAddressType import org.lightningdevkit.ldknode.LogLevel as LdkLogLevel @@ -119,7 +113,6 @@ import org.lightningdevkit.ldknode.PreparedOnchainSend as NativePreparedOnchainS private const val VERIFY_TIMEOUT_MS = 2_000L private const val RELEASE_GATE_PROBE_MS = 200L private const val STOP_BOUND_MS = 5_000L -private const val LOCK_PROBE_TIMEOUT_MS = 200L private val SHORT_GATE_TIMEOUT = 200.milliseconds private val detachingRecord = LogRecord( LdkLogLevel.ERROR, @@ -1095,7 +1088,7 @@ class LightningServiceTest : BaseUnitTest() { } @Test - fun `startup config includes enabled active and authorizing accounts for current wallet`() { + fun `account configs include enabled active and authorizing accounts for current wallet`() { val enabled = watchOnlyAccount(accountIndex = 1, walletIndex = 0, enabled = true) val disabled = watchOnlyAccount(accountIndex = 2, walletIndex = 0, enabled = false) val otherWallet = watchOnlyAccount(accountIndex = 3, walletIndex = 1, enabled = true) @@ -1137,13 +1130,22 @@ class LightningServiceTest : BaseUnitTest() { onchainWalletAccounts = emptyList(), ) - val config = nodeConfig(base = base, storageDirPath = "ldk", onchainWalletAccounts = emptyList()) + val config = nodeConfig(base = base, storageDirPath = "ldk") assertTrue(config.trustedPeers0conf.isEmpty()) assertEquals(emptyList(), config.anchorChannelsConfig?.trustedPeersNoReserve) assertEquals(1uL, config.anchorChannelsConfig?.perChannelReserveSats) } + @Test + fun `node config loads no paykit server account at build`() { + val base = buildConfig(listOf(OnchainWalletAccountConfig(AddressType.NATIVE_SEGWIT, 1u, "xpub-1"))) + + val config = nodeConfig(base = base, storageDirPath = "ldk") + + assertTrue(config.onchainWalletAccounts.isEmpty()) + } + @Test fun `idle peers are stored peers with no channel and no claimable balance`() { val peers = listOf( @@ -1227,29 +1229,6 @@ class LightningServiceTest : BaseUnitTest() { verify(node).syncWallets() } - @Test - fun `wallet sync retries watch-only reconciliation and syncs once`() = test { - val account = watchOnlyAccount(accountIndex = 5, walletIndex = 0, enabled = true) - .copy(setupState = WatchOnlyAccountSetupState.Authorizing) - val onchainPayment = mock() - whenever(watchOnlyAccountStore.loadReconciliationState()).thenReturn( - WatchOnlyAccountReconciliationState(listOf(account), emptyList()), - ) - whenever(node.listOnchainWalletAccounts()).thenReturn( - listOf(OnchainWalletAccount(AddressType.NATIVE_SEGWIT, 5u)) - ) - whenever(node.onchainPayment()).thenReturn(onchainPayment) - - sut.sync() - - verify(onchainPayment).revealReceiveAddressesToAccount( - AddressType.NATIVE_SEGWIT, - 5u, - WATCH_ONLY_ACCOUNT_HIGHEST_PRE_REVEALED_ADDRESS_INDEX.toUInt(), - ) - verify(node, times(1)).syncWallets() - } - @Test fun `restore reconciliation unloads replaced account and loads restored account`() = test { val replacedAccount = watchOnlyAccount(accountIndex = 1, walletIndex = 0, enabled = true) @@ -1281,11 +1260,10 @@ class LightningServiceTest : BaseUnitTest() { } @Test - fun `failed restore reconciliation retains removals for the next retry`() = test { + fun `restore reconciliation completes removals once unloaded even when a load fails`() = test { val replacedAccount = watchOnlyAccount(accountIndex = 1, walletIndex = 0, enabled = true) val restoredAccount = watchOnlyAccount(accountIndex = 2, walletIndex = 0, enabled = true) val trackedAccounts = mutableListOf(OnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u)) - var failAdd = true val onchainPayment = mock() whenever(watchOnlyAccountStore.loadReconciliationState()).thenReturn( WatchOnlyAccountReconciliationState( @@ -1301,67 +1279,15 @@ class LightningServiceTest : BaseUnitTest() { } .whenever(node).removeOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u) doAnswer { - check(!failAdd) { "add failed" } - trackedAccounts += OnchainWalletAccount(AddressType.NATIVE_SEGWIT, 2u) + error("add failed") }.whenever(node).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 2u, restoredAccount.xpub) assertTrue(runCatching { sut.reconcileWatchOnlyAccounts(syncAfterReconcile = false) }.isFailure) - verify(watchOnlyAccountStore, never()).completeReconciliation(walletIndex = 0) - - failAdd = false - sut.reconcileWatchOnlyAccounts(syncAfterReconcile = false) - assertEquals(listOf(OnchainWalletAccount(AddressType.NATIVE_SEGWIT, 2u)), trackedAccounts) + assertTrue(trackedAccounts.isEmpty()) verify(watchOnlyAccountStore).completeReconciliation(walletIndex = 0) } - @Test - fun `build without paykit server accounts when the node rejects one`() = test { - val account = OnchainWalletAccountConfig(AddressType.NATIVE_SEGWIT, 1u, "xpub-1") - val built = mock() - val attempts = mutableListOf>() - - val result = buildAcceptingPaykitServerAccounts(buildConfig(listOf(account))) { - attempts += it.onchainWalletAccounts - if (it.onchainWalletAccounts.isNotEmpty()) throw BuildException.InvalidSeedBytes("xpub mismatch") - built - } - - assertSame(built, result) - assertEquals(listOf(listOf(account), emptyList()), attempts) - } - - @Test - fun `build fails without retry when no paykit server account is configured`() = test { - var attempts = 0 - - val error = assertFailsWith { - buildAcceptingPaykitServerAccounts(buildConfig(emptyList())) { - attempts++ - throw BuildException.InvalidSeedBytes("bad seed") - } - } - - assertEquals(1, attempts) - assertEquals("InvalidSeedBytes", error.compactType) - } - - @Test - fun `build fails without retry on other build errors`() = test { - var attempts = 0 - - assertFailsWith { - buildAcceptingPaykitServerAccounts( - buildConfig(listOf(OnchainWalletAccountConfig(AddressType.NATIVE_SEGWIT, 1u, "xpub-1"))), - ) { - attempts++ - throw BuildException.WalletSetupFailed("wallet") - } - } - - assertEquals(1, attempts) - } - @Test fun `reconciliation loads the other accounts when the node rejects one`() = test { val rejected = watchOnlyAccount(accountIndex = 1, walletIndex = 0, enabled = true) @@ -1386,74 +1312,34 @@ class LightningServiceTest : BaseUnitTest() { } @Test - fun `wallet sync runs when reconciliation fails`() = test { - val rejected = watchOnlyAccount(accountIndex = 1, walletIndex = 0, enabled = true) - whenever(watchOnlyAccountStore.loadReconciliationState()).thenReturn( - WatchOnlyAccountReconciliationState(listOf(rejected), emptyList()), - ) - whenever(node.listOnchainWalletAccounts()).thenReturn(emptyList()) - whenever(node.onchainPayment()).thenReturn(mock()) - doThrow(NodeException.InvalidSeedBytes("xpub mismatch")) - .whenever(node).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, rejected.xpub) - - sut.sync() - - verify(node, times(1)).syncWallets() - } - - @OptIn(ExperimentalCoroutinesApi::class) - @Test - fun `wallet sync succeeds and retries a transient account failure on its own`() = test { + fun `wallet sync leaves paykit server accounts to the worker`() = test { val account = watchOnlyAccount(accountIndex = 1, walletIndex = 0, enabled = true) - val status = mock() - whenever(status.isRunning).thenReturn(true) - whenever(node.status()).thenReturn(status) whenever(watchOnlyAccountStore.loadReconciliationState()).thenReturn( WatchOnlyAccountReconciliationState(listOf(account), emptyList()), ) - whenever(node.listOnchainWalletAccounts()).thenReturn(emptyList()) - whenever(node.onchainPayment()).thenReturn(mock()) - var failAdd = true - doAnswer { if (failAdd) throw NodeException.PersistenceFailed("vss write failed") } - .whenever(node).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, account.xpub) - val lockFreeDuringSync = mutableListOf() - doAnswer { lockFreeDuringSync += isWatchOnlyLockFree() }.whenever(node).syncWallets() sut.sync() - verify(node, times(1)).syncWallets() - - failAdd = false - advanceTimeBy(16.seconds) - runCurrent() - - verify(node, times(2)).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, account.xpub) - verify(node, times(2)).syncWallets() - assertEquals(listOf(true, true), lockFreeDuringSync) - advanceTimeBy(60.seconds) - runCurrent() - verify(node, times(2)).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, account.xpub) + verify(node, never()).addOnchainWalletAccount(any(), any(), any()) + verify(node).syncWallets() } - @OptIn(ExperimentalCoroutinesApi::class) @Test - fun `stop ends the account retry before releasing the node`() = test { - val account = watchOnlyAccount(accountIndex = 1, walletIndex = 0, enabled = true) - whenever(watchOnlyAccountStore.loadReconciliationState()).thenReturn( - WatchOnlyAccountReconciliationState(listOf(account), emptyList()), - ) + fun `reconciliation skips an account whose tracking was turned off while others loaded`() = test { + val first = watchOnlyAccount(accountIndex = 1, walletIndex = 0, enabled = true) + val second = watchOnlyAccount(accountIndex = 2, walletIndex = 0, enabled = true) + var accounts = listOf(first, second) + whenever(watchOnlyAccountStore.loadReconciliationState()).thenAnswer { + WatchOnlyAccountReconciliationState(accounts, emptyList()) + } whenever(node.listOnchainWalletAccounts()).thenReturn(emptyList()) whenever(node.onchainPayment()).thenReturn(mock()) - doThrow(NodeException.PersistenceFailed("vss write failed")) - .whenever(node).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, account.xpub) + doAnswer { accounts = listOf(first, second.copy(isTrackingEnabled = false)) } + .whenever(node).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, first.xpub) - sut.sync() - sut.stop() - advanceTimeBy(60.seconds) - runCurrent() + sut.reconcileWatchOnlyAccounts(syncAfterReconcile = false) - verify(node, times(1)).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, account.xpub) - verify(node, times(1)).syncWallets() + verify(node, never()).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 2u, second.xpub) } @Test @@ -1470,11 +1356,6 @@ class LightningServiceTest : BaseUnitTest() { verify(node, never()).addOnchainWalletAccount(any(), any(), any()) } - // Mutex.withLock on a free mutex returns without suspending; a held one times out. - private fun isWatchOnlyLockFree(): Boolean = runBlocking { - withTimeoutOrNull(LOCK_PROBE_TIMEOUT_MS) { watchOnlyAccountLifecycleCoordinator.withLock { true } } ?: false - } - private fun buildConfig(accounts: List) = Config( storageDirPath = "", network = Network.REGTEST, diff --git a/changelog.d/next/2238.changed.md b/changelog.d/next/2238.changed.md new file mode 100644 index 0000000000..537140b3ef --- /dev/null +++ b/changelog.d/next/2238.changed.md @@ -0,0 +1 @@ +The wallet starts faster when it tracks Paykit server accounts. From a84d871370000806ba00b84db6dc932dc9d59382 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 16:50:47 +0100 Subject: [PATCH 2/4] docs: run app-close-proof network work in workers Verified: none (docs only) --- AGENTS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/AGENTS.md b/AGENTS.md index d7dc04cbdf..17db358630 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -604,3 +604,4 @@ suspend fun getData(): Result = 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` From c98fc078156d4ebeb1df8fe4533b9a31882792e8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 17:37:33 +0100 Subject: [PATCH 3/4] fix: load watch-only accounts without a foreground notice The worker is plain unique work with a network constraint, so Android 9 to 11 show no foreground notification at each start, and a transient failure retries on a linear 15 s backoff instead of an exponential one. It is queued once the node runs and keeps its network graph. The check before queuing reads the store under the lifecycle lock, so an approval that began before the node ran counts, and it also counts removals a restore left pending. The load stops once the node is stopped or replaced, and the worker then skips the sync. Each failure is logged once, and "Loaded Paykit Server accounts" logs only for a current node. The approval-while-node-restarts journey no longer expects the build log line, since the build loads no accounts. Verified: ./gradlew compileDevDebugKotlin testDevDebugUnitTest (WatchOnlyAccountsWorkerTest, LightningServiceTest, LightningRepoTest, WatchOnlyAccount*, BackupRepoTest) detekt --- .../to/bitkit/repositories/LightningRepo.kt | 5 +- .../repositories/WatchOnlyAccountsWorker.kt | 45 +++++++--------- .../to/bitkit/services/LightningService.kt | 52 +++++++++++++------ .../main/java/to/bitkit/ui/Notifications.kt | 1 - .../to/bitkit/repositories/BackupRepoTest.kt | 2 +- .../WatchOnlyAccountsWorkerTest.kt | 12 +++++ .../bitkit/services/LightningServiceTest.kt | 13 +++++ .../approval-while-node-restarts.xml | 2 +- 8 files changed, 88 insertions(+), 44 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 921aafc770..73f97f36a4 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -542,7 +542,6 @@ class LightningRepo @Inject constructor( } lightningService.start(timeout, ::onEvent) - queueWatchOnlyAccountsLoad() _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) } listPaymentsKeepingSendHashes() @@ -563,6 +562,10 @@ class LightningRepo @Inject constructor( return@withLock Result.success(Unit) } + // Queued once the node runs and keeps its graph, so the worker neither syncs a node not yet running nor + // holds the LDK queue ahead of a graph reset. + queueWatchOnlyAccountsLoad() + // Post-startup tasks (non-blocking) disconnectIdlePeers().onFailure { Logger.error("Failed to disconnect idle peers", it, context = TAG) diff --git a/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountsWorker.kt b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountsWorker.kt index 75f0bd462d..f248275cc3 100644 --- a/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountsWorker.kt +++ b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountsWorker.kt @@ -2,28 +2,25 @@ 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.ForegroundInfo import androidx.work.NetworkType import androidx.work.OneTimeWorkRequestBuilder -import androidx.work.OutOfQuotaPolicy 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.R -import to.bitkit.androidServices.LightningNodeService.Companion.CHANNEL_ID_NODE import to.bitkit.ext.runSuspendCatching import to.bitkit.services.LightningService import to.bitkit.services.isRejectedPaykitServerAccount -import to.bitkit.ui.ID_NOTIFICATION_WATCH_ONLY_ACCOUNTS -import to.bitkit.ui.notificationBuilder 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 @@ -35,12 +32,14 @@ class WatchOnlyAccountsWork @Inject constructor( ) { companion object { const val WORK_NAME = "watch-only-accounts-load" + private val RETRY_DELAY = 15.seconds } fun schedule() { val request = OneTimeWorkRequestBuilder() .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()) - .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST) + // A transient failure (VSS, Electrum) retries soon after it clears, not after an exponential backoff. + .setBackoffCriteria(BackoffPolicy.LINEAR, RETRY_DELAY.toJavaDuration()) .build() // 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) @@ -65,28 +64,24 @@ class WatchOnlyAccountsWorker @AssistedInject constructor( Logger.info("Skipped loading Paykit Server accounts: node not running", context = TAG) return Result.success() } - val failure = runSuspendCatching { lightningService.reconcileWatchOnlyAccounts(syncAfterReconcile = false) } - .exceptionOrNull() - if (failure != null && !failure.isRejectedPaykitServerAccount()) { - Logger.warn("Failed to load Paykit Server accounts, retrying", failure, context = TAG) - return Result.retry() - } - if (failure != null) { - Logger.warn("Skipped Paykit Server accounts the node rejects", failure, context = TAG) - } else { - Logger.info("Loaded Paykit Server accounts", context = TAG) + // 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) } return Result.success() } - - override suspend fun getForegroundInfo(): ForegroundInfo = ForegroundInfo( - ID_NOTIFICATION_WATCH_ONLY_ACCOUNTS, - applicationContext.notificationBuilder(channelId = CHANNEL_ID_NODE) - .setContentTitle(applicationContext.getString(R.string.app_name)) - .setContentText(applicationContext.getString(R.string.notification__service__body)) - .build(), - ) } diff --git a/app/src/main/java/to/bitkit/services/LightningService.kt b/app/src/main/java/to/bitkit/services/LightningService.kt index 5e7f98d6e2..d097c6d7f6 100644 --- a/app/src/main/java/to/bitkit/services/LightningService.kt +++ b/app/src/main/java/to/bitkit/services/LightningService.kt @@ -15,7 +15,6 @@ import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update -import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout @@ -545,18 +544,29 @@ class LightningService internal constructor( /** * Loads the current wallet's Paykit Server accounts into the running node and unloads the ones it no longer wants. * Each account loads in its own LDK queue hop and lock hold: one takes about 2 s, and sends and Pubky auth - * approvals must not wait behind all of them. + * approvals must not wait behind all of them. Returns false when no node ran or it stopped before the accounts + * loaded. */ - suspend fun reconcileWatchOnlyAccounts(syncAfterReconcile: Boolean = true) { - val node = node ?: return - val configs = watchOnlyAccountLifecycleCoordinator.withLock { unloadUnwantedWatchOnlyAccounts(node) } ?: return + suspend fun reconcileWatchOnlyAccounts(syncAfterReconcile: Boolean = true): Boolean { + val node = node ?: return false + val configs = runSuspendCatching { + watchOnlyAccountLifecycleCoordinator.withLock { unloadUnwantedWatchOnlyAccounts(node) } + }.onFailure { + Logger.error("Failed to unload Paykit Server accounts", it, context = TAG) + }.getOrThrow() ?: return false // One account the node rejects must not keep the others from loading. A transient failure is rethrown ahead of // a rejected xpub so the caller retries it. - val failures = configs.mapNotNull { config -> - runSuspendCatching { loadWatchOnlyAccount(node, config) }.exceptionOrNull()?.also { - Logger.error("Failed to load Paykit Server account '${config.accountIndex}'", it, context = TAG) - } + val failures = mutableListOf() + for (config in configs) { + val isLoaded = runSuspendCatching { loadWatchOnlyAccount(node, config) } + .onFailure { + Logger.error("Failed to load Paykit Server account '${config.accountIndex}'", it, context = TAG) + failures += it + } + .getOrDefault(true) + // The node was stopped or replaced; nothing more loads into it. + if (!isLoaded) return false } val retryable = failures.firstOrNull { !it.isRejectedPaykitServerAccount() } (retryable ?: failures.firstOrNull())?.let { throw it } @@ -566,11 +576,21 @@ class LightningService internal constructor( if (this@LightningService.node === node && node.status().isRunning) node.syncWallets() } } + return true } - /** Whether the current wallet tracks any Paykit Server account, which the node loads after start. */ - suspend fun hasTrackedWatchOnlyAccounts(): Boolean = - enabledOnchainWalletAccountConfigs(watchOnlyAccountStore.load(), currentWalletIndex).isNotEmpty() + /** + * Whether the current wallet tracks any Paykit Server account or has one pending removal, which the node loads or + * unloads after start. Reads under the + * lifecycle lock so an approval that began before the node ran has saved its tracking first. + */ + suspend fun hasTrackedWatchOnlyAccounts(): Boolean = watchOnlyAccountLifecycleCoordinator.withLock { + val walletIndex = currentWalletIndex + val state = watchOnlyAccountStore.loadReconciliationState() + // A restore can leave removals pending that only the worker completes. + state.accountsPendingRemoval.any { it.walletIndex == walletIndex } || + enabledOnchainWalletAccountConfigs(state.accounts, walletIndex).isNotEmpty() + } /** * Unloads the accounts the store no longer wants and completes their pending removal in the same lock hold, so a @@ -607,13 +627,14 @@ class LightningService internal constructor( return desiredConfigs } - private suspend fun loadWatchOnlyAccount(node: Node, config: OnchainWalletAccountConfig) = + /** Returns false when `node` was stopped or replaced before the account loaded. */ + private suspend fun loadWatchOnlyAccount(node: Node, config: OnchainWalletAccountConfig): Boolean = watchOnlyAccountLifecycleCoordinator.withLock { // Tracking may have been turned off while the accounts before this one loaded. val records = watchOnlyAccountStore.loadReconciliationState().accounts - if (config !in enabledOnchainWalletAccountConfigs(records, currentWalletIndex)) return@withLock + if (config !in enabledOnchainWalletAccountConfigs(records, currentWalletIndex)) return@withLock true ServiceQueue.LDK.background(ldkQueue) { - if (this@LightningService.node !== node) return@background + if (this@LightningService.node !== node) return@background false val isTracked = node.listOnchainWalletAccounts().any { it.addressType == config.addressType && it.accountIndex == config.accountIndex } @@ -625,6 +646,7 @@ class LightningService internal constructor( config.accountIndex, WATCH_ONLY_ACCOUNT_HIGHEST_PRE_REVEALED_ADDRESS_INDEX.toUInt(), ) + true } } diff --git a/app/src/main/java/to/bitkit/ui/Notifications.kt b/app/src/main/java/to/bitkit/ui/Notifications.kt index b762cf854b..36a26faf62 100644 --- a/app/src/main/java/to/bitkit/ui/Notifications.kt +++ b/app/src/main/java/to/bitkit/ui/Notifications.kt @@ -27,7 +27,6 @@ import kotlin.random.Random const val ID_NOTIFICATION_SKIPPED = -1 const val ID_NOTIFICATION_NODE = 1 const val ID_NOTIFICATION_WAKE = 2 -const val ID_NOTIFICATION_WATCH_ONLY_ACCOUNTS = 3 const val EXTRA_PAYKIT_SUBSCRIPTION_PAYMENT_DUE = "paykit_subscription_payment_due" const val EXTRA_PAYKIT_PAYER_IDENTITY = "paykit_payer_identity" const val EXTRA_PAYKIT_PAYMENT_REQUEST_ID = "paykit_payment_request_id" diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 069bb5f5d0..c759f8c522 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -2821,7 +2821,7 @@ class BackupRepoTest : BaseUnitTest() { } whenever { lightningService.reconcileWatchOnlyAccounts() }.thenAnswer { assertTrue(accountsWereRestored) - Unit + true } val result = sut.performFullRestoreFromLatestBackup() diff --git a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountsWorkerTest.kt b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountsWorkerTest.kt index 1de3365432..c07750a00f 100644 --- a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountsWorkerTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountsWorkerTest.kt @@ -30,6 +30,7 @@ class WatchOnlyAccountsWorkerTest : BaseUnitTest() { @Test fun `loads the accounts and syncs the wallet`() = test { stubNodeRunning(true) + whenever(lightningService.reconcileWatchOnlyAccounts(syncAfterReconcile = false)).thenReturn(true) whenever(walletRepo.syncNodeAndWallet(any())).thenReturn(Result.success(Unit)) val result = worker().doWork() @@ -49,6 +50,17 @@ class WatchOnlyAccountsWorkerTest : BaseUnitTest() { verifyBlocking(lightningService, never()) { reconcileWatchOnlyAccounts(any()) } } + @Test + fun `skips the sync when the node stopped before the accounts loaded`() = test { + stubNodeRunning(true) + whenever(lightningService.reconcileWatchOnlyAccounts(syncAfterReconcile = false)).thenReturn(false) + + val result = worker().doWork() + + assertEquals(ListenableWorker.Result.success(), result) + verifyBlocking(walletRepo, never()) { syncNodeAndWallet(any()) } + } + @Test fun `retries a transient load failure`() = test { stubNodeRunning(true) diff --git a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt index 9bd8eadfba..280c9d03ef 100644 --- a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt @@ -1229,6 +1229,19 @@ class LightningServiceTest : BaseUnitTest() { verify(node).syncWallets() } + @Test + fun `a pending removal alone queues the account worker`() = test { + val removedAccount = watchOnlyAccount(accountIndex = 1, walletIndex = 0, enabled = true) + whenever(watchOnlyAccountStore.loadReconciliationState()).thenReturn( + WatchOnlyAccountReconciliationState( + accounts = emptyList(), + accountsPendingRemoval = listOf(removedAccount), + ), + ) + + assertTrue(sut.hasTrackedWatchOnlyAccounts()) + } + @Test fun `restore reconciliation unloads replaced account and loads restored account`() = test { val replacedAccount = watchOnlyAccount(accountIndex = 1, walletIndex = 0, enabled = true) diff --git a/journeys/pubky-marketplace/approval-while-node-restarts.xml b/journeys/pubky-marketplace/approval-while-node-restarts.xml index 232a79c3d8..997e1e7a20 100644 --- a/journeys/pubky-marketplace/approval-while-node-restarts.xml +++ b/journeys/pubky-marketplace/approval-while-node-restarts.xml @@ -18,6 +18,6 @@ Release the VSS hold Wait for the wallet to finish syncing, then open the watch-only accounts list in Settings Verify exactly one new account was added, named after the requesting service, with tracking on - Verify the app log shows the node loaded that account index ("Registered derived on-chain wallet account" or "Loaded configured wallet for OnchainWalletAccount" with its account_index) and no "Provided xpub does not match the node's master seed" error + Verify the app log shows the node loaded that account index ("Registered derived on-chain wallet account" with its account_index) and no "Provided xpub does not match the node's master seed" error From 6f2d58d6444163832ad36caa9c121f1acda3faf0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 3 Dec 2026 18:15:13 +0100 Subject: [PATCH 4/4] fix: queue the account load as soon as the node runs The worker is queued right after the node reaches Running, so a later start step that fails or is cancelled no longer leaves the Paykit Server accounts unloaded, and it is also queued when the tracked read fails. Adds tests for the tracked check, the work request and the sync after a rejected account, and corrects the companion claims doc, which still said the accounts load before the node starts. Verified: ./gradlew compileDevDebugKotlin testDevDebugUnitTest (WatchOnlyAccountsWorkerTest, LightningServiceTest, LightningRepoTest, WatchOnlyAccount*, BackupRepoTest) detekt --- .../to/bitkit/repositories/LightningRepo.kt | 13 +++---- .../repositories/WatchOnlyAccountsWorker.kt | 13 +++---- .../bitkit/repositories/LightningRepoTest.kt | 15 ++++++++ .../WatchOnlyAccountsWorkerTest.kt | 14 ++++++++ .../bitkit/services/LightningServiceTest.kt | 34 ++++++++++++++++++- docs/pubky-auth-companion-claims.md | 4 +-- 6 files changed, 78 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 73f97f36a4..83c897a0f2 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -544,6 +544,9 @@ class LightningRepo @Inject constructor( 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 @@ -562,10 +565,6 @@ class LightningRepo @Inject constructor( return@withLock Result.success(Unit) } - // Queued once the node runs and keeps its graph, so the worker neither syncs a node not yet running nor - // holds the LDK queue ahead of a graph reset. - queueWatchOnlyAccountsLoad() - // Post-startup tasks (non-blocking) disconnectIdlePeers().onFailure { Logger.error("Failed to disconnect idle peers", it, context = TAG) @@ -673,9 +672,11 @@ class LightningRepo @Inject constructor( /** Queues the load of the Paykit Server accounts, which the node is built without, when the wallet tracks any. */ private suspend fun queueWatchOnlyAccountsLoad() { - runSuspendCatching { lightningService.hasTrackedWatchOnlyAccounts() } + // 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) } - .onSuccess { if (it) watchOnlyAccountsWork.schedule() } + .getOrDefault(true) + if (hasTracked) watchOnlyAccountsWork.schedule() } private suspend fun releaseUnsavedConfigNode() { diff --git a/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountsWorker.kt b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountsWorker.kt index f248275cc3..57a785cac9 100644 --- a/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountsWorker.kt +++ b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountsWorker.kt @@ -36,14 +36,15 @@ class WatchOnlyAccountsWork @Inject constructor( } fun schedule() { - val request = OneTimeWorkRequestBuilder() - .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() // 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) + WorkManager.getInstance(context).enqueueUniqueWork(WORK_NAME, ExistingWorkPolicy.REPLACE, request()) } + + internal fun request() = OneTimeWorkRequestBuilder() + .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. */ diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index f7ee66eca2..36ba9fb53b 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -818,6 +818,21 @@ class LightningRepoTest : BaseUnitTest() { verify(watchOnlyAccountsWork, never()).schedule() } + @Test + fun `start queues the paykit server account load when the tracked read fails`() = test { + sut.setInitNodeLifecycleState() + whenever(lightningService.hasTrackedWatchOnlyAccounts()).doSuspendableAnswer { + throw IOException("datastore read failed") + } + whenever(lightningService.node).thenReturn(mock()) + whenever(coreService.blocktank).thenReturn(mock()) + + val result = sut.start() + + assertTrue(result.isSuccess) + verify(watchOnlyAccountsWork).schedule() + } + @Test fun `start queues the paykit server account load when the node is already running`() = test { sut.setInitNodeLifecycleState() diff --git a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountsWorkerTest.kt b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountsWorkerTest.kt index c07750a00f..baf57a809a 100644 --- a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountsWorkerTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountsWorkerTest.kt @@ -2,7 +2,9 @@ package to.bitkit.repositories import android.content.Context import androidx.test.core.app.ApplicationProvider +import androidx.work.BackoffPolicy import androidx.work.ListenableWorker +import androidx.work.NetworkType import androidx.work.WorkerParameters import org.junit.Test import org.junit.runner.RunWith @@ -19,6 +21,7 @@ import org.robolectric.annotation.Config import to.bitkit.services.LightningService import to.bitkit.test.BaseUnitTest import kotlin.test.assertEquals +import kotlin.test.assertFalse @Config(sdk = [34]) @RunWith(RobolectricTestRunner::class) @@ -83,6 +86,17 @@ class WatchOnlyAccountsWorkerTest : BaseUnitTest() { val result = worker().doWork() assertEquals(ListenableWorker.Result.success(), result) + verifyBlocking(walletRepo) { syncNodeAndWallet(any()) } + } + + @Test + fun `the request needs a network and retries on a linear backoff`() { + val spec = WatchOnlyAccountsWork(context).request().workSpec + + assertEquals(NetworkType.CONNECTED, spec.constraints.requiredNetworkType) + assertEquals(BackoffPolicy.LINEAR, spec.backoffPolicy) + assertEquals(15_000L, spec.backoffDelayDuration) + assertFalse(spec.expedited) } private fun stubNodeRunning(isRunning: Boolean) { diff --git a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt index 280c9d03ef..751f0f3c52 100644 --- a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt @@ -1229,6 +1229,38 @@ class LightningServiceTest : BaseUnitTest() { verify(node).syncWallets() } + @Test + fun `only an enabled account of the current wallet queues the account worker`() = test { + val otherWallet = watchOnlyAccount(accountIndex = 1, walletIndex = 1, enabled = true) + val disabled = watchOnlyAccount(accountIndex = 2, walletIndex = 0, enabled = false) + val enabled = watchOnlyAccount(accountIndex = 3, walletIndex = 0, enabled = true) + whenever(watchOnlyAccountStore.loadReconciliationState()).thenReturn( + WatchOnlyAccountReconciliationState(listOf(otherWallet, disabled), emptyList()), + WatchOnlyAccountReconciliationState(listOf(otherWallet, disabled, enabled), emptyList()), + ) + + assertFalse(sut.hasTrackedWatchOnlyAccounts()) + assertTrue(sut.hasTrackedWatchOnlyAccounts()) + } + + @Test + fun `the tracked account check waits for an approval holding the account lock`() = test { + whenever(watchOnlyAccountStore.loadReconciliationState()).thenReturn( + WatchOnlyAccountReconciliationState(emptyList(), emptyList()), + ) + val release = CompletableDeferred() + val holder = launch { watchOnlyAccountLifecycleCoordinator.withLock { release.await() } } + testScheduler.runCurrent() + + val check = async { sut.hasTrackedWatchOnlyAccounts() } + testScheduler.runCurrent() + assertFalse(check.isCompleted) + + release.complete(Unit) + holder.join() + assertFalse(check.await()) + } + @Test fun `a pending removal alone queues the account worker`() = test { val removedAccount = watchOnlyAccount(accountIndex = 1, walletIndex = 0, enabled = true) @@ -1363,7 +1395,7 @@ class LightningServiceTest : BaseUnitTest() { WatchOnlyAccountReconciliationState(listOf(account), emptyList()) } - sut.reconcileWatchOnlyAccounts(syncAfterReconcile = false) + assertFalse(sut.reconcileWatchOnlyAccounts(syncAfterReconcile = false)) verify(node, never()).listOnchainWalletAccounts() verify(node, never()).addOnchainWalletAccount(any(), any(), any()) diff --git a/docs/pubky-auth-companion-claims.md b/docs/pubky-auth-companion-claims.md index a9003836f9..1ca595909c 100644 --- a/docs/pubky-auth-companion-claims.md +++ b/docs/pubky-auth-companion-claims.md @@ -50,9 +50,9 @@ The server verifies the signature with the creator's Pubky Ed25519 public key fr - Account registration and address revelation finish before authorization. LDK's periodic sync fetches transaction history; a full wallet sync is not a prerequisite for delivering the authorization. - If Paykit reports that companion delivery succeeded but normal AuthToken delivery failed, Bitkit leaves the account authorizing and tracked. The same conservative state is retained if local activation persistence fails after Paykit returns success. Retrying reruns the combined Paykit approval with the same account and xpub payload; retry failures keep the account tracked so Bitkit does not lose visibility into addresses the server may already have derived. - Disabling tracking unloads the account from LDK Node at runtime. It does not delete persisted wallet state, the xpub, or the server session. -- Enabled active or authorizing accounts are configured before LDK Node starts. Electrum full scans use a batch size of `100` and stop gap of `1000`. +- LDK Node starts without the accounts; after each start a WorkManager worker loads enabled active or authorizing accounts into the running node, and keeps loading when the app closes. Electrum full scans use a batch size of `100` and stop gap of `1000`. - Bitkit pre-reveals external receive indexes `0...999` for each tracked account. LDK then maintains a rolling stop-gap window: the first address with transaction history must be at or below index `999`, and after activity at index `n`, the next active index must be at or below `n + 1000` so there are never `1000` consecutive inactive addresses. -- On startup and before app-driven sync, Bitkit reconciles persisted account state with LDK and restores the pre-revealed range. Accounts removed by a backup remain scheduled for unload until reconciliation succeeds, allowing transient failures to retry safely. +- After each node start, the worker reconciles persisted account state with LDK and restores the pre-revealed range. Accounts removed by a backup remain scheduled for unload until reconciliation succeeds, allowing transient failures to retry safely. - Account metadata and monotonic allocation state are included in the existing encrypted wallet backup and use the same JSON field names on iOS and Android. ## Shared fixtures and consent