diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index f89482b7..9e0cc242 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -701,6 +701,10 @@ Shorter Longer Proposing shows this group's admins to the admins of every group named here, and each group that accepts shows its own. Once every group has accepted, every admin of every group can join the key ceremony. + Has announced no inbox, so the proposal could not reach it + Set up this group's inbox first: a confederation's proposal and every answer are sent from it. + A confederation can name at most %1$d groups + Try the key ceremony again This group shows its %1$d admins and its threshold of %2$d to the groups it names Only one of the group's admins can propose a confederation This group cannot take part: it needs at least as many admins as its threshold, and a threshold of two or more diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt index af3bcb5e..0221d6d2 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt @@ -107,6 +107,12 @@ class DatabaseConfederationRepository( override suspend fun isAdmin(chatRoomId: String, userPublicKey: HexKey): Boolean = RoomAdmins.of(database, chatRoomId)?.admins?.contains(userPublicKey) == true + override suspend fun hasInbox(groupPublicKey: HexKey): Boolean = + mobi.giza.compose.managers.InboxReplies.hasAnnouncedKey(database, groupPublicKey) + + override suspend fun holdsAnnouncedInbox(chatRoomId: String, userPublicKey: HexKey): Boolean = + ConfederationManager.announcedInboxKey(database, chatRoomId, userPublicKey) != null + override suspend fun disclosure(chatRoomId: String): ConfederationManager.Disclosure? = ConfederationManager.disclosureFor(database, chatRoomId) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt index 31a4b377..659f5d0c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt @@ -22,6 +22,7 @@ import mobi.giza.compose.nostr.confederation.ConfederationKinds import mobi.giza.compose.nostr.confederation.ConfederationProposalState import mobi.giza.compose.nostr.confederation.ConfederationStatements import mobi.giza.compose.nostr.confederation.ConfederationStatus +import mobi.giza.compose.nostr.DirectMessagePeerSync import mobi.giza.compose.nostr.frost.FrostSigningEvents import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.inbox.InboxReplyManifest @@ -270,6 +271,22 @@ object ConfederationManager { suspend fun announcedInboxKey(database: GizaDatabase, roomId: HexKey, userPublicKey: HexKey) = database.inboxKeyDao().getKeys(roomId, userPublicKey).firstOrNull { it.state == InboxKeyState.ANNOUNCED && it.secretKey != null } + /** + * Asks the relays, for [ownerPublicKey], about every group [proposalId] names whose inbox this + * device has not heard announced: its profile, its 10044 and its 10050 (D5). A group answering + * seals its statement to every other group's announced key, so the device of every admin who + * may propose an answer has to have heard them. + */ + suspend fun askAboutGroups(database: GizaDatabase, proposalId: HexKey, ownerPublicKey: HexKey?) { + val proposal = proposal(database, proposalId) ?: return + val unheard = proposal.groupPublicKeys.filterNot { InboxReplies.hasAnnouncedKey(database, it) } + if (unheard.isEmpty()) return + database.synchronizeNostrEventRequestDao().insert( + unheard.flatMap { DirectMessagePeerSync.profileRequests(it, DirectMessagePeerSync.GROUP_KINDS) } + .map { it.copy(ownerPublicKey = it.ownerPublicKey ?: ownerPublicKey) } + ) + } + /** Why [group] cannot be sent a statement from this device, or null when it can: it has to have announced an inbox (D5). */ suspend fun inboxProblem(database: GizaDatabase, group: HexKey): String? = if (InboxReplies.hasAnnouncedKey(database, group)) null else "${nameOf(database, group)} has announced no inbox" diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt index 4c98e0b8..31f3ab65 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt @@ -10,6 +10,7 @@ import mobi.giza.compose.database.model.ChatMessage import mobi.giza.compose.database.model.GroupInboxMessage import mobi.giza.compose.database.model.GroupInboxWrap import mobi.giza.compose.database.model.InboxKey +import mobi.giza.compose.nostr.confederation.ConfederationKinds import mobi.giza.compose.nostr.confederation.ConfederationStatements import mobi.giza.compose.nostr.inbox.InboxAnnouncement import mobi.giza.compose.nostr.inbox.InboxConversation @@ -89,7 +90,10 @@ object GroupInboxManager { // A confederation's statement, from one group to the others it names: the confederation's // to file, not a conversation in the inbox (docs/confederation-without-coordinator.md, D7). if (ConfederationStatements.isStatementKind(rumor.kind)) { - ConfederationManager.recordStatement(database, rumor, opened.seal, roomId) + if (ConfederationManager.recordStatement(database, rumor, opened.seal, roomId) && rumor.kind == ConfederationKinds.PROPOSAL) { + runCatching { ConfederationManager.askAboutGroups(database, rumor.id, userPublicKey) } + .onFailure { logger.w(throwable = it) { "Could not ask about the groups of ${rumor.id.take(8)}" } } + } database.groupInboxDao().markOpened(wrap.id, key.generation) return null } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/DirectMessagePeerSync.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/DirectMessagePeerSync.kt index 37b255b4..45d57e3f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/DirectMessagePeerSync.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/DirectMessagePeerSync.kt @@ -83,12 +83,18 @@ object DirectMessagePeerSync { } /** - * The kind 0 alone, as a REQ to `SignInSync.bootstrapRelays` -- the indexers plus + * What a group has to have published to be part of a confederation: its profile, the inbox + * key its admins hold and where its mail goes (docs/confederation-without-coordinator.md, D5). + */ + val GROUP_KINDS = arrayOf(MetadataEvent.KIND, InboxAnnouncement.KEY_KIND, InboxAnnouncement.RELAYS_KIND) + + /** + * The kind 0 alone, or [kinds], as a REQ to `SignInSync.bootstrapRelays` -- the indexers plus * our own -- which is where a key pasted from elsewhere has lived. */ - fun profileRequests(peerPublicKey: HexKey): List { + fun profileRequests(peerPublicKey: HexKey, kinds: Array = arrayOf(MetadataEvent.KIND)): List { val synchronizationFilter = SynchronizationFilter( - kinds = arrayOf(MetadataEvent.KIND), + kinds = kinds, authors = arrayOf(peerPublicKey), ) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt index 3c23f294..a475cc78 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt @@ -39,6 +39,12 @@ interface ConfederationRepository { /** Whether [userPublicKey] is one of [chatRoomId]'s current admins, and so may propose its statements. */ suspend fun isAdmin(chatRoomId: String, userPublicKey: HexKey): Boolean + /** Whether this device has heard [groupPublicKey] announce an inbox: a signed 10044 (docs/confederation-without-coordinator.md, D5). */ + suspend fun hasInbox(groupPublicKey: HexKey): Boolean + + /** Whether [userPublicKey] holds the inbox key [chatRoomId] has announced: what its statements are sealed from. */ + suspend fun holdsAnnouncedInbox(chatRoomId: String, userPublicKey: HexKey): Boolean + /** What an acceptance by [chatRoomId] would disclose, read as its signers will read it. Null when it could not take part. */ suspend fun disclosure(chatRoomId: String): ConfederationManager.Disclosure? @@ -107,6 +113,8 @@ interface ConfederationRepository { override fun observeStatusesNaming(groupPublicKey: HexKey): Flow> = flowOf(emptyList()) override fun observeStatus(proposalId: HexKey): Flow = flowOf(null) override suspend fun isAdmin(chatRoomId: String, userPublicKey: HexKey): Boolean = false + override suspend fun hasInbox(groupPublicKey: HexKey): Boolean = false + override suspend fun holdsAnnouncedInbox(chatRoomId: String, userPublicKey: HexKey): Boolean = false override suspend fun disclosure(chatRoomId: String): ConfederationManager.Disclosure? = null override suspend fun nameOf(groupPublicKey: HexKey, inRoom: String?): String = groupPublicKey.take(8) override suspend fun proposeConfederation( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationRitualScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationRitualScreen.kt index b6cf7ee0..382be47b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationRitualScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationRitualScreen.kt @@ -43,6 +43,7 @@ import mobi.giza.compose.resources.confederation_groups import mobi.giza.compose.resources.confederation_groups_to_act import mobi.giza.compose.resources.group_signs_with import mobi.giza.compose.resources.join_the_key_ceremony +import mobi.giza.compose.resources.try_the_key_ceremony_again import mobi.giza.compose.resources.joining_gives_you_a_share import mobi.giza.compose.resources.key_ceremony import mobi.giza.compose.resources.the_ceremony_ended @@ -65,7 +66,8 @@ import org.jetbrains.compose.resources.stringResource /** * A confederation's key ceremony (docs/confederation.md, Phase 11): the groups and who holds a role * for each, the one thing a member is asked -- to join -- and then each step, naming whom it is - * still waiting on. Any participant can abandon a running ceremony; it ends for everybody. + * still waiting on. Any participant can abandon a running ceremony; it ends for everybody, and any + * participant can then try it again (docs/confederation-without-coordinator.md, D10). */ @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -123,10 +125,19 @@ fun ConfederationRitualScreen( text = stringResource(Res.string.the_confederations_key_is_made), style = MaterialTheme.typography.titleMedium, ) - ConfederationCeremonyStage.FAILED -> Text( - text = stringResource(Res.string.the_ceremony_ended, ceremony.failureReason.orEmpty()), - color = MaterialTheme.colorScheme.error, - ) + ConfederationCeremonyStage.FAILED -> { + Text( + text = stringResource(Res.string.the_ceremony_ended, ceremony.failureReason.orEmpty()), + color = MaterialTheme.colorScheme.error, + ) + // Anyone may try again: their join is the next attempt's first message + // (docs/confederation-without-coordinator.md, D10). + if (identityCanSign) { + OutlinedButton(modifier = Modifier.fillMaxWidth(), enabled = !current.isActing, onClick = viewModel::join) { + Text(stringResource(Res.string.try_the_key_ceremony_again)) + } + } + } else -> Unit } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProposeConfederationScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProposeConfederationScreen.kt index cf01067f..5127b48f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProposeConfederationScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProposeConfederationScreen.kt @@ -70,7 +70,11 @@ import mobi.giza.compose.resources.that_is_not_an_npub import mobi.giza.compose.resources.this_group_cannot_take_part_in_a_confederation import mobi.giza.compose.resources.this_group_discloses_its_admins import mobi.giza.compose.resources.this_group_has_no_public_profile +import mobi.giza.compose.nostr.confederation.ConfederationKinds import mobi.giza.compose.resources.proposing_shows_admins_to_the_groups +import mobi.giza.compose.resources.too_many_groups_for_a_confederation +import mobi.giza.compose.resources.this_group_has_no_inbox +import mobi.giza.compose.resources.no_inbox_announced import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute import mobi.giza.compose.ui.composable.navigation.routes.Route import mobi.giza.compose.ui.composable.widgets.Decorative @@ -131,6 +135,7 @@ fun ProposeConfederationScreen( val couldNotPropose = stringResource(Res.string.could_not_propose_the_confederation) val notAnNpub = stringResource(Res.string.that_is_not_an_npub) val alreadyOnIt = stringResource(Res.string.that_group_is_already_on_the_proposal) + val tooMany = stringResource(Res.string.too_many_groups_for_a_confederation, ConfederationKinds.MAX_SUPERGROUP_GROUPS) val nameField = rememberTextFieldState() val npubField = rememberTextFieldState() @@ -217,6 +222,13 @@ fun ProposeConfederationScreen( Text(text = stringResource(Res.string.confederation_groups), style = MaterialTheme.typography.titleSmall) GroupLookupRow(group = current.ownGroup, isThisGroup = true, onRemove = null) + if (current.isAdmin && !current.hasInbox) { + Text( + text = stringResource(Res.string.this_group_has_no_inbox), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } if (current.ownGroup.lookup is Lookup.NotFound) { Text( text = stringResource(Res.string.this_group_has_no_public_profile), @@ -241,6 +253,7 @@ fun ProposeConfederationScreen( ProposeConfederationViewModel.AddResult.ADDED -> npubField.clearText() ProposeConfederationViewModel.AddResult.NOT_AN_NPUB -> notify(notAnNpub) ProposeConfederationViewModel.AddResult.ALREADY_ON_IT -> notify(alreadyOnIt) + ProposeConfederationViewModel.AddResult.TOO_MANY -> notify(tooMany) } } ) { @@ -279,16 +292,18 @@ fun ProposeConfederationScreen( @Composable private fun GroupLookupRow(group: GroupLookup, isThisGroup: Boolean, onRemove: (() -> Unit)?) { val found = group.lookup as? Lookup.Found + val noInbox = group.lookup as? Lookup.NoInbox val npub = group.publicKey.hexToByteArray().toNpub() ListItem( leadingContent = { - ProfileAvatar(size = MaterialTheme.spacing.space500, publicKey = group.publicKey, picture = found?.picture, name = found?.name) + ProfileAvatar(size = MaterialTheme.spacing.space500, publicKey = group.publicKey, picture = found?.picture ?: noInbox?.picture, name = found?.name ?: noInbox?.name) }, - headlineContent = { Text(text = found?.name ?: npub, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + headlineContent = { Text(text = found?.name ?: noInbox?.name ?: npub, maxLines = 1, overflow = TextOverflow.Ellipsis) }, supportingContent = { when (group.lookup) { Lookup.Looking -> Text(stringResource(Res.string.looking_for_its_public_profile)) Lookup.NotFound -> Text(stringResource(Res.string.no_public_profile_found), color = MaterialTheme.colorScheme.error) + is Lookup.NoInbox -> Text(stringResource(Res.string.no_inbox_announced), color = MaterialTheme.colorScheme.error) is Lookup.Found -> Text(text = npub, maxLines = 1, overflow = TextOverflow.Ellipsis) } }, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModel.kt index 85eca487..2c46e9a3 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModel.kt @@ -1,5 +1,7 @@ package mobi.giza.compose.ui.view.model +import kotlin.time.Duration.Companion.milliseconds +import kotlinx.coroutines.delay import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope @@ -35,8 +37,10 @@ import mobi.giza.compose.ui.view.state.ProposeConfederationUIState.Lookup * Phase 6): the groups, how many must act, a name and how long the proposal stays open. * * Every group on it -- this one included -- is looked up on the relays as it is added, and only - * a group whose kind:0 the relays return can take part (D2). A profile this group signed and - * never sent is not public, so this group is looked up the same way. + * a group whose kind:0 and inbox (a 10044) the relays return can take part + * (docs/confederation-without-coordinator.md, D5): the proposal is sealed to every group's inbox. + * A profile this group signed and never sent is not public, so this group is looked up the same + * way; and this group has to have an inbox this device holds the key of, since it is sent from it. */ class ProposeConfederationViewModel( val activeUserPublicKey: HexKey, @@ -80,12 +84,13 @@ class ProposeConfederationViewModel( groupThreshold = disclosure?.threshold?.takeIf { canTakePart }, isAdmin = confederationRepository.isAdmin(chatRoomId, activeUserPublicKey), canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && chatRepository.canSign(chatRoomId), + hasInbox = confederationRepository.holdsAnnouncedInbox(chatRoomId, activeUserPublicKey), ) lookUp(chatRoomId) } } - enum class AddResult { ADDED, NOT_AN_NPUB, ALREADY_ON_IT } + enum class AddResult { ADDED, NOT_AN_NPUB, ALREADY_ON_IT, TOO_MANY } /** Adds the group [raw] names -- an npub, or its 64-character hex -- and asks the relays for its profile. */ fun addGroup(raw: String): AddResult { @@ -97,11 +102,13 @@ class ProposeConfederationViewModel( var result = AddResult.ADDED updateLoaded { loaded -> - if (publicKey == chatRoomId || loaded.invitees.any { it.publicKey == publicKey } || - loaded.groupCount >= ConfederationKinds.MAX_GROUPS - ) { + if (publicKey == chatRoomId || loaded.invitees.any { it.publicKey == publicKey }) { result = AddResult.ALREADY_ON_IT loaded + } else if (loaded.groupCount >= ConfederationKinds.MAX_SUPERGROUP_GROUPS) { + // Every statement is sealed to every group: past this, one no longer fits a message. + result = AddResult.TOO_MANY + loaded } else { result = AddResult.ADDED loaded.copy( @@ -156,23 +163,25 @@ class ProposeConfederationViewModel( } } - /** Asks the relays for [publicKey]'s kind:0 and waits a while for it to land (D2). */ + /** Asks the relays for [publicKey]'s kind:0, 10044 and 10050, and waits a while for the profile and the inbox (D5). */ private fun lookUp(publicKey: HexKey) { // Not cancelled when its group is removed: what it settles then names nobody on the // form, and is dropped by [settle]. viewModelScope.launch(Dispatchers.IO) { runCatching { - nostrRepository.queueSynchronizeNostrEvent(DirectMessagePeerSync.profileRequests(publicKey)) + nostrRepository.queueSynchronizeNostrEvent(DirectMessagePeerSync.profileRequests(publicKey, DirectMessagePeerSync.GROUP_KINDS)) }.onFailure { logger.w(throwable = it) { "Could not ask the relays about $publicKey" } } val profile: Profile? = withTimeoutOrNull(lookupTimeout) { nostrRepository.observeProfileWithPublicKey(publicKey).first { it?.isResolved() == true } } + val inbox = profile != null && (publicKey == chatRoomId || withTimeoutOrNull(lookupTimeout) { + while (!confederationRepository.hasInbox(publicKey)) delay(INBOX_POLL) + true + } == true) val lookup = profile?.let { - Lookup.Found( - name = it.displayName?.takeIf(String::isNotBlank) ?: it.userName?.takeIf(String::isNotBlank), - picture = it.picture, - ) + val name = it.displayName?.takeIf(String::isNotBlank) ?: it.userName?.takeIf(String::isNotBlank) + if (inbox) Lookup.Found(name = name, picture = it.picture) else Lookup.NoInbox(name = name, picture = it.picture) } ?: Lookup.NotFound settle(publicKey, lookup) } @@ -194,6 +203,9 @@ class ProposeConfederationViewModel( /** How long to wait on the relays for a group's profile before saying none was found. */ val RELAY_LOOKUP_TIMEOUT = 20.seconds + /** How often to look again for a group's inbox announcement while the relays are asked. */ + private val INBOX_POLL = 250.milliseconds + /** A majority of the groups, never fewer than two: the rule a group's own quorum starts on. */ fun defaultThreshold(groupCount: Int): Int = maxOf(ConfederationKinds.MIN_GROUPS, groupCount / 2 + 1) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ProposeConfederationUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ProposeConfederationUIState.kt index 2c15e7d3..ef0882d3 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ProposeConfederationUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ProposeConfederationUIState.kt @@ -21,6 +21,8 @@ sealed interface ProposeConfederationUIState { val isAdmin: Boolean = false, /** Whether this device holds a share of an open room's key. */ val canSign: Boolean = false, + /** Whether this device holds the inbox key this group has announced: its statements are sent from it (D5). */ + val hasInbox: Boolean = false, val isProposing: Boolean = false, ) : ProposeConfederationUIState { /** Every group on the proposal, this one first. */ @@ -32,7 +34,7 @@ sealed interface ProposeConfederationUIState { get() = ownGroup.lookup is Lookup.Found && invitees.all { it.lookup is Lookup.Found } fun canPropose(name: String): Boolean = - canSign && isAdmin && canTakePart && !isProposing && name.isNotBlank() && + canSign && isAdmin && canTakePart && hasInbox && !isProposing && name.isNotBlank() && invitees.isNotEmpty() && everyGroupFound && threshold in 2..groupCount } @@ -42,6 +44,8 @@ sealed interface ProposeConfederationUIState { sealed interface Lookup { data object Looking : Lookup data class Found(val name: String?, val picture: String?) : Lookup + /** A public profile, but no inbox announced: nothing could be sent to it (docs/confederation-without-coordinator.md, D5). */ + data class NoInbox(val name: String?, val picture: String?) : Lookup data object NotFound : Lookup } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt index 8939ed3b..21eaccd4 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt @@ -144,6 +144,19 @@ class ConfederationStorageJvmTest { ) } + @Test + fun `a proposal heard from an inbox asks the relays about every group's inbox it has not heard`() = runBlocking { + file(agora, proposal) + ConfederationManager.askAboutGroups(db, proposal.id, npub(9)) + val asked = db.synchronizeNostrEventRequestDao().getAll() + val authors = asked.flatMap { it.synchronizationFilters.flatMap { f -> f.authors.orEmpty().toList() } }.toSet() + assertEquals(groups.toSet(), authors) + asked.forEach { request -> + assertEquals(listOf(0, 10044, 10050), request.synchronizationFilters.single().kinds!!.toList()) + assertEquals(npub(9), request.ownerPublicKey) + } + } + @Test fun `an admin of two groups is counted twice, and said so, on any device`() = runBlocking { val shared = npub(21) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt index fac4bd01..9e15454f 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt @@ -86,6 +86,60 @@ class ConfederationScreensJvmTest { onNodeWithText("Only one of the group's admins can propose a confederation").assertIsDisplayed() } + @Test + fun `a group with a profile and no inbox is said to be out of reach, and so is this one`() = render( + propose = ProposeConfederationUIState.Loaded( + localChatRoom = localChatRoom, + ownGroup = GroupLookup(roomId, Lookup.Found("Agora", null)), + invitees = listOf(GroupLookup(polis, Lookup.NoInbox("Polis", null))), + adminCount = 3, + groupThreshold = 2, + isAdmin = true, + canSign = true, + hasInbox = false, + ) + ) { + onNodeWithText("Polis").assertIsDisplayed() + onNodeWithText("Has announced no inbox, so the proposal could not reach it").assertIsDisplayed() + onNodeWithText("Set up this group's inbox first", substring = true).assertIsDisplayed() + onNodeWithText("Propose confederation").assertIsNotEnabled() + } + + @Test + fun `once every group has accepted, an admin of any group is offered the join, and nobody opens it`() = renderProposal( + ConfederationProposalUIState.Loaded( + localChatRoom = localChatRoom, + status = accepted(), + names = mapOf(polis to "Polis", roomId to "This group"), + canSign = true, + outcome = mobi.giza.compose.managers.ConfederationManager.Outcome(accepted(), emptyMap(), 4, emptyMap(), emptyList(), emptyList()), + holdsRole = true, + ) + ) { + onNodeWithText("Join the key ceremony").assertIsDisplayed() + onAllNodesWithText("Open the key ceremony").assertCountEquals(0) + } + + @Test + fun `a member who holds no role is not offered the join`() = renderProposal( + ConfederationProposalUIState.Loaded( + localChatRoom = localChatRoom, + status = accepted(), + canSign = true, + outcome = mobi.giza.compose.managers.ConfederationManager.Outcome(accepted(), emptyMap(), 4, emptyMap(), emptyList(), emptyList()), + holdsRole = false, + ) + ) { + onAllNodesWithText("Join the key ceremony").assertCountEquals(0) + } + + private fun accepted() = ConfederationStatus( + proposal = proposal(expiresAt = 4_000_000_000), + state = mobi.giza.compose.nostr.confederation.ConfederationProposalState.ACCEPTED, + answers = mapOf(polis to mobi.giza.compose.nostr.confederation.ConfederationAnswer.ACCEPTED, roomId to mobi.giza.compose.nostr.confederation.ConfederationAnswer.ACCEPTED), + acceptances = emptyMap(), + ) + @Test fun `a proposal is listed with where it stands`() = renderList( ConfederationsUIState.Loaded( @@ -249,6 +303,7 @@ class ConfederationScreensJvmTest { fun `an ended ceremony says why`() = renderRitual(ritual(ConfederationCeremonyStage.FAILED, approved = true, failure = "Abandoned by a participant")) { onNodeWithText("The ceremony ended: Abandoned by a participant").assertIsDisplayed() onAllNodesWithText("Abandon the key ceremony").assertCountEquals(0) + onNodeWithText("Try the key ceremony again").assertIsDisplayed() } private fun renderRitual(state: ConfederationRitualUIState, assertions: ComposeUiTest.() -> Unit) = diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModelJvmTest.kt index e82925e9..2b0bfbe3 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModelJvmTest.kt @@ -37,13 +37,15 @@ import mobi.giza.compose.nostr.confederation.ConfederationStatus import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.ConfederationRepository import mobi.giza.compose.repository.NostrRepository +import mobi.giza.compose.nostr.confederation.ConfederationKinds import mobi.giza.compose.ui.view.state.ProposeConfederationUIState import mobi.giza.compose.ui.view.state.ProposeConfederationUIState.Lookup /** - * The form for proposing a confederation (docs/confederation.md, Phase 6): every group, this one - * included, is looked up on the relays and only one with a public profile can be proposed with; - * the button waits on an admin, a share, a name and every group found. + * The form for proposing a confederation (docs/confederation.md, Phase 6, and + * docs/confederation-without-coordinator.md, Phase 6): every group, this one included, is looked up + * on the relays and only one with a public profile and an inbox can be proposed with; the button + * waits on an admin, a share, this group's own inbox, a name and every group found. */ @OptIn(ExperimentalCoroutinesApi::class) class ProposeConfederationViewModelJvmTest { @@ -72,9 +74,20 @@ class ProposeConfederationViewModelJvmTest { private val asked = mutableListOf() + /** The kinds the relays were asked for, by key. */ + private val askedKinds = mutableMapOf>() + + /** Groups whose inbox this device has heard announced. A key absent here has announced none. */ + private val inboxes = mutableSetOf(polis, ekklesia) + + /** Whether this device holds this group's announced inbox key. */ + private var holdsInbox = true + private val nostr = object : NostrRepository by NostrRepository.NO_OP_NOSTR_REPOSITORY { override suspend fun queueSynchronizeNostrEvent(synchronizeNostrEventRequests: List) { - synchronizeNostrEventRequests.firstOrNull()?.synchronizationFilters?.firstOrNull()?.authors?.firstOrNull()?.let { asked += it } + synchronizeNostrEventRequests.firstOrNull()?.synchronizationFilters?.firstOrNull()?.let { filter -> + filter.authors?.firstOrNull()?.let { asked += it; askedKinds[it] = filter.kinds?.toList().orEmpty() } + } } override suspend fun observeProfileWithPublicKey(publicKey: HexKey): Flow = MutableStateFlow(relays[publicKey]) @@ -95,6 +108,8 @@ class ProposeConfederationViewModelJvmTest { override suspend fun isAdmin(chatRoomId: String, userPublicKey: HexKey) = userPublicKey in admins override suspend fun disclosure(chatRoomId: String) = ConfederationManager.Disclosure(chatRoomId, admins, 2) override suspend fun nameOf(groupPublicKey: HexKey, inRoom: String?) = groupPublicKey.take(8) + override suspend fun hasInbox(groupPublicKey: HexKey) = groupPublicKey in inboxes + override suspend fun holdsAnnouncedInbox(chatRoomId: String, userPublicKey: HexKey) = holdsInbox override suspend fun proposeConfederation( localChatRoom: LocalChatRoom, userPublicKey: HexKey, invitees: List, threshold: Int, name: String, expiresAt: Long, @@ -178,6 +193,50 @@ class ProposeConfederationViewModelJvmTest { assertFalse(vm.loaded().canPropose("Atlas"), "a group without a public profile cannot take part") } + @Test + fun `each group's profile, inbox key and inbox relays are asked for`() { + val vm = viewModel() + eventually { vm.proposeConfederationUIState is ProposeConfederationUIState.Loaded } + vm.addGroup(polis) + eventually { vm.loaded().everyGroupFound } + assertEquals(listOf(0, 10044, 10050), askedKinds[polis]) + } + + @Test + fun `a group that has announced no inbox cannot take part`() { + inboxes -= ekklesia + val vm = viewModel() + eventually { vm.proposeConfederationUIState is ProposeConfederationUIState.Loaded } + vm.addGroup(polis) + vm.addGroup(ekklesia) + eventually { vm.loaded().invitees.last().lookup is Lookup.NoInbox } + assertEquals("Ekklesia", (vm.loaded().invitees.last().lookup as Lookup.NoInbox).name) + assertFalse(vm.loaded().everyGroupFound) + assertFalse(vm.loaded().canPropose("Atlas")) + } + + @Test + fun `without this group's own inbox the button waits`() { + holdsInbox = false + val vm = viewModel() + eventually { (vm.proposeConfederationUIState as? ProposeConfederationUIState.Loaded)?.ownGroup?.lookup is Lookup.Found } + vm.addGroup(polis) + eventually { vm.loaded().everyGroupFound } + assertFalse(vm.loaded().hasInbox) + assertFalse(vm.loaded().canPropose("Atlas")) + } + + @Test + fun `no more groups than one statement can carry`() { + val vm = viewModel() + eventually { vm.proposeConfederationUIState is ProposeConfederationUIState.Loaded } + (10 until 10 + ConfederationKinds.MAX_SUPERGROUP_GROUPS - 1).forEach { + assertEquals(ProposeConfederationViewModel.AddResult.ADDED, vm.addGroup(npub(it))) + } + assertEquals(ProposeConfederationViewModel.AddResult.TOO_MANY, vm.addGroup(npub(40))) + assertEquals(ConfederationKinds.MAX_SUPERGROUP_GROUPS, vm.loaded().groupCount) + } + @Test fun `a member who is not an admin cannot propose`() { admins = setOf(npub(10), npub(11), npub(12)) diff --git a/docs/confederation-without-coordinator.md b/docs/confederation-without-coordinator.md index a7e702e7..c535bf7d 100644 --- a/docs/confederation-without-coordinator.md +++ b/docs/confederation-without-coordinator.md @@ -612,6 +612,19 @@ flips. Tests (`ConfederationScreensJvmTest`): the join offered on every admin's device once accepted; the propose button's reasons; no coordinator line anywhere. +**Built.** The form asks the relays for each group's kind:0, 10044 and 10050 in one request +(`DirectMessagePeerSync.GROUP_KINDS`) and shows a group with a profile and no inbox as out of reach +(`Lookup.NoInbox`); **Propose** waits on this group's own announced inbox key; a thirteenth group is +refused (`MAX_SUPERGROUP_GROUPS`). Two things the phase did not list: a device that hears a proposal +in its inbox asks the relays about every named group whose inbox it has not heard +(`ConfederationManager.askAboutGroups`), since answering seals to every group's announced key; and +**Try again** sits on the ceremony screen under a failed attempt, calling the same join. The admin +lists already received are not listed on the proposal screen: the outcome's role count and overlaps +say what matters, and the ceremony screen lists every group's admins. The join and the coordinator's +removal from every screen landed with Phases 3 to 5 and 7, since the code would not compile without +them. `ConfederationScreensJvmTest` 15/15, `ProposeConfederationViewModelJvmTest` 12/12, +`ConfederationStorageJvmTest` 10/10. Full `jvmTest` 1,784, all passing; `m3Audit`, brand and wallet audits at budget. + ### Phase 7: the ceremony without a coordinator (D8, D9, D10) `ConfederationRitualManager`: