feat(wallet): a member's guarded wallets on their profile, and each one's screen (Phase 8)

The profile lists every guarded wallet of its own this device knows
about, named for the group that guards it: the ones whose key is here,
and the ones a group this device is in has certified for this npub,
which includes wallets made on another device and shown watch-only.
Each row says where the asking has got to -- asked, signing, not
signed, open -- or the balance.

MemberWalletScreen offers addresses only once a group has certified
the wallet. Before then the member can ask again or discard the key,
which is safe exactly then; after, it shows the balance, the address,
the coins and every coin a guardian took, read off the chain. Export
key, behind a confirmation, shows both descriptors with the private
key in them.

wipeData has no callers and deletes nothing yet, so there is no wipe to
guard; a note on it says what a caller must do once it does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-10-24 07:44:30 +02:00
1 parent 0bc076a894
commit eb4d627840
18 files changed
+1126 -3

No files matched your search

@@ -586,4 +586,28 @@
<string name="this_group_s_guardian_keys_can_t_be_read_to_guard_a_wallet">This group's guardian keys can't be read by this version of the app.</string>
<string name="member_wallets_are_not_offered_on_this_network">Guarded wallets for members aren't offered on this network yet.</string>
<string name="this_profile_cannot_watch_its_own_coins">This profile has no wallet of its own to watch the chain with, so it couldn't see its own coins.</string>
<string name="you_have_no_guarded_wallets">You have no guarded wallets.</string>
<string name="waiting_for_someone_in_s_to_put_it_to_the_group">Waiting for someone in %1$s to put it to the group</string>
<string name="s_is_signing">%1$s is signing</string>
<string name="s_did_not_sign">%1$s didn't sign. Ask again, or discard it.</string>
<string name="key_on_another_device">Key on another device</string>
<string name="you_re_no_longer_in_s">You're no longer in %1$s. It still guards this wallet.</string>
<string name="guarded_by_s">Guarded by %1$s</string>
<string name="discard">Discard</string>
<string name="discard_this_wallet_question">Discard this wallet?</string>
<string name="discarding_forgets_its_key">Its key is forgotten. No address of it was ever offered, so nothing can have been paid to it.</string>
<string name="export_key">Export key</string>
<string name="export_this_wallet_s_key_question">Export this wallet's key?</string>
<string name="whoever_holds_these_descriptors_holds_the_coins">Whoever holds these descriptors can spend every coin in this wallet. Keep them where only you can reach them.</string>
<string name="show_key">Show key</string>
<string name="receive_descriptor">Receive descriptor</string>
<string name="change_descriptor">Change descriptor</string>
<string name="copied">Copied.</string>
<string name="copy">Copy</string>
<string name="finding_your_coins">Finding your coins…</string>
<string name="s_took_s_sats_in_s">%1$s took %2$s sats through its guardian leaf, in %3$s.</string>
<string name="taken_by_guardians">Taken by guardians</string>
<string name="the_key_of_this_wallet_is_on_another_device">This wallet's key is on another of your devices, so it can be watched here but not spent from.</string>
<string name="couldn_t_ask_again">Couldn't ask again.</string>
<string name="couldn_t_discard_the_wallet">Couldn't discard the wallet.</string>
</resources>
@@ -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.
}
}
}
@@ -46,6 +46,42 @@ class DatabaseMemberWalletRepository(
return MemberWalletManager.request(database, chatRoomId, key, chain, label)
}
override suspend fun walletsOf(ownerPublicKey: HexKey): List<MemberWalletManager.MemberWalletRow> = 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<String, String>? {
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"
}
@@ -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<String, String> {
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
@@ -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<MemberWalletRow> {
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<String, String>? {
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 ------------------------------------------------
/**
@@ -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<MemberWalletManager.MemberWalletRow>
/** 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<String, String>?
/** 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<LocalChatRoom> = 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<MemberWalletManager.MemberWalletRow> = 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<String, String>? = null
override suspend fun roomName(chatRoomId: String): String? = null
}
}
}
@@ -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.
@@ -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())) },
@@ -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<MemberWalletsViewModel.Row>?,
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))
}
}
@@ -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))
}
}
@@ -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)
@@ -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<ShareProfileRoute> { backStackEntry ->
@@ -1156,6 +1160,19 @@ fun BennuNavHost(
}
)
}
composable<MemberWalletRoute> { backStackEntry ->
val route = backStackEntry.toRoute<MemberWalletRoute>()
MemberWalletScreen(
activeUserPublicKey = route.activeUserPublicKey,
walletId = route.walletId,
memberWalletRepository = databaseMemberWalletRepository,
wallets = groupOnchainWallets,
onNavigateBack = {
navController.popBackStack()
}
)
}
composable<NewMemberWalletRoute> { backStackEntry ->
val route = backStackEntry.toRoute<NewMemberWalletRoute>()
@@ -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()
@@ -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<Boolean> = mutableStateOf(false)
/** The exported descriptors while they are being shown, and only then. */
var exported: Pair<String, String>? 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<TakenLine>()
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) }
}
}
}
@@ -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<Row>? 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) }
}
}
}
@@ -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<TakenLine> = 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,
)
@@ -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) }
}
}
@@ -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<BennuDatabase>())
@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)
}
}