diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt index cd60e65b..0fba90df 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt @@ -149,6 +149,7 @@ import com.machankura.bennu.compose.ui.composable.MemberWalletScreen import com.machankura.bennu.compose.ui.composable.NewMemberWalletScreen import com.machankura.bennu.compose.database.repository.DatabaseMemberWalletRepository import com.machankura.bennu.compose.wallet.GroupOnchainWallets +import com.machankura.bennu.compose.wallet.IdentityElectrum import com.machankura.bennu.compose.wallet.GroupTransactionWatcher import fr.acinq.phoenix.managers.NodeParamsManager import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute @@ -237,14 +238,25 @@ fun BennuNavHost( ) } - // The group wallets this identity is watching, on its own node's Electrum - // client -- null for an nsec or npub profile, which has no node and so no - // chain to watch. Remade with the node and stopped with it, because a switch - // of profile is a restart and a wallet left subscribing on the last one's - // connection is a wallet nobody can see. + // The Electrum client this identity watches the chain on: its node's, or -- + // for an nsec or npub profile, which has no node -- one of its own. Remade + // with the identity, the last one stopped first, because a switch of profile + // is a restart and a wallet left subscribing on the last one's connection is + // a wallet nobody can see. See docs/standalone-electrum.md. val activeIdentityForWallets by sovereignWalletViewModel.activeIdentity.collectAsState() - val groupOnchainWallets = remember(activeIdentityForWallets?.business) { - activeIdentityForWallets?.business?.let { GroupOnchainWallets(it.electrumClient, applicationIOScope) } + val identityElectrum = remember { + IdentityElectrum(IdentityElectrum.standalone(phoenixGlobal.networkMonitor, phoenixGlobal.loggerFactory)) + } + DisposableEffect(identityElectrum) { + onDispose { identityElectrum.stop() } + } + val electrum = remember(activeIdentityForWallets?.id, activeIdentityForWallets?.business) { + identityElectrum.clientFor(activeIdentityForWallets) + } + + // The group wallets this identity is watching. Remade with the client. + val groupOnchainWallets = remember(electrum) { + electrum?.let { GroupOnchainWallets(it, applicationIOScope) } } DisposableEffect(groupOnchainWallets) { onDispose { groupOnchainWallets?.let { wallets -> applicationIOScope.launch { wallets.stop() } } } @@ -252,10 +264,10 @@ fun BennuNavHost( // Sends the group's signed spends to the network from this device too, and // follows them to a confirmation -- whether or not anybody opens the wallet. - // Same lifetime as the wallets: the identity's node, and nothing longer. - val groupTransactionWatcher = remember(activeIdentityForWallets?.business) { - activeIdentityForWallets?.business?.let { - GroupTransactionWatcher(auxDatabaseManager.auxDatabase, it.electrumClient, applicationIOScope).also { watcher -> watcher.start() } + // Same lifetime as the wallets: the identity's client, and nothing longer. + val groupTransactionWatcher = remember(electrum) { + electrum?.let { + GroupTransactionWatcher(auxDatabaseManager.auxDatabase, it, applicationIOScope).also { watcher -> watcher.start() } } } DisposableEffect(groupTransactionWatcher) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/IdentityElectrum.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/IdentityElectrum.kt new file mode 100644 index 00000000..aebe55d5 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/IdentityElectrum.kt @@ -0,0 +1,78 @@ +package com.machankura.bennu.compose.wallet + +import co.touchlab.kermit.Logger +import com.machankura.bennu.compose.identity.Identity +import fr.acinq.lightning.blockchain.electrum.IElectrumClient +import fr.acinq.lightning.logging.LoggerFactory +import fr.acinq.phoenix.managers.NodeParamsManager +import fr.acinq.phoenix.managers.global.NetworkMonitor +import fr.acinq.phoenix.data.WalletId + +/** + * The Electrum client the active identity watches the chain on. + * + * A profile with a node watches on the node's client; one with no node -- an nsec + * or an npub -- gets a [StandaloneElectrum] of its own. Never both: a second + * connection from a profile that has one would tell a second server the same + * addresses, and give the wallets a chain that can disagree with the node's (D1 of + * `docs/standalone-electrum.md`). The test is the node client, not the kind, as + * `switchToIdentity` tests `business`. + * + * One per app, held by the nav host. A change of identity stops the last + * standalone client *before* the next is made, so a switch between two nsec + * profiles never has two connections open; a stopped client cannot be restarted, + * so the next is always new. + */ +class IdentityElectrum( + private val standaloneFor: (Identity) -> StandaloneElectrum, +) { + private val logger = Logger.withTag("IdentityElectrum") + + private var key: Pair? = null + private var client: IElectrumClient? = null + private var standalone: StandaloneElectrum? = null + + /** + * The client for [identity], made the first time it is asked for and kept while + * it stays the same identity on the same node. Null only with no identity. + */ + fun clientFor(identity: Identity?, nodeClient: IElectrumClient? = identity?.business?.electrumClient): IElectrumClient? { + val next = identity?.let { it.id to nodeClient } + if (next == key) return client + + stop() + key = next + client = when { + identity == null -> null + nodeClient != null -> nodeClient + else -> { + logger.i { "starting an Electrum client for ${identity.id}, which has no node" } + standaloneFor(identity).also { it.start() }.also { standalone = it }.client + } + } + return client + } + + /** Stops the standalone client, if the identity has one. The node's is the node's to stop. */ + fun stop() { + standalone?.stop() + standalone = null + client = null + key = null + } + + companion object { + /** The real thing: the identity's own Electrum preferences, the device's network, the node's network. */ + fun standalone(networkMonitor: NetworkMonitor, loggerFactory: LoggerFactory): (Identity) -> StandaloneElectrum = { identity -> + // Idempotent on every platform, and otherwise only the node's daemon calls it. + networkMonitor.start() + StandaloneElectrum( + chain = NodeParamsManager.chain, + networkState = networkMonitor.networkState, + isTorEnabled = identity.userPrefs.getIsTorEnabled, + customServer = identity.userPrefs.getElectrumServer, + link = ElectrumClientLink(loggerFactory), + ) + } + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/IdentityElectrumJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/IdentityElectrumJvmTest.kt new file mode 100644 index 00000000..5ab48da7 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/IdentityElectrumJvmTest.kt @@ -0,0 +1,137 @@ +package com.machankura.bennu.compose.wallet + +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import com.machankura.bennu.compose.identity.Identity +import com.machankura.bennu.compose.identity.IdentityKind +import com.machankura.bennu.compose.identity.toWalletId +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.byteVector32 +import fr.acinq.lightning.utils.ServerAddress +import fr.acinq.phoenix.managers.global.NetworkState +import fr.acinq.phoenix.managers.nostrPublicKeyHex +import fr.acinq.phoenix.utils.preferences.InternalPrefs +import fr.acinq.phoenix.utils.preferences.UserPrefs +import kotlinx.coroutines.flow.flowOf +import okio.Path.Companion.toPath +import org.junit.Rule +import org.junit.rules.TemporaryFolder +import kotlin.random.Random +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotSame +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue +import kotlin.time.Duration + +/** + * Which client each kind of identity watches on, and that a switch never leaves + * the last profile's connection open (D1 of `docs/standalone-electrum.md`). + */ +class IdentityElectrumJvmTest { + @get:Rule + val temporaryFolder = TemporaryFolder() + + /** Never connects: the network is down. What is under test is which client is made, and when it is stopped. */ + private class IdleLink : ElectrumLink { + override val client = FakeElectrum() + var stopped = false + override suspend fun connect(server: ServerAddress, timeout: Duration) {} + override fun disconnect() {} + override fun stop() { + stopped = true + } + } + + private val made = mutableListOf>() + + /** For each client made, whether every one made before it had been stopped by then. */ + private val earlierStopped = mutableListOf() + + private val identityElectrum = IdentityElectrum { identity -> + earlierStopped += made.all { it.second.stopped } + val link = IdleLink() + made += identity to link + StandaloneElectrum( + chain = Chain.Regtest, + networkState = flowOf(NetworkState.NotAvailable), + isTorEnabled = flowOf(false), + customServer = flowOf(null), + link = link, + ) + } + + private fun prefsStore() = PreferenceDataStoreFactory.createWithPath { + temporaryFolder.newFolder().resolve("prefs.preferences_pb").path.toPath() + } + + private fun key() = PrivateKey(Random.nextBytes(32).byteVector32()) + + private fun signing(kind: IdentityKind, key: PrivateKey = key()) = Identity.signing( + id = key.publicKey().xOnly().toWalletId(), + kind = kind, + nostrPrivateKey = key, + userPrefs = UserPrefs(prefsStore()), + internalPrefs = InternalPrefs(prefsStore()), + business = null, + ) + + private fun readOnly(key: PrivateKey = key()) = Identity.readOnly( + id = key.publicKey().xOnly().toWalletId(), + nostrPublicKey = key.nostrPublicKeyHex(), + userPrefs = UserPrefs(prefsStore()), + internalPrefs = InternalPrefs(prefsStore()), + ) + + @Test + fun `a profile with a node watches on the node's client, and no other is made`() { + val node = FakeElectrum() + val client = identityElectrum.clientFor(signing(IdentityKind.Mnemonic), nodeClient = node) + assertSame(node, client) + assertEquals(emptyList(), made) + } + + @Test + fun `an nsec profile and an npub profile each get a client of their own`() { + val nsec = signing(IdentityKind.NostrSecret) + val nsecClient = identityElectrum.clientFor(nsec) + assertSame(made.single { it.first == nsec }.second.client, nsecClient) + + val npub = readOnly() + val npubClient = identityElectrum.clientFor(npub) + assertSame(made.single { it.first == npub }.second.client, npubClient) + } + + @Test + fun `the same identity asked again keeps its client`() { + val nsec = signing(IdentityKind.NostrSecret) + val first = identityElectrum.clientFor(nsec) + assertSame(first, identityElectrum.clientFor(nsec)) + assertEquals(1, made.size) + } + + @Test + fun `switching from one nsec to another stops the first before the second is made`() { + val firstClient = identityElectrum.clientFor(signing(IdentityKind.NostrSecret)) + val secondClient = identityElectrum.clientFor(signing(IdentityKind.NostrSecret)) + + assertEquals(listOf(true, true), earlierStopped) + assertNotSame(firstClient, secondClient) + assertEquals(listOf(true, false), made.map { it.second.stopped }) + } + + @Test + fun `switching to a profile with a node stops the standalone client`() { + identityElectrum.clientFor(signing(IdentityKind.NostrSecret)) + identityElectrum.clientFor(signing(IdentityKind.Mnemonic), nodeClient = FakeElectrum()) + assertTrue(made.single().second.stopped) + } + + @Test + fun `no identity has no client, and the last one is stopped`() { + identityElectrum.clientFor(signing(IdentityKind.NostrSecret)) + assertNull(identityElectrum.clientFor(null)) + assertTrue(made.single().second.stopped) + } +}