diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index aa4408f4f9..45615af198 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1407,6 +1407,11 @@ class LightningRepo @Inject constructor( fun isChangingAddressType(): Boolean = isChangingAddressType.get() + /** Whether the node tracks wallets besides the primary one, which sync in their own pass. */ + suspend fun hasAdditionalWallets(): Result = runSuspendCatching { + lightningService.listOnchainWalletAccounts().size > 1 + } + suspend fun pruneEmptyAddressTypesAfterRestore(): Result = withContext(bgDispatcher) { if (isChangingAddressType.get()) return@withContext Result.success(Unit) diff --git a/app/src/main/java/to/bitkit/services/LightningService.kt b/app/src/main/java/to/bitkit/services/LightningService.kt index f83c2fd50e..4df73a7d7a 100644 --- a/app/src/main/java/to/bitkit/services/LightningService.kt +++ b/app/src/main/java/to/bitkit/services/LightningService.kt @@ -259,6 +259,9 @@ class LightningService internal constructor( private const val RELEASE_AMOUNT_SATS = 1_000uL private const val NODE_ID_PREVIEW_LEN = 20 + /** Paykit Server accounts and other extra wallets sync on their own, less often than the wallet. */ + private const val ADDITIONAL_WALLET_SYNC_INTERVAL_SECS = 60uL + /** LDK's defaults for route parameters, kept when only the routing fee is capped. */ private const val DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA = 1008u private const val DEFAULT_MAX_PATH_COUNT: UByte = 10u @@ -509,6 +512,7 @@ class LightningService internal constructor( onchainWalletSyncIntervalSecs = Env.walletSyncIntervalSecs, lightningWalletSyncIntervalSecs = Env.walletSyncIntervalSecs, feeRateCacheUpdateIntervalSecs = Env.walletSyncIntervalSecs, + additionalWalletSyncIntervalSecs = ADDITIONAL_WALLET_SYNC_INTERVAL_SECS, ), ), ) @@ -524,6 +528,7 @@ class LightningService internal constructor( onchainWalletSyncIntervalSecs = Env.walletSyncIntervalSecs, lightningWalletSyncIntervalSecs = Env.walletSyncIntervalSecs, feeRateCacheUpdateIntervalSecs = Env.walletSyncIntervalSecs, + additionalWalletSyncIntervalSecs = ADDITIONAL_WALLET_SYNC_INTERVAL_SECS, ), connectionTimeoutSecs = Env.walletSyncTimeoutSecs, additionalWalletFullScanBatchSize = 100u, diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index bb6370fd50..ecee86f93a 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -723,6 +723,9 @@ class AppViewModel @Inject constructor( } private var isCompletingMigration = false private var isCompletingRestoreHold = false + + /** The height each on-chain sync pass reported since the node started: the extra wallets sync apart. */ + private val onchainSyncedSinceStart = mutableMapOf() private var addressValidationJob: Job? = null /** @@ -826,6 +829,12 @@ class AppViewModel @Inject constructor( .stateIn(viewModelScope, SharingStarted.Eagerly, false) init { + viewModelScope.launch { + // Cleared again on Starting: a sync from a stopping node can land after the stop cleared it. + lightningRepo.lightningState.map { it.nodeLifecycleState }.distinctUntilChanged().collect { + if (!it.isRunning()) onchainSyncedSinceStart.clear() + } + } viewModelScope.launch { usdtPreferences.enabled.distinctUntilChanged().collect { updateCanSwitchWallet() @@ -2897,17 +2906,27 @@ class AppViewModel @Inject constructor( val onActivitiesSynced: suspend () -> Unit = { viewModelScope.launch { refreshPublicPaykitAddressAfterActivitySync(canPublish) } } - if (event.syncType == SyncType.ONCHAIN_WALLET) completePendingRestoreActivitySeen(event.syncedBlockHeight) + // Recorded before suspending, so a node restart that follows clears it. + recordOnchainSync(event) + val settings = settingsStore.data.first() + val isNeeded = settings.pendingRestoreAddressTypePrune || settings.pendingRestoreActivitySeen || + migrationService.isShowingMigrationLoading.value || migrationService.isRestoringFromRNRemoteBackup.value || + migrationService.needsPostMigrationSync() + val allWalletsSyncedHeight = if (isNeeded && isOnchainSync(event)) allOnchainWalletsSyncedHeight() else null + allWalletsSyncedHeight?.let { completePendingRestoreActivitySeen(it) } + // Read after the suspensions above, which another sync's handler may have spent finishing this work. + val pendingPrune = settingsStore.data.first().pendingRestoreAddressTypePrune val isShowingLoading = migrationService.isShowingMigrationLoading.value val isRestoringRemote = migrationService.isRestoringFromRNRemoteBackup.value val needsPostMigrationSync = migrationService.needsPostMigrationSync() - val pendingPrune = settingsStore.data.first().pendingRestoreAddressTypePrune + val isMigrating = isShowingLoading || needsPostMigrationSync || isRestoringRemote when { + isMigrating && allWalletsSyncedHeight == null -> Unit (isShowingLoading || needsPostMigrationSync) && !isCompletingMigration -> completeMigration() isRestoringRemote && !isCompletingMigration -> completeRNRemoteBackupRestore() - pendingPrune -> { + pendingPrune && allWalletsSyncedHeight != null -> { settingsStore.update { it.copy(pendingRestoreAddressTypePrune = false) } delay(POST_RESTORE_PRUNE_DELAY_MS) lightningRepo.pruneEmptyAddressTypesAfterRestore() @@ -2931,6 +2950,24 @@ class AppViewModel @Inject constructor( } } + private fun isOnchainSync(event: Event.SyncCompleted) = + event.syncType == SyncType.ONCHAIN_WALLET || event.syncType == SyncType.ADDITIONAL_ONCHAIN_WALLETS + + private fun recordOnchainSync(event: Event.SyncCompleted) { + if (isOnchainSync(event)) onchainSyncedSinceStart[event.syncType] = event.syncedBlockHeight + } + + private suspend fun allOnchainWalletsSyncedHeight(): UInt? { + if (onchainSyncedSinceStart[SyncType.ONCHAIN_WALLET] == null) return null + // Unknown wallets wait for the next sync rather than count as none. + val hasAdditionalWallets = lightningRepo.hasAdditionalWallets().getOrNull() ?: return null + // Read after the suspension: a node restart meanwhile clears the heights. + val primary = onchainSyncedSinceStart[SyncType.ONCHAIN_WALLET] ?: return null + if (!hasAdditionalWallets) return primary + val additional = onchainSyncedSinceStart[SyncType.ADDITIONAL_ONCHAIN_WALLETS] ?: return null + return minOf(primary, additional) + } + private suspend fun retryPendingMigrationData() { isCompletingMigration = true try { diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index a0aa9ec43e..2625e2e316 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -53,6 +53,7 @@ import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.Node import org.lightningdevkit.ldknode.NodeException import org.lightningdevkit.ldknode.NodeStatus +import org.lightningdevkit.ldknode.OnchainWalletAccount import org.lightningdevkit.ldknode.PaymentDetails import org.lightningdevkit.ldknode.PaymentDirection import org.lightningdevkit.ldknode.PaymentFailureReason @@ -134,6 +135,7 @@ import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant import breez_sdk_spark.PaymentStatus as SparkPaymentStatus +import org.lightningdevkit.ldknode.AddressType as LdkAddressType @OptIn(kotlin.time.ExperimentalTime::class, ExperimentalCoroutinesApi::class) class LightningRepoTest : BaseUnitTest() { @@ -203,6 +205,21 @@ class LightningRepoTest : BaseUnitTest() { ) } + @Test + fun `hasAdditionalWallets counts wallets besides the primary and reports a failed read`() = test { + val primary = OnchainWalletAccount(LdkAddressType.NATIVE_SEGWIT, 0u) + val derived = OnchainWalletAccount(LdkAddressType.NATIVE_SEGWIT, 1u) + + whenever(lightningService.listOnchainWalletAccounts()).thenReturn(listOf(primary)) + assertEquals(false, sut.hasAdditionalWallets().getOrNull()) + + whenever(lightningService.listOnchainWalletAccounts()).thenReturn(listOf(primary, derived)) + assertEquals(true, sut.hasAdditionalWallets().getOrNull()) + + whenever(lightningService.listOnchainWalletAccounts()).thenAnswer { throw ServiceError.NodeNotSetup() } + assertTrue(sut.hasAdditionalWallets().isFailure) + } + @Test fun `start succeeds and connects no moved peers on regtest when Blocktank is unreachable`() = test { sut.setInitNodeLifecycleState() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 672cf8b27a..67b7730c8f 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -828,6 +828,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(migrationService.isShowingMigrationLoading).thenReturn(MutableStateFlow(false)) whenever { migrationService.needsPostMigrationSync() }.thenReturn(false) whenever { migrationService.isMigrationChecked() }.thenReturn(true) + whenever(migrationService.isRestoringFromRNRemoteBackup).thenReturn(MutableStateFlow(false)) + whenever { lightningRepo.hasAdditionalWallets() }.thenReturn(Result.success(false)) whenever { widgetsRepo.refreshEnabledWidgets() }.thenReturn(Unit) whenever(pubkyRepo.sessionRestorationFailed).thenReturn(MutableStateFlow(false)) whenever(pubkyRepo.sessionRestorationNeedsUpdate).thenReturn(MutableStateFlow(false)) @@ -10328,6 +10330,107 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(100L, settingsData.value.restoreSyncedBlockHeight) } + @Test + fun `restore marks activities seen only once the extra wallets synced too`() = test { + settingsData.value = SettingsData(pendingRestoreActivitySeenSince = RESTORE_STARTED_AT) + whenever { lightningRepo.hasAdditionalWallets() }.thenReturn(Result.success(true)) + whenever { + activityRepo.markAllUnseenActivitiesAsSeen(eq(RESTORE_STARTED_AT.toULong())) + }.thenReturn(Result.success(Unit)) + + emitNodeEvent(Event.SyncCompleted(syncType = SyncType.ONCHAIN_WALLET, syncedBlockHeight = 100u)) + advanceUntilIdle() + verify(activityRepo, never()).markAllUnseenActivitiesAsSeen(any()) + assertTrue(settingsData.value.pendingRestoreActivitySeen) + + emitNodeEvent(Event.SyncCompleted(syncType = SyncType.ADDITIONAL_ONCHAIN_WALLETS, syncedBlockHeight = 98u)) + advanceUntilIdle() + verify(activityRepo).markAllUnseenActivitiesAsSeen(eq(RESTORE_STARTED_AT.toULong())) + assertFalse(settingsData.value.pendingRestoreActivitySeen) + assertEquals(98L, settingsData.value.restoreSyncedBlockHeight) + } + + @Test + fun `migration completes only once the extra wallets synced too`() = test { + whenever(migrationService.isRestoringFromRNRemoteBackup).thenReturn(MutableStateFlow(false)) + whenever(migrationService.needsPostMigrationSync()).thenReturn(true) + whenever { lightningRepo.hasAdditionalWallets() }.thenReturn(Result.success(true)) + whenever(lightningRepo.getPayments()).thenReturn(Result.success(emptyList())) + whenever(activityRepo.markAllUnseenActivitiesAsSeen()).thenReturn(Result.success(Unit)) + + emitNodeEvent(Event.SyncCompleted(syncType = SyncType.ONCHAIN_WALLET, syncedBlockHeight = 100u)) + emitNodeEvent(Event.SyncCompleted(syncType = SyncType.LIGHTNING_WALLET, syncedBlockHeight = 100u)) + advanceUntilIdle() + verify(lightningRepo, never()).getPayments() + + emitNodeEvent(Event.SyncCompleted(syncType = SyncType.ADDITIONAL_ONCHAIN_WALLETS, syncedBlockHeight = 98u)) + advanceUntilIdle() + verify(lightningRepo, atLeastOnce()).getPayments() + } + + @Test + fun `restore waits for the wallet sync when the extra wallets sync first`() = test { + settingsData.value = SettingsData(pendingRestoreActivitySeenSince = RESTORE_STARTED_AT) + whenever { lightningRepo.hasAdditionalWallets() }.thenReturn(Result.success(true)) + whenever { + activityRepo.markAllUnseenActivitiesAsSeen(eq(RESTORE_STARTED_AT.toULong())) + }.thenReturn(Result.success(Unit)) + + emitNodeEvent(Event.SyncCompleted(syncType = SyncType.ADDITIONAL_ONCHAIN_WALLETS, syncedBlockHeight = 98u)) + advanceUntilIdle() + verify(activityRepo, never()).markAllUnseenActivitiesAsSeen(any()) + + emitNodeEvent(Event.SyncCompleted(syncType = SyncType.ONCHAIN_WALLET, syncedBlockHeight = 100u)) + advanceUntilIdle() + verify(activityRepo).markAllUnseenActivitiesAsSeen(eq(RESTORE_STARTED_AT.toULong())) + assertEquals(98L, settingsData.value.restoreSyncedBlockHeight) + } + + @Test + fun `restore does not count syncs from before a node restart or when the wallets are unknown`() = test { + settingsData.value = SettingsData(pendingRestoreActivitySeenSince = RESTORE_STARTED_AT) + val nodeState = lightningRepo.lightningState as MutableStateFlow + nodeState.value = LightningState(nodeLifecycleState = NodeLifecycleState.Running) + whenever { lightningRepo.hasAdditionalWallets() }.thenReturn(Result.success(true)) + whenever { + activityRepo.markAllUnseenActivitiesAsSeen(eq(RESTORE_STARTED_AT.toULong())) + }.thenReturn(Result.success(Unit)) + advanceUntilIdle() + + emitNodeEvent(Event.SyncCompleted(syncType = SyncType.ONCHAIN_WALLET, syncedBlockHeight = 100u)) + advanceUntilIdle() + nodeState.value = LightningState(nodeLifecycleState = NodeLifecycleState.Stopped) + advanceUntilIdle() + nodeState.value = LightningState(nodeLifecycleState = NodeLifecycleState.Running) + advanceUntilIdle() + emitNodeEvent(Event.SyncCompleted(syncType = SyncType.ADDITIONAL_ONCHAIN_WALLETS, syncedBlockHeight = 100u)) + advanceUntilIdle() + verify(activityRepo, never()).markAllUnseenActivitiesAsSeen(any()) + + whenever { lightningRepo.hasAdditionalWallets() }.thenReturn(Result.failure(AppError("node not set up"))) + emitNodeEvent(Event.SyncCompleted(syncType = SyncType.ONCHAIN_WALLET, syncedBlockHeight = 101u)) + advanceUntilIdle() + verify(activityRepo, never()).markAllUnseenActivitiesAsSeen(any()) + assertTrue(settingsData.value.pendingRestoreActivitySeen) + } + + @Test + fun `restore prunes empty address types only once the extra wallets synced too`() = test { + settingsData.value = SettingsData(pendingRestoreAddressTypePrune = true) + whenever { lightningRepo.hasAdditionalWallets() }.thenReturn(Result.success(true)) + whenever { lightningRepo.pruneEmptyAddressTypesAfterRestore() }.thenReturn(Result.success(Unit)) + + emitNodeEvent(Event.SyncCompleted(syncType = SyncType.ONCHAIN_WALLET, syncedBlockHeight = 100u)) + advanceUntilIdle() + verify(lightningRepo, never()).pruneEmptyAddressTypesAfterRestore() + assertTrue(settingsData.value.pendingRestoreAddressTypePrune) + + emitNodeEvent(Event.SyncCompleted(syncType = SyncType.ADDITIONAL_ONCHAIN_WALLETS, syncedBlockHeight = 100u)) + advanceUntilIdle() + verify(lightningRepo).pruneEmptyAddressTypesAfterRestore() + assertFalse(settingsData.value.pendingRestoreAddressTypePrune) + } + @Test fun `first onchain sync after restore keeps the pending flag when marking activities seen fails`() = test { settingsData.value = SettingsData(pendingRestoreActivitySeenSince = RESTORE_STARTED_AT) diff --git a/changelog.d/next/2255.changed.md b/changelog.d/next/2255.changed.md new file mode 100644 index 0000000000..74c8f56b72 --- /dev/null +++ b/changelog.d/next/2255.changed.md @@ -0,0 +1 @@ +Paykit Server accounts and other extra wallets sync on their own schedule, so they no longer slow down wallet sync. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 7b6cb2f889..56a8875671 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -69,7 +69,7 @@ ktor-client-logging = { module = "io.ktor:ktor-client-logging", version.ref = "k ktor-client-mock = { module = "io.ktor:ktor-client-mock", version.ref = "ktor" } ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" } ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" } -ldk-node-android = { module = "com.synonym:ldk-node-android", version = "0.7.0-rc.85" } +ldk-node-android = { module = "com.synonym:ldk-node-android", version = "0.7.0-rc.88" } lifecycle-process = { group = "androidx.lifecycle", name = "lifecycle-process", version.ref = "lifecycle" } lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" } lifecycle-runtime-ktx = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "lifecycle" } diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index 8f18e6af9e..196727ec61 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -4461,6 +4461,17 @@ + + + + + + + + + + + diff --git a/journeys/backup-restore/README.md b/journeys/backup-restore/README.md index 4c9d66a1db..5ee4f7e457 100644 --- a/journeys/backup-restore/README.md +++ b/journeys/backup-restore/README.md @@ -49,7 +49,8 @@ recovery phrase, and what the app is allowed to upload while that restore is sti - Backup flow: `BackupIntroViewContinue`, `TapToReveal`, `SeedContainer`; data backups list `BackupScrollView`. - Reset: `restore_reset_button`, `restore_reset_dialog`. -- Restore: `RestoreWallet`, `Word-`, `RestoreButton`, `GetStartedButton`. +- Restore: `Continue`, `SkipIntro`, `RestoreWallet`, `MultipleDevices-button`, `Word-`, + `RestoreButton`, `GetStartedButton`. - Receive: `Receive`, `ShowDetails`, `ReceiveCopyQR`. - Activity: `ActivityShort-`, `ActivityTag`, `ActivityTags`, `AddTagInput`, `AddTagSave`. - Transfer: `ActivitySavings`, `TransferToSpending`, `TransferIntro-button`, `FundTransfer`, diff --git a/journeys/backup-restore/restore-waits-for-extra-wallets.xml b/journeys/backup-restore/restore-waits-for-extra-wallets.xml new file mode 100644 index 0000000000..67e29136e5 --- /dev/null +++ b/journeys/backup-restore/restore-waits-for-extra-wallets.xml @@ -0,0 +1,32 @@ + + + ldk-node syncs the wallet's own address type and its extra wallets (other monitored address types, + Paykit Server accounts) in separate background passes: the wallet's every 10 s, the extras' every + 60 s. A restore must not treat the wallet's pass alone as "every wallet synced": the restore hold + that marks replayed activities seen waits until both passes have completed since the node started. + + Funds on a monitored Taproot address make the extras' pass matter: their receive is only found by + that pass, so it must not pop a "Received" sheet after the restore, and the balance must include it. + + Precondition: a dev (regtest) build, onboarded with a NEW wallet, and the staging LSP reachable + through the `lsp` helper at the repo root for funding and mining (see ../README.md). The journey + wipes the wallet half way through, so do not run it against a wallet whose funds matter. + + + Launch the Bitkit app and go to the wallet home screen + Open Settings, then the "Advanced" tab (testTag "Tab-advanced"), then "Address Type" (testTag "AddressTypePreference"), and verify the monitoring section is shown; a debug build has dev mode on by default, otherwise turn it on by opening the menu, Support (testTag "DrawerSupport") and tapping the version row five times + Select Taproot as the primary address type (testTag "p2tr") and wait for the change to apply + Return to Home, tap the Receive button (testTag "Receive"), tap "Show Details" (testTag "ShowDetails") and read the on-chain savings address (testTag "ReceiveOnchainAddress"); verify it starts with `bcrt1p` + Run `./lsp POST /regtest/chain/deposit '{"address":"<taproot address>","amountSat":300000}'` then `./lsp POST /regtest/chain/mine '{"count":3}'`, and wait for the 300 000 sat receive to appear on Home + Open Settings, then the "Advanced" tab, then "Address Type", select Native Segwit as the primary address type (testTag "p2wpkh") and verify Taproot stays monitored (testTag "MonitorToggle-p2tr" on) + Open Settings, then the "Security" tab (testTag "Tab-security"), then tap "Back Up Your Money" (testTag "BackupWallet"), continue past the intro (testTag "BackupIntroViewContinue"), tap to reveal the phrase (testTag "TapToReveal") and record the phrase from the word grid (testTag "SeedContainer") + Return to Home and wait two minutes, then read the app log and verify `LDK event fired` lines carry `SyncCompleted` for both `ONCHAIN_WALLET` and `ADDITIONAL_ONCHAIN_WALLETS`, each repeating on its own schedule + Open Settings, then the "Security" tab, then "Data Backups" (testTag "BackupSettings"), and wait on the list (testTag "BackupScrollView") until the "Transaction Log" row reports a recent backup — that row carries no testTag, so read its text + Open Settings, then the "Security" tab, then "Reset And Restore" (testTag "ResetAndRestore"), tap "Reset Wallet" (testTag "restore_reset_button") and confirm in the dialog (testTag "restore_reset_dialog") + Accept the terms (testTag "Continue"), skip the intro (testTag "SkipIntro"), tap "Restore" (testTag "RestoreWallet"), confirm the multiple-devices warning (testTag "MultipleDevices-button"), enter the recorded words into the word inputs (testTag "Word-0" onwards) and tap Restore (testTag "RestoreButton") + Wait for the restore to finish and tap "Get Started" (testTag "GetStartedButton") + Stay on Home for two minutes and verify no "Received" sheet opens for the 300 000 sat receive + Verify Home lists the 300 000 sat receive and the savings balance includes it + Read the app log after the restore and verify `Marking activities replayed by the first sync after restore as seen` comes after a `SyncCompleted` for `ADDITIONAL_ONCHAIN_WALLETS`, not straight after the first `ONCHAIN_WALLET` one + +