diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 7dd87438..9ebcf789 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -265,6 +265,11 @@ Start a group chat Start chat via npub or nip05 Start key ceremony + 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. + A shared key needs at least %1$s members to split it between. + Couldn't load this group. + Couldn't read your keys. + Couldn't start the key ceremony. Startup error Taking part with these members Tap to load diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt index a2ef8fdf..b7ca73fb 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt @@ -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 ) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/CreateSharedKeyScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/CreateSharedKeyScreen.kt new file mode 100644 index 00000000..194ced89 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/CreateSharedKeyScreen.kt @@ -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, + 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 = {}, + ) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgRitualScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgRitualScreen.kt index e77f5151..571768bd 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgRitualScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/DkgRitualScreen.kt @@ -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() { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectChatRoomTypeScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectChatRoomTypeScreen.kt index 6b5de38e..ec17dce2 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectChatRoomTypeScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectChatRoomTypeScreen.kt @@ -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)) + } + } } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt index 5342fe5d..1ac07c83 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt @@ -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 { backStackEntry -> + val route = backStackEntry.toRoute() + + 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 { inclusive = true } + } + }, + onNavigateBack = { navController.popBackStack() } + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/CreateSharedKeyRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/CreateSharedKeyRoute.kt new file mode 100644 index 00000000..6e81c652 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/CreateSharedKeyRoute.kt @@ -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() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/CreateSharedKeyViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/CreateSharedKeyViewModel.kt new file mode 100644 index 00000000..be4898e6 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/CreateSharedKeyViewModel.kt @@ -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, + val chatRepository: ChatRepository, + val dkgRepository: DkgRepository, +) : ViewModel() { + + var uiState: CreateSharedKeyUIState by mutableStateOf(initialUIState) + private set + + private val logger = Logger.withTag(TAG) + + val isActionPending: MutableState = 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 = 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, + chatRepository: ChatRepository, + dkgRepository: DkgRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + CreateSharedKeyViewModel( + chatRoomId = chatRoomId, + activeUserPublicKey = activeUserPublicKey, + initialUIState = initialUIState, + activeIdentityStateFlow = activeIdentityStateFlow, + chatRepository = chatRepository, + dkgRepository = dkgRepository, + ) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/CreateSharedKeyUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/CreateSharedKeyUIState.kt new file mode 100644 index 00000000..3942a9b9 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/CreateSharedKeyUIState.kt @@ -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 +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/CreateSharedKeyViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/CreateSharedKeyViewModelJvmTest.kt new file mode 100644 index 00000000..3c711c64 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/CreateSharedKeyViewModelJvmTest.kt @@ -0,0 +1,229 @@ +package com.machankura.bennu.compose.ui.view.model + +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.phoenix.utils.preferences.InternalPrefs +import fr.acinq.phoenix.utils.preferences.UserPrefs +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import okio.Path.Companion.toPath +import org.junit.Rule +import org.junit.rules.TemporaryFolder +import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.DkgSession +import com.machankura.bennu.compose.database.model.Participant +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.database.model.intermdiate.LocalParticipant +import com.machankura.bennu.compose.database.model.types.DkgRitualStage +import com.machankura.bennu.compose.identity.Identity +import com.machankura.bennu.compose.identity.IdentityKind +import com.machankura.bennu.compose.identity.toWalletId +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.DkgRepository +import com.machankura.bennu.compose.ui.view.state.CreateSharedKeyUIState +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNull + +/** + * The one screen that starts a group's own key ceremony. + * + * What it must decide before it draws a button: whether the room can hold a + * ceremony of its own at all, and whether it already has one. A Marmot room + * cannot, and the ceremony screen offering it one anyway is how a second + * ceremony opened beside a subgroup's -- see docs/ceremony-creation.md. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class CreateSharedKeyViewModelJvmTest { + @get:Rule + val temporaryFolder = TemporaryFolder() + + @BeforeTest + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + } + + @AfterTest + fun tearDown() { + Dispatchers.resetMain() + } + + private val chatRoomId = "9a17".repeat(16) + + private val key = PrivateKey(ByteVector32("0e".repeat(32))) + private val ada = "a".repeat(64) + private val bob = "b".repeat(64) + private val cleo = "c".repeat(64) + + private fun room( + members: List = listOf(ada, bob, cleo), + mlsGroupState: String? = null, + ) = LocalChatRoom( + chatRoom = ChatRoom( + id = chatRoomId, + userPublicKey = ada, + subject = "Checkers", + description = null, + mlsGroupState = mlsGroupState, + ), + localParticipants = members.map { + LocalParticipant(Participant(participantPublicKey = it, chatRoomId = chatRoomId, relayHint = null), null) + }, + ) + + private fun session(id: String, stage: DkgRitualStage) = DkgSession( + id = id, + chatRoomId = chatRoomId, + coordinatorPublicKey = bob, + userPublicKey = ada, + threshold = 2, + participantCount = 3, + stage = stage, + hostPublicKey = ada, + round1Random = "aa".repeat(32), + round2AuxRandom = "bb".repeat(32), + ) + + /** What `proposeRitual` was asked for, one entry per call. */ + private val proposed = mutableListOf() + + private fun dkgRepository(own: DkgSession? = null) = + object : DkgRepository by DkgRepository.NO_OP_DKG_REPOSITORY { + override fun observeLatestSessionForChatRoom( + chatRoomId: String, + parentChatRoomId: String?, + ): Flow = flowOf(own.takeIf { parentChatRoomId == null }) + + override suspend fun proposeRitual( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + threshold: Int, + parentChatRoomId: HexKey?, + participantPublicKeys: Set?, + subject: String? + ): DkgSession? { + proposed += threshold + return session("new".padEnd(64, '0'), DkgRitualStage.COLLECTING_HOST_KEYS) + } + } + + private fun chatRepository(room: LocalChatRoom?) = + object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { + override suspend fun getChatRoomByIdentifier(id: HexKey): LocalChatRoom? = + room.takeIf { id == chatRoomId } + } + + private fun prefsStore(name: String) = PreferenceDataStoreFactory.createWithPath { + temporaryFolder.newFolder().resolve("$name.preferences_pb").path.toPath() + } + + private fun viewModel(room: LocalChatRoom?, own: DkgSession? = null) = CreateSharedKeyViewModel( + chatRoomId = chatRoomId, + activeUserPublicKey = ada, + initialUIState = CreateSharedKeyUIState.Loading, + activeIdentityStateFlow = MutableStateFlow( + Identity.signing( + id = key.publicKey().xOnly().toWalletId(), + kind = IdentityKind.NostrSecret, + nostrPrivateKey = key, + userPrefs = UserPrefs(prefsStore("user")), + internalPrefs = InternalPrefs(prefsStore("internal")), + business = null, + ) + ), + chatRepository = chatRepository(room), + dkgRepository = dkgRepository(own), + ) + + private suspend fun CreateSharedKeyViewModel.awaitSettled(): CreateSharedKeyUIState = + withTimeout(5_000) { + while (uiState == CreateSharedKeyUIState.Loading) delay(10) + uiState + } + + @Test + fun `a group with no ceremony is offered one, at the majority default`(): Unit = runBlocking { + val viewModel = viewModel(room()) + viewModel.initiate() + + val loaded = assertIs(viewModel.awaitSettled()) + assertEquals(3, loaded.participantCount) + assertEquals(2, viewModel.threshold.value) + + val opened = CompletableDeferred() + viewModel.create { opened.complete(it) } + + assertEquals("new".padEnd(64, '0'), withTimeout(5_000) { opened.await() }) + assertEquals(listOf(2), proposed) + } + + @Test + fun `a group with a ceremony already is handed to it`(): Unit = runBlocking { + val running = session("run".padEnd(64, '0'), DkgRitualStage.COLLECTING_ROUND_1) + val viewModel = viewModel(room(), own = running) + viewModel.initiate() + + assertEquals(CreateSharedKeyUIState.Existing(running.id), viewModel.awaitSettled()) + assertEquals(emptyList(), proposed, "and nothing is proposed") + } + + @Test + fun `a failed ceremony is there to be replaced`(): Unit = runBlocking { + val failed = session("bad".padEnd(64, '0'), DkgRitualStage.FAILED) + val viewModel = viewModel(room(), own = failed) + viewModel.initiate() + + assertIs(viewModel.awaitSettled()) + } + + @Test + fun `a Marmot room is refused, and says why`(): Unit = runBlocking { + val viewModel = viewModel(room(mlsGroupState = "state")) + viewModel.initiate() + + assertEquals( + CreateSharedKeyUIState.Refused(CreateSharedKeyUIState.Refused.Reason.MARMOT_ROOM), + viewModel.awaitSettled(), + ) + + viewModel.create { error("a refused room opens nothing") } + assertEquals(emptyList(), proposed) + } + + @Test + fun `a group of one is refused`(): Unit = runBlocking { + val viewModel = viewModel(room(members = listOf(ada))) + viewModel.initiate() + + assertEquals( + CreateSharedKeyUIState.Refused(CreateSharedKeyUIState.Refused.Reason.TOO_FEW_MEMBERS), + viewModel.awaitSettled(), + ) + } + + @Test + fun `a room that cannot be read is an error with a way to retry`(): Unit = runBlocking { + val viewModel = viewModel(room = null) + viewModel.initiate() + + val error = assertIs(viewModel.awaitSettled()) + assertEquals(CreateSharedKeyUIState.Error.Reason.ROOM_NOT_FOUND, error.reason) + assertNull(proposed.firstOrNull()) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModelJvmTest.kt index 1ec9cc1a..36ef16e0 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModelJvmTest.kt @@ -187,6 +187,7 @@ class DkgRitualViewModelJvmTest { viewModel.initiate() assertEquals(sessionId, viewModel.awaitLoaded().session?.id) + val watchers = sessionSubscriptions // What the screen does each time it comes back into view. viewModel.initiate() @@ -197,7 +198,7 @@ class DkgRitualViewModelJvmTest { assertEquals(sessionId, state.session?.id, "the ceremony is never dropped from the screen") delay(5) } - assertEquals(1, sessionSubscriptions, "and its watchers are started once, not once per visit") + assertEquals(watchers, sessionSubscriptions, "and its watchers are started once, not once per visit") } @Test