From 24d06d2eee432afa7de7916eb06e2ed8ba4295f3 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 08:11:47 +0200 Subject: [PATCH] feat(wallet): a screen to open a group's wallet and receive into it (Phase 5) GroupWalletRoute and GroupWalletScreen, reached from a Group wallet row on the group's screen. A group that has not opened a wallet gets an empty state with, for a member who can sign, what opening one asks of everybody -- including that shares are unencrypted at rest -- and the button that proposes the statement. An open wallet shows the balance, confirmed and on the way said apart, the next receive address as a BIP21 QR code, selectable text and a copy button, the coins, and an export of the two watch-only descriptors with what they give away. The wallets are watched on the identity's own Electrum client and made per PhoenixBusiness in BennuNavHost; a profile with no node sees the wallet and is told it cannot watch the chain. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 28 ++ .../com/machankura/bennu/compose/text/Sats.kt | 16 + .../ui/composable/ChatRoomDetailScreen.kt | 35 ++ .../ui/composable/GroupWalletScreen.kt | 400 ++++++++++++++++++ .../ui/composable/navigation/BennuNavHost.kt | 35 ++ .../navigation/routes/GroupWalletRoute.kt | 14 + .../ui/view/model/ChatRoomDetailViewModel.kt | 2 + .../ui/view/model/GroupWalletViewModel.kt | 156 +++++++ .../ui/view/state/ChatRoomDetailUIState.kt | 9 + .../ui/view/state/GroupWalletUIState.kt | 43 ++ .../bennu/compose/wallet/GroupChainWallet.kt | 3 + .../view/model/GroupWalletViewModelJvmTest.kt | 169 ++++++++ docs/group-chain-wallet.md | 3 + 13 files changed, 913 insertions(+) create mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/Sats.kt create mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt create mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupWalletRoute.kt create mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt create mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt create mode 100644 composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index a01b90bb..3347f0ea 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -788,4 +788,32 @@ You already have a chat with %1$s. Checking whether %1$s can receive messages here. %1$s hasn't set up messaging on Bennu yet. Try again later, or ask them to open Bennu. + + Group wallet + Open a group wallet + Not opened yet + Open on %1$s + This group has not opened a wallet. + Opening a wallet asks the group to agree that it keeps coins here. Any quorum of members can then spend them together, and nobody can spend them alone. + Each member's share of the group's key is stored unencrypted on their device. Anyone with an unlocked device, or a copy of its data, holds that member's share. + Couldn't ask the group to open a wallet. + Balance + %1$s sats + %1$s sats on the way + Receive address + Copy address + Address copied + Finding the group's coins… + Nothing has been sent to this wallet yet. + This profile has no wallet of its own to watch the chain with, so the balance and the next address can't be shown here. + Coins + Change + Received + Waiting for a confirmation + %1$s confirmations + %1$s · %2$s + Not known yet + Export watch-only + Watch-only descriptors copied + Anyone with these can see every address of this wallet and its whole balance. They can't spend from it. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/Sats.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/Sats.kt new file mode 100644 index 00000000..e1d4063a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/Sats.kt @@ -0,0 +1,16 @@ +package com.machankura.bennu.compose.text + +import fr.acinq.bitcoin.Satoshi + +/** + * An amount in sats, its thousands grouped: `120,000`. + * + * Sats rather than bitcoin, everywhere the group's wallet shows an amount: a + * signer comparing a fee to an output is comparing two integers, and a decimal + * point eight places in is the easiest digit on the screen to misread. + */ +fun Satoshi.grouped(): String { + val digits = sat.toString().removePrefix("-") + val grouped = digits.reversed().chunked(3).joinToString(",").reversed() + return if (sat < 0) "-$grouped" else grouped +} 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 f27ac274..15a19383 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,11 @@ package com.machankura.bennu.compose.ui.composable +import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletRoute +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import bennu.composeapp.generated.resources.open_on_s +import bennu.composeapp.generated.resources.not_opened_yet +import bennu.composeapp.generated.resources.group_wallet +import androidx.compose.material.icons.filled.AccountBalanceWallet import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer @@ -515,6 +521,35 @@ fun ChatRoomDetailScreen( ) } + // The group's coins. After the identity block's + // last signed row and before the paste, because it + // is signed by the same key and read by nobody + // outside the room: the statement opening it never + // leaves the group. Shown to every member, open or + // not -- the screen behind it is where a member who + // can sign asks the group to open one. + item { + SignedWorkRow( + icon = Icons.Default.AccountBalanceWallet, + headline = stringResource(Res.string.group_wallet), + supporting = chatRoomDetailUIState.groupWallet?.let { wallet -> + stringResource( + Res.string.open_on_s, + GroupWalletStatementEvent.chainName(wallet.chain) + ) + } ?: stringResource(Res.string.not_opened_yet), + onOpen = { + onNavigateToRoute.invoke( + GroupWalletRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = relayHint + ) + ) + } + ) + } + // 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 new file mode 100644 index 00000000..9f94af92 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt @@ -0,0 +1,400 @@ +package com.machankura.bennu.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AccountBalanceWallet +import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.Visibility +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import bennu.composeapp.generated.resources.Res +import bennu.composeapp.generated.resources.address_copied +import bennu.composeapp.generated.resources.anyone_with_these_can_see_every_address +import bennu.composeapp.generated.resources.balance +import bennu.composeapp.generated.resources.balance_not_known_yet +import bennu.composeapp.generated.resources.change +import bennu.composeapp.generated.resources.coins +import bennu.composeapp.generated.resources.copy_address +import bennu.composeapp.generated.resources.couldn_t_ask_the_group_to_open_a_wallet +import bennu.composeapp.generated.resources.each_member_s_share_is_stored_unencrypted +import bennu.composeapp.generated.resources.export_watch_only +import bennu.composeapp.generated.resources.finding_the_group_s_coins +import bennu.composeapp.generated.resources.group_wallet +import bennu.composeapp.generated.resources.nothing_has_been_sent_to_this_wallet_yet +import bennu.composeapp.generated.resources.open_a_group_wallet +import bennu.composeapp.generated.resources.opening_a_wallet_asks_the_group_to_agree +import bennu.composeapp.generated.resources.receive_address +import bennu.composeapp.generated.resources.received +import bennu.composeapp.generated.resources.s_confirmations +import bennu.composeapp.generated.resources.s_dot_s +import bennu.composeapp.generated.resources.s_sats +import bennu.composeapp.generated.resources.s_sats_on_the_way +import bennu.composeapp.generated.resources.this_group_has_not_opened_a_wallet +import bennu.composeapp.generated.resources.this_profile_cannot_watch_the_chain +import bennu.composeapp.generated.resources.waiting_for_a_confirmation +import bennu.composeapp.generated.resources.watch_only_descriptors_copied +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.FrostSigningRepository +import com.machankura.bennu.compose.text.grouped +import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.Route +import com.machankura.bennu.compose.ui.composable.widgets.Decorative +import com.machankura.bennu.compose.ui.composable.widgets.EmptyState +import com.machankura.bennu.compose.ui.composable.widgets.ErrorState +import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator +import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState +import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton +import com.machankura.bennu.compose.ui.composable.widgets.QRCodeView +import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition +import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier +import com.machankura.bennu.compose.ui.theme.readableContent +import com.machankura.bennu.compose.ui.theme.spacing +import com.machankura.bennu.compose.ui.view.model.GroupWalletViewModel +import com.machankura.bennu.compose.ui.view.state.GroupWalletUIState +import com.machankura.bennu.compose.wallet.GroupChainWallets +import com.machankura.bennu.compose.wallet.bip21Uri +import com.machankura.bennu.compose.wallet.GroupUtxo +import com.machankura.bennu.compose.wallet.GroupWalletState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Chain +import org.jetbrains.compose.resources.stringResource + +/** + * The group's wallet: what it holds, where to pay it, and the coins themselves. + * + * Pushed from its row on the group's screen. A group that has not opened a + * wallet gets an empty state that says so -- and, for a member holding a share, + * the way to ask the group to open one, with what that asks of everybody. + * + * The address is the only thing on the screen a person acts on outside the app, + * so it is shown three ways: as a QR code, as selectable text, and on a copy + * button. Every one of them is derived on this device from the room's key; the + * statement the group signed is what says the wallet exists, never where it is. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GroupWalletScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + chain: Chain, + initialGroupWalletUIState: GroupWalletUIState = GroupWalletUIState.Loading, + chatRepository: ChatRepository, + frostSigningRepository: FrostSigningRepository, + wallets: GroupChainWallets?, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val groupWalletViewModel: GroupWalletViewModel = viewModel( + factory = GroupWalletViewModel.factory( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + chain = chain, + initialGroupWalletUIState = initialGroupWalletUIState, + chatRepository = chatRepository, + frostSigningRepository = frostSigningRepository, + wallets = wallets, + ) + ) + + LaunchedEffect(true) { + if (initialGroupWalletUIState == GroupWalletUIState.Loading) { + groupWalletViewModel.initiate() + } + } + + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotOpen = stringResource(Res.string.couldn_t_ask_the_group_to_open_a_wallet) + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { + Text( + text = stringResource(Res.string.group_wallet), + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + }, + navigationIcon = { NavigateBackButton(onNavigateBack) } + ) + } + ) { padding -> + ScreenStateTransition(groupWalletViewModel.groupWalletUIState) { uiState -> + when (val state = uiState) { + is GroupWalletUIState.Error -> { + // Nothing to retry: the room came from a navigation argument. + ErrorState( + modifier = Modifier.padding(padding), + message = state.message, + onRetry = null + ) + } + + GroupWalletUIState.Loading -> { + LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) + } + + is GroupWalletUIState.NotOpened -> { + EmptyState( + modifier = Modifier.padding(padding).readableContent(), + message = stringResource(Res.string.this_group_has_not_opened_a_wallet), + icon = Icons.Default.AccountBalanceWallet, + // Hidden rather than disabled, the way every gated way in + // on the group's screens is: a device with no share cannot + // propose, and a room with no key has nothing to open. + action = if (state.canSign && state.account != null) { + { + OpenWalletAction( + isPending = groupWalletViewModel.isActionPending.value, + onOpen = { + groupWalletViewModel.openWallet( + onSuccess = { sessionId -> + // Onto the session: the wallet does + // not exist until a quorum signs. + onNavigateToRoute( + FrostSigningRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + sessionId = sessionId + ) + ) + }, + onFailure = { notify(couldNotOpen) } + ) + } + ) + } + } else null + ) + } + + is GroupWalletUIState.Loaded -> { + OpenWallet( + modifier = Modifier.padding(padding), + state = state, + notify = notify, + ) + } + } + } + } +} + +/** + * What opening a wallet asks of the group, said before the button rather than + * after it: that any quorum can then spend together and nobody alone, and what + * an unencrypted share on a member's device means once there are coins behind it. + */ +@Composable +private fun OpenWalletAction(isPending: Boolean, onOpen: () -> Unit) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) + ) { + Text( + text = stringResource(Res.string.opening_a_wallet_asks_the_group_to_agree), + style = MaterialTheme.typography.bodyMedium, + ) + Text( + text = stringResource(Res.string.each_member_s_share_is_stored_unencrypted), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Button(onClick = onOpen, enabled = !isPending) { + Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.open_a_group_wallet)) + } + } +} + +@Composable +private fun OpenWallet( + modifier: Modifier, + state: GroupWalletUIState.Loaded, + notify: (String) -> Unit, +) { + val clipboardManager = LocalClipboardManager.current + val addressCopied = stringResource(Res.string.address_copied) + val descriptorsCopied = stringResource(Res.string.watch_only_descriptors_copied) + val walletState = state.walletState + + LazyColumn( + modifier = modifier.readableContent().fillMaxSize() + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) + ) { + item { BalanceCard(walletState) } + + when { + !state.canWatch -> item { + Text( + text = stringResource(Res.string.this_profile_cannot_watch_the_chain), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + walletState?.receiveAddress == null -> item { + LoadingDataIndicator( + fillScreen = false, + text = stringResource(Res.string.finding_the_group_s_coins) + ) + } + + else -> { + val address = walletState.receiveAddress!! + + item { + Card(modifier = Modifier.fillMaxWidth()) { + Column( + modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) + ) { + Text( + text = stringResource(Res.string.receive_address), + style = MaterialTheme.typography.titleMedium, + ) + // BIP21, so a scanning wallet knows what the text is. + QRCodeView(bip21Uri(address)) + SelectionContainer { + Text(text = address, style = MaterialTheme.typography.bodyMedium) + } + TextButton( + onClick = { + clipboardManager.setText(buildAnnotatedString { append(address) }) + notify(addressCopied) + } + ) { + Icon(Icons.Default.ContentCopy, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.copy_address)) + } + } + } + } + + item { + Text( + text = stringResource(Res.string.coins), + style = MaterialTheme.typography.titleMedium, + ) + } + + if (walletState.utxos.isEmpty()) { + item { + EmptyState(message = stringResource(Res.string.nothing_has_been_sent_to_this_wallet_yet)) + } + } else { + items(walletState.utxos, key = { it.utxo.outPoint.toString() }) { utxo -> + CoinRow(utxo = utxo, confirmations = walletState.confirmations(utxo)) + } + } + } + } + + item { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + TextButton( + onClick = { + val account = state.wallet.account + clipboardManager.setText( + buildAnnotatedString { + append(account.receiveDescriptor) + append("\n") + append(account.changeDescriptor) + } + ) + notify(descriptorsCopied) + } + ) { + Icon(Icons.Default.Visibility, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.export_watch_only)) + } + Text( + text = stringResource(Res.string.anyone_with_these_can_see_every_address), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } +} + +/** Confirmed and on-the-way said apart: only the first can be spent by a send-all. */ +@Composable +private fun BalanceCard(walletState: GroupWalletState?) { + Card(modifier = Modifier.fillMaxWidth()) { + Column( + modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) + ) { + Text( + text = stringResource(Res.string.balance), + style = MaterialTheme.typography.titleMedium, + ) + Text( + text = walletState?.let { stringResource(Res.string.s_sats, it.confirmedBalance.grouped()) } + ?: stringResource(Res.string.balance_not_known_yet), + style = MaterialTheme.typography.headlineMedium, + ) + walletState?.pendingBalance?.takeIf { it.sat > 0 }?.let { pending -> + Text( + text = stringResource(Res.string.s_sats_on_the_way, pending.grouped()), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } +} + +@Composable +private fun CoinRow(utxo: GroupUtxo, confirmations: Int) { + ListItem( + leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) }, + headlineContent = { Text(stringResource(Res.string.s_sats, utxo.amount.grouped())) }, + supportingContent = { + val branch = stringResource( + if (utxo.derivation.change == GroupWalletDerivation.CHANGE) Res.string.change else Res.string.received + ) + val depth = if (confirmations == 0) { + stringResource(Res.string.waiting_for_a_confirmation) + } else { + stringResource(Res.string.s_confirmations, confirmations.toString()) + } + Text(text = stringResource(Res.string.s_dot_s, branch, depth), maxLines = 1, overflow = TextOverflow.Ellipsis) + } + ) +} 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 8600d16e..23acce26 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 @@ -52,6 +52,7 @@ import com.machankura.bennu.compose.ui.composable.ProposeGroupEventScreen import com.machankura.bennu.compose.ui.composable.EditGroupRelaysScreen import com.machankura.bennu.compose.ui.composable.GroupNostrProfileScreen import com.machankura.bennu.compose.ui.composable.GroupRelaysScreen +import com.machankura.bennu.compose.ui.composable.GroupWalletScreen import com.machankura.bennu.compose.ui.composable.GroupPostsScreen import com.machankura.bennu.compose.ui.composable.GroupCuratedSchemasScreen import com.machankura.bennu.compose.ui.composable.GroupCuratedEntriesScreen @@ -160,6 +161,9 @@ import com.machankura.bennu.compose.ui.composable.navigation.routes.ProposeGroup import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupRelaysRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupNostrProfileRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupRelaysRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletRoute +import com.machankura.bennu.compose.wallet.GroupChainWallets +import fr.acinq.phoenix.managers.NodeParamsManager import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupPostsRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupCuratedSchemasRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupCuratedEntriesRoute @@ -263,6 +267,19 @@ 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. + val activeIdentityForWallets by sovereignWalletViewModel.activeIdentity.collectAsState() + val groupChainWallets = remember(activeIdentityForWallets?.business) { + activeIdentityForWallets?.business?.let { GroupChainWallets(it.electrumClient, applicationIOScope) } + } + DisposableEffect(groupChainWallets) { + onDispose { groupChainWallets?.let { wallets -> applicationIOScope.launch { wallets.stop() } } } + } + val navigationViewModel: NavigationViewModel = viewModel ( factory = NavigationViewModel.factory( activeIdentity = sovereignWalletViewModel.activeIdentity, @@ -1211,6 +1228,24 @@ fun BennuNavHost( } ) } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + GroupWalletScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + chain = NodeParamsManager.chain, + chatRepository = databaseChatRepository, + frostSigningRepository = databaseFrostSigningRepository, + wallets = groupChainWallets, + onNavigateToRoute = { actionRoute -> + navController.navigate(route = actionRoute) + }, + onNavigateBack = { + navController.popBackStack() + } + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() 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 new file mode 100644 index 00000000..bf05425f --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupWalletRoute.kt @@ -0,0 +1,14 @@ +package com.machankura.bennu.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** + * The group's on-chain wallet: its balance, the address to be paid at, its + * coins, and -- for a group that has not opened one -- the way to ask it to. + */ +@Serializable +data class GroupWalletRoute( + val activeUserPublicKey: String, + val chatRoomId: String, + val relayHint: String? +): 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 c4faee87..23c1cfaa 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 fr.acinq.phoenix.managers.NodeParamsManager import com.machankura.bennu.compose.nostr.MarmotProfile import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue @@ -98,6 +99,7 @@ class ChatRoomDetailViewModel( groupPosts = chatRepository.groupPosts(chatRoomId), groupCuratedSchemas = chatRepository.groupCuratedSchemas(chatRoomId), groupCuratedEntries = chatRepository.groupCuratedEntries(chatRoomId), + groupWallet = chatRepository.groupWallet(chatRoomId, NodeParamsManager.chain), canEditNostrProfile = canSign, canAddSubgroup = canSign, canGovern = canGovern, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt new file mode 100644 index 00000000..b21c1ec9 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt @@ -0,0 +1,156 @@ +package com.machankura.bennu.compose.ui.view.model + +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import co.touchlab.kermit.Logger +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.FrostSigningRepository +import com.machankura.bennu.compose.ui.view.state.GroupWalletUIState +import com.machankura.bennu.compose.wallet.GroupChainWallets +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Chain +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * The group's wallet, read once for what the group has signed and then watched + * for what the chain says. + * + * The statement is a read, like every other group-signed thing's screen; the + * coins are a watch, because a payment arriving while the screen is open is the + * one moment somebody is looking at it. + * + * [wallets] is null for a profile with no node of its own -- an nsec or an npub + * -- which can see that the group keeps a wallet, and cannot see the chain. + */ +class GroupWalletViewModel( + val activeUserPublicKey: HexKey, + val chatRoomId: String, + val chain: Chain, + initialGroupWalletUIState: GroupWalletUIState, + val chatRepository: ChatRepository, + val frostSigningRepository: FrostSigningRepository, + private val wallets: GroupChainWallets?, +): ViewModel() { + private val logger = Logger.withTag(TAG) + + var groupWalletUIState: GroupWalletUIState by mutableStateOf(initialGroupWalletUIState) + private set + + val isActionPending: MutableState = mutableStateOf(false) + + private var watching: Job? = null + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) + if (localChatRoom == null) { + groupWalletUIState = GroupWalletUIState.Error("Couldn't find the group") + return@launch + } + + val canSign = localChatRoom.chatRoom.mlsGroupState != null && chatRepository.canSign(chatRoomId) + val wallet = chatRepository.groupWallet(chatRoomId, chain) + + if (wallet == null) { + groupWalletUIState = GroupWalletUIState.NotOpened( + localChatRoom = localChatRoom, + account = chatRepository.groupWalletAccount(chatRoomId, chain), + canSign = canSign, + ) + return@launch + } + + val loaded = GroupWalletUIState.Loaded( + localChatRoom = localChatRoom, + wallet = wallet, + walletState = null, + canWatch = wallets != null, + canSign = canSign, + ) + groupWalletUIState = loaded + + val chainWallet = wallets?.walletFor(wallet.account) ?: return@launch + watching?.cancel() + watching = viewModelScope.launch(Dispatchers.IO) { + chainWallet.state.collect { state -> + groupWalletUIState = loaded.copy(walletState = state) + } + } + } + } + + /** + * Asks the group to open its wallet: one signing session over one statement. + * + * Never batched with anything, for the reason `GroupWalletStatementEvent` + * gives -- every spend is opened against this, and it should never be as + * available as its worst co-passenger. + */ + fun openWallet(onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { + val state = groupWalletUIState as? GroupWalletUIState.NotOpened ?: return + val account = state.account ?: return + // A second statement for the same account is harmless -- the same values + // under the same `d` tag -- but it is a second quorum asked for nothing. + if (isActionPending.value) return + isActionPending.value = true + + val template = GroupWalletStatementEvent.template(account) + + viewModelScope.launch(Dispatchers.IO) { + val session = runCatching { + frostSigningRepository.proposeSigning( + localChatRoom = state.localChatRoom, + userPublicKey = activeUserPublicKey, + kind = template.kind, + tags = template.tags, + content = template.content, + ) + }.onFailure { error -> + logger.e("Failed to propose a wallet for $chatRoomId", error) + }.getOrNull() + + withContext(Dispatchers.Main) { + if (session != null) onSuccess(session.id) else onFailure() + } + + isActionPending.value = false + } + } + + companion object { + private const val TAG = "GroupWalletViewModel" + + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + chain: Chain, + initialGroupWalletUIState: GroupWalletUIState = GroupWalletUIState.Loading, + chatRepository: ChatRepository, + frostSigningRepository: FrostSigningRepository, + wallets: GroupChainWallets?, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + GroupWalletViewModel( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + chain = chain, + initialGroupWalletUIState = initialGroupWalletUIState, + chatRepository = chatRepository, + frostSigningRepository = frostSigningRepository, + wallets = wallets, + ) + } + } + } +} 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 75f3e339..2e505c04 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 @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.ui.view.state +import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.machankura.bennu.compose.database.model.GroupKeyState import com.machankura.bennu.compose.managers.SubgroupManager @@ -108,6 +109,14 @@ sealed interface ChatRoomDetailUIState { * nothing, which is every group until a quorum signs an entry. */ val groupCuratedEntries: List = emptyList(), + /** + * The wallet this group has opened on the app's network, or null for one + * it has not. Under the identity block because it is not part of the + * group's account of itself on nostr -- nobody outside the room reads it -- + * and the row says only whether it is open; the coins are read on + * `GroupWalletScreen`. + */ + val groupWallet: 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/ui/view/state/GroupWalletUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt new file mode 100644 index 00000000..ab31c141 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt @@ -0,0 +1,43 @@ +package com.machankura.bennu.compose.ui.view.state + +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.nostr.wallet.GroupWallet +import com.machankura.bennu.compose.wallet.GroupWalletState + +sealed interface GroupWalletUIState { + /** + * A room whose group has not signed a wallet statement. + * + * [account] is what a statement would carry, or null for a room with no key + * at all -- there is nothing to open then. [canSign] gates the way in, for + * the reason every proposing screen gives: `proposeSigning` throws for a + * device holding no share. + */ + data class NotOpened( + val localChatRoom: LocalChatRoom, + val account: GroupWalletDerivation.Account?, + val canSign: Boolean, + ): GroupWalletUIState + + /** + * An open wallet. + * + * [walletState] is null in two different situations, told apart by + * [canWatch]: before Electrum's first answer, and for a profile with no node + * to watch the chain with at all. + */ + data class Loaded( + val localChatRoom: LocalChatRoom, + val wallet: GroupWallet, + val walletState: GroupWalletState?, + val canWatch: Boolean, + val canSign: Boolean, + ): GroupWalletUIState + + data class Error( + val message: String + ): GroupWalletUIState + + data object Loading: GroupWalletUIState +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainWallet.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainWallet.kt index 1421040b..60c643ab 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainWallet.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainWallet.kt @@ -167,3 +167,6 @@ data class GroupWalletState( .map { (branch, index) -> GroupWalletDerivation.derive(account, branch, index) } .firstOrNull { it.pubkeyScript == script } } + +/** A BIP21 URI for [address], so a scanning wallet knows what the text it read is. */ +fun bip21Uri(address: String): String = "bitcoin:$address" diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt new file mode 100644 index 00000000..98500b64 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt @@ -0,0 +1,169 @@ +package com.machankura.bennu.compose.ui.view.model + +import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.FrostSigningSession +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.nostr.wallet.GroupWallet +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.FrostSigningRepository +import com.machankura.bennu.compose.ui.view.state.GroupWalletUIState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.secp256k1.Hex +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.time.Instant + +/** + * What the wallet screen's view model decides: which of its states a room is in, + * and what it asks the group to sign when a member opens a wallet. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class GroupWalletViewModelJvmTest { + @BeforeTest + fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) + + @AfterTest + fun tearDown() = Dispatchers.resetMain() + + private val chatRoomId = "d4c3b2a1".repeat(8) + private val me = "a".repeat(64) + + private val localChatRoom = LocalChatRoom( + chatRoom = ChatRoom( + id = chatRoomId, + userPublicKey = me, + subject = "Treasury", + description = null, + initialGiftWrapPayloadId = "payload", + mlsGroupState = "state", + ) + ) + + private val account = GroupWalletDerivation.account( + PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString(), + Chain.Mainnet, + ) + + /** The repository's answer is the thing under test's input; the statement's own checks are `GroupWalletStatementEventTest`'s. */ + private val wallet = GroupWallet( + signedEvent = GroupSignedEvent( + id = "e".repeat(64), + chatRoomId = chatRoomId, + publicKey = chatRoomId, + kind = GroupWalletStatementEvent.KIND, + tags = GroupWalletStatementEvent.template(account).tags, + content = account.xpub, + signature = "f".repeat(128), + createdAt = Instant.fromEpochSeconds(1_700_000_000), + ), + account = account, + ) + + private fun repository(opened: GroupWallet?, canSign: Boolean = true, hasKey: Boolean = true) = + object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { + override suspend fun getChatRoomByIdentifier(identifier: String): LocalChatRoom? = localChatRoom + override suspend fun canSign(chatRoomId: String): Boolean = canSign + override suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? = opened + override suspend fun groupWalletAccount(chatRoomId: String, chain: Chain): GroupWalletDerivation.Account? = + account.takeIf { hasKey } + } + + private class RecordingSigning : FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY { + var proposed: Triple>, String>? = null + + override suspend fun proposeSigning( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + kind: Kind, + tags: Array>, + content: String, + ): FrostSigningSession? { + proposed = Triple(kind, tags, content) + return null + } + } + + private fun viewModel(chat: ChatRepository, signing: FrostSigningRepository = RecordingSigning()) = + GroupWalletViewModel( + activeUserPublicKey = me, + chatRoomId = chatRoomId, + chain = Chain.Mainnet, + initialGroupWalletUIState = GroupWalletUIState.Loading, + chatRepository = chat, + frostSigningRepository = signing, + wallets = null, + ) + + private fun GroupWalletViewModel.settled(): GroupWalletUIState = runBlocking { + withTimeout(5_000) { + while (groupWalletUIState == GroupWalletUIState.Loading) delay(10) + groupWalletUIState + } + } + + @Test + fun `a group that has not opened a wallet is offered the account it would open`() { + val state = assertIs(viewModel(repository(opened = null)).apply { initiate() }.settled()) + + assertEquals(account, state.account) + assertEquals(true, state.canSign) + } + + @Test + fun `a room with no key has nothing to open`() { + val state = assertIs( + viewModel(repository(opened = null, hasKey = false)).apply { initiate() }.settled() + ) + + assertNull(state.account) + } + + @Test + fun `an open wallet on a profile with no node is shown, and says it cannot watch`() { + val state = assertIs(viewModel(repository(opened = wallet)).apply { initiate() }.settled()) + + assertEquals(wallet, state.wallet) + assertFalse(state.canWatch) + assertNull(state.walletState) + } + + @Test + fun `opening a wallet proposes the statement for the account, and nothing else`() { + val signing = RecordingSigning() + val model = viewModel(repository(opened = null), signing).apply { initiate() } + model.settled() + + var failed = false + model.openWallet(onSuccess = {}, onFailure = { failed = true }) + runBlocking { withTimeout(5_000) { while (signing.proposed == null || model.isActionPending.value) delay(10) } } + + val (kind, tags, content) = assertNotNull(signing.proposed) + assertEquals(GroupWalletStatementEvent.KIND, kind) + assertEquals(account.xpub, content) + assertEquals(account, GroupWalletStatementEvent.read(tags, content)?.verifiedAgainst( + PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString() + )) + runBlocking { withTimeout(5_000) { while (!failed) delay(10) } } + } +} diff --git a/docs/group-chain-wallet.md b/docs/group-chain-wallet.md index 20ef8435..fcd7b018 100644 --- a/docs/group-chain-wallet.md +++ b/docs/group-chain-wallet.md @@ -29,6 +29,9 @@ kept as written; where the build chose differently the table below says so. | the transcript line is checked by signature | by signature *and* rederivation, through `GroupWallet.of` — a line people will send money on is held to the same check as the wallet screen | | `GroupWalletManager` starts a wallet for every room with a statement, under the identity's `collectLatest` | `GroupChainWallets`, one per identity, makes a room's wallet the first time its screen asks and keeps it for the identity's life. Starting every room's at launch would subscribe a member in twenty groups to two hundred addresses before they looked at one; `GroupWalletManager` kept the reads (the key, the account, the statement) and nothing that runs | | `receiveAddress` is the first unused address | it is, and that is `ElectrumMiniWallet`'s rule: the *lowest* unused index, so a gap below a paid address is refilled before the next one is offered. Null until Electrum has answered, rather than `/0/0` | +| members who can sign see *Open a group wallet* on the group's screen; others see nothing | every member sees a *Group wallet* row, saying *Open on mainnet* or *Not opened yet*; the open action lives on the wallet screen's empty state, behind the same `canSign` gate, with Phase 10's sentence about unencrypted shares above the button | +| the wallet's network is the identity's | `NodeParamsManager.chain`, read statically. An nsec or npub profile has no node, and still has to know which network's statement to look for | +| `GroupChainWallets` started under the identity's `collectLatest` | made in `BennuNavHost`, remembered on the identity's `PhoenixBusiness` and stopped in a `DisposableEffect` when it changes — the same lifetime, held where the business already is | The headline: **the best path is BIP86's own unhardened tail, `//`, hung under an account key the group's threshold key is tweaked to, with the