diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index b5816a43..8789c2de 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -586,4 +586,28 @@ This group's guardian keys can't be read by this version of the app. Guarded wallets for members aren't offered on this network yet. This profile has no wallet of its own to watch the chain with, so it couldn't see its own coins. + You have no guarded wallets. + Waiting for someone in %1$s to put it to the group + %1$s is signing + %1$s didn't sign. Ask again, or discard it. + Key on another device + You're no longer in %1$s. It still guards this wallet. + Guarded by %1$s + Discard + Discard this wallet? + Its key is forgotten. No address of it was ever offered, so nothing can have been paid to it. + Export key + Export this wallet's key? + Whoever holds these descriptors can spend every coin in this wallet. Keep them where only you can reach them. + Show key + Receive descriptor + Change descriptor + Copied. + Copy + Finding your coins… + %1$s took %2$s sats through its guardian leaf, in %3$s. + Taken by guardians + This wallet's key is on another of your devices, so it can be watched here but not spent from. + Couldn't ask again. + Couldn't discard the wallet. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/BennuDatabase.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/BennuDatabase.kt index e6eb68be..7da2744a 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/BennuDatabase.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/BennuDatabase.kt @@ -471,6 +471,11 @@ abstract class BennuDatabase: RoomDatabase() { useWriterConnection { transactor -> transactor.immediateTransaction { // TODO: Actually delete the data... + // + // When this does: MemberWallet holds the only copy of keys that + // coins may sit behind (docs/member-guarded-wallets.md, D6). A + // caller wiping a profile that holds an open member wallet has to + // say so first and offer the key's export, before anything goes. } } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMemberWalletRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMemberWalletRepository.kt index 4e86cf57..31aebf02 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMemberWalletRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMemberWalletRepository.kt @@ -46,6 +46,42 @@ class DatabaseMemberWalletRepository( return MemberWalletManager.request(database, chatRoomId, key, chain, label) } + override suspend fun walletsOf(ownerPublicKey: HexKey): List = try { + MemberWalletManager.walletsOf(database, ownerPublicKey) + } catch (e: Throwable) { + // A profile that lists no wallets is wrong and survivable; one that will + // not open because reading them threw is neither. + logger.e("Error reading $ownerPublicKey's guarded wallets", e) + emptyList() + } + + override suspend fun walletOf(ownerPublicKey: HexKey, walletId: String): MemberWalletManager.MemberWalletRow? = try { + MemberWalletManager.walletOf(database, ownerPublicKey, walletId) + } catch (e: Throwable) { + logger.e("Error reading guarded wallet $walletId", e) + null + } + + override suspend fun askAgain(walletId: String) { + val wallet = database.memberWalletDao().getById(walletId) ?: throw IllegalStateException("No key for $walletId here") + check(wallet.ownerPublicKey == activeIdentity.value?.nostrPublicKey) { "Not this profile's wallet" } + MemberWalletManager.askAgain(database, wallet) + } + + override suspend fun discard(walletId: String) { + val wallet = database.memberWalletDao().getById(walletId) ?: return + check(wallet.ownerPublicKey == activeIdentity.value?.nostrPublicKey) { "Not this profile's wallet" } + MemberWalletManager.discard(database, walletId) + } + + override suspend fun exportKey(walletId: String): Pair? { + val owner = activeIdentity.value?.nostrPublicKey ?: return null + return MemberWalletManager.exportKey(database, owner, walletId) + } + + override suspend fun roomName(chatRoomId: String): String? = + database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.subject?.takeIf { it.isNotBlank() } + companion object { private const val TAG = "DatabaseMemberWalletRepository" } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletDerivation.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletDerivation.kt index fe45cab5..6fa8ec41 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletDerivation.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletDerivation.kt @@ -9,6 +9,7 @@ import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.ByteVector64 import fr.acinq.bitcoin.Chain import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.Descriptor import fr.acinq.bitcoin.DeterministicWallet import fr.acinq.bitcoin.KeyPath import fr.acinq.bitcoin.PrivateKey @@ -104,6 +105,24 @@ object MemberWalletDerivation { return accountPrivateKey(walletPrivateKey, chain).derivePrivateKey(listOf(change, index)).privateKey } + /** + * The receive and change descriptors of [account] with the account's private + * key in place of its xpub -- what any wallet that imports taproot + * descriptors can sweep the coins with. The member's backup of last resort, + * shown only behind a confirmation: whoever holds these holds the coins. + */ + fun privateDescriptors(walletPrivateKey: PrivateKey, account: GroupWalletDerivation.Account): Pair { + val extended = accountPrivateKey(walletPrivateKey, account.chain) + require(extended.extendedPublicKey == account.extendedPublicKey) { "this key does not open this account" } + val xprv = extended.encode(if (account.chain.isMainnet()) DeterministicWallet.xprv else DeterministicWallet.tprv) + + fun swap(descriptor: String): String { + val body = descriptor.substringBefore('#').replaceFirst(account.xpub, xprv) + return "$body#${Descriptor.checksum(body)}" + } + return swap(account.receiveDescriptor) to swap(account.changeDescriptor) + } + /** * The signature [input] of a checked spend needs from the wallet's own key: * the address's private key under the address's taproot tweak, over the diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt index 1d27ef02..5622ce47 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt @@ -248,6 +248,105 @@ object MemberWalletManager { .onFailure { logger.w("Asked $chatRoomId, and could not put it to the group: ${it.message}") } } + /** Where a member's wallet has got to, as one fact the profile shows. */ + enum class WalletState { + /** A key and a request here; nobody has put it to the group yet. */ + ASKED, + + /** A session is running over its certificate. */ + SIGNING, + + /** The session failed or was declined, and the group has not certified it. */ + NOT_SIGNED, + + /** Certified, and the key is on this device. */ + OPEN, + + /** Certified, and the key is on another device of this profile's. */ + WATCH_ONLY, + } + + /** One of a member's guarded wallets, as their profile lists it. */ + data class MemberWalletRow( + val walletId: String, + val groupChatRoomId: String, + /** The guarding group's room on this device, or null when this device is not in it. */ + val groupRoom: LocalChatRoom?, + val label: String?, + val chain: Chain, + /** The account the wallet opens: rederived from the request, guardians and all. */ + val account: GroupWalletDerivation.Account, + val state: WalletState, + /** Whether the member is still a member of the guarding group, as far as this device can see. */ + val isMember: Boolean, + /** The stored key's row, for a wallet whose key is here. Never handed to a screen. */ + internal val stored: MemberWallet?, + ) { + val isCertified: Boolean get() = state == WalletState.OPEN || state == WalletState.WATCH_ONLY + } + + /** + * Every guarded wallet of [ownerPublicKey]'s this device knows about, newest + * first: the ones whose key is here, and the ones a group this device is in + * has certified for this profile -- which includes wallets made on another + * of its devices. + */ + suspend fun walletsOf(database: BennuDatabase, ownerPublicKey: HexKey): List { + val stored = database.memberWalletDao().getByOwner(ownerPublicKey) + val certified = database.groupSignedEventDao().getByKind(MemberWalletCertificateEvent.KIND) + .filter { MemberWalletCertificateEvent.memberOf(it.toEvent()).equals(ownerPublicKey, ignoreCase = true) } + .mapNotNull { MemberWalletCertificateEvent.verify(it.toEvent(), it.chatRoomId) } + .distinctBy { it.walletId } + .associateBy { it.walletId } + + val fromKeys = stored.mapNotNull { wallet -> + val request = Event.fromJsonOrNull(wallet.requestJson) ?: return@mapNotNull null + val verified = MemberWalletRequestEvent.verified(request) ?: return@mapNotNull null + val state = when { + certified.containsKey(wallet.walletId) -> WalletState.OPEN + openSessionFor(database, wallet.guardingChatRoomId, request) != null -> WalletState.SIGNING + wasNotSigned(database, wallet.guardingChatRoomId, request) -> WalletState.NOT_SIGNED + else -> WalletState.ASKED + } + row(database, wallet.walletId, wallet.guardingChatRoomId, wallet.label, verified.account, state, ownerPublicKey, wallet) + } + val elsewhere = certified.values + .filter { cert -> stored.none { it.walletId == cert.walletId } } + .map { row(database, it.walletId, it.groupChatRoomId, it.label, it.account, WalletState.WATCH_ONLY, ownerPublicKey, null) } + + return (fromKeys + elsewhere).sortedByDescending { it.stored?.createdAt?.epochSeconds ?: 0L } + } + + private suspend fun row( + database: BennuDatabase, + walletId: String, + groupChatRoomId: String, + label: String?, + account: GroupWalletDerivation.Account, + state: WalletState, + ownerPublicKey: HexKey, + stored: MemberWallet?, + ): MemberWalletRow { + val room = database.chatRoomDao().findChatRoomById(groupChatRoomId) + val isMember = room == null || database.participantDao().findParticipantsByChatRoomId(groupChatRoomId) + .any { it.participantPublicKey.equals(ownerPublicKey, ignoreCase = true) } + return MemberWalletRow(walletId, groupChatRoomId, room, label, account.chain, account, state, isMember, stored) + } + + /** [ownerPublicKey]'s wallet [walletId], or null when this device knows of none. */ + suspend fun walletOf(database: BennuDatabase, ownerPublicKey: HexKey, walletId: String): MemberWalletRow? = + walletsOf(database, ownerPublicKey).firstOrNull { it.walletId == walletId } + + /** + * [walletId]'s descriptors with its private key in them, or null when the key + * is not on this device. See `MemberWalletDerivation.privateDescriptors`. + */ + suspend fun exportKey(database: BennuDatabase, ownerPublicKey: HexKey, walletId: String): Pair? { + val row = walletOf(database, ownerPublicKey, walletId) ?: return null + val key = row.stored?.walletPrivateKey?.let { PrivateKey.fromHex(it) } ?: return null + return MemberWalletDerivation.privateDescriptors(key, row.account) + } + // ---- The group's side ------------------------------------------------ /** diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MemberWalletRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MemberWalletRepository.kt index e0e7dec6..b93214de 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MemberWalletRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MemberWalletRepository.kt @@ -28,6 +28,24 @@ interface MemberWalletRepository { /** Makes the key, works out the leaves, stores the key, and asks [chatRoomId] to guard it. */ suspend fun request(chatRoomId: String, chain: Chain, label: String?): MemberWallet + /** Every guarded wallet of [ownerPublicKey]'s this device knows about, newest first. */ + suspend fun walletsOf(ownerPublicKey: HexKey): List + + /** One of them, or null. */ + suspend fun walletOf(ownerPublicKey: HexKey, walletId: String): MemberWalletManager.MemberWalletRow? + + /** Asks the group again, with the request the wallet was first asked with. */ + suspend fun askAgain(walletId: String) + + /** Forgets a wallet's key -- refused once a group guards it. */ + suspend fun discard(walletId: String) + + /** The wallet's receive and change descriptors with its private key in them, or null when the key is not here. */ + suspend fun exportKey(walletId: String): Pair? + + /** What [chatRoomId] is called on this device, or null when it has no room for it. */ + suspend fun roomName(chatRoomId: String): String? + companion object { val NO_OP = object : MemberWalletRepository { override suspend fun groupsOf(ownerPublicKey: HexKey): List = emptyList() @@ -36,6 +54,12 @@ interface MemberWalletRepository { override suspend fun askForGroupKey(chatRoomId: String): Boolean = false override suspend fun request(chatRoomId: String, chain: Chain, label: String?): MemberWallet = throw UnsupportedOperationException("no repository") + override suspend fun walletsOf(ownerPublicKey: HexKey): List = emptyList() + override suspend fun walletOf(ownerPublicKey: HexKey, walletId: String): MemberWalletManager.MemberWalletRow? = null + override suspend fun askAgain(walletId: String) = Unit + override suspend fun discard(walletId: String) = Unit + override suspend fun exportKey(walletId: String): Pair? = null + override suspend fun roomName(chatRoomId: String): String? = null } } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ActiveProfileScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ActiveProfileScreen.kt index 4017c0ef..6c153fa9 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ActiveProfileScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ActiveProfileScreen.kt @@ -1,5 +1,10 @@ package com.machankura.bennu.compose.ui.composable +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.wallet.GroupOnchainWallets +import com.machankura.bennu.compose.ui.view.model.MemberWalletsViewModel +import com.machankura.bennu.compose.ui.composable.navigation.routes.MemberWalletRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.NewMemberWalletRoute import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -99,6 +104,11 @@ fun ActiveProfileScreen( // an identity to sign out of (previews, tests), in which case the button keeps its // pending route for every kind. signOut: SignOutDependencies? = null, + // The member's guarded wallets (docs/member-guarded-wallets.md). The no-op + // repository lists none, for previews and tests; null wallets is a profile + // that cannot watch the chain, whose rows show no balance. + memberWalletRepository: MemberWalletRepository = MemberWalletRepository.NO_OP, + wallets: GroupOnchainWallets? = null, ) { // Whether this identity can sign, which decides which rows below exist. @@ -130,6 +140,16 @@ fun ActiveProfileScreen( if (signOutState is SignOutViewModel.State.Failed) notify(couldNotSignOut) } + val memberWalletsViewModel: MemberWalletsViewModel = viewModel( + factory = MemberWalletsViewModel.factory( + ownerPublicKey = activeUserPublicKey, + memberWalletRepository = memberWalletRepository, + wallets = wallets, + ), + ) + // Each time the profile is shown: a certificate can arrive while it is not. + LaunchedEffect(true) { memberWalletsViewModel.refresh() } + val activeProfileViewModel: ActiveProfileViewModel = viewModel( factory = ActiveProfileViewModel.factory( nostrEventId = nostrEventId, @@ -272,6 +292,17 @@ fun ActiveProfileScreen( } } + memberWalletItems( + rows = memberWalletsViewModel.rows, + onOpen = { walletId -> + onNavigateToRoute.invoke(MemberWalletRoute(activeUserPublicKey = activeUserPublicKey, walletId = walletId)) + }, + // A read-only identity cannot sign a request, so it is not offered one. + onNew = if (canSign) { + { onNavigateToRoute.invoke(NewMemberWalletRoute(activeUserPublicKey = activeUserPublicKey)) } + } else null, + ) + // Key packages are signed, and there is nothing to recover for // an identity the device holds no secret for: neither row for a // read-only identity. 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 65b06227..6043aeb0 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 @@ -714,7 +714,7 @@ private fun LazyListScope.guardianItems( } @Composable -private fun BalanceCard(walletState: GroupWalletState?) { +internal fun BalanceCard(walletState: GroupWalletState?) { Card(modifier = Modifier.fillMaxWidth()) { Column( modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), @@ -741,7 +741,7 @@ private fun BalanceCard(walletState: GroupWalletState?) { } @Composable -private fun CoinRow(utxo: GroupUtxo, confirmations: Int) { +internal fun CoinRow(utxo: GroupUtxo, confirmations: Int) { ListItem( leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) }, headlineContent = { Text(stringResource(Res.string.s_sats, utxo.amount.grouped())) }, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletItems.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletItems.kt new file mode 100644 index 00000000..9b6bfeee --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletItems.kt @@ -0,0 +1,112 @@ +package com.machankura.bennu.compose.ui.composable + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AccountBalanceWallet +import androidx.compose.material.icons.filled.Add +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.minimumInteractiveComponentSize +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import bennu.composeapp.generated.resources.Res +import bennu.composeapp.generated.resources.a_group +import bennu.composeapp.generated.resources.balance_not_known_yet +import bennu.composeapp.generated.resources.guarded_wallets +import bennu.composeapp.generated.resources.key_on_another_device +import bennu.composeapp.generated.resources.new_guarded_wallet +import bennu.composeapp.generated.resources.s_did_not_sign +import bennu.composeapp.generated.resources.s_dot_s +import bennu.composeapp.generated.resources.s_is_signing +import bennu.composeapp.generated.resources.s_sats +import bennu.composeapp.generated.resources.waiting_for_someone_in_s_to_put_it_to_the_group +import bennu.composeapp.generated.resources.you_have_no_guarded_wallets +import bennu.composeapp.generated.resources.you_re_no_longer_in_s +import com.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.text.grouped +import com.machankura.bennu.compose.ui.composable.widgets.Decorative +import com.machankura.bennu.compose.ui.composable.widgets.EmptyState +import com.machankura.bennu.compose.ui.theme.spacing +import com.machankura.bennu.compose.ui.view.model.MemberWalletsViewModel +import org.jetbrains.compose.resources.stringResource + +/** + * A member's guarded wallets, on their own profile: one row per wallet, named + * for the group that guards it, and the way to ask for another. + * `docs/member-guarded-wallets.md`, Phase 8. + * + * Never published. A profile's kind 0 is public, and a member wallet's xpub + * never leaves an encryption. + */ +fun LazyListScope.memberWalletItems( + rows: List?, + onOpen: (walletId: String) -> Unit, + onNew: (() -> Unit)?, +) { + item { + Text( + modifier = Modifier.fillMaxWidth(), + text = stringResource(Res.string.guarded_wallets), + style = MaterialTheme.typography.titleMedium, + ) + } + + when { + rows == null -> Unit + rows.isEmpty() -> item { EmptyState(message = stringResource(Res.string.you_have_no_guarded_wallets), icon = Icons.Default.AccountBalanceWallet) } + else -> items(rows, key = { "member-wallet-" + it.wallet.walletId }) { row -> + ListItem( + modifier = Modifier.clickable { onOpen(row.wallet.walletId) }.minimumInteractiveComponentSize(), + leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) }, + headlineContent = { + val group = groupNameOf(row.wallet) + Text( + text = row.wallet.label?.let { stringResource(Res.string.s_dot_s, group, it) } ?: group, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + }, + supportingContent = { Text(supportingLine(row)) }, + ) + } + } + + onNew?.let { new -> + item { + TextButton(onClick = new) { + Icon(Icons.Default.Add, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.new_guarded_wallet)) + } + } + } +} + +/** The guarding group as the member's rows name it: the room's name here, or a generic one. */ +@Composable +internal fun groupNameOf(wallet: MemberWalletManager.MemberWalletRow): String = + wallet.groupRoom?.chatRoom?.subject?.takeIf { it.isNotBlank() } ?: stringResource(Res.string.a_group) + +@Composable +private fun supportingLine(row: MemberWalletsViewModel.Row): String { + val group = groupNameOf(row.wallet) + if (!row.wallet.isMember) return stringResource(Res.string.you_re_no_longer_in_s, group) + val balance = row.walletState?.let { stringResource(Res.string.s_sats, it.confirmedBalance.grouped()) } + ?: stringResource(Res.string.balance_not_known_yet) + return when (row.wallet.state) { + MemberWalletManager.WalletState.ASKED -> stringResource(Res.string.waiting_for_someone_in_s_to_put_it_to_the_group, group) + MemberWalletManager.WalletState.SIGNING -> stringResource(Res.string.s_is_signing, group) + MemberWalletManager.WalletState.NOT_SIGNED -> stringResource(Res.string.s_did_not_sign, group) + MemberWalletManager.WalletState.OPEN -> balance + MemberWalletManager.WalletState.WATCH_ONLY -> stringResource(Res.string.s_dot_s, balance, stringResource(Res.string.key_on_another_device)) + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletScreen.kt new file mode 100644 index 00000000..afbd1f17 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletScreen.kt @@ -0,0 +1,378 @@ +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.rememberScrollState +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.Key +import androidx.compose.material.icons.filled.Send +import androidx.compose.material3.Button +import androidx.compose.material3.AlertDialog +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.OutlinedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +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.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +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.a_group +import bennu.composeapp.generated.resources.address_copied +import bennu.composeapp.generated.resources.ask_again +import bennu.composeapp.generated.resources.cancel +import bennu.composeapp.generated.resources.change_descriptor +import bennu.composeapp.generated.resources.close +import bennu.composeapp.generated.resources.coins +import bennu.composeapp.generated.resources.copied +import bennu.composeapp.generated.resources.copy_address +import bennu.composeapp.generated.resources.couldn_t_ask_again +import bennu.composeapp.generated.resources.couldn_t_discard_the_wallet +import bennu.composeapp.generated.resources.discard +import bennu.composeapp.generated.resources.discard_this_wallet_question +import bennu.composeapp.generated.resources.discarding_forgets_its_key +import bennu.composeapp.generated.resources.export_key +import bennu.composeapp.generated.resources.export_this_wallet_s_key_question +import bennu.composeapp.generated.resources.finding_your_coins +import bennu.composeapp.generated.resources.copy +import bennu.composeapp.generated.resources.send +import bennu.composeapp.generated.resources.guarded_by_s +import bennu.composeapp.generated.resources.guarded_wallet +import bennu.composeapp.generated.resources.if_you_lose_this_device_those_groups_can_still_move_your_coins +import bennu.composeapp.generated.resources.nothing_has_been_sent_to_this_wallet_yet +import bennu.composeapp.generated.resources.receive_address +import bennu.composeapp.generated.resources.receive_descriptor +import bennu.composeapp.generated.resources.s_did_not_sign +import bennu.composeapp.generated.resources.s_is_signing +import bennu.composeapp.generated.resources.s_took_s_sats_in_s +import bennu.composeapp.generated.resources.show_key +import bennu.composeapp.generated.resources.taken_by_guardians +import bennu.composeapp.generated.resources.the_key_of_this_wallet_is_on_another_device +import bennu.composeapp.generated.resources.this_profile_cannot_watch_its_own_coins +import bennu.composeapp.generated.resources.waiting_for_someone_in_s_to_put_it_to_the_group +import bennu.composeapp.generated.resources.whoever_holds_these_descriptors_holds_the_coins +import bennu.composeapp.generated.resources.you_re_no_longer_in_s +import com.machankura.bennu.compose.managers.MemberWalletManager.WalletState +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.text.grouped +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.MemberWalletViewModel +import com.machankura.bennu.compose.ui.view.state.MemberWalletUIState +import com.machankura.bennu.compose.wallet.GroupOnchainWallets +import com.machankura.bennu.compose.wallet.bip21Uri +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import org.jetbrains.compose.resources.stringResource + +/** + * One of the member's guarded wallets. + * + * Before a group has certified it, where the asking has got to and the two + * things the member can do about it: ask again, or discard the key -- which is + * safe exactly then, because no address was ever offered. Once certified, the + * wallet itself: balance, the address to be paid at, the coins, and every coin + * a guardian took, read off the chain. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun MemberWalletScreen( + activeUserPublicKey: HexKey, + walletId: String, + initialUIState: MemberWalletUIState = MemberWalletUIState.Loading, + memberWalletRepository: MemberWalletRepository, + wallets: GroupOnchainWallets?, + /** The send form for this wallet, or null where there is none to offer. */ + onSend: ((walletId: String) -> Unit)? = null, + onNavigateBack: () -> Unit, +) { + val viewModel: MemberWalletViewModel = viewModel( + factory = MemberWalletViewModel.factory( + ownerPublicKey = activeUserPublicKey, + walletId = walletId, + initialUIState = initialUIState, + memberWalletRepository = memberWalletRepository, + wallets = wallets, + ) + ) + + LaunchedEffect(true) { + if (initialUIState == MemberWalletUIState.Loading) viewModel.initiate() + } + + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotAskAgain = stringResource(Res.string.couldn_t_ask_again) + val couldNotDiscard = stringResource(Res.string.couldn_t_discard_the_wallet) + val addressCopied = stringResource(Res.string.address_copied) + val copied = stringResource(Res.string.copied) + val clipboardManager = LocalClipboardManager.current + + var confirmingDiscard by remember { mutableStateOf(false) } + var confirmingExport by remember { mutableStateOf(false) } + + val title = (viewModel.uiState as? MemberWalletUIState.Loaded)?.wallet?.label ?: stringResource(Res.string.guarded_wallet) + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + } + ) { padding -> + ScreenStateTransition(viewModel.uiState) { uiState -> + when (val state = uiState) { + MemberWalletUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) + + // Nothing to retry: the wallet came from a navigation argument. + is MemberWalletUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null) + + is MemberWalletUIState.Loaded -> { + val wallet = state.wallet + val group = wallet.groupRoom?.chatRoom?.subject?.takeIf { it.isNotBlank() } ?: stringResource(Res.string.a_group) + val walletState = state.walletState + + LazyColumn( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + item { Text(stringResource(Res.string.guarded_by_s, group), style = MaterialTheme.typography.titleMedium) } + item { + Text( + reachText(group, state.reach), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (!wallet.isMember) item { Text(stringResource(Res.string.you_re_no_longer_in_s, group)) } + + when (wallet.state) { + WalletState.ASKED, WalletState.SIGNING, WalletState.NOT_SIGNED -> { + item { + Text( + stringResource( + when (wallet.state) { + WalletState.SIGNING -> Res.string.s_is_signing + WalletState.NOT_SIGNED -> Res.string.s_did_not_sign + else -> Res.string.waiting_for_someone_in_s_to_put_it_to_the_group + }, + group, + ) + ) + } + if (wallet.state != WalletState.SIGNING) { + item { + OutlinedButton( + onClick = { viewModel.askAgain(onAsked = {}, onFailure = { notify(couldNotAskAgain) }) }, + enabled = !viewModel.isActionPending.value, + ) { Text(stringResource(Res.string.ask_again)) } + } + item { + TextButton(onClick = { confirmingDiscard = true }, enabled = !viewModel.isActionPending.value) { + Text(stringResource(Res.string.discard)) + } + } + } + } + + WalletState.OPEN, WalletState.WATCH_ONLY -> { + item { BalanceCard(walletState) } + + if (wallet.state == WalletState.WATCH_ONLY) { + item { + Text( + stringResource(Res.string.the_key_of_this_wallet_is_on_another_device), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + onSend?.takeIf { wallet.state == WalletState.OPEN && state.canWatch }?.let { send -> + item { SendButton(onClick = { send(wallet.walletId) }) } + } + + when { + !state.canWatch -> item { + Text( + stringResource(Res.string.this_profile_cannot_watch_its_own_coins), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + walletState?.receiveAddress == null -> item { + LoadingDataIndicator(fillScreen = false, text = stringResource(Res.string.finding_your_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(stringResource(Res.string.receive_address), style = MaterialTheme.typography.titleMedium) + 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(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)) + } + } + } + } + + if (state.taken.isNotEmpty()) { + item { Text(stringResource(Res.string.taken_by_guardians), style = MaterialTheme.typography.titleMedium) } + items(state.taken, key = { "taken-" + it.txid + it.guardianName }) { line -> + ListItem( + headlineContent = { + Text(stringResource(Res.string.s_took_s_sats_in_s, line.guardianName ?: stringResource(Res.string.a_group), line.amount.grouped(), line.txid)) + } + ) + } + } + + if (wallet.state == WalletState.OPEN) { + item { + TextButton(onClick = { confirmingExport = true }) { + Icon(Icons.Default.Key, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.export_key)) + } + } + } + } + } + + item { + Text( + stringResource(Res.string.if_you_lose_this_device_those_groups_can_still_move_your_coins), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } + } + } + + if (confirmingDiscard) { + AlertDialog( + onDismissRequest = { confirmingDiscard = false }, + title = { Text(stringResource(Res.string.discard_this_wallet_question)) }, + text = { Text(stringResource(Res.string.discarding_forgets_its_key)) }, + confirmButton = { + TextButton(onClick = { + confirmingDiscard = false + viewModel.discard(onDiscarded = onNavigateBack, onFailure = { notify(couldNotDiscard) }) + }) { Text(stringResource(Res.string.discard)) } + }, + dismissButton = { TextButton(onClick = { confirmingDiscard = false }) { Text(stringResource(Res.string.cancel)) } }, + ) + } + + if (confirmingExport) { + AlertDialog( + onDismissRequest = { confirmingExport = false }, + title = { Text(stringResource(Res.string.export_this_wallet_s_key_question)) }, + text = { Text(stringResource(Res.string.whoever_holds_these_descriptors_holds_the_coins)) }, + confirmButton = { + TextButton(onClick = { + confirmingExport = false + viewModel.exportKey() + }) { Text(stringResource(Res.string.show_key)) } + }, + dismissButton = { TextButton(onClick = { confirmingExport = false }) { Text(stringResource(Res.string.cancel)) } }, + ) + } + + viewModel.exported?.let { (receive, change) -> + AlertDialog( + onDismissRequest = viewModel::hideKey, + title = { Text(stringResource(Res.string.export_key)) }, + text = { + Column( + modifier = Modifier.verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + listOf(Res.string.receive_descriptor to receive, Res.string.change_descriptor to change).forEach { (name, descriptor) -> + Text(stringResource(name), style = MaterialTheme.typography.titleSmall) + SelectionContainer { Text(descriptor, style = MaterialTheme.typography.bodySmall) } + TextButton(onClick = { + clipboardManager.setText(buildAnnotatedString { append(descriptor) }) + notify(copied) + }) { + Icon(Icons.Default.ContentCopy, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.copy)) + } + } + } + }, + confirmButton = { TextButton(onClick = viewModel::hideKey) { Text(stringResource(Res.string.close)) } }, + ) + } +} + +@Composable +private fun SendButton(onClick: () -> Unit) { + Button(onClick = onClick) { + Icon(Icons.Default.Send, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.send)) + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/NewMemberWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/NewMemberWalletScreen.kt index 7a8b7ecb..02e393b6 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/NewMemberWalletScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/NewMemberWalletScreen.kt @@ -217,7 +217,7 @@ fun NewMemberWalletScreen( /** Who can take the member's coins: the group alone, the group and its parent, or the group and N above it. */ @Composable -private fun reachText(groupName: String, reach: Int): String { +internal fun reachText(groupName: String, reach: Int): String { val delay = GuardianDerivation.ANCESTOR_DELAY.toInt() return when (reach) { 1 -> stringResource(Res.string.s_can_take_any_coin_without_asking_you, groupName, delay) 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 a049a904..a28dff3b 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 @@ -140,6 +140,8 @@ import kotlinx.coroutines.launch import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletAddressesRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.NewMemberWalletRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.MemberWalletRoute +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 @@ -919,6 +921,8 @@ fun BennuNavHost( ) }, signOut = signOutOfReadOnlyIdentity, + memberWalletRepository = databaseMemberWalletRepository, + wallets = groupOnchainWallets, ) } composable { backStackEntry -> @@ -1156,6 +1160,19 @@ fun BennuNavHost( } ) } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + MemberWalletScreen( + activeUserPublicKey = route.activeUserPublicKey, + walletId = route.walletId, + memberWalletRepository = databaseMemberWalletRepository, + wallets = groupOnchainWallets, + onNavigateBack = { + navController.popBackStack() + } + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberWalletRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberWalletRoute.kt new file mode 100644 index 00000000..df587573 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberWalletRoute.kt @@ -0,0 +1,14 @@ +package com.machankura.bennu.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** + * One of the active member's guarded wallets: its balance, where to be paid, + * its coins, what its guardians took, and -- while no group has certified it -- + * where the asking has got to. `docs/member-guarded-wallets.md`, Phase 8. + */ +@Serializable +data class MemberWalletRoute( + val activeUserPublicKey: String, + val walletId: String, +): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletViewModel.kt new file mode 100644 index 00000000..bb1cf196 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletViewModel.kt @@ -0,0 +1,123 @@ +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.repository.MemberWalletRepository +import com.machankura.bennu.compose.ui.view.state.MemberWalletUIState +import com.machankura.bennu.compose.ui.view.state.TakenLine +import com.machankura.bennu.compose.wallet.GroupOnchainWallets +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.distinctUntilChangedBy +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * One of the member's guarded wallets: read once for where the asking has got + * to, then -- for a certified wallet on a profile that can watch the chain -- + * watched for its coins, and searched for what its guardians took. + * + * Addresses are offered only once a group has certified the wallet: a wallet + * nobody has agreed to guard should not be handed out to be paid. + */ +class MemberWalletViewModel( + private val ownerPublicKey: HexKey, + val walletId: String, + initialUIState: MemberWalletUIState, + private val memberWalletRepository: MemberWalletRepository, + private val wallets: GroupOnchainWallets?, +) : ViewModel() { + private val logger = Logger.withTag(TAG) + + var uiState: MemberWalletUIState by mutableStateOf(initialUIState) + private set + + val isActionPending: MutableState = mutableStateOf(false) + + /** The exported descriptors while they are being shown, and only then. */ + var exported: Pair? by mutableStateOf(null) + private set + + private var watching: Job? = null + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val wallet = memberWalletRepository.walletOf(ownerPublicKey, walletId) + if (wallet == null) { + uiState = MemberWalletUIState.Error("Couldn't find this wallet") + return@launch + } + val loaded = MemberWalletUIState.Loaded(wallet = wallet, canWatch = wallets != null) + uiState = loaded + + watching?.cancel() + if (!wallet.isCertified || wallets == null) return@launch + watching = viewModelScope.launch(Dispatchers.IO) { + var taken = emptyList() + wallets.walletFor(wallet.account).state + .distinctUntilChangedBy { state -> state.utxos.map { it.utxo.outPoint } to state.tipHeight } + .collect { state -> + uiState = loaded.copy(walletState = state, taken = taken) + // History, not a watch: a device asleep when a guardian took a + // coin still finds it, since the chain keeps the record. + taken = wallets.guardianSpends(state).map { spend -> + TakenLine(spend.txid.toString(), memberWalletRepository.roomName(spend.guardian.chatRoomId), spend.amount) + } + uiState = loaded.copy(walletState = state, taken = taken) + } + } + } + } + + fun askAgain(onAsked: () -> Unit, onFailure: () -> Unit) = act(onAsked, onFailure) { + memberWalletRepository.askAgain(walletId) + initiate() + } + + fun discard(onDiscarded: () -> Unit, onFailure: () -> Unit) = act(onDiscarded, onFailure) { + memberWalletRepository.discard(walletId) + } + + fun exportKey() { + viewModelScope.launch(Dispatchers.IO) { exported = memberWalletRepository.exportKey(walletId) } + } + + fun hideKey() { + exported = null + } + + private fun act(onDone: () -> Unit, onFailure: () -> Unit, action: suspend () -> Unit) { + if (isActionPending.value) return + isActionPending.value = true + viewModelScope.launch(Dispatchers.IO) { + val done = runCatching { action() }.onFailure { logger.e("Couldn't act on wallet $walletId", it) }.isSuccess + withContext(Dispatchers.Main) { + isActionPending.value = false + if (done) onDone() else onFailure() + } + } + } + + companion object { + private const val TAG = "MemberWalletViewModel" + + fun factory( + ownerPublicKey: HexKey, + walletId: String, + initialUIState: MemberWalletUIState = MemberWalletUIState.Loading, + memberWalletRepository: MemberWalletRepository, + wallets: GroupOnchainWallets?, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { MemberWalletViewModel(ownerPublicKey, walletId, initialUIState, memberWalletRepository, wallets) } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletsViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletsViewModel.kt new file mode 100644 index 00000000..a6d97d86 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletsViewModel.kt @@ -0,0 +1,70 @@ +package com.machankura.bennu.compose.ui.view.model + +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 com.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.wallet.GroupOnchainWallets +import com.machankura.bennu.compose.wallet.GroupWalletState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.launch + +/** + * A member's guarded wallets, as their profile lists them: each one's state, + * and -- for the ones a group has certified, on a profile that can watch the + * chain -- its balance. + */ +class MemberWalletsViewModel( + private val ownerPublicKey: HexKey, + private val memberWalletRepository: MemberWalletRepository, + private val wallets: GroupOnchainWallets?, +) : ViewModel() { + /** One wallet and, once the chain has answered, its coins. */ + data class Row(val wallet: MemberWalletManager.MemberWalletRow, val walletState: GroupWalletState?) + + /** Null until the first read. */ + var rows: List? by mutableStateOf(null) + private set + + private var watching: Job? = null + + /** Reads the list again: called each time the profile is shown, since a certificate can arrive while it is not. */ + fun refresh() { + viewModelScope.launch(Dispatchers.IO) { + val found = memberWalletRepository.walletsOf(ownerPublicKey) + rows = found.map { Row(it, walletState = null) } + + watching?.cancel() + val watched = found.filter { it.isCertified } + if (wallets == null || watched.isEmpty()) return@launch + watching = viewModelScope.launch(Dispatchers.IO) { + val states = found.map { wallet -> + if (wallet.isCertified) wallets.walletFor(wallet.account).state else flowOf(null) + } + combine(states) { it.toList() }.collect { current -> + rows = found.zip(current) { wallet, state -> Row(wallet, state) } + } + } + } + } + + companion object { + fun factory( + ownerPublicKey: HexKey, + memberWalletRepository: MemberWalletRepository, + wallets: GroupOnchainWallets?, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { MemberWalletsViewModel(ownerPublicKey, memberWalletRepository, wallets) } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberWalletUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberWalletUIState.kt new file mode 100644 index 00000000..c1381b27 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberWalletUIState.kt @@ -0,0 +1,31 @@ +package com.machankura.bennu.compose.ui.view.state + +import com.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.wallet.GroupWalletState +import fr.acinq.bitcoin.Satoshi + +sealed interface MemberWalletUIState { + data object Loading : MemberWalletUIState + + data class Error(val message: String) : MemberWalletUIState + + data class Loaded( + val wallet: MemberWalletManager.MemberWalletRow, + /** Null before Electrum's first answer, for a wallet no group has certified, and for a profile that cannot watch the chain. */ + val walletState: GroupWalletState? = null, + /** Whether this profile has an Electrum client to watch the chain with. */ + val canWatch: Boolean, + /** What the wallet's guardians took from it, read off the chain: never stored, found again on each look. */ + val taken: List = emptyList(), + /** How many groups guard it, for the line under the title. */ + val reach: Int = wallet.account.guardians.size, + ) : MemberWalletUIState +} + +/** One guardian spend from a member's wallet, named for the group that made it. */ +data class TakenLine( + val txid: String, + /** The guardian's room name on this device, or null when this device is not in it. */ + val guardianName: String?, + val amount: Satoshi, +) diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletDerivationTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletDerivationTest.kt index ed73802f..cef93ce4 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletDerivationTest.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletDerivationTest.kt @@ -152,4 +152,17 @@ class MemberWalletDerivationTest { assertEquals(GuardianDerivation.leafKey(grant[position], chain, MemberWalletDerivation.ACCOUNT, 0, 4), signing.leafKey) } } + + @Test + fun `the exported descriptors carry the private key and nothing else changes`() { + val (receive, change) = MemberWalletDerivation.privateDescriptors(walletPrivateKey, account) + for ((exported, public) in listOf(receive to account.receiveDescriptor, change to account.changeDescriptor)) { + val (body, checksum) = exported.split('#') + assertEquals(Descriptor.checksum(body), checksum) + assertTrue(body.contains("tprv"), "a test network's private key") + assertTrue(!body.contains(account.xpub), "the account xpub is gone") + assertEquals(public.substringBefore('#').replace(account.xpub, ""), body.replace(Regex("tprv[1-9A-HJ-NP-Za-km-z]+"), "")) + } + assertFails { MemberWalletDerivation.privateDescriptors(privateKey(0xb0b), account) } + } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletsJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletsJvmTest.kt new file mode 100644 index 00000000..d9e9e823 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletsJvmTest.kt @@ -0,0 +1,127 @@ +package com.machankura.bennu.compose.managers + +import androidx.room3.Room +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.database.model.types.FrostSigningStage +import com.machankura.bennu.compose.managers.GroupFixtures.fileKeyState +import com.machankura.bennu.compose.managers.GroupFixtures.guardedCertificate +import com.machankura.bennu.compose.managers.GroupFixtures.keyMaterial +import com.machankura.bennu.compose.managers.GroupFixtures.roomOf +import com.machankura.bennu.compose.managers.GroupFixtures.signedAsRoom +import com.machankura.bennu.compose.managers.GroupFixtures.signingRoom +import com.machankura.bennu.compose.managers.MemberWalletManager.WalletState +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.secp256k1.Hex +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * A member's guarded wallets as their profile lists them: one state per wallet, + * read off the key here, the sessions in the group's room and the group's + * certificates -- and a wallet made on another device, which this one can + * only watch. + */ +class MemberWalletsJvmTest { + private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val chain = Chain.Regtest + + private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) + + private val parent = keyMaterial("9a9e") + private val group = keyMaterial("6a0b") + private val groupRoom = roomOf(group) + + private val member = privateKey(0x3e3be7) + private val memberPublicKey = member.xOnlyPublicKey().value.toHex() + + private suspend fun setUp(signer: Boolean = false) { + signingRoom(db, group, members = listOf(memberPublicKey), holdsShare = signer) + fileKeyState(db, group, guardedCertificate(parent, group)) + } + + private suspend fun certify(request: Event) { + val template = MemberWalletCertificateEvent.template(request) + val signed = signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) + db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(signed, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) + } + + private suspend fun stateOf(walletId: String): WalletState? = + MemberWalletManager.walletsOf(db, memberPublicKey).firstOrNull { it.walletId == walletId }?.state + + @Test + fun `asked, then certified`(): Unit = runBlocking { + setUp() + val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = "Savings") + assertEquals(WalletState.ASKED, stateOf(wallet.walletId)) + + certify(Event.fromJson(wallet.requestJson)) + val row = assertNotNull(MemberWalletManager.walletOf(db, memberPublicKey, wallet.walletId)) + assertEquals(WalletState.OPEN, row.state) + assertTrue(row.isCertified) + assertTrue(row.isMember) + assertEquals("Savings", row.label) + assertEquals(groupRoom, row.groupRoom?.chatRoom?.id) + assertEquals(2, row.account.guardians.size) + assertNotNull(MemberWalletManager.exportKey(db, memberPublicKey, wallet.walletId)) + } + + @Test + fun `signing, then not signed`(): Unit = runBlocking { + setUp(signer = true) + val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + assertEquals(WalletState.SIGNING, stateOf(wallet.walletId), "a signer puts it to the group at once") + + val session = assertNotNull(MemberWalletManager.openSessionFor(db, groupRoom, Event.fromJson(wallet.requestJson))) + db.frostSigningSessionDao().upsert(session.copy(stage = FrostSigningStage.FAILED)) + assertEquals(WalletState.NOT_SIGNED, stateOf(wallet.walletId)) + } + + @Test + fun `a wallet made on another device is listed to watch`(): Unit = runBlocking { + setUp() + val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + certify(Event.fromJson(wallet.requestJson)) + // As the other device sees it: the certificate, and no key. + db.memberWalletDao().delete(wallet.walletId) + + val row = assertNotNull(MemberWalletManager.walletOf(db, memberPublicKey, wallet.walletId)) + assertEquals(WalletState.WATCH_ONLY, row.state) + assertNull(MemberWalletManager.exportKey(db, memberPublicKey, wallet.walletId), "no key to export here") + } + + @Test + fun `somebody else's wallets are not listed`(): Unit = runBlocking { + setUp() + val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + certify(Event.fromJson(wallet.requestJson)) + assertTrue(MemberWalletManager.walletsOf(db, privateKey(0xb0b).xOnlyPublicKey().value.toHex()).isEmpty()) + } + + @Test + fun `a member who left keeps the wallet, and is told`(): Unit = runBlocking { + setUp() + val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) + certify(Event.fromJson(wallet.requestJson)) + db.participantDao().delete(db.participantDao().findParticipantsByChatRoomId(groupRoom).filter { it.participantPublicKey == memberPublicKey }) + + val row = assertNotNull(MemberWalletManager.walletOf(db, memberPublicKey, wallet.walletId)) + assertFalse(row.isMember) + assertEquals(WalletState.OPEN, row.state) + } +}