diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 6fe92099..74872822 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -643,6 +643,21 @@ %1$s has changed its delay since you asked. Asking again makes a new request at the new delay. %1$s has stopped guarding members' wallets, so this request won't be signed. You can discard it. %1$s would refuse this request. Asking again makes a new one. + Guards members' wallets + Doesn't guard members' wallets + Stopped guarding new members' wallets + After %1$s + Guard members' wallets + How long before this group can take a coin from a member's wallet + A coin the member moves starts waiting again, so a long delay lets them keep their coins out of reach by moving them. + Wallets already guarded keep the delay they were guarded at. + Members whose app is older than this one can only be guarded at 12 blocks, and don't know this group can close. + Ask the group + Stop guarding new wallets + Stop guarding new members' wallets? + Wallets already guarded stay guarded, and this group can still take their coins after their delay. + Stop + Couldn't ask the group. This group doesn't guard members' wallets. This group has stopped guarding members' wallets. You have no guarded wallets. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMemberWalletRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMemberWalletRepository.kt index 15ea4877..dfe62b02 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMemberWalletRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMemberWalletRepository.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.database.repository +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent import co.touchlab.kermit.Logger import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.database.model.FrostSigningSession @@ -108,6 +109,13 @@ class DatabaseMemberWalletRepository( override fun observeSpends(walletId: String): Flow> = database.memberWalletDao().observeSpends(walletId) + override suspend fun policyOf(chatRoomId: String): MemberWalletPolicyEvent.Policy? = try { + MemberWalletManager.policyFor(database, chatRoomId) + } catch (e: Throwable) { + logger.e("Error reading $chatRoomId's member-wallet policy", e) + null + } + override suspend fun memberWalletsOf(chatRoomId: String): List = try { MemberWalletManager.memberWalletsOf(database, chatRoomId) } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MemberWalletRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MemberWalletRepository.kt index 573db498..5230dc8a 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MemberWalletRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MemberWalletRepository.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.repository +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent import com.machankura.bennu.compose.database.model.FrostSigningSession import com.machankura.bennu.compose.database.model.MemberWallet import com.machankura.bennu.compose.managers.GuardianManager @@ -71,6 +72,9 @@ interface MemberWalletRepository { /** The member wallets [chatRoomId] guards, and the requests waiting for a signer to put them to it. */ suspend fun memberWalletsOf(chatRoomId: String): List + /** [chatRoomId]'s newest member-wallet policy this device holds, or null. See `MemberWalletManager.policyFor`. */ + suspend fun policyOf(chatRoomId: String): MemberWalletPolicyEvent.Policy? + /** Puts a member's request to [chatRoomId]'s quorum as the active profile, which counts as its approval. */ suspend fun putToGroup(chatRoomId: String, request: Event): FrostSigningSession @@ -97,6 +101,8 @@ interface MemberWalletRepository { override suspend fun recordChain(txid: String, confirmations: Int?, broadcastAt: Instant?) = Unit override fun observeSpends(walletId: String): Flow> = flowOf(emptyList()) override suspend fun memberWalletsOf(chatRoomId: String): List = emptyList() + + override suspend fun policyOf(chatRoomId: String): MemberWalletPolicyEvent.Policy? = null override suspend fun putToGroup(chatRoomId: String, request: Event): FrostSigningSession = throw UnsupportedOperationException("no repository") override suspend fun guardedByGroupsHere(ownerPublicKey: HexKey): List = emptyList() } 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 3a845706..91de9ec7 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 @@ -1,5 +1,11 @@ package com.machankura.bennu.compose.ui.composable +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Box +import bennu.composeapp.generated.resources.change +import bennu.composeapp.generated.resources.guard_members_wallets +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent +import com.machankura.bennu.compose.ui.composable.navigation.routes.MemberWalletPolicyRoute import bennu.composeapp.generated.resources.guarded_wallet_after import com.machankura.bennu.compose.ui.composable.widgets.delayText import com.machankura.bennu.compose.managers.MemberWalletManager @@ -468,7 +474,7 @@ fun ChatRoomDetailScreen( // A member's wallet is a person, not a room, so it is its // own section and its row opens the person -- there is no // chat to open. docs/member-guarded-wallets.md, Phase 11. - if (chatRoomDetailUIState.memberWallets.isNotEmpty() || chatRoomDetailUIState.canAskForMemberWallet) { + if (chatRoomDetailUIState.memberWallets.isNotEmpty() || chatRoomDetailUIState.canAskForMemberWallet || chatRoomDetailUIState.showsMemberWalletPolicy) { item { HorizontalDivider() } item { Text( @@ -476,6 +482,23 @@ fun ChatRoomDetailScreen( style = MaterialTheme.typography.labelMedium ) } + // Whether the group guards members' wallets at all, and at + // what delay -- first, because every row under it is a + // wallet it agreed to under one. docs/member-wallet-delay.md. + if (chatRoomDetailUIState.showsMemberWalletPolicy) { + item { + MemberWalletPolicyRow( + policy = chatRoomDetailUIState.memberWalletPolicy, + onChange = if (chatRoomDetailUIState.canSponsor) { + { + onNavigateToRoute.invoke( + MemberWalletPolicyRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId) + ) + } + } else null, + ) + } + } items( items = chatRoomDetailUIState.memberWallets, key = { "member-wallet-" + it.walletId } @@ -1194,6 +1217,31 @@ private fun SubgroupCard( } } +/** + * The group's own stand on its members' wallets, with *Change* -- or *Guard + * members' wallets* when it has none open -- for a device that can put a change + * to the group. `docs/member-wallet-delay.md`, Phase 6. + */ +@Composable +private fun MemberWalletPolicyRow(policy: MemberWalletPolicyEvent.Policy?, onChange: (() -> Unit)?) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + Box(modifier = Modifier.weight(1f)) { MemberWalletPolicyState(policy) } + onChange?.let { change -> + TextButton(onClick = change) { + Text( + stringResource( + if (policy is MemberWalletPolicyEvent.Policy.Open) Res.string.change else Res.string.guard_members_wallets + ) + ) + } + } + } +} + /** * *Guarded wallet, after 144 blocks, about 1 day* or *Unguarded wallet* for a * policy a parent decided, and null for one it left to the subgroup -- diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletPolicyScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletPolicyScreen.kt new file mode 100644 index 00000000..e40514cf --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletPolicyScreen.kt @@ -0,0 +1,229 @@ +package com.machankura.bennu.compose.ui.composable + +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.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.lifecycle.viewmodel.compose.viewModel +import bennu.composeapp.generated.resources.Res +import bennu.composeapp.generated.resources.a_coin_the_member_moves_starts_waiting_again +import bennu.composeapp.generated.resources.after_s +import bennu.composeapp.generated.resources.ask_the_group +import bennu.composeapp.generated.resources.cancel +import bennu.composeapp.generated.resources.couldn_t_ask_the_group +import bennu.composeapp.generated.resources.doesn_t_guard_members_wallets +import bennu.composeapp.generated.resources.guards_members_wallets +import bennu.composeapp.generated.resources.how_long_before_this_group_can_take_a_member_s_coin +import bennu.composeapp.generated.resources.members_guarded_wallets +import bennu.composeapp.generated.resources.members_on_older_apps_can_only_be_guarded_at_12 +import bennu.composeapp.generated.resources.stop +import bennu.composeapp.generated.resources.stop_guarding_new_members_wallets_question +import bennu.composeapp.generated.resources.stop_guarding_new_wallets +import bennu.composeapp.generated.resources.stopped_guarding_new_members_wallets +import bennu.composeapp.generated.resources.wallets_already_guarded_keep_their_delay +import bennu.composeapp.generated.resources.wallets_already_guarded_stay_guarded +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.FrostSigningRepository +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.Route +import com.machankura.bennu.compose.ui.composable.widgets.ErrorState +import com.machankura.bennu.compose.ui.composable.widgets.GuardianDelayChooser +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.delayText +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.MemberWalletPolicyViewModel +import com.machankura.bennu.compose.ui.view.state.MemberWalletPolicyUIState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import org.jetbrains.compose.resources.stringResource + +/** + * Whether the group guards its members' wallets, at what delay, and closing it + * again -- `docs/member-wallet-delay.md`, Phase 6. + * + * What a change reaches is said before the button: only wallets asked for from + * now on, never one already guarded, and closing releases nothing. A device + * that cannot sign sees where the group stands and nothing to press. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun MemberWalletPolicyScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + initialUIState: MemberWalletPolicyUIState = MemberWalletPolicyUIState.Loading, + chatRepository: ChatRepository, + memberWalletRepository: MemberWalletRepository, + frostSigningRepository: FrostSigningRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val viewModel: MemberWalletPolicyViewModel = viewModel( + factory = MemberWalletPolicyViewModel.factory( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + initialUIState = initialUIState, + chatRepository = chatRepository, + memberWalletRepository = memberWalletRepository, + frostSigningRepository = frostSigningRepository, + ) + ) + + LaunchedEffect(chatRoomId) { + if (initialUIState == MemberWalletPolicyUIState.Loading) viewModel.initiate() + } + + // Read above the handlers, which are not composable; the caller's scope, so + // the message outlives the screen moving onto the signing session. + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotAsk = stringResource(Res.string.couldn_t_ask_the_group) + val toSession = { sessionId: String -> + onNavigateToRoute(FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId)) + } + var confirmingClose by remember { mutableStateOf(false) } + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(stringResource(Res.string.members_guarded_wallets)) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + } + ) { padding -> + ScreenStateTransition(viewModel.uiState) { uiState -> + when (val state = uiState) { + MemberWalletPolicyUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) + + is MemberWalletPolicyUIState.Error -> ErrorState( + modifier = Modifier.padding(padding), + message = state.message, + // Reloading reads the group again, which is what failed. + onRetry = viewModel::initiate, + ) + + is MemberWalletPolicyUIState.Loaded -> Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + MemberWalletPolicyState(state.policy) + + if (state.canSign) { + GuardianDelayChooser( + title = stringResource(Res.string.how_long_before_this_group_can_take_a_member_s_coin), + consequence = stringResource(Res.string.a_coin_the_member_moves_starts_waiting_again), + input = viewModel.delay.input.value, + delay = viewModel.delay.delay(), + isCustom = viewModel.delay.isCustom.value, + problem = viewModel.delay.problem(), + onPreset = viewModel.delay::pick, + onCustom = viewModel.delay::useCustom, + onInput = viewModel.delay::type, + ) + Text( + text = stringResource(Res.string.wallets_already_guarded_keep_their_delay), + style = MaterialTheme.typography.bodyMedium, + ) + Text( + text = stringResource(Res.string.members_on_older_apps_can_only_be_guarded_at_12), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + // Disabled, with the reason, while there is nothing to ask: + // a delay out of range, or the one the group already has. + val problem = viewModel.openProblem() + Button( + onClick = { viewModel.proposeOpen(onSuccess = toSession, onFailure = { notify(couldNotAsk) }) }, + enabled = problem == null && !viewModel.isActionPending.value, + ) { Text(stringResource(Res.string.ask_the_group)) } + if (problem != null && viewModel.delay.problem() == null) { + Text(text = problem, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + + if (viewModel.canClose()) { + OutlinedButton( + onClick = { confirmingClose = true }, + enabled = !viewModel.isActionPending.value, + ) { Text(stringResource(Res.string.stop_guarding_new_wallets)) } + } + } + } + } + } + } + + if (confirmingClose) { + AlertDialog( + onDismissRequest = { confirmingClose = false }, + title = { Text(stringResource(Res.string.stop_guarding_new_members_wallets_question)) }, + // What closing leaves alone, said where it is decided: the group's leaf + // is in every address of every wallet it already guards. + text = { Text(stringResource(Res.string.wallets_already_guarded_stay_guarded)) }, + confirmButton = { + TextButton(onClick = { + confirmingClose = false + viewModel.proposeClose(onSuccess = toSession, onFailure = { notify(couldNotAsk) }) + }) { Text(stringResource(Res.string.stop)) } + }, + dismissButton = { + TextButton(onClick = { confirmingClose = false }) { Text(stringResource(Res.string.cancel)) } + }, + ) + } +} + +/** + * Where the group stands on its members' wallets: guarding them after a delay, + * never having said so, or having stopped. Shared with the group's page. + */ +@Composable +internal fun MemberWalletPolicyState(policy: MemberWalletPolicyEvent.Policy?) { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + Text( + text = stringResource( + when (policy) { + is MemberWalletPolicyEvent.Policy.Open -> Res.string.guards_members_wallets + is MemberWalletPolicyEvent.Policy.Closed -> Res.string.stopped_guarding_new_members_wallets + null -> Res.string.doesn_t_guard_members_wallets + } + ), + style = MaterialTheme.typography.titleMedium, + ) + if (policy is MemberWalletPolicyEvent.Policy.Open) { + Text( + text = stringResource(Res.string.after_s, delayText(policy.delay)), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectSubgroupAdminsScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectSubgroupAdminsScreen.kt index b0173426..0a3275cf 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectSubgroupAdminsScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/SelectSubgroupAdminsScreen.kt @@ -1,22 +1,8 @@ package com.machankura.bennu.compose.ui.composable import bennu.composeapp.generated.resources.a_coin_the_subgroup_moves_starts_waiting_again -import bennu.composeapp.generated.resources.delay_in_blocks -import bennu.composeapp.generated.resources.delay_custom -import bennu.composeapp.generated.resources.delay_longest -import bennu.composeapp.generated.resources.delay_six_months -import bennu.composeapp.generated.resources.delay_one_month -import bennu.composeapp.generated.resources.delay_one_week -import bennu.composeapp.generated.resources.delay_one_day -import bennu.composeapp.generated.resources.delay_two_hours -import bennu.composeapp.generated.resources.delay_one_hour import bennu.composeapp.generated.resources.how_long_before_this_group_can_spend_a_coin -import com.machankura.bennu.compose.ui.composable.widgets.delayText -import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.material3.FilterChip -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.foundation.layout.FlowRow -import androidx.compose.foundation.layout.ExperimentalLayoutApi +import com.machankura.bennu.compose.ui.composable.widgets.GuardianDelayChooser import com.machankura.bennu.compose.ui.view.state.onlyGuarded import com.machankura.bennu.compose.ui.view.state.canGuard import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy @@ -325,6 +311,8 @@ fun SelectSubgroupAdminsScreen( if (viewModel.walletPolicy.value == SubgroupWalletPolicy.GUARDED && state.canGuard) { item { GuardianDelayChooser( + title = stringResource(Res.string.how_long_before_this_group_can_spend_a_coin), + consequence = stringResource(Res.string.a_coin_the_subgroup_moves_starts_waiting_again), input = viewModel.guardianDelayInput.value, delay = viewModel.guardianDelay(), isCustom = viewModel.isCustomDelay.value, @@ -453,81 +441,6 @@ private fun WalletPolicyChooser( } } -/** - * How long a coin in the guarded subgroup's wallet waits before this group can - * take it -- the parent's own leaf, `docs/guardian-delay.md`. Presets for what - * people mean, and a field for the exact number of blocks, which says what it - * works out to while it is typed. - */ -@OptIn(ExperimentalLayoutApi::class) -@Composable -private fun GuardianDelayChooser( - input: String, - delay: Long?, - isCustom: Boolean, - problem: String?, - onPreset: (Long) -> Unit, - onCustom: () -> Unit, - onInput: (String) -> Unit, -) { - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - Text( - text = stringResource(Res.string.how_long_before_this_group_can_spend_a_coin), - style = MaterialTheme.typography.titleSmall - ) - FlowRow( - horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - SelectSubgroupAdminsViewModel.DELAY_PRESETS.forEach { preset -> - FilterChip( - selected = !isCustom && delay == preset, - onClick = { onPreset(preset) }, - label = { Text(presetLabel(preset)) } - ) - } - FilterChip( - selected = isCustom, - onClick = onCustom, - label = { Text(stringResource(Res.string.delay_custom)) } - ) - } - if (isCustom) { - OutlinedTextField( - value = input, - onValueChange = onInput, - modifier = Modifier.fillMaxWidth(), - singleLine = true, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), - label = { Text(stringResource(Res.string.delay_in_blocks)) }, - isError = problem != null, - supportingText = { Text(problem ?: delay?.let { delayText(it) }.orEmpty()) } - ) - } else if (delay != null && problem == null) { - Text(text = delayText(delay), style = MaterialTheme.typography.bodyMedium) - } - Text( - text = stringResource(Res.string.a_coin_the_subgroup_moves_starts_waiting_again), - style = MaterialTheme.typography.bodySmall - ) - } -} - -/** What a preset chip calls its delay: the time it was chosen to be, not its estimate. */ -@Composable -private fun presetLabel(blocks: Long): String = when (blocks) { - 6L -> stringResource(Res.string.delay_one_hour) - 12L -> stringResource(Res.string.delay_two_hours) - 144L -> stringResource(Res.string.delay_one_day) - 1_008L -> stringResource(Res.string.delay_one_week) - 4_320L -> stringResource(Res.string.delay_one_month) - 26_280L -> stringResource(Res.string.delay_six_months) - else -> stringResource(Res.string.delay_longest) -} - @Composable private fun WalletPolicyRow( title: String, 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 9825b82a..cd60e65b 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 @@ -1,5 +1,7 @@ package com.machankura.bennu.compose.ui.composable.navigation +import com.machankura.bennu.compose.ui.composable.MemberWalletPolicyScreen +import com.machankura.bennu.compose.ui.composable.navigation.routes.MemberWalletPolicyRoute import com.machankura.bennu.compose.ui.composable.GroupSendScreen import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupSendRoute import androidx.compose.foundation.layout.fillMaxSize @@ -1193,6 +1195,23 @@ fun BennuNavHost( } ) } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + MemberWalletPolicyScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + chatRepository = databaseChatRepository, + memberWalletRepository = databaseMemberWalletRepository, + frostSigningRepository = databaseFrostSigningRepository, + onNavigateToRoute = { actionRoute -> + navController.navigate(route = actionRoute) + }, + onNavigateBack = { + navController.popBackStack() + } + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberWalletPolicyRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberWalletPolicyRoute.kt new file mode 100644 index 00000000..237bfd83 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/MemberWalletPolicyRoute.kt @@ -0,0 +1,13 @@ +package com.machankura.bennu.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** + * Whether the group [chatRoomId] guards its members' wallets, at what delay, + * and closing it again -- `docs/member-wallet-delay.md`, Phase 6. + */ +@Serializable +data class MemberWalletPolicyRoute( + val activeUserPublicKey: String, + val chatRoomId: String, +): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/GuardianDelayChooser.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/GuardianDelayChooser.kt new file mode 100644 index 00000000..96137ae7 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/GuardianDelayChooser.kt @@ -0,0 +1,109 @@ +package com.machankura.bennu.compose.ui.composable.widgets + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.FilterChip +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.input.KeyboardType +import bennu.composeapp.generated.resources.Res +import bennu.composeapp.generated.resources.delay_custom +import bennu.composeapp.generated.resources.delay_in_blocks +import bennu.composeapp.generated.resources.delay_longest +import bennu.composeapp.generated.resources.delay_one_day +import bennu.composeapp.generated.resources.delay_one_hour +import bennu.composeapp.generated.resources.delay_one_month +import bennu.composeapp.generated.resources.delay_one_week +import bennu.composeapp.generated.resources.delay_six_months +import bennu.composeapp.generated.resources.delay_two_hours +import com.machankura.bennu.compose.ui.theme.spacing +import com.machankura.bennu.compose.ui.view.model.GuardianDelayInput +import org.jetbrains.compose.resources.stringResource + +/** + * How long a coin waits before a group can take it through its own leaf: in a + * guarded subgroup's wallet (`docs/guardian-delay.md`) or in the wallets it + * guards for its members (`docs/member-wallet-delay.md`). Presets for what + * people mean, and a field for the exact number of blocks, which says what it + * works out to while it is typed. + * + * The words are the caller's -- [title], and [consequence], the trade a long + * delay makes -- because *the subgroup* and *the member* differ. + */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +fun GuardianDelayChooser( + title: String, + consequence: String, + input: String, + delay: Long?, + isCustom: Boolean, + problem: String?, + onPreset: (Long) -> Unit, + onCustom: () -> Unit, + onInput: (String) -> Unit, +) { + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) + ) { + Text( + text = title, + style = MaterialTheme.typography.titleSmall + ) + FlowRow( + horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) + ) { + GuardianDelayInput.PRESETS.forEach { preset -> + FilterChip( + selected = !isCustom && delay == preset, + onClick = { onPreset(preset) }, + label = { Text(presetLabel(preset)) } + ) + } + FilterChip( + selected = isCustom, + onClick = onCustom, + label = { Text(stringResource(Res.string.delay_custom)) } + ) + } + if (isCustom) { + OutlinedTextField( + value = input, + onValueChange = onInput, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + label = { Text(stringResource(Res.string.delay_in_blocks)) }, + isError = problem != null, + supportingText = { Text(problem ?: delay?.let { delayText(it) }.orEmpty()) } + ) + } else if (delay != null && problem == null) { + Text(text = delayText(delay), style = MaterialTheme.typography.bodyMedium) + } + Text( + text = consequence, + style = MaterialTheme.typography.bodySmall + ) + } +} + +/** What a preset chip calls its delay: the time it was chosen to be, not its estimate. */ +@Composable +private fun presetLabel(blocks: Long): String = when (blocks) { + 6L -> stringResource(Res.string.delay_one_hour) + 12L -> stringResource(Res.string.delay_two_hours) + 144L -> stringResource(Res.string.delay_one_day) + 1_008L -> stringResource(Res.string.delay_one_week) + 4_320L -> stringResource(Res.string.delay_one_month) + 26_280L -> stringResource(Res.string.delay_six_months) + else -> stringResource(Res.string.delay_longest) +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt index 0e4f879e..3af59c15 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -111,6 +111,10 @@ class ChatRoomDetailViewModel( it == null || it == MemberWalletManager.Refusal.KEY_UNKNOWN }, canSponsor = canSign, + memberWalletPolicy = memberWalletRepository.policyOf(chatRoomId), + // Everybody in a Marmot group sees whether it guards members' + // wallets; only a signer is offered to change it. + showsMemberWalletPolicy = !isDisbanded && localChatRoom.chatRoom.mlsGroupState != null, ) } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GuardianDelayInput.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GuardianDelayInput.kt new file mode 100644 index 00000000..66f7999e --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GuardianDelayInput.kt @@ -0,0 +1,70 @@ +package com.machankura.bennu.compose.ui.view.model + +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.mutableStateOf +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.text.groupedBlocks + +/** + * A guardian delay as somebody is choosing it -- a preset, or blocks typed -- + * for the two screens that choose one: the subgroup picker + * (`docs/guardian-delay.md`) and the group's member-wallet policy + * (`docs/member-wallet-delay.md`). + * + * Holds the text as typed and never clamps it, so the field can say *at most + * 65,535 blocks* about the number somebody actually entered. + */ +class GuardianDelayInput(initial: Long = GuardianDerivation.DEFAULT_DELAY) { + /** The delay, in blocks, as typed or picked. */ + val input: MutableState = mutableStateOf(initial.toString()) + + /** Whether the delay is being typed rather than picked from a preset. */ + val isCustom: MutableState = mutableStateOf(initial !in PRESETS) + + /** Picks a preset. */ + fun pick(blocks: Long) { + isCustom.value = false + input.value = blocks.toString() + } + + /** Switches to typing, starting from the delay already chosen. */ + fun useCustom() { + isCustom.value = true + } + + /** What was typed, digits only, kept as typed. */ + fun type(value: String) { + input.value = value.filter { it in '0'..'9' }.take(MAX_DIGITS) + } + + /** Starts again from [blocks]: a preset as its chip, anything else in the field. */ + fun reset(blocks: Long) { + input.value = blocks.toString() + isCustom.value = blocks !in PRESETS + } + + /** The delay typed or picked, or null while the field holds no number. */ + fun delay(): Long? = input.value.toLongOrNull() + + /** Why the delay cannot be used, or null when it can. */ + fun problem(): String? { + val delay = delay() ?: return "Give the delay in blocks." + return when { + delay < GuardianDerivation.MIN_DELAY -> "A delay is at least ${GuardianDerivation.MIN_DELAY} blocks." + delay > GuardianDerivation.MAX_DELAY -> "A delay is at most ${GuardianDerivation.MAX_DELAY.groupedBlocks()} blocks." + else -> null + } + } + + companion object { + /** + * The delays offered as chips, in blocks -- `docs/guardian-delay.md`, D4: + * an hour, two (the default), a day, a week, a month, six months, and the + * longest a leaf can carry. + */ + val PRESETS: List = listOf(6L, 12L, 144L, 1_008L, 4_320L, 26_280L, GuardianDerivation.MAX_DELAY) + + /** Enough digits for anything past the ceiling, so the field can say so. */ + private const val MAX_DIGITS = 7 + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletPolicyViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletPolicyViewModel.kt new file mode 100644 index 00000000..dd904701 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletPolicyViewModel.kt @@ -0,0 +1,142 @@ +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.GuardianDerivation +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.FrostSigningRepository +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.ui.view.state.MemberWalletPolicyUIState +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * Whether a group guards its members' wallets, at what delay, and closing it + * again -- `docs/member-wallet-delay.md`, Phase 6. + * + * Proposes a policy the way opening a wallet proposes a statement: a signing + * session in the group's room, which proposing counts as approving. Nothing + * changes until a quorum signs, and every policy reaches only the wallets asked + * for after it -- one already guarded keeps its delay, and closing never + * releases it. + */ +class MemberWalletPolicyViewModel( + private val activeUserPublicKey: HexKey, + private val chatRoomId: String, + initialUIState: MemberWalletPolicyUIState, + private val chatRepository: ChatRepository, + private val memberWalletRepository: MemberWalletRepository, + private val frostSigningRepository: FrostSigningRepository, +) : ViewModel() { + private val logger = Logger.withTag(TAG) + + var uiState: MemberWalletPolicyUIState by mutableStateOf(initialUIState) + private set + + val isActionPending: MutableState = mutableStateOf(false) + + /** The delay being chosen, starting from the group's own or the default. */ + val delay = GuardianDelayInput() + + /** Whether [initiate] has set [delay] from the group's policy, which it does once. */ + private var started = false + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val room = chatRepository.getChatRoomByIdentifier(chatRoomId) + if (room == null) { + uiState = MemberWalletPolicyUIState.Error("Couldn't find the group") + return@launch + } + val policy = memberWalletRepository.policyOf(chatRoomId) + val canSign = room.chatRoom.mlsGroupState != null && chatRepository.canSign(chatRoomId) + if (!started) { + started = true + delay.reset((policy as? MemberWalletPolicyEvent.Policy.Open)?.delay ?: GuardianDerivation.DEFAULT_DELAY) + } + uiState = MemberWalletPolicyUIState.Loaded(room, policy, canSign) + } + } + + /** + * Why opening at the chosen delay cannot be proposed, or null when it can: + * a delay out of range, or the delay the group already has -- a quorum + * asked to restate itself is asked for nothing. + */ + fun openProblem(): String? { + delay.problem()?.let { return it } + val loaded = uiState as? MemberWalletPolicyUIState.Loaded ?: return "Still loading" + if (!loaded.canSign) return "This device can't put a change to the group." + val current = (loaded.policy as? MemberWalletPolicyEvent.Policy.Open)?.delay + if (current == delay.delay()) return "That is already this group's delay." + return null + } + + /** Whether closing can be proposed: only a group that is open. */ + fun canClose(): Boolean = (uiState as? MemberWalletPolicyUIState.Loaded)?.let { it.isOpen && it.canSign } == true + + /** Asks the group to guard members' wallets at the chosen delay. */ + fun proposeOpen(onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { + if (openProblem() != null) return + propose(MemberWalletPolicyEvent.open(delay.delay() ?: return), onSuccess, onFailure) + } + + /** Asks the group to stop guarding new members' wallets. */ + fun proposeClose(onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { + if (!canClose()) return + propose(MemberWalletPolicyEvent.closed(), onSuccess, onFailure) + } + + private fun propose(template: EventTemplate<*>, onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { + val loaded = uiState as? MemberWalletPolicyUIState.Loaded ?: return + if (isActionPending.value) return + isActionPending.value = true + + viewModelScope.launch(Dispatchers.IO) { + val session = runCatching { + frostSigningRepository.proposeSigning( + localChatRoom = loaded.localChatRoom, + userPublicKey = activeUserPublicKey, + kind = template.kind, + tags = template.tags, + content = template.content, + ) + }.onFailure { logger.e("Failed to propose a member-wallet policy for $chatRoomId", it) }.getOrNull() + + withContext(Dispatchers.Main) { + isActionPending.value = false + if (session != null) onSuccess(session.id) else onFailure() + } + } + } + + companion object { + private const val TAG = "MemberWalletPolicyViewModel" + + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + initialUIState: MemberWalletPolicyUIState = MemberWalletPolicyUIState.Loading, + chatRepository: ChatRepository, + memberWalletRepository: MemberWalletRepository, + frostSigningRepository: FrostSigningRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + MemberWalletPolicyViewModel(activeUserPublicKey, chatRoomId, initialUIState, chatRepository, memberWalletRepository, frostSigningRepository) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/SelectSubgroupAdminsViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/SelectSubgroupAdminsViewModel.kt index 8beb54ae..8166d4d0 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/SelectSubgroupAdminsViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/SelectSubgroupAdminsViewModel.kt @@ -1,7 +1,5 @@ package com.machankura.bennu.compose.ui.view.model -import com.machankura.bennu.compose.text.groupedBlocks -import com.machankura.bennu.compose.managers.GuardianDerivation import com.machankura.bennu.compose.ui.view.state.canGuard import com.machankura.bennu.compose.ui.view.state.onlyGuarded import com.machankura.bennu.compose.database.model.subgroupWalletPolicy @@ -101,17 +99,16 @@ class SelectSubgroupAdminsViewModel( /** * How long a coin in a guarded subgroup's wallet waits before this group can - * take it, in blocks, as typed -- `docs/guardian-delay.md`. The parent's own - * leaf only: each ancestor above keeps the delay it chose. - * - * Held as the text rather than a number, and never clamped, so the field can - * say *at most 65,535 blocks* about the number somebody actually entered. - * [guardianDelay] reads it. + * take it -- `docs/guardian-delay.md`. The parent's own leaf only: each + * ancestor above keeps the delay it chose. */ - val guardianDelayInput: MutableState = mutableStateOf(GuardianDerivation.DEFAULT_DELAY.toString()) + private val delay = GuardianDelayInput() + + /** The delay as typed; see [GuardianDelayInput]. */ + val guardianDelayInput: MutableState get() = delay.input /** Whether the delay is being typed rather than picked from a preset. */ - val isCustomDelay: MutableState = mutableStateOf(false) + val isCustomDelay: MutableState get() = delay.isCustom /** Whether [retrying] has been read into the form, which happens once. */ private var prefilled = false @@ -187,10 +184,7 @@ class SelectSubgroupAdminsViewModel( // failed ceremony can predate the parent's own certificate -- is pulled // back the way the threshold is pulled into its range. failed.subgroupWalletPolicy?.let(::setWalletPolicy) - failed.guardianDelay?.let { delay -> - guardianDelayInput.value = delay.toString() - isCustomDelay.value = delay !in DELAY_PRESETS - } + failed.guardianDelay?.let(delay::reset) } /** @@ -259,37 +253,26 @@ class SelectSubgroupAdminsViewModel( /** Picks a preset delay. */ fun setGuardianDelay(blocks: Long) { if (isActionPending.value) return - - isCustomDelay.value = false - guardianDelayInput.value = blocks.toString() + delay.pick(blocks) } /** Switches to typing a delay, starting from the one already chosen. */ fun useCustomDelay() { if (isActionPending.value) return - - isCustomDelay.value = true + delay.useCustom() } /** What was typed as the delay, kept as typed. */ fun setGuardianDelayInput(value: String) { if (isActionPending.value) return - - guardianDelayInput.value = value.filter { it in '0'..'9' }.take(MAX_DELAY_DIGITS) + delay.type(value) } /** The delay typed or picked, or null while the field holds no number. */ - fun guardianDelay(): Long? = guardianDelayInput.value.toLongOrNull() + fun guardianDelay(): Long? = delay.delay() /** Why the delay cannot be used, or null when it can. */ - fun guardianDelayProblem(): String? { - val delay = guardianDelay() ?: return "Give the delay in blocks." - return when { - delay < GuardianDerivation.MIN_DELAY -> "A delay is at least ${GuardianDerivation.MIN_DELAY} blocks." - delay > GuardianDerivation.MAX_DELAY -> "A delay is at most ${GuardianDerivation.MAX_DELAY.groupedBlocks()} blocks." - else -> null - } - } + fun guardianDelayProblem(): String? = delay.problem() /** The subgroup's admins: everyone ticked, plus the coordinator. */ fun adminCount(): Int = selectedPublicKeys.size + 1 @@ -438,15 +421,8 @@ class SelectSubgroupAdminsViewModel( } companion object { - /** - * The delays the picker offers, in blocks -- `docs/guardian-delay.md`, D4: - * an hour, two (the default), a day, a week, a month, six months, and the - * longest a leaf can carry. - */ - val DELAY_PRESETS: List = listOf(6L, 12L, 144L, 1_008L, 4_320L, 26_280L, GuardianDerivation.MAX_DELAY) - - /** Enough digits for anything past the ceiling, so the field can say so. */ - private const val MAX_DELAY_DIGITS = 7 + /** The delays the picker offers: [GuardianDelayInput.PRESETS]. */ + val DELAY_PRESETS: List get() = GuardianDelayInput.PRESETS private const val TAG = "SelectSubgroupAdminsViewModel" diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt index cf98a65a..444f84cc 100755 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.ui.view.state +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent import com.machankura.bennu.compose.managers.MemberWalletManager import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading import com.machankura.bennu.compose.nostr.wallet.GroupWallet @@ -102,6 +103,14 @@ sealed interface ChatRoomDetailUIState { val canAskForMemberWallet: Boolean = false, /** Whether this device holds a share, and so can put a member's request to the group. */ val canSponsor: Boolean = false, + /** + * Whether this group guards its members' wallets, and at what delay -- + * its newest member-wallet policy, or null for one it never signed. + * `docs/member-wallet-delay.md`. + */ + val memberWalletPolicy: MemberWalletPolicyEvent.Policy? = null, + /** Whether to show that at all: a Marmot group, still going. */ + val showsMemberWalletPolicy: Boolean = false, ): ChatRoomDetailUIState data class Error( diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberWalletPolicyUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberWalletPolicyUIState.kt new file mode 100644 index 00000000..c327b17b --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberWalletPolicyUIState.kt @@ -0,0 +1,23 @@ +package com.machankura.bennu.compose.ui.view.state + +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent + +sealed interface MemberWalletPolicyUIState { + data object Loading : MemberWalletPolicyUIState + + data class Error(val message: String) : MemberWalletPolicyUIState + + /** + * The group, and what it says about its members' wallets now: [policy] is + * its newest, open or closed, or null for one it never signed. [canSign] is + * whether this device can put a change to the group. + */ + data class Loaded( + val localChatRoom: LocalChatRoom, + val policy: MemberWalletPolicyEvent.Policy?, + val canSign: Boolean, + ) : MemberWalletPolicyUIState { + val isOpen: Boolean get() = policy is MemberWalletPolicyEvent.Policy.Open + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletPolicyViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletPolicyViewModelJvmTest.kt new file mode 100644 index 00000000..c9648628 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletPolicyViewModelJvmTest.kt @@ -0,0 +1,141 @@ +package com.machankura.bennu.compose.ui.view.model + +import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.FrostSigningSession +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.managers.GroupFixtures +import com.machankura.bennu.compose.nostr.wallet.MemberWalletPolicyEvent +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.FrostSigningRepository +import com.machankura.bennu.compose.repository.MemberWalletRepository +import com.machankura.bennu.compose.ui.view.state.MemberWalletPolicyUIState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Opening a group to its members' wallets, changing the delay, and closing it -- + * `docs/member-wallet-delay.md`, Phase 6. The repositories are fakes: what is + * under test is what the screen offers and what it proposes. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class MemberWalletPolicyViewModelJvmTest { + @BeforeTest + fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) + + @AfterTest + fun tearDown() = Dispatchers.resetMain() + + private val group = GroupFixtures.keyMaterial("6a0b") + private val chatRoomId = GroupFixtures.roomOf(group) + private val me = "a".repeat(64) + + private val room = LocalChatRoom( + chatRoom = ChatRoom(id = chatRoomId, userPublicKey = me, subject = "#Council", description = null, mlsGroupState = "state") + ) + + private fun chat(canSign: Boolean) = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { + override suspend fun getChatRoomByIdentifier(identifier: String): LocalChatRoom? = room + override suspend fun canSign(chatRoomId: String): Boolean = canSign + } + + private fun members(policy: MemberWalletPolicyEvent.Policy?) = object : MemberWalletRepository by MemberWalletRepository.NO_OP { + override suspend fun policyOf(chatRoomId: String): MemberWalletPolicyEvent.Policy? = policy + } + + private class Proposing : FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY { + var proposed: Pair>>? = null + override suspend fun proposeSigning( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + kind: Kind, + tags: Array>, + content: String, + ): FrostSigningSession? { + proposed = kind to tags + return null + } + } + + private fun open(delay: Long) = MemberWalletPolicyEvent.verify(GroupFixtures.memberWalletPolicy(group, delay), chatRoomId) + private fun closed() = MemberWalletPolicyEvent.verify(GroupFixtures.memberWalletPolicy(group, null), chatRoomId) + + private fun loaded(policy: MemberWalletPolicyEvent.Policy?, canSign: Boolean = true, signing: FrostSigningRepository = Proposing()) = + MemberWalletPolicyViewModel(me, chatRoomId, MemberWalletPolicyUIState.Loading, chat(canSign), members(policy), signing).apply { + initiate() + runBlocking { withTimeout(5_000) { while (uiState !is MemberWalletPolicyUIState.Loaded) delay(10) } } + } + + private fun Proposing.awaitProposed() = runBlocking { withTimeout(5_000) { while (proposed == null) delay(10) } }.let { assertNotNull(proposed) } + + @Test + fun `a group opening for the first time starts at 12, an open one at its own delay`() { + assertEquals(12L, loaded(null).delay.delay()) + assertEquals(12L, loaded(closed()).delay.delay()) + assertEquals(4_320L, loaded(open(4_320)).delay.delay()) + assertTrue(loaded(open(4_320)).delay.isCustom.value.not(), "a preset comes back as its chip") + assertTrue(loaded(open(2_016)).delay.isCustom.value, "anything else in the field") + } + + @Test + fun `opening proposes an open policy at the chosen delay`() { + val signing = Proposing() + val viewModel = loaded(null, signing = signing) + viewModel.delay.pick(1_008) + assertNull(viewModel.openProblem()) + + viewModel.proposeOpen(onSuccess = {}, onFailure = {}) + val (kind, tags) = signing.awaitProposed() + assertEquals(MemberWalletPolicyEvent.KIND, kind) + assertTrue(tags.any { it.toList() == listOf("guardian_delay", "1008") }) + } + + @Test + fun `a delay out of range, or the group's own, is not proposed`() { + val viewModel = loaded(open(144)) + assertEquals("That is already this group's delay.", viewModel.openProblem()) + + viewModel.delay.useCustom() + viewModel.delay.type("5") + assertEquals("A delay is at least 6 blocks.", viewModel.openProblem()) + viewModel.delay.type("65536") + assertEquals("A delay is at most 65,535 blocks.", viewModel.openProblem()) + } + + @Test + fun `closing is offered only to an open group, and proposes a closed policy`() { + assertFalse(loaded(null).canClose()) + assertFalse(loaded(closed()).canClose()) + + val signing = Proposing() + val viewModel = loaded(open(144), signing = signing) + assertTrue(viewModel.canClose()) + viewModel.proposeClose(onSuccess = {}, onFailure = {}) + val (_, tags) = signing.awaitProposed() + assertTrue(tags.any { it.toList() == listOf("closed") }) + } + + @Test + fun `a device that cannot sign is offered nothing to propose`() { + val viewModel = loaded(open(144), canSign = false) + assertIs(viewModel.uiState) + assertNotNull(viewModel.openProblem()) + assertFalse(viewModel.canClose()) + } +}