feat(dkg): one screen that starts a group's own key ceremony (Phase 3)

CreateSharedKeyScreen takes the quorum and a single button, and nothing
else. It refuses a Marmot room and a group of one with a reason, hands over
to a ceremony the group already has rather than offering a second, and
replaces itself with the ceremony once it is opened so back never returns to
an offer. The group details' Shared key button and the card shown when a
robust group was created without its ceremony both lead here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-10-23 16:27:15 +02:00
1 parent 69095ba4a8
commit cc01f4aab9
11 files changed
+839 -53

No files matched your search

@@ -265,6 +265,11 @@
<string name="start_a_group_chat">Start a group chat</string>
<string name="start_chat_via_npub_or_nip05">Start chat via npub or nip05</string>
<string name="start_key_ceremony">Start key ceremony</string>
<string name="this_room_was_made_from_a_key_the_group_already_holds">This room was made from a key the group already holds, so it can't run a key ceremony of its own. A subgroup's ceremony is started from the group's details.</string>
<string name="a_shared_key_needs_at_least_members">A shared key needs at least %1$s members to split it between.</string>
<string name="couldn_t_load_this_group">Couldn't load this group.</string>
<string name="couldn_t_read_your_keys">Couldn't read your keys.</string>
<string name="couldn_t_start_the_key_ceremony">Couldn't start the key ceremony.</string>
<string name="startup_error">Startup error</string>
<string name="taking_part_with_these_members">Taking part with these members</string>
<string name="tap_to_load">Tap to load</string>
@@ -80,7 +80,7 @@ import com.machankura.bennu.compose.repository.MantraRepository
import com.machankura.bennu.compose.repository.NostrRepository
import com.machankura.bennu.compose.ui.composable.navigation.routes.ProfilePreviewRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.Route
import com.machankura.bennu.compose.ui.composable.navigation.routes.DkgRitualRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.CreateSharedKeyRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.ProposeGroupEventRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupNostrProfileRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupRelaysRoute
@@ -619,12 +619,17 @@ fun ChatRoomDetailScreen(
// -- and those are reached from the transcript line that
// names the ceremony they are about, never from here,
// which has no way to say which.
//
// To the creation screen, which hands over to the group's
// ceremony if it already has one: the ceremony screen only
// shows a ceremony it is named, and this button has none
// to name. See docs/ceremony-creation.md.
if (chatRoomDetailUIState.localChatRoom.chatRoom.mlsGroupState == null) {
item {
TextButton(
onClick = {
onNavigateToRoute.invoke(
DkgRitualRoute(
CreateSharedKeyRoute(
activeUserPublicKey = activeUserPublicKey,
chatRoomId = chatRoomId
)
@@ -0,0 +1,302 @@
package com.machankura.bennu.compose.ui.composable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Key
import androidx.compose.material.icons.filled.Remove
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilledIconButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import bennu.composeapp.generated.resources.Res
import bennu.composeapp.generated.resources.a_shared_key_needs_at_least_members
import bennu.composeapp.generated.resources.couldn_t_load_this_group
import bennu.composeapp.generated.resources.couldn_t_read_your_keys
import bennu.composeapp.generated.resources.couldn_t_start_the_key_ceremony
import bennu.composeapp.generated.resources.everyone_has_to_be_online_at_the_same_time
import bennu.composeapp.generated.resources.how_many_members_will_it_take_to_sign
import bennu.composeapp.generated.resources.of
import bennu.composeapp.generated.resources.shared_key_for
import bennu.composeapp.generated.resources.start_key_ceremony
import bennu.composeapp.generated.resources.the_group_can_hold_one_key_together_split_so
import bennu.composeapp.generated.resources.this_is_fixed_once_the_ceremony_runs
import bennu.composeapp.generated.resources.this_room_was_made_from_a_key_the_group_already_holds
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import org.jetbrains.compose.resources.stringResource
import com.machankura.bennu.compose.database.model.ChatRoom
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
import com.machankura.bennu.compose.identity.Identity
import com.machankura.bennu.compose.managers.ChillDkgRitualManager
import com.machankura.bennu.compose.repository.ChatRepository
import com.machankura.bennu.compose.repository.DkgRepository
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.theme.BennuTheme
import com.machankura.bennu.compose.ui.theme.ConformancePreviews
import com.machankura.bennu.compose.ui.theme.readableContent
import com.machankura.bennu.compose.ui.theme.spacing
import com.machankura.bennu.compose.ui.view.model.CreateSharedKeyViewModel
import com.machankura.bennu.compose.ui.view.state.CreateSharedKeyUIState
/**
* Starts a NIP-17 group's own key ceremony: the quorum, and one button.
*
* The only screen that does. The ceremony screen it hands over to shows a
* ceremony and never offers to start one, because doing both from one button
* slot is how a member approving a subgroup's ceremony opened a second, whole-room
* one in the parent's room. See docs/ceremony-creation.md.
*
* [onCeremonyOpened] is called with the ceremony to show, whether this screen
* opened it or found one already there. The caller replaces this screen with it,
* so back from the ceremony goes wherever the member came from.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CreateSharedKeyScreen(
activeUserPublicKey: HexKey,
chatRoomId: String,
initialUIState: CreateSharedKeyUIState = CreateSharedKeyUIState.Loading,
activeIdentityStateFlow: StateFlow<Identity?>,
chatRepository: ChatRepository,
dkgRepository: DkgRepository,
onCeremonyOpened: (dkgSessionId: String) -> Unit,
onNavigateBack: () -> Unit,
) {
val viewModel: CreateSharedKeyViewModel = viewModel(
factory = CreateSharedKeyViewModel.factory(
chatRoomId = chatRoomId,
activeUserPublicKey = activeUserPublicKey,
initialUIState = initialUIState,
activeIdentityStateFlow = activeIdentityStateFlow,
chatRepository = chatRepository,
dkgRepository = dkgRepository,
)
)
LaunchedEffect(true) {
if (initialUIState == CreateSharedKeyUIState.Loading) {
viewModel.initiate()
}
}
val state = viewModel.uiState
LaunchedEffect(state) {
if (state is CreateSharedKeyUIState.Existing) onCeremonyOpened(state.dkgSessionId)
}
Scaffold(
snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
topBar = {
TopAppBar(
title = {
Text(
text = stringResource(
Res.string.shared_key_for,
(state as? CreateSharedKeyUIState.Loaded)?.localChatRoom?.chatRoom?.subject.orEmpty()
),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
navigationIcon = { NavigateBackButton(onNavigateBack) },
)
}
) { innerPadding ->
ScreenStateTransition(state) { uiState ->
when (uiState) {
// Existing is a hand-over in flight: nothing to draw but the wait.
CreateSharedKeyUIState.Loading,
is CreateSharedKeyUIState.Existing -> LoadingDataIndicator(
modifier = Modifier.padding(innerPadding).fillMaxSize()
)
is CreateSharedKeyUIState.Error -> ErrorState(
modifier = Modifier.padding(innerPadding).readableContent(),
message = when (uiState.reason) {
CreateSharedKeyUIState.Error.Reason.ROOM_NOT_FOUND ->
stringResource(Res.string.couldn_t_load_this_group)
CreateSharedKeyUIState.Error.Reason.NO_KEYS ->
stringResource(Res.string.couldn_t_read_your_keys)
CreateSharedKeyUIState.Error.Reason.NOT_STARTED ->
stringResource(Res.string.couldn_t_start_the_key_ceremony)
},
onRetry = viewModel::initiate,
)
is CreateSharedKeyUIState.Refused -> EmptyState(
modifier = Modifier.padding(innerPadding).readableContent(),
icon = Icons.Default.Key,
message = when (uiState.reason) {
CreateSharedKeyUIState.Refused.Reason.MARMOT_ROOM ->
stringResource(Res.string.this_room_was_made_from_a_key_the_group_already_holds)
CreateSharedKeyUIState.Refused.Reason.TOO_FEW_MEMBERS ->
stringResource(
Res.string.a_shared_key_needs_at_least_members,
ChillDkgRitualManager.MINIMUM_PARTICIPANTS
)
},
)
is CreateSharedKeyUIState.Loaded -> {
val isActionPending = viewModel.isActionPending.value
Column(
modifier = Modifier
.padding(innerPadding)
.readableContent()
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(MaterialTheme.spacing.containerPadding),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)
) {
Text(
text = stringResource(Res.string.the_group_can_hold_one_key_together_split_so),
style = MaterialTheme.typography.bodyMedium
)
Text(
text = stringResource(
Res.string.everyone_has_to_be_online_at_the_same_time,
uiState.participantCount
),
style = MaterialTheme.typography.bodyMedium
)
SharedKeyQuorumStepper(
threshold = viewModel.threshold.value,
participantCount = uiState.participantCount,
quorumRange = viewModel.quorumRange(),
onThresholdChange = viewModel::setThreshold
)
Button(
modifier = Modifier.fillMaxWidth(),
enabled = !isActionPending,
onClick = { viewModel.create(onCreated = onCeremonyOpened) }
) {
if (isActionPending) {
CircularProgressIndicator(modifier = Modifier.size(20.dp))
} else {
Icon(Icons.Default.Key, contentDescription = Decorative)
Text(
modifier = Modifier.padding(start = MaterialTheme.spacing.relatedGap),
text = stringResource(Res.string.start_key_ceremony)
)
}
}
}
}
}
}
}
}
/** Same shape as the group-creation quorum picker, so the choice reads the same. */
@Composable
internal fun SharedKeyQuorumStepper(
threshold: Int,
participantCount: Int,
quorumRange: IntRange,
onThresholdChange: (Int) -> Unit,
) {
Column(
modifier = Modifier.fillMaxWidth().padding(top = MaterialTheme.spacing.space50),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space50)
) {
Text(
text = stringResource(Res.string.how_many_members_will_it_take_to_sign),
style = MaterialTheme.typography.titleSmall
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space200),
verticalAlignment = Alignment.CenterVertically
) {
FilledIconButton(
onClick = { onThresholdChange(threshold - 1) },
enabled = threshold > quorumRange.first
) {
Icon(Icons.Default.Remove, contentDescription = "Fewer signers")
}
Text(
text = stringResource(Res.string.of, threshold, participantCount),
style = MaterialTheme.typography.titleMedium
)
FilledIconButton(
onClick = { onThresholdChange(threshold + 1) },
enabled = threshold < quorumRange.last
) {
Icon(Icons.Default.Add, contentDescription = "More signers")
}
}
Text(
text = stringResource(Res.string.this_is_fixed_once_the_ceremony_runs),
style = MaterialTheme.typography.labelMedium
)
}
}
@ConformancePreviews
@Composable
private fun CreateSharedKeyScreenPreview() {
BennuTheme {
Surface(modifier = Modifier.fillMaxSize()) {
CreateSharedKeyScreen(
activeUserPublicKey = "",
chatRoomId = "chatRoomId",
initialUIState = CreateSharedKeyUIState.Loaded(
localChatRoom = LocalChatRoom(
chatRoom = ChatRoom(
id = "chatRoomId",
userPublicKey = "",
subject = "Group discussions",
description = null,
mlsGroupState = null,
)
),
participantCount = 3,
),
activeIdentityStateFlow = MutableStateFlow(null),
chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY,
dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY,
onCeremonyOpened = {},
onNavigateBack = {},
)
}
}
}
@@ -283,7 +283,7 @@ fun DkgRitualScreen(
)
if (canStartRitual) {
QuorumStepper(
SharedKeyQuorumStepper(
threshold = dkgRitualViewModel.threshold.value,
participantCount = participantCount,
quorumRange = dkgRitualViewModel.quorumRange(),
@@ -815,55 +815,6 @@ private fun RitualStep(
}
}
/** Same shape as the group-creation quorum picker, so the choice reads the same. */
@Composable
private fun QuorumStepper(
threshold: Int,
participantCount: Int,
quorumRange: IntRange,
onThresholdChange: (Int) -> Unit,
) {
Column(
modifier = Modifier.fillMaxWidth().padding(top = MaterialTheme.spacing.space50),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space50)
) {
Text(
text = stringResource(Res.string.how_many_members_will_it_take_to_sign),
style = MaterialTheme.typography.titleSmall
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space200),
verticalAlignment = Alignment.CenterVertically
) {
FilledIconButton(
onClick = { onThresholdChange(threshold - 1) },
enabled = threshold > quorumRange.first
) {
Icon(Icons.Default.Remove, contentDescription = "Fewer signers")
}
Text(
text = stringResource(Res.string.of, threshold, participantCount),
style = MaterialTheme.typography.titleMedium
)
FilledIconButton(
onClick = { onThresholdChange(threshold + 1) },
enabled = threshold < quorumRange.last
) {
Icon(Icons.Default.Add, contentDescription = "More signers")
}
}
Text(
text = stringResource(Res.string.this_is_fixed_once_the_ceremony_runs),
style = MaterialTheme.typography.labelMedium
)
}
}
@ConformancePreviews
@Composable
private fun DkgRitualScreenPreview() {
@@ -32,6 +32,9 @@ import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.material3.TextButton
import com.machankura.bennu.compose.ui.composable.navigation.routes.CreateSharedKeyRoute
import bennu.composeapp.generated.resources.start_the_key_ceremony
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -223,6 +226,25 @@ fun SelectChatRoomTypeScreen(
text = stringResource(Res.string.was_created_but_its_shared_key_ceremony, name),
style = MaterialTheme.typography.bodyMedium
)
// Straight to the one screen that starts a group's own
// ceremony, rather than leaving the member to find it
// through the group's details.
selectChatRoomTypeViewModel.createdChatRoomId.value?.let { createdChatRoomId ->
TextButton(
modifier = Modifier.padding(horizontal = MaterialTheme.spacing.space100),
onClick = {
onNavigateToRoute(
CreateSharedKeyRoute(
activeUserPublicKey = activeUserPublicKey,
chatRoomId = createdChatRoomId,
)
)
}
) {
Text(stringResource(Res.string.start_the_key_ceremony))
}
}
}
}
@@ -40,6 +40,7 @@ import com.machankura.bennu.compose.ui.composable.ChatRoomDetailScreen
import com.machankura.bennu.compose.ui.composable.ChatRoomMessagingScreen
import com.machankura.bennu.compose.ui.composable.CreateProfileScreen
import com.machankura.bennu.compose.ui.composable.DkgJoinApprovalScreen
import com.machankura.bennu.compose.ui.composable.CreateSharedKeyScreen
import com.machankura.bennu.compose.ui.composable.DkgRitualScreen
import com.machankura.bennu.compose.ui.composable.DkgRound1ApprovalScreen
import com.machankura.bennu.compose.ui.composable.DkgRound2ApprovalScreen
@@ -86,6 +87,7 @@ import com.machankura.bennu.compose.ui.composable.navigation.routes.ChatRoomDeta
import com.machankura.bennu.compose.ui.composable.navigation.routes.ChatRoomMessagingRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.CreateProfileRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.DkgJoinApprovalRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.CreateSharedKeyRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.DkgRitualRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.DkgRound1ApprovalRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.DkgRound2ApprovalRoute
@@ -648,6 +650,32 @@ fun BennuNavHost(
}
)
}
composable<CreateSharedKeyRoute> { backStackEntry ->
val route = backStackEntry.toRoute<CreateSharedKeyRoute>()
CreateSharedKeyScreen(
activeUserPublicKey = route.activeUserPublicKey,
chatRoomId = route.chatRoomId,
activeIdentityStateFlow = sovereignWalletViewModel.activeIdentity,
chatRepository = databaseChatRepository,
dkgRepository = databaseDkgRepository,
// Replaces this screen with the ceremony, whether it was just
// opened or was already there, so back from the ceremony goes
// wherever the member came from rather than to a second offer.
onCeremonyOpened = { dkgSessionId ->
navController.navigate(
DkgRitualRoute(
activeUserPublicKey = route.activeUserPublicKey,
chatRoomId = route.chatRoomId,
dkgSessionId = dkgSessionId
)
) {
popUpTo<CreateSharedKeyRoute> { inclusive = true }
}
},
onNavigateBack = { navController.popBackStack() }
)
}
composable<DkgRitualRoute> { backStackEntry ->
val route = backStackEntry.toRoute<DkgRitualRoute>()
@@ -0,0 +1,19 @@
package com.machankura.bennu.compose.ui.composable.navigation.routes
import kotlinx.serialization.Serializable
/**
* Starting a NIP-17 group's own key ceremony, and nothing else.
*
* The one place a group that has no key yet asks for one. Group creation and
* the subgroup picker start their own ceremonies because they already know what
* each is for; this is for a group that exists and has none. The ceremony screen
* that follows only ever shows a ceremony -- it used to offer to start one too,
* from the same button the approvals used, which is how a member joining a
* subgroup's ceremony opened a second. See docs/ceremony-creation.md.
*/
@Serializable
data class CreateSharedKeyRoute(
val activeUserPublicKey: String,
val chatRoomId: String,
): Route()
@@ -0,0 +1,184 @@
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.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import com.machankura.bennu.compose.database.model.types.ChatRoomType
import com.machankura.bennu.compose.database.model.types.DkgRitualStage
import com.machankura.bennu.compose.identity.Identity
import com.machankura.bennu.compose.managers.ChillDkgRitualManager
import com.machankura.bennu.compose.repository.ChatRepository
import com.machankura.bennu.compose.repository.DkgRepository
import com.machankura.bennu.compose.ui.view.state.CreateSharedKeyUIState
import com.machankura.bennu.compose.ui.view.state.CreateSharedKeyUIState.Refused.Reason
/**
* Starts a NIP-17 group's own key ceremony.
*
* Everything about *starting* that the ceremony screen used to carry: the
* quorum, the size check, and the proposal. The ceremony screen only shows one
* now, so nothing it draws can be mistaken for a way to open another.
*
* The refusals are made here rather than by hiding a button, so the screen can
* say why, and `ChillDkgRitualManager.proposeRitual` makes the Marmot one again
* underneath -- a screen not drawing something is not a guard.
*/
class CreateSharedKeyViewModel(
val chatRoomId: String,
val activeUserPublicKey: HexKey,
initialUIState: CreateSharedKeyUIState,
val activeIdentityStateFlow: StateFlow<Identity?>,
val chatRepository: ChatRepository,
val dkgRepository: DkgRepository,
) : ViewModel() {
var uiState: CreateSharedKeyUIState by mutableStateOf(initialUIState)
private set
private val logger = Logger.withTag(TAG)
val isActionPending: MutableState<Boolean> = mutableStateOf(false)
/**
* The quorum the ceremony will generate a key for. Pre-filled with the same
* majority default the group-creation screen offers.
*/
val threshold: MutableState<Int> = mutableStateOf(ChatRoomType.MINIMUM_QUORUM)
fun initiate() {
uiState = CreateSharedKeyUIState.Loading
viewModelScope.launch(Dispatchers.IO) {
val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId)
if (localChatRoom == null) {
uiState = CreateSharedKeyUIState.Error(CreateSharedKeyUIState.Error.Reason.ROOM_NOT_FOUND)
return@launch
}
if (ChillDkgRitualManager.isMarmotRoom(localChatRoom)) {
uiState = CreateSharedKeyUIState.Refused(Reason.MARMOT_ROOM)
return@launch
}
if (!ChillDkgRitualManager.canRunRitual(localChatRoom)) {
uiState = CreateSharedKeyUIState.Refused(Reason.TOO_FEW_MEMBERS)
return@launch
}
// The room's own, which in a NIP-17 room is every ceremony it holds:
// subgroups run in their parent's Marmot room. A finished one counts --
// the group has its key, and the ceremony screen is where the next step
// after it is offered.
val own = dkgRepository.observeLatestSessionForChatRoom(chatRoomId, parentChatRoomId = null)
.first()
if (own != null && own.stage != DkgRitualStage.FAILED) {
uiState = CreateSharedKeyUIState.Existing(own.id)
return@launch
}
val participantCount = ChillDkgRitualManager.memberPublicKeys(localChatRoom).size
threshold.value = ChatRoomType.defaultQuorum(participantCount)
.coerceIn(quorumRange(participantCount))
uiState = CreateSharedKeyUIState.Loaded(
localChatRoom = localChatRoom,
participantCount = participantCount,
)
}
}
fun quorumRange(): IntRange {
val loaded = uiState as? CreateSharedKeyUIState.Loaded
?: return ChatRoomType.quorumRange(ChatRoomType.MINIMUM_QUORUM)
return quorumRange(loaded.participantCount)
}
// Below the minimum the range runs backwards and is empty, which `coerceIn`
// rejects outright. There is no ceremony to run at that size either.
private fun quorumRange(participantCount: Int): IntRange =
ChatRoomType.quorumRange(maxOf(participantCount, ChatRoomType.MINIMUM_QUORUM))
fun setThreshold(value: Int) {
if (isActionPending.value) return
threshold.value = value.coerceIn(quorumRange())
}
/**
* Opens the ceremony, making this device its coordinator, and hands over to
* the screen that shows it.
*/
fun create(onCreated: (dkgSessionId: String) -> Unit) {
if (isActionPending.value) return
val loaded = uiState as? CreateSharedKeyUIState.Loaded ?: return
val nostrPrivateKey = activeIdentityStateFlow.value?.nostrPrivateKey
if (nostrPrivateKey == null) {
uiState = CreateSharedKeyUIState.Error(CreateSharedKeyUIState.Error.Reason.NO_KEYS)
return
}
isActionPending.value = true
viewModelScope.launch(Dispatchers.IO) {
// A ceremony somebody else opened since this screen loaded comes back
// here rather than a second one -- `proposeRitual` checks again.
val session = dkgRepository.proposeRitual(
localChatRoom = loaded.localChatRoom,
userPublicKey = activeUserPublicKey,
nostrPrivateKey = nostrPrivateKey.value.toByteArray(),
threshold = threshold.value
)
isActionPending.value = false
if (session == null) {
logger.e("Failed to start a key ceremony in $chatRoomId")
uiState = CreateSharedKeyUIState.Error(CreateSharedKeyUIState.Error.Reason.NOT_STARTED)
return@launch
}
withContext(Dispatchers.Main) { onCreated(session.id) }
}
}
companion object {
private const val TAG = "CreateSharedKeyViewModel"
fun factory(
chatRoomId: String,
activeUserPublicKey: HexKey,
initialUIState: CreateSharedKeyUIState = CreateSharedKeyUIState.Loading,
activeIdentityStateFlow: StateFlow<Identity?>,
chatRepository: ChatRepository,
dkgRepository: DkgRepository,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
CreateSharedKeyViewModel(
chatRoomId = chatRoomId,
activeUserPublicKey = activeUserPublicKey,
initialUIState = initialUIState,
activeIdentityStateFlow = activeIdentityStateFlow,
chatRepository = chatRepository,
dkgRepository = dkgRepository,
)
}
}
}
}
@@ -0,0 +1,40 @@
package com.machankura.bennu.compose.ui.view.state
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
sealed interface CreateSharedKeyUIState {
/** The room, and how many people a ceremony in it would be split across. */
data class Loaded(
val localChatRoom: LocalChatRoom,
val participantCount: Int,
) : CreateSharedKeyUIState
/**
* The group already has a ceremony that has not failed -- running, or finished
* with a key. The screen hands over to it rather than offering a second: a
* second is another participant set for every member to reconcile, and the key
* the first produced would be left with nothing pointing at it.
*/
data class Existing(val dkgSessionId: String) : CreateSharedKeyUIState
/** This room cannot hold a ceremony of its own, and the screen says why. */
data class Refused(val reason: Reason) : CreateSharedKeyUIState {
enum class Reason {
/**
* A Marmot room's id is derived from the key it already has, so a key
* of its own is one it could never answer to. It hosts its subgroups'
* ceremonies, which are started from the subgroup picker.
*/
MARMOT_ROOM,
/** A key held by one person is just a key. */
TOO_FEW_MEMBERS,
}
}
data class Error(val reason: Reason) : CreateSharedKeyUIState {
enum class Reason { ROOM_NOT_FOUND, NO_KEYS, NOT_STARTED }
}
data object Loading : CreateSharedKeyUIState
}