diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 7dd87438..4128301c 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -609,6 +609,7 @@ %1$s hasn't set up messaging on Bennu yet. Try again later, or ask them to open Bennu. Group onchain wallet + Group onchain wallet on %1$s Open a group onchain wallet Not opened yet Open on %1$s diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt index a2ef8fdf..f64d1667 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt @@ -1,5 +1,8 @@ package com.machankura.bennu.compose.ui.composable +import bennu.composeapp.generated.resources.group_wallet_on_s +import fr.acinq.phoenix.managers.NodeParamsManager +import com.machankura.bennu.compose.wallet.GroupLightningRollout import com.machankura.bennu.compose.wallet.GroupWalletRollout import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletRoute import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent @@ -483,6 +486,29 @@ fun ChatRoomDetailScreen( ) } + // The same wallet on the network the Lightning wallet is + // tried on, which it closes to: a Lightning wallet cannot + // be opened without one there (docs/group-lightning-wallet.md). + if (GroupWalletRollout.ENABLED && GroupLightningRollout.ENABLED && GroupLightningRollout.NETWORK != NodeParamsManager.chain) item { + val network = GroupWalletStatementEvent.chainName(GroupLightningRollout.NETWORK) + SignedWorkRow( + icon = Icons.Default.AccountBalanceWallet, + headline = stringResource(Res.string.group_wallet_on_s, network), + supporting = chatRoomDetailUIState.testNetworkWallet?.let { stringResource(Res.string.open_on_s, network) } + ?: stringResource(Res.string.not_opened_yet), + onOpen = { + onNavigateToRoute.invoke( + GroupWalletRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = relayHint, + chain = network + ) + ) + } + ) + } + // The untyped way into everything above it. Each // row opens a screen with a form that builds one // kind of event; this takes any of those kinds as diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt index fd1ea3d8..2a4c1d2a 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.ui.composable +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent import androidx.compose.foundation.layout.Row import com.machankura.bennu.compose.text.ProposedSpend import com.machankura.bennu.compose.ui.view.state.SpendRow @@ -240,7 +241,8 @@ fun GroupWalletScreen( GroupSendRoute( activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, - relayHint = null + relayHint = null, + chain = GroupWalletStatementEvent.chainName(chain) ) ) } @@ -249,7 +251,8 @@ fun GroupWalletScreen( onNavigateToRoute( GroupWalletAddressesRoute( activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId + chatRoomId = chatRoomId, + chain = GroupWalletStatementEvent.chainName(chain) ) ) }, 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 5342fe5d..87577df5 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 @@ -1,5 +1,7 @@ package com.machankura.bennu.compose.ui.composable.navigation +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.wallet.GroupChainClients import com.machankura.bennu.compose.ui.composable.GroupSendScreen import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupSendRoute import androidx.compose.foundation.layout.fillMaxSize @@ -266,8 +268,17 @@ fun BennuNavHost( // of profile is a restart and a wallet left subscribing on the last one's // connection is a wallet nobody can see. val activeIdentityForWallets by sovereignWalletViewModel.activeIdentity.collectAsState() - val groupOnchainWallets = remember(activeIdentityForWallets?.business) { - activeIdentityForWallets?.business?.let { GroupOnchainWallets(it.electrumClient, applicationIOScope) } + // One Electrum connection per network: the node's own for its network, and one of + // their own for any other a group keeps a wallet on (testnet3, while a Lightning + // wallet is tried there). Shared by the wallets and the watcher below. + val groupChainClients = remember(activeIdentityForWallets?.business) { + activeIdentityForWallets?.business?.let { GroupChainClients.forNode(NodeParamsManager.chain, it.electrumClient, applicationIOScope, it.loggerFactory) } + } + DisposableEffect(groupChainClients) { + onDispose { groupChainClients?.let { clients -> applicationIOScope.launch { clients.stop() } } } + } + val groupOnchainWallets = remember(groupChainClients) { + groupChainClients?.let { GroupOnchainWallets(it, applicationIOScope) } } DisposableEffect(groupOnchainWallets) { onDispose { groupOnchainWallets?.let { wallets -> applicationIOScope.launch { wallets.stop() } } } @@ -276,9 +287,9 @@ 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() } + val groupTransactionWatcher = remember(groupChainClients) { + groupChainClients?.let { + GroupTransactionWatcher(auxDatabaseManager.auxDatabase, it, applicationIOScope).also { watcher -> watcher.start() } } } DisposableEffect(groupTransactionWatcher) { @@ -1239,7 +1250,7 @@ fun BennuNavHost( GroupWalletScreen( activeUserPublicKey = route.activeUserPublicKey, chatRoomId = route.chatRoomId, - chain = NodeParamsManager.chain, + chain = route.chain?.let(GroupWalletStatementEvent::chainNamed) ?: NodeParamsManager.chain, chatRepository = databaseChatRepository, frostSigningRepository = databaseFrostSigningRepository, wallets = groupOnchainWallets, @@ -1257,7 +1268,7 @@ fun BennuNavHost( GroupWalletAddressesScreen( chatRoomId = route.chatRoomId, - chain = NodeParamsManager.chain, + chain = route.chain?.let(GroupWalletStatementEvent::chainNamed) ?: NodeParamsManager.chain, chatRepository = databaseChatRepository, wallets = groupOnchainWallets, onNavigateBack = { @@ -1271,7 +1282,7 @@ fun BennuNavHost( GroupSendScreen( activeUserPublicKey = route.activeUserPublicKey, chatRoomId = route.chatRoomId, - chain = NodeParamsManager.chain, + chain = route.chain?.let(GroupWalletStatementEvent::chainNamed) ?: NodeParamsManager.chain, chatRepository = databaseChatRepository, frostSigningRepository = databaseFrostSigningRepository, wallets = groupOnchainWallets, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupSendRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupSendRoute.kt index 52db5baa..b09b665d 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupSendRoute.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupSendRoute.kt @@ -7,5 +7,7 @@ import kotlinx.serialization.Serializable data class GroupSendRoute( val activeUserPublicKey: String, val chatRoomId: String, - val relayHint: String? + val relayHint: String?, + /** The wallet's network, as `GroupWalletStatementEvent.chainName` spells it; null for the node's own. */ + val chain: String? = null, ): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupWalletAddressesRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupWalletAddressesRoute.kt index 915c1963..c7817306 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupWalletAddressesRoute.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupWalletAddressesRoute.kt @@ -10,4 +10,6 @@ import kotlinx.serialization.Serializable data class GroupWalletAddressesRoute( val activeUserPublicKey: String, val chatRoomId: String, + /** The wallet's network, as `GroupWalletStatementEvent.chainName` spells it; null for the node's own. */ + val chain: String? = null, ): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupWalletRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupWalletRoute.kt index bf05425f..179ca38e 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupWalletRoute.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupWalletRoute.kt @@ -10,5 +10,7 @@ import kotlinx.serialization.Serializable data class GroupWalletRoute( val activeUserPublicKey: String, val chatRoomId: String, - val relayHint: String? + val relayHint: String?, + /** The wallet's network, as `GroupWalletStatementEvent.chainName` spells it; null for the node's own. */ + val chain: String? = null, ): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt index a7f77e8b..fcf7bad6 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.ui.view.model +import com.machankura.bennu.compose.wallet.GroupLightningRollout import fr.acinq.phoenix.managers.NodeParamsManager import com.machankura.bennu.compose.nostr.MarmotProfile import androidx.compose.runtime.MutableState @@ -98,6 +99,9 @@ class ChatRoomDetailViewModel( groupRelayLists = chatRepository.groupRelayLists(chatRoomId), groupPosts = chatRepository.groupPosts(chatRoomId), groupWallet = chatRepository.groupWallet(chatRoomId, NodeParamsManager.chain), + testNetworkWallet = if (GroupLightningRollout.ENABLED && GroupLightningRollout.NETWORK != NodeParamsManager.chain) { + chatRepository.groupWallet(chatRoomId, GroupLightningRollout.NETWORK) + } else null, canEditNostrProfile = canSign, canAddSubgroup = canSign, canGovern = canGovern, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModel.kt index 6168caa8..5bd754c8 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModel.kt @@ -88,7 +88,7 @@ class GroupSendViewModel( ) groupSendUIState = ready - wallets.suggestedFeeratePerVbyte()?.let { suggested -> + wallets.suggestedFeeratePerVbyte(chain)?.let { suggested -> withContext(Dispatchers.Main) { if (feerateField.text.isEmpty()) feerateField.setTextAndPlaceCursorAtEnd(suggested.toString()) } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt index 60729548..c2199fb3 100755 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -92,6 +92,12 @@ sealed interface ChatRoomDetailUIState { * `GroupWalletScreen`. */ val groupWallet: GroupWallet? = null, + /** + * The wallet this group has opened on the Lightning wallet's test network, which is not the app's + * own network while the Lightning wallet is tried there. Null when it has not, or when the + * Lightning wallet is not offered on this build (`GroupLightningRollout`). + */ + val testNetworkWallet: GroupWallet? = null, /** * Whether this device could sign an event for the group, which on this * screen gates the paste at the end of the identity block. Each of the diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainClients.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainClients.kt new file mode 100644 index 00000000..fd7eabf3 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainClients.kt @@ -0,0 +1,90 @@ +package com.machankura.bennu.compose.wallet + +import co.touchlab.kermit.Logger +import fr.acinq.bitcoin.Chain +import fr.acinq.lightning.blockchain.electrum.ElectrumClient +import fr.acinq.lightning.blockchain.electrum.ElectrumConnectionStatus +import fr.acinq.lightning.blockchain.electrum.ElectrumServers +import fr.acinq.lightning.blockchain.electrum.IElectrumClient +import fr.acinq.lightning.io.TcpSocket +import fr.acinq.lightning.logging.LoggerFactory +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlin.time.Duration.Companion.seconds + +/** + * The Electrum connection each network's group wallets watch through, for one identity. + * + * The identity's own node has one, for the network the node runs on, and every wallet on that network + * shares it as before. A group may keep a wallet on another network as well -- testnet3, while its + * Lightning wallet is tried there (`docs/group-lightning-wallet.md`, Phase 4) -- and that network gets a + * connection of its own, made the first time a wallet on it asks and kept for the identity's life, for + * the reason [GroupOnchainWallets] keeps its wallets: a subscription is cheap and the first answer slow. + */ +class GroupChainClients( + private val nodeChain: Chain, + private val nodeClient: IElectrumClient, + private val connect: suspend (Chain) -> Connection, +) { + /** A connection this object made, and how to close it. */ + class Connection(val client: IElectrumClient, val close: () -> Unit) + + private val mutex = Mutex() + private val others = mutableMapOf() + + suspend fun clientFor(chain: Chain): IElectrumClient = + if (chain == nodeChain) nodeClient else mutex.withLock { others.getOrPut(chain) { connect(chain) }.client } + + suspend fun stop() = mutex.withLock { + others.values.forEach { it.close() } + others.clear() + } + + companion object { + /** Every network on one client: for a test, whose fake client answers for whatever it is asked. */ + fun single(client: IElectrumClient): GroupChainClients = + GroupChainClients(Chain.Mainnet, client) { Connection(client) {} } + + /** + * The identity's node for its own network, and a standalone [ElectrumClient] on a random public + * server for any other that lightning-kmp lists servers for (mainnet and testnet3), reconnecting + * whenever it drops. + */ + fun forNode(nodeChain: Chain, nodeClient: IElectrumClient, scope: CoroutineScope, loggerFactory: LoggerFactory): GroupChainClients = + GroupChainClients(nodeChain, nodeClient) { chain -> standalone(chain, scope, loggerFactory) } + + private fun standalone(chain: Chain, scope: CoroutineScope, loggerFactory: LoggerFactory): Connection { + val logger = Logger.withTag("GroupChainClients") + val client = ElectrumClient(scope, loggerFactory, pingInterval = 30.seconds, rpcTimeout = 10.seconds) + val socketBuilder = TcpSocket.Builder() + val job: Job = scope.launch { + var backoff = 1.seconds + while (isActive) { + if (client.connectionStatus.value is ElectrumConnectionStatus.Closed) { + val server = ElectrumServers.pickElectrumServer(chain) + val connected = try { + client.connect(server, socketBuilder) + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + logger.w("Could not reach ${server.host} for $chain", e) + false + } + backoff = if (connected) 1.seconds else (backoff * 2).coerceAtMost(60.seconds) + } + delay(backoff) + } + } + return Connection(client) { + job.cancel() + client.stop() + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupLightningRollout.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupLightningRollout.kt new file mode 100644 index 00000000..8535a9f1 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupLightningRollout.kt @@ -0,0 +1,28 @@ +package com.machankura.bennu.compose.wallet + +import fr.acinq.bitcoin.Chain + +/** + * The gates the group Lightning wallet ships behind -- `docs/group-lightning-wallet.md`, Phase 15 -- + * in one place, each with the condition that lifts it. + * + * As with [GroupWalletRollout], these decide what this device offers, never what it accepts: a device + * with a gate closed still verifies and co-signs for a wallet another member opened. + */ +object GroupLightningRollout { + /** + * Whether the group's screen offers a Lightning wallet, and the test-network on-chain wallet it closes + * to. Lifts when Phases 0 to 12 are in, the JVM suite passes and a regtest end-to-end run passes. + */ + const val ENABLED: Boolean = false + + /** + * The only network a Lightning wallet may be opened on. Iceberg says not to put money behind it, so + * mainnet is refused in code rather than hidden; this lifts only when the scheme and the DKG have + * been reviewed outside the project and a testnet3 group has run for a month without a refused label + * or a lost channel. + */ + val NETWORK: Chain = Chain.Testnet3 + + fun allows(chain: Chain): Boolean = chain == NETWORK +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt index e1347ffb..a66a76aa 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt @@ -1,6 +1,7 @@ package com.machankura.bennu.compose.wallet import com.machankura.bennu.compose.managers.GroupWalletDerivation +import fr.acinq.bitcoin.Chain import fr.acinq.lightning.blockchain.electrum.IElectrumClient import fr.acinq.lightning.blockchain.fee.FeeratePerByte import kotlinx.coroutines.CoroutineScope @@ -8,7 +9,9 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock /** - * The group wallets one identity is watching, on that identity's Electrum client. + * The group wallets one identity is watching, each on the Electrum client for its network + * ([GroupChainClients]): the identity's own node for the network it runs on, a connection of its own + * for any other. * * One per identity, made where the identity's node is, and stopped with it: a * profile switch is a restart, and a wallet left watching on the last profile's @@ -18,15 +21,18 @@ import kotlinx.coroutines.sync.withLock * cheap and the first answer is slow. */ class GroupOnchainWallets( - private val electrum: IElectrumClient, + private val clients: GroupChainClients, private val scope: CoroutineScope, ) { + /** Every network on [electrum]: what the tests, whose fake client answers anything, construct. */ + constructor(electrum: IElectrumClient, scope: CoroutineScope) : this(GroupChainClients.single(electrum), scope) + private val mutex = Mutex() private val wallets = mutableMapOf() /** The wallet watching [account], made the first time it is asked for. Keyed by xpub, which names one account of one group on one network. */ suspend fun walletFor(account: GroupWalletDerivation.Account): GroupOnchainWallet = mutex.withLock { - wallets.getOrPut(account.xpub) { GroupOnchainWallet(account, electrum, scope) } + wallets.getOrPut(account.xpub) { GroupOnchainWallet(account, clients.clientFor(account.chain), scope) } } /** @@ -34,8 +40,8 @@ class GroupOnchainWallets( * estimate for six blocks, or null when it has none. A suggestion the member * edits, never a value a spend is built on without them seeing it. */ - suspend fun suggestedFeeratePerVbyte(): Long? = - electrum.estimateFees(6)?.let { FeeratePerByte(it).feerate.sat }?.coerceAtLeast(1) + suspend fun suggestedFeeratePerVbyte(chain: Chain): Long? = + clients.clientFor(chain).estimateFees(6)?.let { FeeratePerByte(it).feerate.sat }?.coerceAtLeast(1) suspend fun stop() = mutex.withLock { wallets.values.forEach { it.stop() } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcher.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcher.kt index 75cc0f13..dc2bae31 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcher.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcher.kt @@ -4,6 +4,7 @@ import co.touchlab.kermit.Logger import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.database.model.GroupTransaction import com.machankura.bennu.compose.managers.FrostSigningManager +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent import fr.acinq.bitcoin.Transaction import fr.acinq.lightning.blockchain.electrum.IElectrumClient import kotlinx.coroutines.CancellationException @@ -37,10 +38,18 @@ import kotlin.time.Instant */ class GroupTransactionWatcher( private val database: BennuDatabase, - private val electrum: IElectrumClient, + private val clients: GroupChainClients, private val scope: CoroutineScope, private val now: () -> Instant = { Clock.System.now() }, ) { + /** Every network on [electrum]: what the tests construct. */ + constructor(database: BennuDatabase, electrum: IElectrumClient, scope: CoroutineScope, now: () -> Instant = { Clock.System.now() }) : + this(database, GroupChainClients.single(electrum), scope, now) + + /** The client for [transaction]'s own network, which a statement named and the row kept. */ + private suspend fun electrumFor(transaction: GroupTransaction): IElectrumClient? = + GroupWalletStatementEvent.chainNamed(transaction.chain)?.let { clients.clientFor(it) } + private val logger = Logger.withTag("GroupTransactionWatcher") private var job: Job? = null @@ -79,6 +88,7 @@ class GroupTransactionWatcher( suspend fun broadcastAgain(sessionId: String): Boolean { val transaction = database.groupTransactionDao().getBySessionId(sessionId) ?: return false val signed = transaction.signedTransaction?.let { Transaction.read(it) } ?: return false + val electrum = electrumFor(transaction) ?: return false electrum.broadcastTransaction(signed) database.groupTransactionDao().upsert(transaction.copy(broadcastAt = now())) return true @@ -91,6 +101,7 @@ class GroupTransactionWatcher( val transaction = database.groupTransactionDao().getBySessionId(listed.frostSigningSessionId) ?: return if (transaction.confirmedAt != null || transaction.replacedByTxid != null) return val signed = Transaction.read(transaction.signedTransaction ?: return) + val electrum = electrumFor(transaction) ?: return var row = transaction val due = row.broadcastAt?.let { now() - it >= REBROADCAST_AFTER } ?: true diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupChainClientsJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupChainClientsJvmTest.kt new file mode 100644 index 00000000..a8a99a72 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupChainClientsJvmTest.kt @@ -0,0 +1,38 @@ +package com.machankura.bennu.compose.wallet + +import fr.acinq.bitcoin.Chain +import kotlinx.coroutines.runBlocking +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertSame + +/** + * One Electrum connection per network: the node's own is used as it is, any other is made once, on + * first use, and closed with the identity. + */ +class GroupChainClientsJvmTest { + @Test + fun `the node's network uses the node's client and connects nothing`() = runBlocking { + val node = FakeElectrum() + val made = mutableListOf() + val clients = GroupChainClients(Chain.Mainnet, node) { chain -> made += chain; GroupChainClients.Connection(FakeElectrum()) {} } + assertSame(node, clients.clientFor(Chain.Mainnet)) + assertEquals(emptyList(), made) + } + + @Test + fun `another network gets one connection of its own, reused, and closed on stop`() = runBlocking { + val node = FakeElectrum() + val made = mutableListOf() + var closed = 0 + val clients = GroupChainClients(Chain.Mainnet, node) { chain -> made += chain; GroupChainClients.Connection(FakeElectrum()) { closed++ } } + val first = clients.clientFor(Chain.Testnet3) + assertSame(first, clients.clientFor(Chain.Testnet3)) + assertEquals(listOf(Chain.Testnet3), made) + clients.stop() + assertEquals(1, closed) + // A wallet asked for after a stop -- a profile switched back -- connects again. + clients.clientFor(Chain.Testnet3) + assertEquals(listOf(Chain.Testnet3, Chain.Testnet3), made) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcherJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcherJvmTest.kt index 97a16184..2d8bc5b1 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcherJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcherJvmTest.kt @@ -100,7 +100,7 @@ class GroupTransactionWatcherJvmTest { db.chatRoomDao().upsert(ChatRoom(id = room, userPublicKey = user, subject = null, description = null, mlsGroupState = "00")) } - private suspend fun spend(id: String, tx: Transaction, stage: FrostSigningStage, signed: Boolean) { + private suspend fun spend(id: String, tx: Transaction, stage: FrostSigningStage, signed: Boolean, chain: String = "regtest") { db.frostSigningSessionDao().upsert( FrostSigningSession( id = id, chatRoomId = room, coordinatorPublicKey = user, userPublicKey = user, dkgSessionId = "dkg", @@ -109,13 +109,38 @@ class GroupTransactionWatcherJvmTest { ) db.groupTransactionDao().insertIfAbsent( GroupTransaction( - frostSigningSessionId = id, chatRoomId = room, chain = "regtest", account = 0, + frostSigningSessionId = id, chatRoomId = room, chain = chain, account = 0, psbt = GroupSpend.encode(Psbt(tx)), txid = tx.txid.toString(), signedTransaction = if (signed) Hex.encode(Transaction.write(tx)) else null, ) ) } + @Test + fun `each spend goes out on its own network's connection`() = runBlocking { + // A group with wallets on two networks: the node's, and the test network a Lightning wallet is + // tried on. Each signed spend must reach the network it spends on, and only that one. + seed() + val testnet = FakeElectrum() + val clients = GroupChainClients(fr.acinq.bitcoin.Chain.Regtest, electrum) { GroupChainClients.Connection(testnet) {} } + val watcher = GroupTransactionWatcher(db, clients, CoroutineScope(Dispatchers.Default), now = { clock }) + val onNode = spending(coin, pay = 9_000) + val onTestnet = spending(OutPoint(TxId(ByteVector32(ByteArray(32) { 4 })), 0), pay = 8_000) + spend("a", onNode, FrostSigningStage.COMPLETE, signed = true) + spend("b", onTestnet, FrostSigningStage.COMPLETE, signed = true, chain = "testnet3") + watcher.pass() + assertEquals(listOf(onNode.txid), electrum.broadcasts) + assertEquals(listOf(onTestnet.txid), testnet.broadcasts) + } + + @Test + fun `a spend on a network nobody named is left alone`() = runBlocking { + seed() + spend("a", spending(coin, pay = 9_000), FrostSigningStage.COMPLETE, signed = true, chain = "litecoin") + watcher.pass() + assertTrue(electrum.broadcasts.isEmpty()) + } + @Test fun `a signed spend is sent, and sent again while nobody has seen it`() = runBlocking { seed() diff --git a/docs/group-lightning-wallet.md b/docs/group-lightning-wallet.md index a42007dc..664eba71 100644 --- a/docs/group-lightning-wallet.md +++ b/docs/group-lightning-wallet.md @@ -33,6 +33,7 @@ build chose differently, this table says so. | 1 | done: `IcebergDkg`, 11 tests, among them a byte-for-byte match against the library's dealer and a signature from every 2-of-4 and 3-of-7 quorum | | 2 | done, in the fork (`4bc973df`): the three signing methods suspend, `RemoteIcebergFundingSigner`, pings answered outside the channel loop. lightning-kmp's JVM suite, 985 tests, passes | | 3 | done: in the fork (`e15e31ba`), `withGroupBasepoints`, `GroupHeldOutputs` and `KeyManager.defaultFinalScriptPubKey`, 991 tests passing. In the app, `GroupLightningDerivation`, pinned, with a FROST quorum spending `to_remote` and `to_local` | +| 4 | done: `GroupChainClients`, one Electrum connection per network for the wallets and the watcher; the wallet routes carry a chain; a second wallet row for testnet3 behind `GroupLightningRollout`, which is off | | what the plan said | what it turned out to be | |---|---| @@ -48,6 +49,10 @@ build chose differently, this table says so. | the closing script comes from a provider the app supplies | `KeyManager.defaultFinalScriptPubKey`, defaulting to `finalOnChainWallet`'s first address. It is fixed in a channel's parameters when the channel opens, as it always was. A close to a different onchain wallet address goes through `Shutdown`'s script override | | one channel per group node, because two would share a `shaSeed` | not needed. Channel keys derive from a random funding key *path* per channel, not from the funding key, so two channels have different per-commitment secrets even with the same group funding key. Only `RecoveredChannelKeys`, which a group node never uses, keys off the funding key | | `HtlcDelayedTx` is node-keyed | it is keyed from the delayed basepoint, so it pays the group too. What stays node-keyed is the HTLC transaction itself and the claims from the counterparty's commitment, which is the in-flight exposure the statement caps | +| *Open a group wallet* offers testnet3 | a second row on the group's screen, *Group onchain wallet on testnet3*, opening the same wallet screen on that network. Behind `GroupLightningRollout.ENABLED`, which stays off until Phase 15, so nothing a member sees changes yet | +| a testnet3 Electrum client per identity, from `AppConfigurationManager.randomElectrumServer` | from lightning-kmp's `ElectrumServers.pickElectrumServer`, which lists the same servers and needs no Phoenix business to call. The node's own client still serves the node's network | +| `GroupOnchainWallets` is keyed by `(chain, account)` | it stays keyed by xpub, which already names one account on one network. What changed is the client: each wallet is made on its own network's | +| a regtest test opens, receives and spends with mainnet unaffected | the existing wallet suites run on regtest unchanged through the new registry, and two new tests check that each spend goes out on its own network's connection, and that a spend naming no known network is left alone | | the kinds are reserved | in code: `GroupLightningEvents`, 30333-30349, with a test asserting the run is unbroken and touches no kind the app already dispatches on | | library phases land in the forks' `threshold` branches | on a new branch, `claude/group-lightning-wallet`, in `lightning-kmp-app` and in `experimental/lightning-kmp`. It is local and not pushed. The app's submodule pointer follows it, so a checkout of this branch needs those commits from the same machine until they are pushed |