feat(wallet): a member asks a group to guard a wallet only they can spend from (Phase 6)

MemberWalletManager.request makes a random key, works out the group's
leaf and every inherited one, builds both descriptors, stores the key,
and only then puts the signed request into the group's room. It checks
the request the way every signer will before it goes, and a member who
holds a share of the group's key puts it to the group in the same step.

NewMemberWalletScreen is a consent screen first: who can take the
member's coins and after how long, who will see them, and that the
group is the recovery path -- then an optional label and one button.
Every refusal is named, and a member who does not know the group's key
can ask for it from there. Its entrances arrive with the profile's
guarded wallets (Phase 8) and the group's page (Phase 11).

GroupWalletRollout.MEMBER_WALLETS_ON_MAINNET is shut: the entrances are
offered on test networks only, since the member's own spend is the
first single-signer path the app has.

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:38:30 +02:00
1 parent e181690f81
commit 0bc076a894
12 files changed
+885 -1

No files matched your search

@@ -563,4 +563,27 @@
<string name="the_subgroup_s_wallet_will_not_be_guarded">The subgroup's wallet will not be guarded: only the subgroup can spend from it.</string>
<string name="the_group_above_decided_this_wallet_is_guarded">The group above this one decided this group's wallet is guarded. Each group above it can spend any coin in it once it has %1$d confirmations, without this group agreeing.</string>
<string name="the_group_above_decided_this_wallet_is_not_guarded">The group above this one decided this group's wallet is not guarded. Only this group can spend from it.</string>
<!-- A member's guarded wallet: docs/member-guarded-wallets.md -->
<string name="new_guarded_wallet">New guarded wallet</string>
<string name="a_group">A group</string>
<string name="choose_a_group_to_guard_it">Choose a group to guard it</string>
<string name="you_are_in_no_groups_that_can_guard_a_wallet">You're in no groups that could guard a wallet for you.</string>
<string name="a_wallet_only_you_can_spend_from_guarded_by_s">A wallet only you can spend from, guarded by %1$s</string>
<string name="s_can_take_any_coin_without_asking_you">%1$s can take any coin in it that has been confirmed for %2$d blocks, without asking you.</string>
<string name="s_and_the_group_above_it_can_take_any_coin_without_asking_you">%1$s and the group above it can take any coin in it that has been confirmed for %2$d blocks, without asking you.</string>
<string name="s_and_the_d_groups_above_it_can_take_any_coin_without_asking_you">%1$s and the %2$d groups above it can take any coin in it that has been confirmed for %3$d blocks, without asking you.</string>
<string name="members_of_those_groups_will_see_this_wallet">Members of the groups that guard it will see its balance, and that it's yours.</string>
<string name="if_you_lose_this_device_those_groups_can_still_move_your_coins">If you lose this device, those groups can still move your coins for you.</string>
<string name="label_optional">Label (optional)</string>
<string name="ask_s">Ask %1$s</string>
<string name="asked_s_to_guard_a_wallet">Asked %1$s to guard a wallet.</string>
<string name="couldn_t_ask_the_group_to_guard_a_wallet">Couldn't ask the group to guard a wallet.</string>
<string name="this_profile_cannot_sign_a_request">This profile can only look, so it can't sign a request.</string>
<string name="only_a_group_can_guard_a_wallet">Only a group with a shared key can guard a wallet.</string>
<string name="this_device_does_not_know_what_this_group_signs_with">This device doesn't know what this group signs with yet, so it can't work out the group's leaves.</string>
<string name="ask_the_group_for_its_key">Ask the group for its key</string>
<string name="asked_for_the_group_s_key">Asked. A member who holds the group's key will answer when their device next reads the room.</string>
<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>
</resources>
@@ -0,0 +1,52 @@
package com.machankura.bennu.compose.database.repository
import co.touchlab.kermit.Logger
import com.machankura.bennu.compose.database.BennuDatabase
import com.machankura.bennu.compose.database.model.MemberWallet
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
import com.machankura.bennu.compose.identity.Identity
import com.machankura.bennu.compose.managers.MemberWalletManager
import com.machankura.bennu.compose.repository.MemberWalletRepository
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import fr.acinq.bitcoin.Chain
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
class DatabaseMemberWalletRepository(
private val database: BennuDatabase,
private val activeIdentity: StateFlow<Identity?> = MutableStateFlow(null),
) : MemberWalletRepository {
private val logger = Logger.withTag(TAG)
override suspend fun groupsOf(ownerPublicKey: HexKey): List<LocalChatRoom> =
database.chatRoomDao().getChatRoomListByUserPublicKey(ownerPublicKey)
.filter { it.chatRoom.mlsGroupState != null }
override suspend fun refusal(chatRoomId: String, chain: Chain): MemberWalletManager.Refusal? = try {
MemberWalletManager.refusal(database, chatRoomId, canSign = activeIdentity.value?.canSign == true, chain = chain)
} catch (e: Throwable) {
logger.e("Error reading whether $chatRoomId can guard a wallet", e)
MemberWalletManager.Refusal.KEY_UNKNOWN
}
override suspend fun reachOf(chatRoomId: String): Int? = try {
MemberWalletManager.reachOf(database, chatRoomId)
} catch (e: Throwable) {
logger.e("Error reading how far $chatRoomId's guard reaches", e)
null
}
override suspend fun askForGroupKey(chatRoomId: String): Boolean {
val identity = activeIdentity.value ?: return false
return MemberWalletManager.askForGroupKey(database, chatRoomId, identity.nostrPublicKey)
}
override suspend fun request(chatRoomId: String, chain: Chain, label: String?): MemberWallet {
val key = activeIdentity.value?.nostrPrivateKey ?: throw IllegalStateException("This profile cannot sign")
return MemberWalletManager.request(database, chatRoomId, key, chain, label)
}
companion object {
private const val TAG = "DatabaseMemberWalletRepository"
}
}
@@ -3,15 +3,21 @@ package com.machankura.bennu.compose.managers
import co.touchlab.kermit.Logger
import com.machankura.bennu.compose.database.BennuDatabase
import com.machankura.bennu.compose.database.model.FrostSigningSession
import com.machankura.bennu.compose.database.model.MemberWallet
import com.machankura.bennu.compose.database.model.MarmotInnerEvent
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
import com.machankura.bennu.compose.database.model.types.FrostSigningStage
import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent
import com.machankura.bennu.compose.nostr.wallet.GroupKeyNoticeEvent
import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent
import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent
import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
import com.machankura.bennu.compose.wallet.GroupWalletRollout
import fr.acinq.bitcoin.Chain
import fr.acinq.bitcoin.PrivateKey
import kotlin.time.Clock
import kotlin.time.Instant
@@ -96,6 +102,152 @@ object MemberWalletManager {
return true
}
// ---- The member's side -----------------------------------------------
/** Why a member cannot ask a group to guard a wallet for them here, said as a reason the screen can name. */
enum class Refusal {
/** A read-only profile: it cannot sign the request. */
CANNOT_SIGN,
/** The room is not a Marmot group, so there is no quorum to sign and no room to carry it. */
NOT_A_GROUP,
/** This device does not know what the group signs with -- [askForGroupKey] is the way on. */
KEY_UNKNOWN,
/** The group's certificate carries guardian keys this build cannot read. */
GUARDIANS_UNREADABLE,
/** Member wallets are not offered on this network yet: `GroupWalletRollout.offersMemberWalletsOn`. */
NOT_ON_THIS_NETWORK,
/** The profile has no Electrum client, so it could not see its own coins. Read by the screen, not here. */
CANNOT_WATCH,
}
/** Why [chatRoomId] cannot guard a wallet for this profile on [chain], or null when it can. */
suspend fun refusal(database: BennuDatabase, chatRoomId: String, canSign: Boolean, chain: Chain): Refusal? {
if (!canSign) return Refusal.CANNOT_SIGN
if (!GroupWalletRollout.offersMemberWalletsOn(chain)) return Refusal.NOT_ON_THIS_NETWORK
val room = database.chatRoomDao().findChatRoomById(chatRoomId)
if (room?.chatRoom?.mlsGroupState == null) return Refusal.NOT_A_GROUP
val groupKey = groupKeyFor(database, chatRoomId) ?: return Refusal.KEY_UNKNOWN
if (groupKey.certificate != null && SubgroupBirthCertificateEvent.parseGuardians(groupKey.certificate.tags) == null) {
return Refusal.GUARDIANS_UNREADABLE
}
return null
}
/**
* How many groups a wallet guarded by [chatRoomId] would be guarded by: the
* group, and every group above it whose key it passes down. Null when this
* device does not know the group's key.
*/
suspend fun reachOf(database: BennuDatabase, chatRoomId: String): Int? =
groupKeyFor(database, chatRoomId)?.let { it.guardians.size + 1 }
/**
* Steps 1 and 2: makes a random key, works out every ancestor's leaf and
* both descriptors, stores the key, and only then asks [chatRoomId] to
* guard the wallet, as the member [memberPrivateKey] holds.
*
* The row is written before the request is queued, so a crash between the
* two leaves a key and no request rather than a request and no key. The
* request is checked the way every signer will check it before it goes, so
* a quorum is never shown one this device would refuse. A member who holds a
* share of the group's key puts it to the group in the same breath; anybody
* else waits for a signer to.
*
* @throws IllegalStateException with the [Refusal] when it cannot be asked
*/
suspend fun request(
database: BennuDatabase,
chatRoomId: String,
memberPrivateKey: PrivateKey,
chain: Chain,
label: String?,
createdAt: Instant = Clock.System.now(),
): MemberWallet {
refusal(database, chatRoomId, canSign = true, chain)?.let { throw IllegalStateException("Cannot ask: $it") }
val groupKey = groupKeyFor(database, chatRoomId) ?: throw IllegalStateException("Cannot ask: ${Refusal.KEY_UNKNOWN}")
val memberPublicKey = memberPrivateKey.xOnlyPublicKey().value.toHex()
val walletPrivateKey = MemberWalletDerivation.generate()
val walletId = MemberWalletDerivation.walletId(walletPrivateKey.publicKey())
val grant = GuardianDerivation.grant(groupKey.thresholdPublicKey, chatRoomId.lowercase(), groupKey.guardians, walletId)
val account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, grant)
val request = MemberWalletRequestEvent.build(
memberPrivateKey = memberPrivateKey,
groupChatRoomId = chatRoomId,
walletPrivateKey = walletPrivateKey,
account = account,
label = label,
createdAt = createdAt.epochSeconds,
)
checkNotNull(MemberWalletRequestEvent.verified(request)) { "The request this device built does not check out" }
val wallet = MemberWallet(
walletId = walletId,
ownerPublicKey = memberPublicKey,
guardingChatRoomId = chatRoomId,
chain = GroupWalletStatementEvent.chainName(chain),
walletPrivateKey = walletPrivateKey.value.toHex(),
label = MemberWalletRequestEvent.read(request)?.label,
requestJson = request.toJson(),
// The request's own second: the row and the event it carries agree on when.
createdAt = Instant.fromEpochSeconds(request.createdAt),
)
database.memberWalletDao().upsert(wallet)
send(database, chatRoomId, request)
logger.i("Asked $chatRoomId to guard wallet ${walletId.take(8)}")
sponsorIfSigner(database, chatRoomId, memberPublicKey, request)
return wallet
}
/**
* Asks again with the request [wallet] was asked with, unchanged -- for a
* request no signer put to the group, or one the group did not sign.
*/
suspend fun askAgain(database: BennuDatabase, wallet: MemberWallet) {
val request = Event.fromJsonOrNull(wallet.requestJson) ?: throw IllegalStateException("The stored request does not read")
send(database, wallet.guardingChatRoomId, request)
sponsorIfSigner(database, wallet.guardingChatRoomId, wallet.ownerPublicKey, request)
}
/**
* Forgets [walletId]'s key. Refused once a group has certified the wallet:
* from then on its addresses may have been paid. Before, none was ever
* offered, so no coin can be behind the key.
*/
suspend fun discard(database: BennuDatabase, walletId: String) {
val wallet = database.memberWalletDao().getById(walletId) ?: return
check(certificatesOf(database, wallet.guardingChatRoomId).none { it.walletId == walletId }) {
"A group guards this wallet: its key is not discarded"
}
database.memberWalletDao().delete(walletId)
}
/** The request into [chatRoomId], whole, as an inner event's content: see `MemberWalletRequestEvent`. */
private suspend fun send(database: BennuDatabase, chatRoomId: String, request: Event) {
queue(
database = database,
chatRoomId = chatRoomId,
userPublicKey = request.pubKey,
tags = arrayOf(arrayOf("h", chatRoomId.lowercase())),
content = request.toJson(),
kind = MemberWalletRequestEvent.KIND,
)
}
private suspend fun sponsorIfSigner(database: BennuDatabase, chatRoomId: String, memberPublicKey: HexKey, request: Event) {
if (!FrostSigningManager.canSign(database, chatRoomId)) return
val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return
runCatching { putToGroup(database, room, memberPublicKey, request) }
.onFailure { logger.w("Asked $chatRoomId, and could not put it to the group: ${it.message}") }
}
// ---- The group's side ------------------------------------------------
/**
@@ -0,0 +1,41 @@
package com.machankura.bennu.compose.repository
import com.machankura.bennu.compose.database.model.MemberWallet
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
import com.machankura.bennu.compose.managers.MemberWalletManager
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import fr.acinq.bitcoin.Chain
/**
* A member's guarded wallets, for the screens: asking a group to guard one, and
* -- from the group's side -- the requests and certificates in a room.
* `docs/member-guarded-wallets.md`. The key-holding identity is the
* repository's, never the screen's: nothing above this layer touches a key.
*/
interface MemberWalletRepository {
/** The groups [ownerPublicKey] is in that could guard a wallet: Marmot rooms, whether or not their key is known yet. */
suspend fun groupsOf(ownerPublicKey: HexKey): List<LocalChatRoom>
/** Why [chatRoomId] cannot guard a wallet for the active profile on [chain], or null when it can. */
suspend fun refusal(chatRoomId: String, chain: Chain): MemberWalletManager.Refusal?
/** How many groups a wallet guarded by [chatRoomId] would be guarded by, or null while its key is unknown. */
suspend fun reachOf(chatRoomId: String): Int?
/** Asks [chatRoomId] what it signs with, for a member who holds no key state. Whether it asked. */
suspend fun askForGroupKey(chatRoomId: String): Boolean
/** 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
companion object {
val NO_OP = object : MemberWalletRepository {
override suspend fun groupsOf(ownerPublicKey: HexKey): List<LocalChatRoom> = emptyList()
override suspend fun refusal(chatRoomId: String, chain: Chain): MemberWalletManager.Refusal? = MemberWalletManager.Refusal.CANNOT_SIGN
override suspend fun reachOf(chatRoomId: String): Int? = null
override suspend fun askForGroupKey(chatRoomId: String): Boolean = false
override suspend fun request(chatRoomId: String, chain: Chain, label: String?): MemberWallet =
throw UnsupportedOperationException("no repository")
}
}
}
@@ -0,0 +1,239 @@
package com.machankura.bennu.compose.ui.composable
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountBalanceWallet
import androidx.compose.material.icons.filled.Groups
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
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.material3.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
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.a_wallet_only_you_can_spend_from_guarded_by_s
import bennu.composeapp.generated.resources.ask_s
import bennu.composeapp.generated.resources.ask_the_group_for_its_key
import bennu.composeapp.generated.resources.asked_for_the_group_s_key
import bennu.composeapp.generated.resources.asked_s_to_guard_a_wallet
import bennu.composeapp.generated.resources.choose_a_group_to_guard_it
import bennu.composeapp.generated.resources.couldn_t_ask_the_group_to_guard_a_wallet
import bennu.composeapp.generated.resources.if_you_lose_this_device_those_groups_can_still_move_your_coins
import bennu.composeapp.generated.resources.label_optional
import bennu.composeapp.generated.resources.member_wallets_are_not_offered_on_this_network
import bennu.composeapp.generated.resources.members_of_those_groups_will_see_this_wallet
import bennu.composeapp.generated.resources.new_guarded_wallet
import bennu.composeapp.generated.resources.only_a_group_can_guard_a_wallet
import bennu.composeapp.generated.resources.s_and_the_d_groups_above_it_can_take_any_coin_without_asking_you
import bennu.composeapp.generated.resources.s_and_the_group_above_it_can_take_any_coin_without_asking_you
import bennu.composeapp.generated.resources.s_can_take_any_coin_without_asking_you
import bennu.composeapp.generated.resources.this_device_does_not_know_what_this_group_signs_with
import bennu.composeapp.generated.resources.this_group_s_guardian_keys_can_t_be_read_to_guard_a_wallet
import bennu.composeapp.generated.resources.this_profile_cannot_sign_a_request
import bennu.composeapp.generated.resources.this_profile_cannot_watch_its_own_coins
import bennu.composeapp.generated.resources.you_are_in_no_groups_that_can_guard_a_wallet
import com.machankura.bennu.compose.managers.GuardianDerivation
import com.machankura.bennu.compose.managers.MemberWalletManager
import com.machankura.bennu.compose.repository.MemberWalletRepository
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.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.NewMemberWalletViewModel
import com.machankura.bennu.compose.ui.view.state.NewMemberWalletUIState
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import fr.acinq.bitcoin.Chain
import org.jetbrains.compose.resources.stringResource
/**
* Asking a group to guard a wallet only this member can spend from.
*
* A consent screen first and a form second: what the member gives up -- the
* groups that can take their coins, and see them -- is said before the one
* button, in the words `docs/member-guarded-wallets.md` uses. Nothing leaves the
* device until that button: the key is made, the leaves worked out and the key
* stored, and only then is the group asked.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NewMemberWalletScreen(
activeUserPublicKey: HexKey,
chatRoomId: String?,
chain: Chain,
canWatch: Boolean,
initialUIState: NewMemberWalletUIState = NewMemberWalletUIState.Loading,
memberWalletRepository: MemberWalletRepository,
onNavigateBack: () -> Unit,
) {
val viewModel: NewMemberWalletViewModel = viewModel(
factory = NewMemberWalletViewModel.factory(
activeUserPublicKey = activeUserPublicKey,
chatRoomId = chatRoomId,
chain = chain,
canWatch = canWatch,
initialUIState = initialUIState,
memberWalletRepository = memberWalletRepository,
)
)
LaunchedEffect(true) {
if (initialUIState == NewMemberWalletUIState.Loading) viewModel.initiate()
}
// Read above the handlers: the notifier and the strings are composable and
// an onClick is not. The caller's scope, so "asked" outlives the screen
// navigating away.
val notify = rememberNotifier(rememberCoroutineScope())
val couldNotAsk = stringResource(Res.string.couldn_t_ask_the_group_to_guard_a_wallet)
val fallbackName = stringResource(Res.string.a_group)
val chosenName = (viewModel.uiState as? NewMemberWalletUIState.Chosen)?.room?.chatRoom?.subject?.takeIf { it.isNotBlank() } ?: fallbackName
val asked = stringResource(Res.string.asked_s_to_guard_a_wallet, chosenName)
Scaffold(
snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
topBar = {
TopAppBar(
title = { Text(stringResource(Res.string.new_guarded_wallet)) },
navigationIcon = { NavigateBackButton(onNavigateBack) },
)
}
) { padding ->
ScreenStateTransition(viewModel.uiState) { uiState ->
when (val state = uiState) {
NewMemberWalletUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding))
// Nothing to retry: the group came from a navigation argument.
is NewMemberWalletUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null)
is NewMemberWalletUIState.Picking -> if (state.groups.isEmpty()) {
EmptyState(
modifier = Modifier.padding(padding).readableContent(),
message = stringResource(Res.string.you_are_in_no_groups_that_can_guard_a_wallet),
icon = Icons.Default.Groups,
)
} else {
LazyColumn(
modifier = Modifier.padding(padding).readableContent().fillMaxSize()
.padding(MaterialTheme.spacing.screenMargin),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap),
) {
item {
Text(stringResource(Res.string.choose_a_group_to_guard_it), style = MaterialTheme.typography.titleMedium)
}
items(state.groups, key = { it.room.chatRoom.id }) { choice ->
ListItem(
modifier = Modifier.clickable { viewModel.pick(choice.room.chatRoom.id) }.minimumInteractiveComponentSize(),
leadingContent = { Icon(Icons.Default.Groups, contentDescription = Decorative) },
headlineContent = {
Text(choice.room.chatRoom.subject?.takeIf { it.isNotBlank() } ?: fallbackName, maxLines = 1, overflow = TextOverflow.Ellipsis)
},
supportingContent = choice.refusal?.let { refusal -> { Text(refusalText(refusal)) } },
)
}
}
}
is NewMemberWalletUIState.Chosen -> Column(
modifier = Modifier.padding(padding).readableContent().fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(MaterialTheme.spacing.screenMargin),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap),
) {
Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative)
Text(
text = stringResource(Res.string.a_wallet_only_you_can_spend_from_guarded_by_s, chosenName),
style = MaterialTheme.typography.titleLarge,
)
state.reach?.let { reach -> Text(reachText(chosenName, reach), style = MaterialTheme.typography.bodyLarge) }
Text(stringResource(Res.string.members_of_those_groups_will_see_this_wallet), style = MaterialTheme.typography.bodyLarge)
Text(
stringResource(Res.string.if_you_lose_this_device_those_groups_can_still_move_your_coins),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
when (val refusal = state.refusal) {
null -> {
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = viewModel.label.value,
onValueChange = viewModel::setLabel,
label = { Text(stringResource(Res.string.label_optional)) },
singleLine = true,
)
Button(
onClick = { viewModel.ask(onAsked = { notify(asked); onNavigateBack() }, onFailure = { notify(couldNotAsk) }) },
enabled = !viewModel.isActionPending.value,
) {
Text(stringResource(Res.string.ask_s, chosenName))
}
}
MemberWalletManager.Refusal.KEY_UNKNOWN -> {
Text(refusalText(refusal), color = MaterialTheme.colorScheme.onSurfaceVariant)
if (state.askedForKey) {
Text(stringResource(Res.string.asked_for_the_group_s_key), color = MaterialTheme.colorScheme.onSurfaceVariant)
} else {
TextButton(onClick = viewModel::askForGroupKey) { Text(stringResource(Res.string.ask_the_group_for_its_key)) }
}
}
else -> Text(refusalText(refusal), color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
}
}
}
/** 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 {
val delay = GuardianDerivation.ANCESTOR_DELAY.toInt()
return when (reach) {
1 -> stringResource(Res.string.s_can_take_any_coin_without_asking_you, groupName, delay)
2 -> stringResource(Res.string.s_and_the_group_above_it_can_take_any_coin_without_asking_you, groupName, delay)
else -> stringResource(Res.string.s_and_the_d_groups_above_it_can_take_any_coin_without_asking_you, groupName, reach - 1, delay)
}
}
@Composable
private fun refusalText(refusal: MemberWalletManager.Refusal): String = stringResource(
when (refusal) {
MemberWalletManager.Refusal.CANNOT_SIGN -> Res.string.this_profile_cannot_sign_a_request
MemberWalletManager.Refusal.NOT_A_GROUP -> Res.string.only_a_group_can_guard_a_wallet
MemberWalletManager.Refusal.KEY_UNKNOWN -> Res.string.this_device_does_not_know_what_this_group_signs_with
MemberWalletManager.Refusal.GUARDIANS_UNREADABLE -> Res.string.this_group_s_guardian_keys_can_t_be_read_to_guard_a_wallet
MemberWalletManager.Refusal.NOT_ON_THIS_NETWORK -> Res.string.member_wallets_are_not_offered_on_this_network
MemberWalletManager.Refusal.CANNOT_WATCH -> Res.string.this_profile_cannot_watch_its_own_coins
}
)
@@ -139,6 +139,9 @@ import kotlinx.coroutines.SupervisorJob
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.NewMemberWalletScreen
import com.machankura.bennu.compose.database.repository.DatabaseMemberWalletRepository
import com.machankura.bennu.compose.wallet.GroupOnchainWallets
import com.machankura.bennu.compose.wallet.GroupTransactionWatcher
import fr.acinq.phoenix.managers.NodeParamsManager
@@ -208,6 +211,13 @@ fun BennuNavHost(
)
}
val databaseMemberWalletRepository = remember {
DatabaseMemberWalletRepository(
database = auxDatabaseManager.auxDatabase,
activeIdentity = sovereignWalletViewModel.activeIdentity,
)
}
val databaseMarmotRepository = remember {
DatabaseMarmotRepository(
database = auxDatabaseManager.auxDatabase,
@@ -1146,6 +1156,20 @@ fun BennuNavHost(
}
)
}
composable<NewMemberWalletRoute> { backStackEntry ->
val route = backStackEntry.toRoute<NewMemberWalletRoute>()
NewMemberWalletScreen(
activeUserPublicKey = route.activeUserPublicKey,
chatRoomId = route.chatRoomId,
chain = NodeParamsManager.chain,
canWatch = groupOnchainWallets != null,
memberWalletRepository = databaseMemberWalletRepository,
onNavigateBack = {
navController.popBackStack()
}
)
}
composable<GroupWalletAddressesRoute> { backStackEntry ->
val route = backStackEntry.toRoute<GroupWalletAddressesRoute>()
@@ -0,0 +1,14 @@
package com.machankura.bennu.compose.ui.composable.navigation.routes
import kotlinx.serialization.Serializable
/**
* Asking a group to guard a wallet only the active member can spend from --
* `docs/member-guarded-wallets.md`, Phase 6. With [chatRoomId] the group is
* already chosen; without it the screen offers the groups this profile is in.
*/
@Serializable
data class NewMemberWalletRoute(
val activeUserPublicKey: String,
val chatRoomId: String? = null,
): Route()
@@ -0,0 +1,124 @@
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.managers.MemberWalletManager
import com.machankura.bennu.compose.repository.MemberWalletRepository
import com.machankura.bennu.compose.ui.view.state.GroupChoice
import com.machankura.bennu.compose.ui.view.state.NewMemberWalletUIState
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import fr.acinq.bitcoin.Chain
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* Asking a group to guard a wallet only this member can spend from.
*
* The screen offers nothing that would be refused. Every refusal is read before
* the button is drawn and again inside `MemberWalletManager.request`, the way
* the subgroup picker refuses: the screen keeps a member out of a dead end, the
* manager keeps a bug out of the room.
*
* [canWatch] is whether this profile has an Electrum client: one without could
* not see its own coins, so it is not offered a wallet it cannot see (D3).
*/
class NewMemberWalletViewModel(
val activeUserPublicKey: HexKey,
private val chatRoomId: String?,
private val chain: Chain,
private val canWatch: Boolean,
initialUIState: NewMemberWalletUIState,
private val memberWalletRepository: MemberWalletRepository,
) : ViewModel() {
private val logger = Logger.withTag(TAG)
var uiState: NewMemberWalletUIState by mutableStateOf(initialUIState)
private set
val label: MutableState<String> = mutableStateOf("")
val isActionPending: MutableState<Boolean> = mutableStateOf(false)
fun initiate() {
viewModelScope.launch(Dispatchers.IO) {
uiState = when (val chosen = chatRoomId) {
null -> NewMemberWalletUIState.Picking(
memberWalletRepository.groupsOf(activeUserPublicKey).map { GroupChoice(it, refusal(it.chatRoom.id)) }
)
else -> choose(chosen) ?: NewMemberWalletUIState.Error("Couldn't find the group")
}
}
}
fun pick(chatRoomId: String) {
viewModelScope.launch(Dispatchers.IO) {
uiState = choose(chatRoomId) ?: NewMemberWalletUIState.Error("Couldn't find the group")
}
}
private suspend fun choose(chatRoomId: String): NewMemberWalletUIState.Chosen? {
val room = memberWalletRepository.groupsOf(activeUserPublicKey).firstOrNull { it.chatRoom.id == chatRoomId } ?: return null
return NewMemberWalletUIState.Chosen(room = room, refusal = refusal(chatRoomId), reach = memberWalletRepository.reachOf(chatRoomId))
}
private suspend fun refusal(chatRoomId: String): MemberWalletManager.Refusal? =
memberWalletRepository.refusal(chatRoomId, chain)
?: if (!canWatch) MemberWalletManager.Refusal.CANNOT_WATCH else null
fun askForGroupKey() {
val chosen = uiState as? NewMemberWalletUIState.Chosen ?: return
viewModelScope.launch(Dispatchers.IO) {
memberWalletRepository.askForGroupKey(chosen.room.chatRoom.id)
uiState = chosen.copy(askedForKey = true)
}
}
fun setLabel(value: String) {
label.value = value.take(LABEL_LENGTH)
}
/** Asks the chosen group; [onAsked] gets the group's name, [onFailure] runs when it could not. */
fun ask(onAsked: () -> Unit, onFailure: () -> Unit) {
val chosen = uiState as? NewMemberWalletUIState.Chosen ?: return
if (chosen.refusal != null || isActionPending.value) return
isActionPending.value = true
viewModelScope.launch(Dispatchers.IO) {
val asked = runCatching {
memberWalletRepository.request(chosen.room.chatRoom.id, chain, label.value.takeIf { it.isNotBlank() })
}.onFailure { logger.e("Couldn't ask ${chosen.room.chatRoom.id} to guard a wallet", it) }.isSuccess
withContext(Dispatchers.Main) {
isActionPending.value = false
if (asked) onAsked() else onFailure()
}
}
}
companion object {
private const val TAG = "NewMemberWalletViewModel"
/** The longest label a request carries -- `MemberWalletRequestEvent.MAX_LABEL_LENGTH`. */
const val LABEL_LENGTH = 64
fun factory(
activeUserPublicKey: HexKey,
chatRoomId: String?,
chain: Chain,
canWatch: Boolean,
initialUIState: NewMemberWalletUIState = NewMemberWalletUIState.Loading,
memberWalletRepository: MemberWalletRepository,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
NewMemberWalletViewModel(activeUserPublicKey, chatRoomId, chain, canWatch, initialUIState, memberWalletRepository)
}
}
}
}
@@ -0,0 +1,31 @@
package com.machankura.bennu.compose.ui.view.state
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
import com.machankura.bennu.compose.managers.MemberWalletManager
sealed interface NewMemberWalletUIState {
data object Loading : NewMemberWalletUIState
data class Error(val message: String) : NewMemberWalletUIState
/** No group chosen yet: every group this profile is in, each with why it cannot guard a wallet, if it cannot. */
data class Picking(val groups: List<GroupChoice>) : NewMemberWalletUIState
/**
* A group chosen. [refusal] null means it can be asked, and [reach] is how
* many groups the wallet would be guarded by -- the group and every group
* above it whose key it passes down.
*/
data class Chosen(
val room: LocalChatRoom,
val refusal: MemberWalletManager.Refusal?,
val reach: Int?,
/** The member already asked the group for its key, and is waiting on an answer. */
val askedForKey: Boolean = false,
) : NewMemberWalletUIState
}
data class GroupChoice(
val room: LocalChatRoom,
val refusal: MemberWalletManager.Refusal?,
)
@@ -43,4 +43,18 @@ object GroupWalletRollout {
const val GUARDIANS_ON_MAINNET: Boolean = true
fun offersGuardiansOn(chain: Chain): Boolean = GUARDIANS_ON_MAINNET || !chain.isMainnet()
/**
* Whether a member is offered a guarded wallet of their own on mainnet --
* `docs/member-guarded-wallets.md`, D8. Test networks are offered one from
* the start. Shut until a three-level hierarchy has watched one member's
* wallet on signet and its root has made a guardian spend from it: the
* member's own spend is the first single-signer path this app has.
*
* The entrances only. A device with it shut still accepts, shows and signs
* a certificate somebody else asked for.
*/
const val MEMBER_WALLETS_ON_MAINNET: Boolean = false
fun offersMemberWalletsOn(chain: Chain): Boolean = MEMBER_WALLETS_ON_MAINNET || !chain.isMainnet()
}
@@ -135,7 +135,13 @@ internal object GroupFixtures {
* a signing session in. Built as a real room is -- the id derived from the
* group's own key -- for the reason `SubgroupManagerJvmTest.parentWith` gives.
*/
suspend fun signingRoom(db: BennuDatabase, material: KeyMaterial, members: List<HexKey>, subject: String = "#Ekklesia"): LocalChatRoom {
suspend fun signingRoom(
db: BennuDatabase,
material: KeyMaterial,
members: List<HexKey>,
subject: String = "#Ekklesia",
holdsShare: Boolean = true,
): LocalChatRoom {
val roomId = roomOf(material)
(members + owner).forEach { seedProfile(db, it) }
@@ -152,6 +158,8 @@ internal object GroupFixtures {
)
db.participantDao().upsert((members + owner).map { Participant(participantPublicKey = it, chatRoomId = roomId, relayHint = null) })
if (!holdsShare) return requireNotNull(db.chatRoomDao().findChatRoomById(roomId))
val ceremonyId = "signing-" + roomId.take(8)
db.dkgSessionDao().upsert(
DkgSession(
@@ -0,0 +1,162 @@
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.MarmotInnerEvent
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.GroupFixtures.thresholdKeyOf
import com.machankura.bennu.compose.managers.MemberWalletManager.Refusal
import com.machankura.bennu.compose.managers.MemberWalletManager.asEvent
import com.machankura.bennu.compose.nostr.wallet.GroupKeyNoticeEvent
import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent
import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent
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.assertFailsWith
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlin.time.Instant
/**
* A member asking a group to guard a wallet: the key stored before anything
* leaves the device, the request one every signer will accept, and each reason
* the screen gives for not asking.
*/
class MemberWalletRequestJvmTest {
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()
/** The group as a member who holds no share sees it: a Marmot room, and nothing to sign with. */
private suspend fun asMember(knowsKey: Boolean = true) {
signingRoom(db, group, members = listOf(memberPublicKey), holdsShare = false)
if (knowsKey) fileKeyState(db, group, guardedCertificate(parent, group))
}
private suspend fun requestsSent(): List<Event> =
db.marmotInnerEventDao().getByChatRoomAndKinds(groupRoom, listOf(MemberWalletRequestEvent.KIND))
.mapNotNull { MemberWalletRequestEvent.carried(it.asEvent()) }
@Test
fun `the key is stored and the request one every signer will accept`(): Unit = runBlocking {
asMember()
val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = "Savings")
assertEquals(wallet, db.memberWalletDao().getById(wallet.walletId))
assertEquals(memberPublicKey, wallet.ownerPublicKey)
assertEquals(groupRoom, wallet.guardingChatRoomId)
assertEquals("Savings", wallet.label)
assertEquals(wallet.walletId, MemberWalletDerivation.walletId(PrivateKey.fromHex(wallet.walletPrivateKey).publicKey()))
val sent = requestsSent().single()
val verified = assertNotNull(MemberWalletRequestEvent.verified(sent))
assertEquals(wallet.walletId, verified.reading.walletId)
assertEquals(SubgroupManager.grantFor(db, groupRoom, thresholdKeyOf(group), wallet.walletId), verified.reading.guardians)
assertEquals(2, verified.reading.guardians.size, "the group, and its parent one step further")
// Exactly what a signer's device will be shown, and it is signable.
val template = MemberWalletCertificateEvent.template(sent)
val proposed = Event(MemberWalletManager.certificateIdFor(groupRoom, sent), groupRoom, template.createdAt, template.kind, template.tags, template.content, "")
assertNull(MemberWalletManager.refuseCertificate(db, groupRoom, thresholdKeyOf(group), proposed))
assertTrue(db.frostSigningSessionDao().getSessionsForChatRoom(groupRoom).isEmpty(), "a member without a share waits for a signer")
assertEquals(listOf(wallet.walletId), MemberWalletManager.awaitingSponsor(db, groupRoom).map { it.reading.walletId })
}
@Test
fun `two requests are two keys`(): Unit = runBlocking {
asMember()
val first = MemberWalletManager.request(db, groupRoom, member, chain, label = null)
val second = MemberWalletManager.request(db, groupRoom, member, chain, label = null)
assertTrue(first.walletId != second.walletId)
assertTrue(first.walletPrivateKey != second.walletPrivateKey)
}
@Test
fun `a member who holds a share puts it to the group at once`(): Unit = runBlocking {
// A share-holding member: one of the ceremony's participants on this device.
signingRoom(db, group, members = listOf(memberPublicKey))
fileKeyState(db, group, guardedCertificate(parent, group))
val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null)
val session = assertNotNull(MemberWalletManager.openSessionFor(db, groupRoom, Event.fromJson(wallet.requestJson)))
assertNotNull(session.signApprovedAt, "proposing is approving")
assertTrue(MemberWalletManager.awaitingSponsor(db, groupRoom).isEmpty())
}
@Test
fun `each refusal holds`(): Unit = runBlocking {
assertEquals(Refusal.CANNOT_SIGN, MemberWalletManager.refusal(db, groupRoom, canSign = false, chain))
assertEquals(Refusal.NOT_A_GROUP, MemberWalletManager.refusal(db, groupRoom, canSign = true, chain))
GroupFixtures.seedRoom(db, groupRoom)
assertEquals(Refusal.NOT_A_GROUP, MemberWalletManager.refusal(db, groupRoom, canSign = true, chain), "a room with no MLS state")
db.chatRoomDao().delete(db.chatRoomDao().findChatRoomById(groupRoom)!!.chatRoom)
asMember(knowsKey = false)
assertEquals(Refusal.KEY_UNKNOWN, MemberWalletManager.refusal(db, groupRoom, canSign = true, chain))
assertFailsWith<IllegalStateException> { MemberWalletManager.request(db, groupRoom, member, chain, label = null) }
assertTrue(db.memberWalletDao().getByOwner(memberPublicKey).isEmpty(), "a refused request makes no key")
assertEquals(Refusal.NOT_ON_THIS_NETWORK, MemberWalletManager.refusal(db, groupRoom, canSign = true, Chain.Mainnet))
}
@Test
fun `a member with no key state can ask once an answer is in the room`(): Unit = runBlocking {
asMember(knowsKey = false)
val answer = GroupKeyNoticeEvent.GroupKey(groupRoom, thresholdKeyOf(group), guardedCertificate(parent, group))
val tags = GroupKeyNoticeEvent.answeringTags("e".repeat(64), answer, GroupFixtures.path)
db.marmotInnerEventDao().upsert(
MarmotInnerEvent(id = "f".repeat(64), publicKey = "5".repeat(64), kind = GroupKeyNoticeEvent.KIND, createdAt = Instant.fromEpochSeconds(1_700_000_000), tags = tags, content = answer.thresholdPublicKey, chatRoomId = groupRoom)
)
assertNull(MemberWalletManager.refusal(db, groupRoom, canSign = true, chain))
assertEquals(2, MemberWalletManager.reachOf(db, groupRoom))
val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null)
assertNotNull(MemberWalletRequestEvent.verified(Event.fromJson(wallet.requestJson)))
}
@Test
fun `a key is discarded only before a group guards its wallet`(): Unit = runBlocking {
asMember()
val unasked = MemberWalletManager.request(db, groupRoom, member, chain, label = null)
MemberWalletManager.discard(db, unasked.walletId)
assertNull(db.memberWalletDao().getById(unasked.walletId))
val guarded = MemberWalletManager.request(db, groupRoom, member, chain, label = null)
val template = MemberWalletCertificateEvent.template(Event.fromJson(guarded.requestJson))
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))
assertFailsWith<IllegalStateException> { MemberWalletManager.discard(db, guarded.walletId) }
assertNotNull(db.memberWalletDao().getById(guarded.walletId))
}
}