Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions app/src/main/java/to/bitkit/repositories/LightningRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<Boolean> = runSuspendCatching {
lightningService.listOnchainWalletAccounts().size > 1
}

suspend fun pruneEmptyAddressTypesAfterRestore(): Result<Unit> = withContext(bgDispatcher) {
if (isChangingAddressType.get()) return@withContext Result.success(Unit)

Expand Down
5 changes: 5 additions & 0 deletions app/src/main/java/to/bitkit/services/LightningService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -509,6 +512,7 @@ class LightningService internal constructor(
onchainWalletSyncIntervalSecs = Env.walletSyncIntervalSecs,
lightningWalletSyncIntervalSecs = Env.walletSyncIntervalSecs,
feeRateCacheUpdateIntervalSecs = Env.walletSyncIntervalSecs,
additionalWalletSyncIntervalSecs = ADDITIONAL_WALLET_SYNC_INTERVAL_SECS,
),
),
)
Expand All @@ -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,
Expand Down
43 changes: 40 additions & 3 deletions app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<SyncType, UInt>()
private var addressValidationJob: Job? = null

/**
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Comment thread
ovitrif marked this conversation as resolved.
Resolved
pendingPrune -> {
pendingPrune && allWalletsSyncedHeight != null -> {
settingsStore.update { it.copy(pendingRestoreAddressTypePrune = false) }
delay(POST_RESTORE_PRUNE_DELAY_MS)
lightningRepo.pruneEmptyAddressTypesAfterRestore()
Expand All @@ -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 {
Expand Down
17 changes: 17 additions & 0 deletions app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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()
Expand Down
103 changes: 103 additions & 0 deletions app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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<LightningState>
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)
Expand Down
1 change: 1 addition & 0 deletions changelog.d/next/2255.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Paykit Server accounts and other extra wallets sync on their own schedule, so they no longer slow down wallet sync.
2 changes: 1 addition & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ ktor-client-logging = { module = "io.ktor:ktor-client-logging", version.ref = "k
ktor-client-mock = { module = "io.ktor:ktor-client-mock", version.ref = "ktor" }
ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" }
ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }
ldk-node-android = { module = "com.synonym:ldk-node-android", version = "0.7.0-rc.85" }
ldk-node-android = { module = "com.synonym:ldk-node-android", version = "0.7.0-rc.89" }
lifecycle-process = { group = "androidx.lifecycle", name = "lifecycle-process", version.ref = "lifecycle" }
lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" }
lifecycle-runtime-ktx = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "lifecycle" }
Expand Down
11 changes: 11 additions & 0 deletions gradle/verification-metadata.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4461,6 +4461,17 @@
<sha256 value="608d5ee49ddc64bb24b2c97bf1340f69726c4e28345ec825f9e74946eac0eba2" origin="Generated by Gradle"/>
</artifact>
</component>
<component group="com.synonym" name="ldk-node-android" version="0.7.0-rc.89">
<artifact name="ldk-node-android-0.7.0-rc.89-native-debug-symbols.zip">
<sha256 value="c5c379a9303d7ea296a7b853898a240528d5464d0686c2ed828dfa9031a65866" origin="Generated by Gradle"/>
</artifact>
<artifact name="ldk-node-android-0.7.0-rc.89.aar">
<sha256 value="186e5a65431a685c704bc44819ebfb9555cc61f93e1d55d093cd727de66ace43" origin="Generated by Gradle"/>
</artifact>
<artifact name="ldk-node-android-0.7.0-rc.89.module">
<sha256 value="ee510d90209f6d113783e00505928a9f8d57d47ea93d34e67f7bee019e04e5f6" origin="Generated by Gradle"/>
</artifact>
</component>
<component group="com.synonym" name="paykit-android" version="0.1.1-rc8">
<artifact name="paykit-android-0.1.1-rc8-native-debug-symbols.zip">
<sha256 value="a876e5ca61b8c2bac6166460906e561090f5f1f39995d751fbe9c8cc99b18a1e" origin="Generated by Gradle"/>
Expand Down
3 changes: 2 additions & 1 deletion journeys/backup-restore/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<index>`, `RestoreButton`, `GetStartedButton`.
- Restore: `Continue`, `SkipIntro`, `RestoreWallet`, `MultipleDevices-button`, `Word-<index>`,
`RestoreButton`, `GetStartedButton`.
- Receive: `Receive`, `ShowDetails`, `ReceiveCopyQR`.
- Activity: `ActivityShort-<index>`, `ActivityTag`, `ActivityTags`, `AddTagInput`, `AddTagSave`.
- Transfer: `ActivitySavings`, `TransferToSpending`, `TransferIntro-button`, `FundTransfer`,
Expand Down
Loading