From bacd53a1ae9ce876ed15c435b6f9bb38ecb49550 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 01:10:30 +0200 Subject: [PATCH] feat: what a confederation signs: its profile, its posts and its charter (confederation, Phase 15) The profile and post editors work in a confederation's room, proposing through the confederation instead of a FROST key, and the signed event lands where the existing screens read it. A charter names exactly the confederation's groups under its name; once signed it goes to relays, and every member group's room hears of it, which is how members who are not admins learn the confederation exists. A request to sign opens from its line in the room for each member to approve or decline. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 12 ++ .../repository/DatabaseChatRepository.kt | 25 +++ .../DatabaseConfederationRepository.kt | 19 ++ .../compose/managers/ConfederationManager.kt | 30 ++++ .../managers/ConfederationSigningManager.kt | 41 ++++- .../ConfederationCharterEvent.kt | 51 ++++++ .../nostr/confederation/ConfederationKinds.kt | 5 +- .../giza/compose/repository/ChatRepository.kt | 11 ++ .../repository/ConfederationRepository.kt | 19 ++ .../mobi/giza/compose/text/ProposedEvent.kt | 5 + .../ui/composable/AddGroupPostScreen.kt | 18 +- .../ui/composable/ChatRoomDetailScreen.kt | 35 +++- .../ui/composable/ChatRoomMessagingScreen.kt | 6 + .../composable/ConfederationSigningScreen.kt | 169 ++++++++++++++++++ .../composable/EditGroupNostrProfileScreen.kt | 18 +- .../ui/composable/navigation/GizaNavHost.kt | 11 ++ .../routes/ConfederationSigningRoute.kt | 10 ++ .../composable/widgets/chat/ChatTranscript.kt | 17 ++ .../ui/view/model/AddGroupPostViewModel.kt | 29 ++- .../ui/view/model/ChatRoomDetailViewModel.kt | 12 ++ .../model/ConfederationSigningViewModel.kt | 85 +++++++++ .../model/EditGroupNostrProfileViewModel.kt | 29 ++- .../view/model/GroupNostrProfileViewModel.kt | 2 +- .../ui/view/model/GroupPostsViewModel.kt | 2 +- .../ui/view/state/ChatRoomDetailUIState.kt | 2 + .../view/state/ConfederationSigningUIState.kt | 21 +++ .../managers/ConfederationSigningJvmTest.kt | 42 +++++ .../composable/ConfederationScreensJvmTest.kt | 51 ++++++ docs/confederation.md | 1 + 29 files changed, 739 insertions(+), 39 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationCharterEvent.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationSigningScreen.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationSigningRoute.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationSigningViewModel.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationSigningUIState.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index b9b806df..03441aa7 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -740,4 +740,16 @@ %1$s: %2$d of %3$d admins to sign Formed This is the room of the confederation %1$s. Its key is held by the admins of its groups together. Until the confederation can sign, who is in this room cannot change. + The confederation's signature + Approve + Decline + Signed by %1$d admins of %2$d groups together, once enough of them approve. You approve for every group you are an admin of. + The confederation signed it + The confederation did not sign it: %1$s + You declined this + Approved + Declined + This device holds no such request for the confederation to sign + Propose the charter + The charter is the confederation's public statement of the groups it is made of, signed with its own key. It is how members who are not admins hear of it. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 0923f292..2bf6a1b1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -270,6 +270,31 @@ class DatabaseChatRepository( override suspend fun confederationProposalCount(chatRoomId: String): Int = database.confederationDao().getProposalsNaming(chatRoomId).size + override suspend fun canSignAsConfederation(chatRoomId: String): Boolean { + if (!ExperimentalFeatures.confederation) return false + val me = activeIdentity.value?.takeIf { it.canSign }?.nostrPublicKey ?: return false + return ConfederationSigningManager.canSign(database, chatRoomId, me) + } + + override suspend fun proposeAsConfederation( + localChatRoom: LocalChatRoom, + kind: Kind, + tags: Array>, + content: String, + ): String { + val identity = activeIdentity.value ?: throw IllegalStateException("No identity is signed in") + val secret = identity.nostrPrivateKey ?: throw IllegalStateException("This identity cannot sign") + return ConfederationSigningManager.propose( + database, localChatRoom, identity.nostrPublicKey, kind, tags, content, secret.value.toByteArray(), + ).id + } + + override suspend fun proposeCharter(localChatRoom: LocalChatRoom): String { + val (kind, tags, content) = ConfederationSigningManager.charterTemplate(database, localChatRoom.chatRoom.id) + ?: throw IllegalStateException("This device holds no confederation for this room") + return proposeAsConfederation(localChatRoom, kind, tags, content) + } + override suspend fun confederationOfRoom(chatRoomId: String): String? = database.confederationCeremonyDao().getConfederation(chatRoomId) ?.takeIf { ConfederationFormation.verifies(it) } 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 3e857c81..e188f111 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 @@ -16,6 +16,9 @@ import mobi.giza.compose.database.model.Confederation import mobi.giza.compose.database.model.ConfederationCeremony import mobi.giza.compose.database.model.ConfederationCeremonyMessage import mobi.giza.compose.database.model.ConfederationEvent +import mobi.giza.compose.database.model.ConfederationSigningAttempt +import mobi.giza.compose.database.model.ConfederationSigningMessage +import mobi.giza.compose.managers.ConfederationSigningManager import mobi.giza.compose.managers.ConfederationRitualManager import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder @@ -59,6 +62,22 @@ class DatabaseConfederationRepository( override suspend fun abandonCeremony(sessionId: String) = ConfederationRitualManager.abandon(database, sessionId) + override fun observeSigningAttempt(attemptId: String): Flow = + database.confederationCeremonyDao().observeAttempt(attemptId) + + override fun observeSigningMessages(attemptId: String): Flow> = + database.confederationCeremonyDao().observeSigningMessages(attemptId) + + override suspend fun confederationPlan(confederationId: HexKey): ConfederationRosterBuilder.Plan? = + ConfederationSigningManager.held(database, confederationId)?.plan + + override suspend fun approveSigning(attemptId: String) { + val secret = activeIdentity.value?.nostrPrivateKey ?: return + ConfederationSigningManager.approve(database, attemptId, secret.value.toByteArray()) + } + + override suspend fun declineSigning(attemptId: String) = ConfederationSigningManager.decline(database, attemptId) + override fun observeConfederationsOf(groupPublicKey: HexKey): Flow> = database.confederationCeremonyDao().observeConfederationsOf(groupPublicKey) 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 62a6b66c..8ff6ad23 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt @@ -16,6 +16,7 @@ import mobi.giza.compose.database.model.FrostSigningSession import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.confederation.ConfederationAdminList +import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent import mobi.giza.compose.nostr.confederation.ConfederationKinds import mobi.giza.compose.nostr.confederation.ConfederationProposalAcceptanceEvent import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent @@ -58,6 +59,9 @@ object ConfederationManager { ?.let { it.proposalId to emptyList() } ConfederationKinds.WITHDRAWAL -> ConfederationProposalWithdrawalEvent.parse(event) ?.let { it.proposalId to emptyList() } + // Filed under its own id, and under every group it names, so each member group finds it. + ConfederationKinds.CHARTER -> ConfederationCharterEvent.parse(event) + ?.let { it.id to it.groups } else -> null } ?: run { logger.w("Confederation event ${event.id.take(8)} of kind ${event.kind} is not well formed; dropping") @@ -96,6 +100,7 @@ object ConfederationManager { * not hold yet gets its line when the proposal is filed. */ private suspend fun announce(database: GizaDatabase, event: Event, proposalId: HexKey) { + if (event.kind == ConfederationKinds.CHARTER) return announceCharter(database, event) val proposal = proposal(database, proposalId) ?: return val rooms = proposal.groupPublicKeys.mapNotNull { database.chatRoomDao().findChatRoomById(it) } if (rooms.isEmpty()) return @@ -134,6 +139,31 @@ object ConfederationManager { } } + /** + * A line in each member group's room this device holds: the one way a group's members who are + * not admins hear that their group is part of a confederation. A claim by the confederation's + * key, which the line says. + */ + private suspend fun announceCharter(database: GizaDatabase, event: Event) { + val charter = ConfederationCharterEvent.parse(event) ?: return + charter.groups.forEach { group -> + if (database.chatRoomDao().findChatRoomById(group) == null) return@forEach + database.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = event.pubKey, + isUserMessage = false, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = group, + content = "The confederation ${charter.name} signed its charter, naming this group among its ${charter.groups.size}", + messageType = ChatMessage.TYPE_CONFEDERATION_FORMED, + createdAt = Instant.fromEpochSeconds(event.createdAt), + ) + ) + } + } + /** How a line names a group: "This group" in its own room, else its profile's name or its npub. */ suspend fun nameOf(database: GizaDatabase, group: HexKey, inRoom: String? = null): String { if (group == inRoom) return "This group" diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt index 2e1f1619..8ce1580a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt @@ -39,6 +39,7 @@ import mobi.giza.compose.database.model.GroupSignedEvent import mobi.giza.compose.database.model.MarmotInnerEvent import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder.Plan @@ -76,8 +77,8 @@ object ConfederationSigningManager { private fun signerKey(user: HexKey, attemptId: String, role: ConfederationRoleId) = "$user/$attemptId/${role.groupId}:${role.adminId}" - /** The kinds a confederation signs here: its profile and its posts (Phase 15). */ - val SIGNABLE_KINDS: Set = setOf(MetadataEvent.KIND, TextNoteEvent.KIND) + /** The kinds a confederation signs here: its profile, its posts and its charter (Phase 15). */ + val SIGNABLE_KINDS: Set = setOf(MetadataEvent.KIND, TextNoteEvent.KIND, ConfederationCharterEvent.KIND) const val RESTARTED = "A device restarted while signing, so this attempt cannot finish. Propose it again" @@ -113,13 +114,31 @@ object ConfederationSigningManager { /** Why this device would not sign [event] for [held]'s confederation, or null. */ private fun refusalOf(held: Held, event: Event): String? = when { event.pubKey != held.confederation.id -> "The event is not authored by the confederation" - event.kind !in SIGNABLE_KINDS -> "A confederation signs only its profile and its posts here" + event.kind !in SIGNABLE_KINDS -> "A confederation signs only its profile, its posts and its charter here" + event.kind == ConfederationCharterEvent.KIND && !isTrueCharter(held, event) -> + "The charter does not name exactly this confederation's groups, under its name" event.kind == MetadataEvent.KIND && GroupStatementRefusal.isUnreadableProfile(event.tags, event.content) -> GroupStatementRefusal.REASON event.kind == TextNoteEvent.KIND && GroupStatementRefusal.isBlankPost(event.content) -> GroupStatementRefusal.REASON EventHasher.hashId(event.pubKey, event.createdAt, event.kind, event.tags, event.content) != event.id -> "The event's id is not the hash of its fields" else -> null } + /** A charter names exactly the groups the confederation was formed from, under its name. */ + private fun isTrueCharter(held: Held, event: Event): Boolean { + val charter = ConfederationCharterEvent.parse(event) ?: return false + return charter.groups.toSet() == held.plan.groups.toSet() && charter.name == held.confederation.name + } + + /** The charter [held]'s confederation would sign: its groups, under its name. */ + suspend fun charterTemplate(database: GizaDatabase, confederationId: HexKey): Triple>, String>? { + val held = held(database, confederationId) ?: return null + return Triple( + ConfederationCharterEvent.KIND, + ConfederationCharterEvent.assembleTags(held.confederation.name, held.plan.groups), + ConfederationCharterEvent.content(held.confederation.name, held.plan.groups.size), + ) + } + // ---- proposing ------------------------------------------------------------------------- /** Proposes that the confederation whose room is [localChatRoom] sign one event. Proposing is the proposer's approval. */ @@ -403,9 +422,19 @@ object ConfederationSigningManager { database.groupSignedEventDao().record(GroupSignedEvent.fromEvent(signed, chatRoomId = held.confederation.id)) announce( database, attempt, - if (signed.kind == MetadataEvent.KIND) ChatMessage.TYPE_GROUP_PROFILE_SIGNED else ChatMessage.TYPE_GROUP_POST_SIGNED, + when (signed.kind) { + MetadataEvent.KIND -> ChatMessage.TYPE_GROUP_PROFILE_SIGNED + ConfederationCharterEvent.KIND -> ChatMessage.TYPE_CONFEDERATION_FORMED + else -> ChatMessage.TYPE_GROUP_POST_SIGNED + }, "The confederation signed ${describe(signed)}", ) + // The charter is the confederation's public statement: filed as Part A's events are, and + // owed to relays by the device that proposed it (D9), where the member groups' devices hear it. + if (signed.kind == ConfederationCharterEvent.KIND) { + ConfederationManager.record(database, signed) + if (attempt.proposerPublicKey == attempt.userPublicKey) database.confederationDao().markOwn(signed.id, attempt.id) + } logger.i("Confederation ${held.confederation.id.take(12)} signed ${signed.id.take(8)}") } @@ -541,12 +570,16 @@ object ConfederationSigningManager { private fun describe(event: Event): String = when (event.kind) { MetadataEvent.KIND -> "its profile" TextNoteEvent.KIND -> "a post" + ConfederationCharterEvent.KIND -> "its charter" else -> "an event of kind ${event.kind}" } private suspend fun announce(database: GizaDatabase, attempt: ConfederationSigningAttempt, type: String, content: String) { database.chatMessageDao().upsert( ChatMessage( + // The attempt, so the line opens it. Not a FROST session: the column has no key + // onto one, and the transcript reads it by the line's type. + frostSigningSessionId = attempt.id, senderPublicKey = attempt.proposerPublicKey, isUserMessage = false, giftWrapPayloadId = null, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationCharterEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationCharterEvent.kt new file mode 100644 index 00000000..ee5fc770 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationCharterEvent.kt @@ -0,0 +1,51 @@ +package mobi.giza.compose.nostr.confederation + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import mobi.giza.compose.nostr.confederation.tags.ConfederationGroupTag + +/** + * A confederation saying, with its own key, which groups it is made of (docs/confederation.md, + * Phase 15). + * + * ``` + * kind: 9434 + * pubkey: set by the signing attempt + * content: a sentence for clients that know nothing of this kind + * tags: + * ["p", , "", "group"] one per member group + * ["name", ] + * ["alt", ...] + * ``` + * + * The one public statement that the confederation exists, and the only way a group's members + * who are not its admins hear of it: the `p` tags reach every member group's devices through the + * same relay filter that brings them proposals. What it proves is that whoever holds the + * confederation's key named these groups -- a reader cannot check the roster behind the key, any + * more than it can tell a group's key from a person's. + */ +object ConfederationCharterEvent { + val KIND: Kind = ConfederationKinds.CHARTER + const val ALT = "A confederation of nostr groups, naming its member groups" + + data class Charter(val id: HexKey, val confederation: HexKey, val name: String, val groups: List) + + fun assembleTags(name: String, groups: List): Array> = ( + groups.sorted().map { ConfederationGroupTag.assemble(it, null) } + listOf( + arrayOf(ConfederationProposalEvent.NAME_TAG, name), + arrayOf(ConfederationProposalEvent.ALT_TAG, ALT), + ) + ).toTypedArray() + + fun content(name: String, groupCount: Int): String = "$name, a confederation of $groupCount groups" + + fun parse(event: Event): Charter? = runCatching { + if (event.kind != KIND || !ConfederationKinds.isPublicKey(event.pubKey)) return null + val groups = event.tags.mapNotNull(ConfederationGroupTag::parse).map { it.groupPublicKey } + if (groups.size !in ConfederationKinds.MIN_GROUPS..ConfederationKinds.MAX_GROUPS) return null + if (groups.any { !ConfederationKinds.isPublicKey(it) } || groups.toSet().size != groups.size) return null + val name = ConfederationProposalEvent.single(event.tags, ConfederationProposalEvent.NAME_TAG)?.takeIf { it.isNotBlank() } ?: return null + Charter(event.id, event.pubKey, name, groups) + }.getOrNull() +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationKinds.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationKinds.kt index 01df2e11..9d8127c5 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationKinds.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationKinds.kt @@ -20,7 +20,10 @@ object ConfederationKinds { const val REJECTION: Kind = 9432 const val WITHDRAWAL: Kind = 9433 - val ALL: Set = setOf(PROPOSAL, ACCEPTANCE, REJECTION, WITHDRAWAL) + /** The confederation's own public statement of which groups it is made of (Phase 15). Signed by the confederation. */ + const val CHARTER: Kind = 9434 + + val ALL: Set = setOf(PROPOSAL, ACCEPTANCE, REJECTION, WITHDRAWAL, CHARTER) /** The answers a group can give, and the one a proposing group can take back. */ val ANSWERS: Set = setOf(ACCEPTANCE, REJECTION, WITHDRAWAL) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index a43e518e..5330b466 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -138,6 +138,17 @@ interface ChatRepository { /** The confederation whose room [chatRoomId] is, by name, if its record verifies here. docs/confederation.md, Phase 13. */ suspend fun confederationOfRoom(chatRoomId: String): String? = null + /** Whether this device holds a role in the confederation whose room [chatRoomId] is. docs/confederation.md, Phase 15. */ + suspend fun canSignAsConfederation(chatRoomId: String): Boolean = false + + /** Proposes that the confederation whose room [localChatRoom] is sign one event. The attempt's id. */ + suspend fun proposeAsConfederation(localChatRoom: LocalChatRoom, kind: Kind, tags: Array>, content: String): String = + throw UnsupportedOperationException("No confederation here") + + /** Proposes that the confederation sign its charter: its groups, under its name. The attempt's id. */ + suspend fun proposeCharter(localChatRoom: LocalChatRoom): String = + throw UnsupportedOperationException("No confederation here") + /** * Why these members cannot hold a subgroup ceremony together, or null when * they can. 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 9e25b3a9..b7abbc20 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt @@ -9,6 +9,8 @@ import mobi.giza.compose.database.model.Confederation import mobi.giza.compose.database.model.ConfederationCeremony import mobi.giza.compose.database.model.ConfederationCeremonyMessage import mobi.giza.compose.database.model.ConfederationEvent +import mobi.giza.compose.database.model.ConfederationSigningAttempt +import mobi.giza.compose.database.model.ConfederationSigningMessage import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder import mobi.giza.compose.database.model.FrostSigningSession import mobi.giza.compose.database.model.intermdiate.LocalChatRoom @@ -86,6 +88,18 @@ interface ConfederationRepository { suspend fun abandonCeremony(sessionId: String) + /** One attempt by a confederation to sign an event, as it changes. docs/confederation.md, Phase 14. */ + fun observeSigningAttempt(attemptId: String): Flow + + fun observeSigningMessages(attemptId: String): Flow> + + /** The roster's plan for the confederation whose room [confederationId] is, if this device holds it. */ + suspend fun confederationPlan(confederationId: HexKey): ConfederationRosterBuilder.Plan? + + suspend fun approveSigning(attemptId: String) + + suspend fun declineSigning(attemptId: String) + /** The confederations [groupPublicKey] is part of, on this device. docs/confederation.md, Phase 12. */ fun observeConfederationsOf(groupPublicKey: HexKey): Flow> @@ -126,6 +140,11 @@ interface ConfederationRepository { override suspend fun joinCeremony(sessionId: String) = Unit override suspend fun abandonCeremony(sessionId: String) = Unit override fun observeConfederationsOf(groupPublicKey: HexKey): Flow> = flowOf(emptyList()) + override fun observeSigningAttempt(attemptId: String): Flow = flowOf(null) + override fun observeSigningMessages(attemptId: String): Flow> = flowOf(emptyList()) + override suspend fun confederationPlan(confederationId: HexKey): ConfederationRosterBuilder.Plan? = null + override suspend fun approveSigning(attemptId: String) = Unit + override suspend fun declineSigning(attemptId: String) = Unit } } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt index 4fb9f820..84a3d385 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt @@ -4,6 +4,7 @@ import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent import mobi.giza.compose.nostr.confederation.ConfederationKinds import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent import mobi.giza.compose.managers.SharedKeyDerivation @@ -124,6 +125,10 @@ object ProposedEvent { ) } ?: Summary(label = "A confederation that cannot be read", detail = "") + ConfederationKinds.CHARTER -> ConfederationCharterEvent.parse(event)?.let { charter -> + Summary(label = "The confederation's charter", detail = "${charter.name}, naming its ${charter.groups.size} groups") + } ?: Summary(label = "A charter that cannot be read", detail = "") + ConfederationKinds.ACCEPTANCE -> Summary( label = "Accepting a confederation", detail = "Discloses this group's admins and threshold to the coordinator", diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/AddGroupPostScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/AddGroupPostScreen.kt index d6877905..ec70d970 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/AddGroupPostScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/AddGroupPostScreen.kt @@ -41,6 +41,7 @@ import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.FrostSigningRepository +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationSigningRoute 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.ErrorState @@ -158,11 +159,18 @@ fun AddGroupPostScreen( // on the list it is not in would // read as a failure. onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) + if (addGroupPostViewModel.isConfederation) { + ConfederationSigningRoute( + activeUserPublicKey = activeUserPublicKey, + attemptId = sessionId + ) + } else { + FrostSigningRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + sessionId = sessionId + ) + } ) }, // Both stay on the draft. One is an diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 79fb2290..add4cb6d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -17,6 +17,9 @@ import mobi.giza.compose.resources.no_confederations_yet import mobi.giza.compose.resources.one_confederation_proposal import mobi.giza.compose.resources.n_confederation_proposals import mobi.giza.compose.resources.this_is_the_confederations_room +import mobi.giza.compose.resources.propose_the_charter +import mobi.giza.compose.resources.the_charter_names_the_groups +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationSigningRoute import androidx.compose.material.icons.filled.Campaign import mobi.giza.compose.resources.not_described_yet import mobi.giza.compose.resources.no_name_on_this_profile @@ -721,11 +724,35 @@ fun ChatRoomDetailScreen( chatRoomDetailUIState.confederationName?.let { name -> item { Card(modifier = Modifier.fillMaxWidth()) { - Text( + Column( modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), - text = stringResource(Res.string.this_is_the_confederations_room, name), - style = MaterialTheme.typography.bodyMedium, - ) + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + Text( + text = stringResource(Res.string.this_is_the_confederations_room, name), + style = MaterialTheme.typography.bodyMedium, + ) + // Its charter, which it signs itself (Phase 15). + if (chatRoomDetailUIState.canSignAsConfederation && identityCanSign) { + Text( + text = stringResource(Res.string.the_charter_names_the_groups), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + TextButton(onClick = { + chatRoomDetailViewModel.proposeCharter( + onSuccess = { attemptId -> + onNavigateToRoute.invoke( + ConfederationSigningRoute(activeUserPublicKey = activeUserPublicKey, attemptId = attemptId) + ) + }, + onFailure = {}, + ) + }) { + Text(stringResource(Res.string.propose_the_charter)) + } + } + } } } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt index 45ac06e2..39b9166a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt @@ -46,6 +46,7 @@ import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.DkgRepository import mobi.giza.compose.repository.FrostSigningRepository import mobi.giza.compose.repository.NostrRepository +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationSigningRoute import mobi.giza.compose.ui.composable.navigation.routes.ChatRoomDetailRoute import mobi.giza.compose.ui.composable.navigation.routes.DkgRitualRoute import mobi.giza.compose.ui.composable.navigation.routes.ProposalListRoute @@ -185,6 +186,11 @@ fun ChatRoomMessagingScreen( ) ) }, + onOpenConfederationSigning = { attemptId -> + onNavigateToRoute.invoke( + ConfederationSigningRoute(activeUserPublicKey = activeUserPublicKey, attemptId = attemptId) + ) + }, onOpenSigning = { sessionId -> onNavigateToRoute.invoke( proposalDestination( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationSigningScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationSigningScreen.kt new file mode 100644 index 00000000..1c8d49ec --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationSigningScreen.kt @@ -0,0 +1,169 @@ +package mobi.giza.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.material.icons.Icons +import androidx.compose.material.icons.filled.Block +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material.icons.filled.HourglassEmpty +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +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.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import mobi.giza.compose.database.model.ConfederationSigningStage +import mobi.giza.compose.managers.ConfederationSigningManager +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.answer_no +import mobi.giza.compose.resources.answer_waiting +import mobi.giza.compose.resources.answer_yes +import mobi.giza.compose.resources.approve_for_the_confederation +import mobi.giza.compose.resources.confederation_signing +import mobi.giza.compose.resources.decline_for_the_confederation +import mobi.giza.compose.resources.signed_by_admins_of_groups +import mobi.giza.compose.resources.the_confederation_did_not_sign_it +import mobi.giza.compose.resources.the_confederation_signed_it +import mobi.giza.compose.resources.this_device_holds_no_such_request +import mobi.giza.compose.resources.you_declined_this +import mobi.giza.compose.text.ProposedEvent +import mobi.giza.compose.ui.composable.widgets.Decorative +import mobi.giza.compose.ui.composable.widgets.EmptyState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.ConfederationSigningViewModel +import mobi.giza.compose.ui.view.state.ConfederationSigningUIState +import org.jetbrains.compose.resources.stringResource + +/** + * A confederation's request to sign one event (docs/confederation.md, Phase 15): what it would + * sign, said the way a group's signing screen says it, who has approved, and -- for a member not + * yet asked -- approve or decline, which counts for every group they are an admin of. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ConfederationSigningScreen( + attemptId: String, + initialConfederationSigningUIState: ConfederationSigningUIState = ConfederationSigningUIState.Loading, + confederationRepository: ConfederationRepository, + onNavigateBack: () -> Unit, +) { + val viewModel: ConfederationSigningViewModel = viewModel( + factory = ConfederationSigningViewModel.factory(attemptId, initialConfederationSigningUIState, confederationRepository) + ) + LaunchedEffect(true) { + if (initialConfederationSigningUIState == ConfederationSigningUIState.Loading) viewModel.initiate() + } + val state by viewModel.uiState.collectAsState() + val identityCanSign = LocalCanSign.current + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(text = stringResource(Res.string.confederation_signing), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + ) { padding -> + ScreenStateTransition(state) { uiState -> + when (val current = uiState) { + ConfederationSigningUIState.Loading -> LoadingDataIndicator(modifier = Modifier.padding(padding)) + + ConfederationSigningUIState.NotHeld -> EmptyState( + modifier = Modifier.padding(padding), + message = stringResource(Res.string.this_device_holds_no_such_request), + ) + + is ConfederationSigningUIState.Loaded -> Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + val attempt = current.attempt + val summary = ProposedEvent.summarize(current.event) + Text(text = summary.label, style = MaterialTheme.typography.labelMedium) + Text(text = summary.detail, style = MaterialTheme.typography.titleMedium) + Text( + text = stringResource(Res.string.signed_by_admins_of_groups, current.roleCount, current.groupCount), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + when { + attempt.stage == ConfederationSigningStage.COMPLETE -> + Text(text = stringResource(Res.string.the_confederation_signed_it), style = MaterialTheme.typography.titleSmall) + attempt.stage == ConfederationSigningStage.FAILED -> + Text( + text = stringResource(Res.string.the_confederation_did_not_sign_it, attempt.failureReason.orEmpty()), + color = MaterialTheme.colorScheme.error, + ) + attempt.declinedAt != null -> + Text(text = stringResource(Res.string.you_declined_this)) + } + + if (ConfederationSigningManager.isAwaitingApproval(attempt) && identityCanSign) { + Button(modifier = Modifier.fillMaxWidth(), enabled = !current.isActing, onClick = viewModel::approve) { + Text(stringResource(Res.string.approve_for_the_confederation)) + } + OutlinedButton(modifier = Modifier.fillMaxWidth(), enabled = !current.isActing, onClick = viewModel::decline) { + Text(stringResource(Res.string.decline_for_the_confederation)) + } + } + + HorizontalDivider() + current.answers.forEach { (name, answer) -> + ListItem( + leadingContent = { + Icon( + imageVector = when (answer) { + true -> Icons.Default.CheckCircle + false -> Icons.Default.Block + null -> Icons.Default.HourglassEmpty + }, + contentDescription = Decorative, + ) + }, + headlineContent = { Text(name, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + supportingContent = { + Text( + stringResource( + when (answer) { + true -> Res.string.answer_yes + false -> Res.string.answer_no + null -> Res.string.answer_waiting + } + ) + ) + }, + ) + } + } + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditGroupNostrProfileScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditGroupNostrProfileScreen.kt index 00211c4c..d59a79c1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditGroupNostrProfileScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditGroupNostrProfileScreen.kt @@ -47,6 +47,7 @@ import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.FrostSigningRepository +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationSigningRoute 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.ErrorState @@ -198,11 +199,18 @@ fun EditGroupNostrProfileScreen( // group still showing the old one // would read as a failure. onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) + if (editGroupNostrProfileViewModel.isConfederation) { + ConfederationSigningRoute( + activeUserPublicKey = activeUserPublicKey, + attemptId = sessionId + ) + } else { + FrostSigningRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + sessionId = sessionId + ) + } ) }, // Stay on the form with what was typed diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index 66e2df5b..feee98a7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -8,6 +8,8 @@ import mobi.giza.compose.ui.composable.navigation.routes.AddGroupPostRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationsRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProposalRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRitualRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationSigningRoute +import mobi.giza.compose.ui.composable.ConfederationSigningScreen import mobi.giza.compose.ui.composable.ConfederationRitualScreen import mobi.giza.compose.ui.composable.ConfederationProposalScreen import mobi.giza.compose.ui.composable.navigation.routes.ProposeConfederationRoute @@ -1319,6 +1321,15 @@ fun GizaNavHost( onNavigateBack = { navController.popBackStack() } ) } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + ConfederationSigningScreen( + attemptId = route.attemptId, + confederationRepository = databaseConfederationRepository, + onNavigateBack = { navController.popBackStack() } + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationSigningRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationSigningRoute.kt new file mode 100644 index 00000000..82b3c028 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationSigningRoute.kt @@ -0,0 +1,10 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** One attempt by a confederation to sign an event. docs/confederation.md, Phase 15. */ +@Serializable +data class ConfederationSigningRoute( + val activeUserPublicKey: String, + val attemptId: String, +): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt index 62321c23..3bdbb693 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt @@ -123,6 +123,8 @@ fun ChatTranscript( * and cannot say which one it meant. */ onOpenSigning: (sessionId: String?) -> Unit, + /** Opens a confederation's request to sign: docs/confederation.md, Phase 15. */ + onOpenConfederationSigning: (attemptId: String) -> Unit = {}, /** Opens the room's proposals, all of them, whatever their state. */ onOpenProposals: () -> Unit, ) { @@ -375,6 +377,21 @@ fun ChatTranscript( // settled because it reports rather than asks -- a // quorum has already signed by the time this line // exists. It leads nowhere. + // A request for the confederation to sign: it opens, since a + // member answers it there. docs/confederation.md, Phase 15. + if (localChatMessage.chatMessage.messageType == ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED) { + RitualNotice( + localChatMessage = localChatMessage, + isAnswered = false, + isSettled = true, + onClick = { + localChatMessage.chatMessage.frostSigningSessionId?.let(onOpenConfederationSigning) + }, + opens = null, + ) + return@items + } + if (localChatMessage.chatMessage.messageType in ChatMessage.GROUP_IDENTITY_TYPES) { RitualNotice( localChatMessage = localChatMessage, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/AddGroupPostViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/AddGroupPostViewModel.kt index a696c125..7ae9b3fd 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/AddGroupPostViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/AddGroupPostViewModel.kt @@ -51,6 +51,10 @@ class AddGroupPostViewModel( val isActionPending: MutableState = mutableStateOf(false) + /** Whether this room is a confederation's, whose statements the confederation signs. Read at load. */ + var isConfederation: Boolean = false + private set + fun initiateAddGroupPost() { viewModelScope.launch(Dispatchers.IO) { val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) @@ -64,7 +68,8 @@ class AddGroupPostViewModel( // The same condition the group detail screen gates the entry // point on. canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && - frostSigningRepository.canSign(chatRoomId), + (frostSigningRepository.canSign(chatRoomId) || + chatRepository.canSignAsConfederation(chatRoomId).also { isConfederation = it }), ) } } @@ -107,20 +112,26 @@ class AddGroupPostViewModel( viewModelScope.launch(Dispatchers.IO) { val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - kind = template.kind, - tags = template.tags, - content = template.content, - ) + // A confederation's room signs through the confederation, not a FROST + // key: docs/confederation.md, Phase 15. + if (isConfederation) { + chatRepository.proposeAsConfederation(localChatRoom, template.kind, template.tags, template.content) + } else { + frostSigningRepository.proposeSigning( + localChatRoom = localChatRoom, + userPublicKey = activeUserPublicKey, + kind = template.kind, + tags = template.tags, + content = template.content, + )?.id + } }.onFailure { error -> logger.e("Failed to propose a post for $chatRoomId", error) }.getOrNull() viewModelScope.launch(Dispatchers.Main) { if (session != null) { - onSuccess.invoke(session.id) + onSuccess.invoke(session) } else { onFailure.invoke() } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index d048388b..4777c5dd 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -134,6 +134,7 @@ class ChatRoomDetailViewModel( groupPosts = chatRepository.groupPosts(chatRoomId), confederationProposalCount = chatRepository.confederationProposalCount(chatRoomId), confederationName = chatRepository.confederationOfRoom(chatRoomId), + canSignAsConfederation = chatRepository.canSignAsConfederation(chatRoomId), canProposeAsGroup = canSign && roomIsOpen, subgroupsNeedAWallet = canSign && subgroupsNeedAWallet, canGovern = canGovern, @@ -510,6 +511,17 @@ class ChatRoomDetailViewModel( } + /** Proposes the confederation's charter, in its own room. docs/confederation.md, Phase 15. */ + fun proposeCharter(onSuccess: (attemptId: String) -> Unit, onFailure: () -> Unit) { + val loaded = chatRoomDetailUIState as? ChatRoomDetailUIState.Loaded ?: return + viewModelScope.launch(Dispatchers.IO) { + val attemptId = runCatching { chatRepository.proposeCharter(loaded.localChatRoom) } + .onFailure { logger.e("Could not propose the charter for $chatRoomId", it) } + .getOrNull() + viewModelScope.launch(Dispatchers.Main) { if (attemptId != null) onSuccess(attemptId) else onFailure() } + } + } + companion object { private const val TAG = "ChatRoomDetailViewModel" diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationSigningViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationSigningViewModel.kt new file mode 100644 index 00000000..d299ac6e --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationSigningViewModel.kt @@ -0,0 +1,85 @@ +package mobi.giza.compose.ui.view.model + +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.Event +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents +import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.ui.view.state.ConfederationSigningUIState + +/** One attempt by a confederation to sign an event, watched as answers arrive (docs/confederation.md, Phase 15). */ +class ConfederationSigningViewModel( + val attemptId: String, + initialConfederationSigningUIState: ConfederationSigningUIState, + val confederationRepository: ConfederationRepository, +) : ViewModel() { + private val logger = Logger.withTag("ConfederationSigningViewModel") + private val state = MutableStateFlow(initialConfederationSigningUIState) + val uiState: StateFlow = state.asStateFlow() + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + combine( + confederationRepository.observeSigningAttempt(attemptId), + confederationRepository.observeSigningMessages(attemptId), + ) { attempt, messages -> attempt to messages }.collect { (attempt, messages) -> + if (attempt == null) { + state.value = ConfederationSigningUIState.NotHeld + return@collect + } + val plan = confederationRepository.confederationPlan(attempt.confederationId) + val event = Event.fromJsonOrNull(attempt.signedEventJson ?: attempt.eventJson) ?: return@collect + val said = messages.filter { it.kind == ConfederationSigningEvents.AVAILABILITY }.associate { message -> + message.senderPublicKey to (ConfederationRitualEvents.decodeByGroup(message.payload)?.values?.all { it == ConfederationSigningEvents.YES } == true) + } + val answers = plan?.people.orEmpty().map { person -> confederationRepository.nameOf(person) to said[person] } + val acting = (state.value as? ConfederationSigningUIState.Loaded)?.isActing == true + state.value = ConfederationSigningUIState.Loaded( + attempt = attempt, + event = event, + answers = answers, + roleCount = plan?.seats?.size ?: 0, + groupCount = plan?.groups?.size ?: 0, + isActing = acting, + ) + } + } + } + + fun approve() = act { confederationRepository.approveSigning(attemptId) } + + fun decline() = act { confederationRepository.declineSigning(attemptId) } + + private fun act(action: suspend () -> Unit) { + val loaded = state.value as? ConfederationSigningUIState.Loaded ?: return + if (loaded.isActing) return + state.update { (it as? ConfederationSigningUIState.Loaded)?.copy(isActing = true) ?: it } + viewModelScope.launch(Dispatchers.IO) { + runCatching { action() }.onFailure { logger.e("Signing action failed", it) } + state.update { (it as? ConfederationSigningUIState.Loaded)?.copy(isActing = false) ?: it } + } + } + + companion object { + fun factory( + attemptId: String, + initialConfederationSigningUIState: ConfederationSigningUIState = ConfederationSigningUIState.Loading, + confederationRepository: ConfederationRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { ConfederationSigningViewModel(attemptId, initialConfederationSigningUIState, confederationRepository) } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModel.kt index fef838bc..15395d18 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModel.kt @@ -48,6 +48,10 @@ class EditGroupNostrProfileViewModel( val isActionPending: MutableState = mutableStateOf(false) + /** Whether this room is a confederation's, whose statements the confederation signs. Read at load. */ + var isConfederation: Boolean = false + private set + fun initiateEditGroupNostrProfile() { viewModelScope.launch(Dispatchers.IO) { val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) @@ -61,7 +65,8 @@ class EditGroupNostrProfileViewModel( // The same condition the group detail screen gates the entry // point on. canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && - frostSigningRepository.canSign(chatRoomId), + (frostSigningRepository.canSign(chatRoomId) || + chatRepository.canSignAsConfederation(chatRoomId).also { isConfederation = it }), ) } } @@ -108,20 +113,26 @@ class EditGroupNostrProfileViewModel( viewModelScope.launch(Dispatchers.IO) { val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - kind = template.kind, - tags = template.tags, - content = template.content, - ) + // A confederation's room signs through the confederation, not a FROST + // key: docs/confederation.md, Phase 15. + if (isConfederation) { + chatRepository.proposeAsConfederation(localChatRoom, template.kind, template.tags, template.content) + } else { + frostSigningRepository.proposeSigning( + localChatRoom = localChatRoom, + userPublicKey = activeUserPublicKey, + kind = template.kind, + tags = template.tags, + content = template.content, + )?.id + } }.onFailure { error -> logger.e("Failed to propose a nostr profile for $chatRoomId", error) }.getOrNull() viewModelScope.launch(Dispatchers.Main) { if (session != null) { - onSuccess.invoke(session.id) + onSuccess.invoke(session) } else { onFailure.invoke() } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupNostrProfileViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupNostrProfileViewModel.kt index b7a0ed79..f23b1e7e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupNostrProfileViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupNostrProfileViewModel.kt @@ -44,7 +44,7 @@ class GroupNostrProfileViewModel( localChatRoom = localChatRoom, groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && - chatRepository.canSign(chatRoomId), + (chatRepository.canSign(chatRoomId) || chatRepository.canSignAsConfederation(chatRoomId)), ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupPostsViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupPostsViewModel.kt index 7e7a9c29..164582a7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupPostsViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupPostsViewModel.kt @@ -40,7 +40,7 @@ class GroupPostsViewModel( groupPosts = chatRepository.groupPosts(chatRoomId), groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && - chatRepository.canSign(chatRoomId), + (chatRepository.canSign(chatRoomId) || chatRepository.canSignAsConfederation(chatRoomId)), ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt index 03a951bd..600d2db3 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -76,6 +76,8 @@ sealed interface ChatRoomDetailUIState { val confederationProposalCount: Int = 0, /** The confederation whose room this is, by name: its membership is fixed until it can sign. */ val confederationName: String? = null, + /** Whether this device holds a role in that confederation, and so can propose what it signs. */ + val canSignAsConfederation: Boolean = false, /** * Whether this device could put a profile or a post to the group's quorum: * a Marmot room it has not left, not disbanded, where it holds a share of diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationSigningUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationSigningUIState.kt new file mode 100644 index 00000000..cdc890ba --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationSigningUIState.kt @@ -0,0 +1,21 @@ +package mobi.giza.compose.ui.view.state + +import com.vitorpamplona.quartz.nip01Core.core.Event +import mobi.giza.compose.database.model.ConfederationSigningAttempt + +/** One attempt by a confederation to sign an event (docs/confederation.md, Phase 15). */ +sealed interface ConfederationSigningUIState { + data class Loaded( + val attempt: ConfederationSigningAttempt, + val event: Event, + /** Every role holder by name, with their answer: true, false, or null while they have not said. */ + val answers: List>, + val roleCount: Int, + val groupCount: Int, + val isActing: Boolean = false, + ) : ConfederationSigningUIState + + data object NotHeld : ConfederationSigningUIState + + data object Loading : ConfederationSigningUIState +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt index 17cbf424..85d50e9a 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt @@ -16,6 +16,7 @@ import kotlin.test.assertNotNull import kotlin.test.assertTrue import kotlin.time.Clock import kotlin.time.Instant +import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.builder.getRoomDatabase @@ -28,6 +29,7 @@ import mobi.giza.compose.database.model.Profile import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents import mobi.giza.compose.nostr.frost.GroupKeyStateEvent @@ -214,4 +216,44 @@ class ConfederationSigningJvmTest { assertFailsWith { propose(kind = 30023, content = "long form") } assertFailsWith { propose(kind = TextNoteEvent.KIND, content = " ") } } + + // ---- Phase 15: the charter ------------------------------------------------------------ + + @Test + fun `a charter naming exactly its groups is signed, filed and owed to relays`() { + val polisMember = devices.getValue(npub(secret(22))) + runBlocking { + polisMember.db.chatRoomDao().upsert(ChatRoom(id = groups[1], userPublicKey = polisMember.person, subject = "#Polis", description = null, mlsGroupState = "00")) + } + val (kind, tags, content) = runBlocking { assertNotNull(ConfederationSigningManager.charterTemplate(proposer.db, confederation.id)) } + val attempt = runBlocking { ConfederationSigningManager.propose(proposer.db, proposer.room, proposer.person, kind, tags, content, proposer.nsec) } + pump() + approve(attempt.id, people - 11) + pump() + + attempts(attempt.id).values.forEach { assertEquals(ConfederationSigningStage.COMPLETE, it?.stage, it?.failureReason) } + val signed = Event.fromJson(attempts(attempt.id).getValue(proposer.person)!!.signedEventJson!!) + runBlocking { + val owed = proposer.db.confederationDao().observeUnpublished().first() + assertEquals(listOf(signed.id), owed.map { it.id }, "the proposer's device owes it to relays") + assertEquals(groups.toSet(), proposer.db.confederationDao().getEvent(signed.id)?.let { listOf(it) }?.let { + ConfederationCharterEvent.parse(it.single().toEvent())?.groups?.toSet() + }) + assertTrue( + polisMember.db.chatMessageDao().getChatMessagesByChatRoomId(groups[1]) + .any { it.chatMessage.content.contains("signed its charter") }, + "Polis's room hears of it", + ) + } + } + + @Test + fun `a charter that leaves out a group is refused`() { + val wrong = ConfederationCharterEvent.assembleTags(confederation.name, groups.take(2)) + assertFailsWith { + runBlocking { + ConfederationSigningManager.propose(proposer.db, proposer.room, proposer.person, ConfederationCharterEvent.KIND, wrong, "x", proposer.nsec) + } + } + } } 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 60474fb1..93b244b6 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 @@ -23,6 +23,9 @@ import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost import mobi.giza.compose.ui.theme.GizaTheme import mobi.giza.compose.ui.view.state.ConfederationProposalUIState import mobi.giza.compose.ui.view.state.ConfederationRitualUIState +import mobi.giza.compose.ui.view.state.ConfederationSigningUIState +import mobi.giza.compose.database.model.ConfederationSigningAttempt +import mobi.giza.compose.database.model.ConfederationSigningStage import mobi.giza.compose.database.model.ConfederationCeremony import mobi.giza.compose.database.model.ConfederationCeremonyStage import mobi.giza.compose.ui.view.state.ConfederationsUIState @@ -267,4 +270,52 @@ class ConfederationScreensJvmTest { } assertions() } + + private fun signing(stage: ConfederationSigningStage, approved: Boolean, failure: String? = null) = ConfederationSigningUIState.Loaded( + attempt = ConfederationSigningAttempt( + id = "s".repeat(64), confederationId = roomId, proposerPublicKey = polis, userPublicKey = "a".repeat(64), + eventJson = "{}", stage = stage, approvedAt = if (approved) kotlin.time.Instant.fromEpochSeconds(1) else null, failureReason = failure, + ), + event = com.vitorpamplona.quartz.nip01Core.core.Event("e".repeat(64), roomId, 1, 1, emptyArray(), "The first words of a group of groups", ""), + answers = listOf("Ana" to true, "Bo" to null, "Cy" to false), + roleCount = 9, + groupCount = 3, + ) + + @Test + fun `a member is asked to approve what the confederation would sign, and sees who has answered`() = + renderSigning(signing(ConfederationSigningStage.SELECTING, approved = false)) { + onNodeWithText("The first words of a group of groups").assertIsDisplayed() + onNodeWithText("Approve").assertIsDisplayed() + onNodeWithText("Decline").assertIsDisplayed() + onNodeWithText("Signed by 9 admins of 3 groups together", substring = true).assertIsDisplayed() + onNodeWithText("Ana").assertIsDisplayed() + onNodeWithText("Approved").assertIsDisplayed() + } + + @Test + fun `an attempt that did not finish says why, and asks nothing`() = + renderSigning(signing(ConfederationSigningStage.FAILED, approved = true, failure = "A device restarted while signing")) { + onNodeWithText("The confederation did not sign it: A device restarted while signing").assertIsDisplayed() + onAllNodesWithText("Approve").assertCountEquals(0) + } + + private fun renderSigning(state: ConfederationSigningUIState, assertions: ComposeUiTest.() -> Unit) = + runDesktopComposeUiTest(width = 400, height = 3000) { + setContent { + GizaTheme { + ProvideSnackbarHost { + Box(modifier = Modifier.fillMaxSize()) { + ConfederationSigningScreen( + attemptId = "s".repeat(64), + initialConfederationSigningUIState = state, + confederationRepository = ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY, + onNavigateBack = {}, + ) + } + } + } + } + assertions() + } } diff --git a/docs/confederation.md b/docs/confederation.md index 2944baef..0c96c012 100644 --- a/docs/confederation.md +++ b/docs/confederation.md @@ -93,6 +93,7 @@ the reasoning. Where the build chose differently: | 12 | done. `ConfederationFormation.onComplete` files a `Confederation` (room id, X, roster, key state, genesis, the `(configSeq, rpdHash, ksdHash)` triple, this device's recovery packages) and `ConfederationMember` rows, folded into schema 44 since it has not shipped. The genesis is verified against the key state before anything is written. A line goes into each of this device's own member groups' rooms; nothing is sent to them. **No 30389 key-state event:** every founding member of the room took part and holds the record, so `ConfederationFormation.verifies` checks the stored descriptors instead; a member added later needs one, which waits for Part C's governance. A formed confederation reads "Formed" on the group's list. `ConfederationCeremonyJvmTest` now also checks every device files the same verified confederation under the room its key derives | | 13 | done. `ConfederationFollowThrough` on the coordinator's device makes the room once every member's key package is in, retrying when one arrives, through `MarmotGroupCreation.create` rather than a new `createForConfederation`: id `marmotGroupId(02‖X)`, a random routing address, every role holder a member and an admin, `#name`, born governed with `Quorum.minimumAdmins(T)`. A record that no longer verifies, or a device holding no role, makes no room. Adoption needs no new check: every founding member holds the `Confederation` row under the room's id, and `confederationOfRoom` reads it only if it verifies. The room's screen says whose room it is and that its members are fixed until the confederation can sign. `ConfederationCeremonyJvmTest` 9/9. `./gradlew check` passes, jvmTest 1,621 | | 14 | done. `ConfederationSigningManager` over upstream's `ConfederationSigning`, in the confederation's Marmot room. Kinds 30390 (proposal), 30391 (each person's yes or no per role), 30392 (the proposer's selection and D_sign), 30393 (nonces), 30394 (confirmations), 30395 (partials), 30399 (failure). Only the selection is coordinated: the first `T` groups in roster order with `t_g` yeses, the lowest admins first. The transcript, the certificate, every group's partial and the signature take no secret, so **every device computes them itself** and checks the signature against the room's id before keeping it: no group coordinator and no outer coordinator message. Signer state is held in memory only; a device that restarts after sending a nonce ends the attempt out loud on its next step, and `resumeRunning` does it on start. A confederation signs kinds 0 and 1 only, with Part A's statement refusals; anything else is declined out loud. A signed event lands in `GroupSignedEvent` under the room, so the existing profile, posts and broadcast screens read it. Schema 45. `ConfederationSigningJvmTest` 5/5 on nine devices: a profile signed and read back on every device; two groups of two admins enough; a restart between nonces and confirmations failing it everywhere; too many declines; refused kinds. jvmTest 1,626 | +| 15 | done but for governance. **Profile and posts:** the existing editors work in a confederation's room. `ChatRepository.canSignAsConfederation` opens them to a role holder, and `proposeAsConfederation` sends the proposal through `ConfederationSigningManager` instead of FROST; the signed event lands where the profile and posts screens and the broadcast screen already read. **Charter (9434):** the confederation's own public statement naming its groups, proposed from its room's card. A device signs only a charter naming exactly the confederation's groups under its name. Once signed it is filed as Part A's events are and owed to relays by the proposer's device, and every member group's devices hear it through the existing `#p` filter and write a line in the group's room. That is how members who are not admins learn of it. `ConfederationSigningScreen` approves or declines for every role a person holds and lists who has answered, opened from the line in the room's transcript (the line carries the attempt id) or after proposing. **Not done:** admin changes in the confederation's room signed by the confederation; the room stays fixed at its founders. `ConfederationSigningJvmTest` 7/7, `ConfederationScreensJvmTest` 12/12. `./gradlew check` passes, jvmTest 1,630 | ---