From 7e42609af3be06f3ccf5c11955a1c28d471b7204 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Mon, 23 Nov 2026 10:11:14 +0200 Subject: [PATCH] feat: everything a confederation signs goes through its groups, as proposals Posts and the charter now take the path profile changes already took (docs/confederation-proposals.md): one group proposes a 9435 carrying the unsigned kind:1 or 9434, the others endorse or object by their own quorum, and the confederation signs once T groups have vouched, with nobody asked. - ConfederationChangeStatements (was ...ProfileStatements) carries any signable kind; a base only on a kind:0. The wire's "profile" tag keeps its name so vouchers stay readable across builds. - Refusals by kind: a blank post, an untrue or second charter. - ConfederationSigningManager refuses anything without T groups' vouchers; approve, decline and the per-person ask are gone. - A charter supersedes a later charter; a post is never superseded. - ConfederationScreen: "Profile changes" becomes "Proposals" for every kind; Add post and Propose the charter start the group's session; the Signing section, screen, view model and route are removed. Signing lines open the proposal, an older line's attempt id resolved to it. - Profile* types that now hold any kind renamed to Change*. jvmTest 2,014, all passing; m3, brand and wallet audits at budget; compileDebugKotlinAndroid builds. No device run. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 49 ++-- .../compose/database/dao/ConfederationDao.kt | 4 +- .../compose/database/model/ChatMessage.kt | 17 +- .../repository/DatabaseChatRepository.kt | 12 +- .../DatabaseConfederationRepository.kt | 95 +++----- ...kt => ConfederationChangeFollowThrough.kt} | 30 +-- ...fusal.kt => ConfederationChangeRefusal.kt} | 98 +++++--- .../compose/managers/ConfederationManager.kt | 2 +- .../managers/ConfederationProfileManager.kt | 230 +++++++++++++----- .../compose/managers/ConfederationRefusal.kt | 14 +- .../managers/ConfederationSigningManager.kt | 158 +++++------- .../compose/managers/GroupInboxManager.kt | 2 +- .../giza/compose/managers/InboxReplies.kt | 2 +- ...ts.kt => ConfederationChangeStatements.kt} | 109 +++++---- ...Status.kt => ConfederationChangeStatus.kt} | 81 +++--- .../nostr/confederation/ConfederationKinds.kt | 21 +- .../notifications/NotificationClassifier.kt | 4 +- .../giza/compose/repository/ChatRepository.kt | 15 +- .../repository/ConfederationRepository.kt | 90 +++---- .../mobi/giza/compose/text/ProposedEvent.kt | 9 +- .../ui/composable/AddGroupPostScreen.kt | 21 +- .../ui/composable/ChatRoomDetailScreen.kt | 1 - .../ui/composable/ChatRoomMessagingScreen.kt | 12 +- ...Screen.kt => ConfederationChangeScreen.kt} | 91 ++++--- .../ui/composable/ConfederationScreen.kt | 205 ++++++++-------- .../composable/ConfederationSigningScreen.kt | 190 --------------- .../ui/composable/navigation/GizaNavHost.kt | 21 +- .../navigation/routes/ConfederationRoute.kt | 2 +- .../routes/ConfederationSigningRoute.kt | 10 - .../composable/widgets/chat/ChatTranscript.kt | 20 +- .../ui/view/model/AddGroupPostViewModel.kt | 14 +- ...del.kt => ConfederationChangeViewModel.kt} | 63 ++--- .../model/ConfederationSigningViewModel.kt | 97 -------- .../ui/view/model/ConfederationViewModel.kt | 50 ++-- .../EditConfederationProfileViewModel.kt | 2 +- ...State.kt => ConfederationChangeUIState.kt} | 18 +- .../view/state/ConfederationSigningUIState.kt | 34 --- .../ui/view/state/ConfederationUIState.kt | 36 +-- .../state/EditConfederationProfileUIState.kt | 4 +- .../ConfederationChangeStatementsTest.kt | 194 +++++++++++++++ .../ConfederationProfileStatementsTest.kt | 175 ------------- .../ConfederationProfileNetworkJvmTest.kt | 92 ++++--- .../ConfederationProfileReceiveJvmTest.kt | 8 +- .../ConfederationProfileStatementJvmTest.kt | 48 ++-- .../ConfederationProfileStorageJvmTest.kt | 26 +- .../ConfederationSharedSeatsSigningJvmTest.kt | 49 ++-- .../managers/ConfederationSigningJvmTest.kt | 208 ++++++++-------- .../ConfederationProfileScreensJvmTest.kt | 119 +++++---- .../composable/ConfederationScreensJvmTest.kt | 94 ------- docs/README.md | 1 + docs/confederation-profile.md | 2 +- docs/confederation-proposals.md | 117 +++++++++ 52 files changed, 1448 insertions(+), 1618 deletions(-) rename composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/{ConfederationProfileFollowThrough.kt => ConfederationChangeFollowThrough.kt} (83%) rename composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/{ConfederationProfileRefusal.kt => ConfederationChangeRefusal.kt} (60%) rename composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/{ConfederationProfileStatements.kt => ConfederationChangeStatements.kt} (71%) rename composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/{ConfederationProfileChangeStatus.kt => ConfederationChangeStatus.kt} (50%) rename composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/{ConfederationProfileChangeScreen.kt => ConfederationChangeScreen.kt} (76%) delete mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationSigningScreen.kt delete mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationSigningRoute.kt rename composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/{ConfederationProfileChangeViewModel.kt => ConfederationChangeViewModel.kt} (60%) delete mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationSigningViewModel.kt rename composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/{ConfederationProfileChangeUIState.kt => ConfederationChangeUIState.kt} (70%) delete mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationSigningUIState.kt create mode 100644 composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationChangeStatementsTest.kt delete mode 100644 composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileStatementsTest.kt create mode 100644 docs/confederation-proposals.md diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 6fd98311..a54e5e0f 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -758,37 +758,33 @@ The ceremony ended: %1$s %1$s: %2$d of %3$d admins to sign Formed - 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 - Approved for %1$s - Declined for %1$s - Not for %1$s, which had not endorsed it when signing began - 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. + 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. This group proposes it, and the confederation signs it once enough groups endorse it. Member of %1$s Profile The confederation has signed no profile yet %1$d admins hold its key - Profile changes - Only the group's admins see proposed changes. - No changes to its profile have been proposed + Only the group's admins see proposals. + Nothing has been proposed for the confederation to sign + %1$s · %2$s + Profile + Post + Charter + The confederation's charter + Its public statement of the groups it is made of, and how many of them must act, signed with its own key + What it would sign + The charter has been proposed, and is signed once enough groups endorse it + Posted + Another charter was signed first Edit profile How it was formed This device knows nothing of that confederation This device holds no record of the confederation This group is not one of the confederation's This group cannot sign from this device - Only one of the group's admins can propose a change - Set up the group's inbox first: a change is sent from it + Only one of the group's admins can make a proposal + Set up the group's inbox first: a proposal is sent from it %1$s has no inbox, so it cannot be asked Open Endorsed, being signed @@ -804,19 +800,18 @@ Propose from Propose to the groups Couldn't propose the change - Profile change - This device does not hold that change + Proposal Endorse Object - Withdraw the change - Endorsing lets the confederation's admins sign this profile once enough groups have endorsed it. Nobody is asked again. + Withdraw the proposal + Endorsing lets the confederation sign this once enough groups have endorsed it. Nobody is asked again. Proposed it Endorsed Objected Was: %1$s Becomes: %1$s Nothing - This change edits no field shown here + This proposal edits no field shown here Being signed. Waiting on %1$s Open the confederation @@ -824,12 +819,6 @@ Charter The confederation has signed its charter, naming its groups The confederation has no charter yet - Signing - Nothing is being signed - Waiting for your answer - Being signed - Signed - Not signed Couldn't propose the charter The key ceremony for %1$s is complete. Its groups open it from their own screens. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationDao.kt index fb0969e3..218fde58 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationDao.kt @@ -118,8 +118,8 @@ abstract class ConfederationDao { abstract suspend fun getChartersNaming(groupPublicKey: HexKey): List /** Every profile change this device holds, for the follow-through's sweep. */ - @Query("SELECT * FROM ConfederationEvent WHERE kind = ${ConfederationKinds.PROFILE_CHANGE} ORDER BY eventCreatedAt DESC, id DESC") - abstract suspend fun getProfileChanges(): List + @Query("SELECT * FROM ConfederationEvent WHERE kind = ${ConfederationKinds.CHANGE} ORDER BY eventCreatedAt DESC, id DESC") + abstract suspend fun getChanges(): List @Query("SELECT * FROM ConfederationSigning WHERE sessionId = :sessionId") abstract suspend fun getSigning(sessionId: String): ConfederationSigning? diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt index 80e9aa99..8e5037e3 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt @@ -573,18 +573,19 @@ data class ChatMessage( const val TYPE_CONFEDERATION_SIGNING_FAILED = "confederationSigningFailed" /** - * The confederation asking this person to sign, for their seats: a post or its charter, where - * every role holder answers as a person. Written by their own device, so it is theirs, and a - * notification asks for them (docs/confederation-room-removal.md, D9). + * The confederation asking this person to sign, for their seats: a post or its charter, when + * every role holder answered as a person. No longer written -- what a confederation signs its + * groups decide (docs/confederation-proposals.md) -- but kept, since a device may hold such lines. */ const val TYPE_CONFEDERATION_SIGNING_ASKED = "confederationSigningAsked" /** - * A formed confederation's profile, decided by its groups (docs/confederation-profile.md, D8): - * a group proposing a change, another endorsing or objecting to it, and the new profile once - * the confederation has signed it. Written by each device into its own member groups' rooms. - * [frostSigningSessionId] carries the change's id, or for a published profile the - * confederation's, so the line opens what it is about. + * What a formed confederation signs, decided by its groups (docs/confederation-profile.md, D8; + * docs/confederation-proposals.md): a group proposing a profile, a post or its charter, another + * endorsing or objecting to it, and the new profile once the confederation has signed it. + * Named for profiles, which went this way first; the values are stored, so they stay. Written + * by each device into its own member groups' rooms. [frostSigningSessionId] carries the + * proposal's id, or for a published profile the confederation's, so the line opens what it is about. */ const val TYPE_CONFEDERATION_PROFILE_PROPOSED = "confederationProfileProposed" const val TYPE_CONFEDERATION_PROFILE_ENDORSED = "confederationProfileEndorsed" 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 4c3552cb..126a5972 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 @@ -206,7 +206,7 @@ class DatabaseChatRepository( if (ExperimentalFeatures.confederation) { // A change to a formed confederation's profile its groups endorsed, signed by the // confederation with nobody asked. docs/confederation-profile.md, D6. - launch { mobi.giza.compose.managers.ConfederationProfileFollowThrough.observe(database = database, keyPair = keyPair) } + launch { mobi.giza.compose.managers.ConfederationChangeFollowThrough.observe(database = database, keyPair = keyPair) } // Each group's admins carrying the confederation's signing between the group's room and // the other groups' inboxes. docs/confederation-room-removal.md, D4. launch { mobi.giza.compose.managers.ConfederationBridge.observe(database = database, keyPair = keyPair) } @@ -378,22 +378,22 @@ class DatabaseChatRepository( emptyList() } - override suspend fun canSignAsConfederation(confederationId: HexKey): Boolean { + override suspend fun canSignAsConfederation(chatRoomId: String, confederationId: HexKey): Boolean { if (!ExperimentalFeatures.confederation) return false val me = activeIdentity.value?.takeIf { it.canSign }?.nostrPublicKey ?: return false - return ConfederationSigningManager.canSign(database, confederationId, me) + return mobi.giza.compose.managers.ConfederationProfileManager.changeProblem(database, chatRoomId, me, confederationId) == null } override suspend fun proposeAsConfederation( + localChatRoom: LocalChatRoom, confederationId: HexKey, 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, confederationId, identity.nostrPublicKey, kind, tags, content, secret.value.toByteArray(), + return mobi.giza.compose.managers.ConfederationProfileManager.proposeChange( + database, localChatRoom, identity.nostrPublicKey, confederationId, tags, content, kind = kind, ).id } 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 9c7e0023..88d78ce4 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,16 +16,16 @@ import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import mobi.giza.compose.managers.ConfederationProfileManager -import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus -import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatus +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatements import mobi.giza.compose.nostr.GroupNostrProfile import mobi.giza.compose.database.model.GroupSignedEvent import mobi.giza.compose.nostr.GroupPost import mobi.giza.compose.nostr.frost.GroupKeyStateEvent -import mobi.giza.compose.managers.ConfederationProfileRefusal +import mobi.giza.compose.managers.ConfederationChangeRefusal import mobi.giza.compose.managers.FrostSigningManager import mobi.giza.compose.managers.InboxReplies -import mobi.giza.compose.repository.ProfileChangeProblem +import mobi.giza.compose.repository.ChangeProblem import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.Confederation @@ -79,26 +79,6 @@ 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) { - // Signed like every signing message (docs/confederation-room-removal.md, D3). - val secret = activeIdentity.value?.nostrPrivateKey ?: return - ConfederationSigningManager.decline(database, attemptId, secret.value.toByteArray()) - } - override fun observeConfederationsOf(groupPublicKey: HexKey): Flow> = database.confederationCeremonyDao().observeConfederationsOf(groupPublicKey) @@ -130,9 +110,14 @@ class DatabaseConfederationRepository( ConfederationManager.statusOf(proposal, rows) } - override fun observeProfileChanges(confederationId: HexKey): Flow> = - database.confederationDao().observeEventsForConfederation(confederationId).map { rows -> - ConfederationProfileManager.statusesFrom(rows, ConfederationProfileManager.profiles(database, confederationId), Clock.System.now().epochSeconds) + override fun observeChanges(confederationId: HexKey): Flow> = + combine( + database.confederationDao().observeEventsForConfederation(confederationId), + // A charter is filed under its author, not the confederation's column: watched beside it. + database.confederationDao().observeChartersOf(confederationId), + ) { rows, charters -> + val signed = ConfederationProfileManager.signedFrom(confederationId, rows, charters, ConfederationProfileManager.profiles(database, confederationId)) + ConfederationProfileManager.statusesFrom(rows, signed, Clock.System.now().epochSeconds) } override fun observeKnownConfederations(): Flow> = @@ -167,40 +152,18 @@ class DatabaseConfederationRepository( override suspend fun formingProposalOf(confederationId: HexKey): HexKey? = database.confederationCeremonyDao().getConfederation(confederationId)?.proposalId - override suspend fun holdsSeat(confederationId: HexKey, userPublicKey: HexKey): Boolean = - ConfederationSigningManager.canSign(database, confederationId, userPublicKey) - - override fun observeSigningAttempts(confederationId: HexKey, userPublicKey: HexKey): Flow> = - database.confederationCeremonyDao().observeAttempts(confederationId).map { attempts -> attempts.filter { it.userPublicKey == userPublicKey } } - override fun observeCharterSigned(confederationId: HexKey): Flow = database.confederationDao().observeChartersOf(confederationId).map { rows -> rows.any { GroupKeyStateEvent.isSignedByRoom(it.toEvent(), confederationId) } } - override suspend fun proposeCharter(confederationId: HexKey): String { - val identity = activeIdentity.value ?: throw IllegalStateException("No identity is signed in") - val secret = identity.nostrPrivateKey ?: throw IllegalStateException("This identity cannot sign") - val (kind, tags, content) = ConfederationSigningManager.charterTemplate(database, confederationId) - ?: throw IllegalStateException("This device holds no record of the confederation") - return ConfederationSigningManager.propose(database, confederationId, identity.nostrPublicKey, kind, tags, content, secret.value.toByteArray()).id - } + override suspend fun proposeCharter(localChatRoom: LocalChatRoom, userPublicKey: HexKey, confederationId: HexKey): FrostSigningSession = + ConfederationProfileManager.proposeCharter(database, localChatRoom, userPublicKey, confederationId) - override suspend fun profileChangeProblem(chatRoomId: String, userPublicKey: HexKey, confederationId: HexKey): ProfileChangeProblem? { - val membership = ConfederationProfileManager.membership(database, confederationId) ?: return ProfileChangeProblem.NoRecord - if (!membership.includes(chatRoomId)) return ProfileChangeProblem.NotMember - val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return ProfileChangeProblem.NotMember - if (room.chatRoom.mlsGroupState == null || room.chatRoom.leftGroupAt != null) return ProfileChangeProblem.CannotSign - if (!FrostSigningManager.canSign(database, chatRoomId)) return ProfileChangeProblem.CannotSign - if (RoomAdmins.of(database, chatRoomId)?.admins?.contains(userPublicKey) != true) return ProfileChangeProblem.NotAdmin - if (ConfederationManager.announcedInboxKey(database, chatRoomId, userPublicKey) == null) return ProfileChangeProblem.NoInbox - membership.othersThan(chatRoomId).firstOrNull { !InboxReplies.hasAnnouncedKey(database, it) }?.let { - return ProfileChangeProblem.GroupWithoutInbox(ConfederationManager.nameOf(database, it)) - } - return null - } + override suspend fun changeProblem(chatRoomId: String, userPublicKey: HexKey, confederationId: HexKey): ChangeProblem? = + ConfederationProfileManager.changeProblem(database, chatRoomId, userPublicKey, confederationId) override suspend fun proposingGroupsFor(userPublicKey: HexKey, confederationId: HexKey): List { val membership = ConfederationProfileManager.membership(database, confederationId) ?: return emptyList() - return membership.groups.filter { profileChangeProblem(it, userPublicKey, confederationId) == null } + return membership.groups.filter { changeProblem(it, userPublicKey, confederationId) == null } } override suspend fun profileBaseOf(changeId: HexKey): UserMetadata? { @@ -210,7 +173,7 @@ class DatabaseConfederationRepository( database.confederationDao().getEvent(id)?.toEvent() ?: database.groupSignedEventDao().getById(id)?.toEvent() } - return base?.let(ConfederationProfileRefusal::metadataOf) ?: profiles.newestProfile?.metadata?.takeIf { change.base != null } + return base?.let(ConfederationChangeRefusal::metadataOf) ?: profiles.newestProfile?.metadata?.takeIf { change.base != null } } override suspend fun proposeProfileChange( @@ -221,17 +184,17 @@ class DatabaseConfederationRepository( content: String, ): FrostSigningSession = ConfederationProfileManager.proposeChange(database, localChatRoom, userPublicKey, confederationId, tags, content) - override suspend fun proposeProfileEndorsement(localChatRoom: LocalChatRoom, userPublicKey: HexKey, changeId: HexKey): FrostSigningSession = + override suspend fun proposeEndorsement(localChatRoom: LocalChatRoom, userPublicKey: HexKey, changeId: HexKey): FrostSigningSession = ConfederationProfileManager.proposeEndorsement(database, localChatRoom, userPublicKey, changeId) - override suspend fun proposeProfileObjection(localChatRoom: LocalChatRoom, userPublicKey: HexKey, changeId: HexKey, reason: String): FrostSigningSession = + override suspend fun proposeObjection(localChatRoom: LocalChatRoom, userPublicKey: HexKey, changeId: HexKey, reason: String): FrostSigningSession = ConfederationProfileManager.proposeObjection(database, localChatRoom, userPublicKey, changeId, reason) - override fun observePendingProfileAnswer(chatRoomId: String, changeId: HexKey): Flow = - pendingProfileSession(chatRoomId) { rumor -> rumor.kind != ConfederationKinds.PROFILE_CHANGE && ConfederationProfileStatements.changeIdOf(rumor) == changeId } + override fun observePendingChangeAnswer(chatRoomId: String, changeId: HexKey): Flow = + pendingProfileSession(chatRoomId) { rumor -> rumor.kind != ConfederationKinds.CHANGE && ConfederationChangeStatements.changeIdOf(rumor) == changeId } - override fun observePendingProfileChange(chatRoomId: String, confederationId: HexKey): Flow = - pendingProfileSession(chatRoomId) { rumor -> rumor.kind == ConfederationKinds.PROFILE_CHANGE && ConfederationProfileStatements.confederationOf(rumor) == confederationId } + override fun observePendingChange(chatRoomId: String, confederationId: HexKey): Flow = + pendingProfileSession(chatRoomId) { rumor -> rumor.kind == ConfederationKinds.CHANGE && ConfederationChangeStatements.confederationOf(rumor) == confederationId } private fun pendingProfileSession(chatRoomId: String, matches: (Event) -> Boolean): Flow = database.frostSigningSessionDao().observeSessionsForChatRoom(chatRoomId).map { sessions -> @@ -239,19 +202,21 @@ class DatabaseConfederationRepository( local.session.stage != FrostSigningStage.COMPLETE && local.session.stage != FrostSigningStage.FAILED && ConfederationRefusal.Carried.from(database.confederationDao().getSigning(local.session.id)).rumor - ?.takeIf { it.kind in ConfederationKinds.PROFILE_CHANGE_KINDS }?.let(matches) == true + ?.takeIf { it.kind in ConfederationKinds.CHANGE_KINDS }?.let(matches) == true }?.session } @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) - override fun observeProfileChange(changeId: HexKey): Flow = + override fun observeChange(changeId: HexKey): Flow = database.confederationDao().observeEventsForProposal(changeId).map { rows -> - val change = rows.firstOrNull { it.id == changeId && it.kind == ConfederationKinds.PROFILE_CHANGE } ?: return@map null + val change = rows.firstOrNull { it.id == changeId && it.kind == ConfederationKinds.CHANGE } ?: return@map null change.confederationId }.distinctUntilChanged().flatMapLatest { confederationId -> - if (confederationId == null) flowOf(null) else observeProfileChanges(confederationId).map { list -> list.firstOrNull { it.change.id == changeId } } + if (confederationId == null) flowOf(null) else observeChanges(confederationId).map { list -> list.firstOrNull { it.change.id == changeId } } } + override suspend fun proposalIdOf(id: String): HexKey = ConfederationProfileManager.proposalOfAttempt(database, id) ?: id + override suspend fun isAdmin(chatRoomId: String, userPublicKey: HexKey): Boolean = RoomAdmins.of(database, chatRoomId)?.admins?.contains(userPublicKey) == true diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationChangeFollowThrough.kt similarity index 83% rename from composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileFollowThrough.kt rename to composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationChangeFollowThrough.kt index ff7131f9..1333091a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileFollowThrough.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationChangeFollowThrough.kt @@ -18,21 +18,21 @@ import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.ConfederationSigningAttempt import mobi.giza.compose.database.model.ConfederationSigningStage import mobi.giza.compose.nostr.confederation.ConfederationKinds -import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState +import mobi.giza.compose.nostr.confederation.ConfederationChangeState /** - * From a change its groups endorsed to the confederation's signature on it, with nobody asked - * (docs/confederation-profile.md, D6). + * From a proposal its groups endorsed -- a profile, a post, the charter -- to the confederation's + * signature on it, with nobody asked (docs/confederation-profile.md, D6; docs/confederation-proposals.md). * - * Once a role holder's device holds vouchers from `T` groups for a change, somebody has to start the + * Once a role holder's device holds vouchers from `T` groups for a proposal, somebody has to start the * signing. Nobody is in charge, so an order says who: the roster's people sorted bytewise, the first * at once, the `k`-th once `k` [WAIT_PER_PLACE]s have passed since the `T`-th voucher reached their * device with no attempt for it heard. A failed attempt -- a nonce lost to a restart, a selected * device gone quiet -- is started again by the same rule, after a delay that doubles from - * [WAIT_PER_PLACE] up to [MAX_BACKOFF], until the change expires. + * [WAIT_PER_PLACE] up to [MAX_BACKOFF], until the proposal expires. */ -object ConfederationProfileFollowThrough { - private val logger = Logger.withTag("ConfederationProfileFollowThrough") +object ConfederationChangeFollowThrough { + private val logger = Logger.withTag("ConfederationChangeFollowThrough") private val mutex = Mutex() val WAIT_PER_PLACE: Duration = 10.minutes @@ -46,7 +46,7 @@ object ConfederationProfileFollowThrough { while (true) { runCatching { sweep(database, me, secret) }.onFailure { if (it is CancellationException) throw it - logger.e("Could not follow profile changes through", it) + logger.e("Could not follow proposals through", it) } delay(LOOK_AGAIN) } @@ -54,14 +54,14 @@ object ConfederationProfileFollowThrough { /** One look at every change this device holds. Returns the attempts it started. */ suspend fun sweep(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray, now: Instant = Clock.System.now()): List = - database.confederationDao().getProfileChanges().mapNotNull { row -> + database.confederationDao().getChanges().mapNotNull { row -> runCatching { takeNextStep(database, row.id, userPublicKey, nostrPrivateKey, now) } .onFailure { if (it is CancellationException) throw it; logger.e("Could not follow ${row.id.take(8)} through", it) } .getOrNull() } /** - * Starts the confederation's signing of [changeId]'s kind:0 if it is [userPublicKey]'s turn, and + * Starts the confederation's signing of [changeId]'s event if it is [userPublicKey]'s turn, and * returns the attempt it started; null when there is nothing to do here yet. */ suspend fun takeNextStep( @@ -75,13 +75,13 @@ object ConfederationProfileFollowThrough { val held = ConfederationSigningManager.held(database, change.confederation) ?: return@withLock null val place = held.plan.people.sorted().indexOf(userPublicKey).takeIf { it >= 0 } ?: return@withLock null val status = ConfederationProfileManager.status(database, changeId, now.epochSeconds) ?: return@withLock null - if (status.state != ConfederationProfileChangeState.ENDORSED) return@withLock null + if (status.state != ConfederationChangeState.ENDORSED) return@withLock null - val vouchers = ConfederationSigningManager.vouchersFor(database, held, change.profileId, now.epochSeconds) + val vouchers = ConfederationSigningManager.vouchersFor(database, held, change.eventId, now.epochSeconds) if (vouchers.size < held.plan.proposal.threshold) return@withLock null val attempts = database.confederationCeremonyDao().getAttempts(held.confederation.id, userPublicKey) - .filter { runCatching { Event.fromJson(it.eventJson).id }.getOrNull() == change.profileId } + .filter { runCatching { Event.fromJson(it.eventJson).id }.getOrNull() == change.eventId } if (attempts.any { it.isRunning || it.stage == ConfederationSigningStage.COMPLETE }) return@withLock null val failures = attempts.filter { it.stage == ConfederationSigningStage.FAILED } @@ -94,8 +94,8 @@ object ConfederationProfileFollowThrough { logger.i("Starting the confederation's signing of change ${changeId.take(8)}, place $place, after ${failures.size} failed attempt(s)") ConfederationSigningManager.propose( - database, held.confederation.id, userPublicKey, change.profile.kind, change.profile.tags, change.profile.content, nostrPrivateKey, - createdAt = change.profile.createdAt, vouchers = vouchers, + database, held.confederation.id, userPublicKey, change.event.kind, change.event.tags, change.event.content, nostrPrivateKey, + createdAt = change.event.createdAt, vouchers = vouchers, ) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileRefusal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationChangeRefusal.kt similarity index 60% rename from composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileRefusal.kt rename to composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationChangeRefusal.kt index 53c79650..c84f8a50 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileRefusal.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationChangeRefusal.kt @@ -8,29 +8,36 @@ import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata import kotlin.time.Clock import mobi.giza.compose.database.GizaDatabase +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.ConfederationProfileChangeState -import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements -import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements.Change +import mobi.giza.compose.nostr.confederation.ConfederationChangeState +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatements +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatements.Change import mobi.giza.compose.nostr.inbox.InboxSeal /** - * What a member's device refuses to sign for its group about a confederation's profile, out loud - * (docs/confederation-profile.md, Phase 2). `ConfederationRefusal` routes a session here when the - * statement it carries is a change, an endorsement or an objection. + * What a member's device refuses to sign for its group about what a confederation would sign, out + * loud (docs/confederation-profile.md, Phase 2; docs/confederation-proposals.md). + * `ConfederationRefusal` routes a session here when the statement it carries is a proposal, an + * endorsement or an objection. * * A signer reads what it signs, as for the formation's statements: it holds the group's inbox key, * every seal holds the carried statement, to exactly the confederation's other groups. Then the - * statement itself: a change is this group's, to a profile that can be read, editing the newest - * profile this device holds; an answer answers a change this device can read and that is still - * open; and a change or an endorsement comes with one voucher for exactly its kind:0, which is what - * the confederation's role holders will act on (D5). An objection carries none. + * statement itself: a proposal is this group's, of something that can be shown -- a profile that + * can be read and edits the newest one this device holds, a post with words in it, or a charter that + * names exactly the confederation's groups; an answer answers a proposal this device can read and + * that is still open; and a proposal or an endorsement comes with one voucher for exactly its event, + * which is what the confederation's role holders will act on (D5). An objection carries none. */ -object ConfederationProfileRefusal { +object ConfederationChangeRefusal { const val UNKNOWN_CONFEDERATION = "Declined: this device holds no record of that confederation" const val NOT_MEMBER = "Declined: the statement is not addressed to exactly the confederation's groups" const val THRESHOLD = "Declined: the change states a threshold the confederation was not formed with" const val UNREADABLE = "Declined: the proposed profile is one nothing could show" + const val BLANK_POST = "Declined: the proposed post has nothing in it" + const val UNTRUE_CHARTER = "Declined: the proposed charter does not name exactly the confederation's groups, under its name" + const val CHARTERED = "Declined: the confederation has already signed its charter" const val STALE = "Declined: the confederation's profile has changed since this was written" const val EXPIRY = "Declined: the change has expired, or stays open longer than seven days" const val UNKNOWN_CHANGE = "Declined: this device has not seen the change being answered" @@ -56,37 +63,37 @@ object ConfederationProfileRefusal { carried: ConfederationRefusal.Carried, now: Long = Clock.System.now().epochSeconds, ): String? { - val confederation = ConfederationProfileStatements.confederationOf(rumor) ?: return ConfederationRefusal.SHAPE + val confederation = ConfederationChangeStatements.confederationOf(rumor) ?: return ConfederationRefusal.SHAPE val membership = ConfederationProfileManager.membership(database, confederation) ?: return UNKNOWN_CONFEDERATION if (!membership.includes(chatRoomId)) return NOT_MEMBER val addressees = rumor.tags.filter { it.size >= 2 && it[0] == "p" }.map { it[1] }.toSet() if (addressees != membership.othersThan(chatRoomId).toSet()) return NOT_MEMBER return when (rumor.kind) { - ConfederationKinds.PROFILE_CHANGE -> { - val change = ConfederationProfileStatements.parseChange(rumor) ?: return ConfederationRefusal.SHAPE + ConfederationKinds.CHANGE -> { + val change = ConfederationChangeStatements.parseChange(rumor) ?: return ConfederationRefusal.SHAPE changeRefusal(database, chatRoomId, membership, change, now) ?: voucherRefusal(chatRoomId, change, extras) } else -> { - val answer = ConfederationProfileStatements.parseAnswer(rumor) ?: return ConfederationRefusal.SHAPE + val answer = ConfederationChangeStatements.parseAnswer(rumor) ?: return ConfederationRefusal.SHAPE val change = changeFor(database, chatRoomId, userPublicKey, answer.changeId, carried) ?: return UNKNOWN_CHANGE if (!answer.answers(change)) return ConfederationRefusal.SHAPE val status = ConfederationProfileManager.status(database, change.id, now) ?: return UNKNOWN_CHANGE when { answer.isEndorsement -> when { change.proposingGroup == chatRoomId || status.hasAnswered(chatRoomId) -> ANSWERED - status.state != ConfederationProfileChangeState.OPEN && status.state != ConfederationProfileChangeState.ENDORSED -> CLOSED + status.state != ConfederationChangeState.OPEN && status.state != ConfederationChangeState.ENDORSED -> CLOSED else -> voucherRefusal(chatRoomId, change, extras) } change.proposingGroup == chatRoomId -> when { extras.isNotEmpty() -> ConfederationRefusal.SHAPE - status.state != ConfederationProfileChangeState.OPEN && status.state != ConfederationProfileChangeState.ENDORSED -> CLOSED + status.state != ConfederationChangeState.OPEN && status.state != ConfederationChangeState.ENDORSED -> CLOSED else -> null } else -> when { extras.isNotEmpty() -> ConfederationRefusal.SHAPE status.hasAnswered(chatRoomId) -> ANSWERED - status.state != ConfederationProfileChangeState.OPEN && status.state != ConfederationProfileChangeState.ENDORSED -> CLOSED + status.state != ConfederationChangeState.OPEN && status.state != ConfederationChangeState.ENDORSED -> CLOSED else -> null } } @@ -94,7 +101,7 @@ object ConfederationProfileRefusal { } } - /** D2's rules for a change this group proposes. */ + /** D2's rules for a proposal this group makes, by what it would have the confederation sign. */ private suspend fun changeRefusal( database: GizaDatabase, chatRoomId: String, @@ -106,19 +113,29 @@ object ConfederationProfileRefusal { if (membership.fromRecord && change.threshold != membership.threshold) return THRESHOLD if (change.expiresAt <= now) return EXPIRY if (change.expiresAt > now + ConfederationKinds.MAX_CHANGE_EXPIRY_SECONDS + CLOCK_SLACK_SECONDS) return EXPIRY - if (GroupStatementRefusal.isUnreadableProfile(change.profile.tags, change.profile.content)) return UNREADABLE - // An edit of anything but the newest profile this device holds would undo it. An unknown base - // is only a warning: this device may not have heard the newest profile yet. - val newest = ConfederationProfileManager.profiles(database, change.confederation).newest?.second - if (newest != null && newest != change.base) return STALE - return null + return when (change.kind) { + MetadataEvent.KIND -> { + if (GroupStatementRefusal.isUnreadableProfile(change.event.tags, change.event.content)) return UNREADABLE + // An edit of anything but the newest profile this device holds would undo it. An unknown + // base is only a warning: this device may not have heard the newest profile yet. + val newest = ConfederationProfileManager.profiles(database, change.confederation).newest?.second + if (newest != null && newest != change.base) STALE else null + } + TextNoteEvent.KIND -> if (GroupStatementRefusal.isBlankPost(change.event.content)) BLANK_POST else null + ConfederationKinds.CHARTER -> { + val charter = ConfederationCharterEvent.parse(change.event) ?: return UNTRUE_CHARTER + if (charter.groups.toSet() != membership.groups.toSet() || charter.name != membership.name || charter.threshold != membership.threshold) return UNTRUE_CHARTER + if (ConfederationProfileManager.signed(database, change.confederation).charter != null) CHARTERED else null + } + else -> ConfederationRefusal.SHAPE + } } - /** Exactly one voucher, last, from this group, for exactly [change]'s kind:0 and expiry. */ + /** Exactly one voucher, last, from this group, for exactly [change]'s event and expiry. */ private fun voucherRefusal(chatRoomId: String, change: Change, extras: List): String? { val voucher = extras.singleOrNull() ?: return VOUCHER if (!voucher.pubKey.equals(chatRoomId, ignoreCase = true)) return VOUCHER - val parsed = ConfederationProfileStatements.parseVoucher(voucher) ?: return VOUCHER + val parsed = ConfederationChangeStatements.parseVoucher(voucher) ?: return VOUCHER return if (parsed.vouchesFor(change)) null else VOUCHER } @@ -132,24 +149,33 @@ object ConfederationProfileRefusal { val seal = carried.invitationJson?.let { Event.fromJsonOrNull(it) }?.takeIf { it.kind == InboxSeal.KIND && it.verify() } ?: return null val keys = database.inboxKeyDao().getKeys(roomId, userPublicKey).mapNotNull { it.secretKey } val opened = keys.firstNotNullOfOrNull { InboxSeal.open(seal, it.hexToByteArray()) } ?: return null - val change = ConfederationProfileStatements.parseChange(opened.rumor)?.takeIf { it.id == changeId && it.names(roomId) } ?: return null + val change = ConfederationChangeStatements.parseChange(opened.rumor)?.takeIf { it.id == changeId && it.names(roomId) } ?: return null ConfederationProfileManager.recordStatement(database, opened.rumor, seal, roomId) return change } /** - * What a member should read before approving a session over a profile statement: what would - * change, field by field, and who has endorsed it so far. + * What a member should read before approving a session over a proposal's statement: what the + * confederation would sign -- a profile field by field, a post's words, a charter's groups -- and + * who has endorsed it so far. */ suspend fun notes(database: GizaDatabase, chatRoomId: String, rumor: Event): List { - val change = ConfederationProfileStatements.parseChange(rumor) - ?: ConfederationProfileStatements.parseAnswer(rumor)?.let { ConfederationProfileManager.change(database, it.changeId) } + val change = ConfederationChangeStatements.parseChange(rumor) + ?: ConfederationChangeStatements.parseAnswer(rumor)?.let { ConfederationProfileManager.change(database, it.changeId) } ?: return emptyList() val name = ConfederationProfileManager.membership(database, change.confederation)?.name ?: "the confederation" - val base = ConfederationProfileManager.profiles(database, change.confederation).newestProfile?.metadata - val notes = mutableListOf("A new profile for $name") - notes += differences(base, metadataOf(change.profile)).map { (field, before, after) -> "$field: ${before ?: "(none)"} → ${after ?: "(cleared)"}" } - .ifEmpty { listOf("No field changes") } + val notes = mutableListOf(ConfederationProfileManager.whatIsProposed(change.event, name).replaceFirstChar { it.uppercase() }) + when (change.kind) { + MetadataEvent.KIND -> { + val base = ConfederationProfileManager.profiles(database, change.confederation).newestProfile?.metadata + notes += differences(base, metadataOf(change.event)).map { (field, before, after) -> "$field: ${before ?: "(none)"} → ${after ?: "(cleared)"}" } + .ifEmpty { listOf("No field changes") } + } + ConfederationKinds.CHARTER -> ConfederationCharterEvent.parse(change.event)?.let { charter -> + notes += "Naming " + charter.groups.map { ConfederationManager.nameOf(database, it, chatRoomId) }.joinToString() + } + else -> notes += change.event.content + } notes += "${change.threshold} of ${change.groups.size} groups must endorse it" ConfederationProfileManager.status(database, change.id)?.let { status -> notes += "Endorsed so far by " + status.endorsers.map { ConfederationManager.nameOf(database, it, chatRoomId) }.joinToString() 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 357bd78c..20bdfb61 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt @@ -211,7 +211,7 @@ object ConfederationManager { suspend fun onSigned(database: GizaDatabase, session: FrostSigningSession, signedEvents: List) { val rumor = ConfederationRefusal.Carried.from(database.confederationDao().getSigning(session.id)).rumor ?: return if (signedEvents.none { it.kind == InboxSeal.KIND && it.pubKey.equals(session.chatRoomId, ignoreCase = true) }) return - if (rumor.kind in ConfederationKinds.PROFILE_CHANGE_KINDS) { + if (rumor.kind in ConfederationKinds.CHANGE_KINDS) { ConfederationProfileManager.onSigned(database, session, rumor, signedEvents) return } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileManager.kt index b2e99332..72349ac1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileManager.kt @@ -16,20 +16,23 @@ import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent import mobi.giza.compose.nostr.GroupNostrProfile import mobi.giza.compose.nostr.confederation.ConfederationKinds -import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus -import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatus +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatements import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.inbox.InboxSeal +import mobi.giza.compose.repository.ChangeProblem /** - * A formed confederation's profile, decided by its groups (docs/confederation-profile.md): filing - * what the groups say about a change, and reading back where each change stands. + * What a formed confederation signs, decided by its groups (docs/confederation-profile.md, + * docs/confederation-proposals.md): filing what the groups say about a proposal -- a new profile, a + * post, its charter -- and reading back where each stands; and the confederation's profile itself. * - * A change, an endorsement and an objection are rumors one group seals to every other through their - * inboxes, as the formation's statements are; a voucher is the one thing a group signs that can be - * shown to anyone, and it is what the confederation's role holders act on (D5). All of them are - * filed in `ConfederationEvent` under the confederation they are about, the change's id standing as - * their `proposalId`. + * A proposal (a "change", as the code has called it since it carried only profiles), an endorsement + * and an objection are rumors one group seals to every other through their inboxes, as the + * formation's statements are; a voucher is the one thing a group signs that can be shown to anyone, + * and it is what the confederation's role holders act on (D5). All of them are filed in + * `ConfederationEvent` under the confederation they are about, the proposal's id standing as their + * `proposalId`. */ object ConfederationProfileManager { private val logger = Logger.withTag("ConfederationProfileManager") @@ -44,14 +47,14 @@ object ConfederationProfileManager { * the group's word. Callers have opened it already; this checks again. */ suspend fun recordStatement(database: GizaDatabase, rumor: Event, seal: Event?, inboxRoomId: String?): Boolean { - if (rumor.kind !in ConfederationKinds.PROFILE_CHANGE_KINDS) return false + if (rumor.kind !in ConfederationKinds.CHANGE_KINDS) return false if (seal != null && (!seal.verify() || !seal.pubKey.equals(rumor.pubKey, ignoreCase = true))) { logger.w("Profile statement ${rumor.id.take(8)} came in a seal that is not its author's; dropping") return false } val (changeId, confederation) = when (rumor.kind) { - ConfederationKinds.PROFILE_CHANGE -> ConfederationProfileStatements.parseChange(rumor)?.let { it.id to it.confederation } - else -> ConfederationProfileStatements.parseAnswer(rumor)?.let { it.changeId to it.confederation } + ConfederationKinds.CHANGE -> ConfederationChangeStatements.parseChange(rumor)?.let { it.id to it.confederation } + else -> ConfederationChangeStatements.parseAnswer(rumor)?.let { it.changeId to it.confederation } } ?: run { logger.w("Profile statement ${rumor.id.take(8)} of kind ${rumor.kind} is not well formed; dropping") return false @@ -73,7 +76,7 @@ object ConfederationProfileManager { // its change had nothing to name, so the change writes their lines now: wraps arrive in any order. if (filed) runCatching { announce(database, rumor, changeId) - if (rumor.kind == ConfederationKinds.PROFILE_CHANGE) { + if (rumor.kind == ConfederationKinds.CHANGE) { database.confederationDao().getEventsForProposal(changeId) .filter { it.kind == ConfederationKinds.ENDORSEMENT || it.kind == ConfederationKinds.OBJECTION } .forEach { announce(database, it.toEvent(), changeId) } @@ -94,17 +97,23 @@ object ConfederationProfileManager { val roomId = room.chatRoom.id val who = ConfederationManager.nameOf(database, statement.pubKey, roomId) val proposer = ConfederationManager.nameOf(database, change.proposingGroup, roomId).let { if (it == "This group") "this group" else it } + val what = whatIsProposed(change.event, name) + val proposal = when (change.kind) { + MetadataEvent.KIND -> "change to $name's profile" + ConfederationKinds.CHARTER -> "proposal of $name's charter" + else -> "post for $name" + } val (type, content) = when (statement.kind) { - ConfederationKinds.PROFILE_CHANGE -> ChatMessage.TYPE_CONFEDERATION_PROFILE_PROPOSED to - if (statement.pubKey == roomId) "This group proposed a new profile for $name" else "$who proposes a new profile for $name" + ConfederationKinds.CHANGE -> ChatMessage.TYPE_CONFEDERATION_PROFILE_PROPOSED to + if (statement.pubKey == roomId) "This group proposed $what" else "$who proposes $what" ConfederationKinds.ENDORSEMENT -> ChatMessage.TYPE_CONFEDERATION_PROFILE_ENDORSED to - "$who endorsed $proposer's change to $name's profile" + "$who endorsed $proposer's $proposal" ConfederationKinds.OBJECTION -> { - val reason = ConfederationProfileStatements.parseAnswer(statement)?.reason?.takeIf { it.isNotBlank() }?.let { ": $it" } ?: "" + val reason = ConfederationChangeStatements.parseAnswer(statement)?.reason?.takeIf { it.isNotBlank() }?.let { ": $it" } ?: "" ChatMessage.TYPE_CONFEDERATION_PROFILE_OBJECTED to if (statement.pubKey == change.proposingGroup) { - "$who withdrew its change to $name's profile$reason" + "$who withdrew its $proposal$reason" } else { - "$who objected to $proposer's change to $name's profile$reason" + "$who objected to $proposer's $proposal$reason" } } else -> return@forEach @@ -126,12 +135,19 @@ object ConfederationProfileManager { } } + /** What a line calls [event], proposed for [name] to sign: "a new profile for Atlas", "a post for Atlas", "Atlas's charter". */ + fun whatIsProposed(event: Event, name: String): String = when (event.kind) { + MetadataEvent.KIND -> "a new profile for $name" + ConfederationKinds.CHARTER -> "$name's charter" + else -> "a post for $name" + } + /** * Files [voucher] if it is well formed and its group's key signed it. Returns whether it was new. * Anyone can check one: it needs nothing but the group's npub (Phase 0, check 5). */ suspend fun recordVoucher(database: GizaDatabase, voucher: Event): Boolean { - val parsed = ConfederationProfileStatements.parseVoucher(voucher) ?: run { + val parsed = ConfederationChangeStatements.parseVoucher(voucher) ?: run { logger.w("Voucher ${voucher.id.take(8)} is not well formed; dropping") return false } @@ -166,7 +182,7 @@ object ConfederationProfileManager { return false } val change = changeId ?: database.confederationDao().getEventsForConfederation(signed.pubKey) - .firstOrNull { it.kind == ConfederationKinds.PROFILE_CHANGE && ConfederationProfileStatements.parseChange(it.toEvent())?.profileId == signed.id }?.id + .firstOrNull { it.kind == ConfederationKinds.CHANGE && ConfederationChangeStatements.parseChange(it.toEvent())?.eventId == signed.id }?.id val filed = database.confederationDao().record( ConfederationEvent( id = signed.id, @@ -202,7 +218,7 @@ object ConfederationProfileManager { val profiles = profiles(database, signed.pubKey) if (profiles.newest?.second != signed.id) return val membership = membership(database, signed.pubKey) ?: return - val newName = ConfederationProfileRefusal.metadataOf(signed)?.anyName()?.takeIf { it.isNotBlank() } + val newName = ConfederationChangeRefusal.metadataOf(signed)?.anyName()?.takeIf { it.isNotBlank() } membership.groups.mapNotNull { database.chatRoomDao().findChatRoomById(it) }.forEach { room -> database.chatMessageDao().upsert( ChatMessage( @@ -235,50 +251,75 @@ object ConfederationProfileManager { // ---- reading --------------------------------------------------------------------------------- /** The change [changeId], if this device holds it. */ - suspend fun change(database: GizaDatabase, changeId: HexKey): ConfederationProfileStatements.Change? = + suspend fun change(database: GizaDatabase, changeId: HexKey): ConfederationChangeStatements.Change? = database.confederationDao().getEvent(changeId) - ?.takeIf { it.kind == ConfederationKinds.PROFILE_CHANGE } - ?.let { ConfederationProfileStatements.parseChange(it.toEvent()) } + ?.takeIf { it.kind == ConfederationKinds.CHANGE } + ?.let { ConfederationChangeStatements.parseChange(it.toEvent()) } /** Where [changeId] stands on this device, or null if it does not hold the change. */ - suspend fun status(database: GizaDatabase, changeId: HexKey, now: Long = Clock.System.now().epochSeconds): ConfederationProfileChangeStatus? { + suspend fun status(database: GizaDatabase, changeId: HexKey, now: Long = Clock.System.now().epochSeconds): ConfederationChangeStatus? { val change = change(database, changeId) ?: return null val rows = database.confederationDao().getEventsForProposal(changeId) - return statusOf(change, rows, profiles(database, change.confederation), now) + return statusOf(change, rows, signed(database, change.confederation), now) } - /** Every change to [confederationId]'s profile this device holds, newest first, with where each stands. */ - suspend fun statusesOf(database: GizaDatabase, confederationId: HexKey, now: Long = Clock.System.now().epochSeconds): List = - statusesFrom(database.confederationDao().getEventsForConfederation(confederationId), profiles(database, confederationId), now) + /** Every proposal for [confederationId] this device holds, newest first, with where each stands. */ + suspend fun statusesOf(database: GizaDatabase, confederationId: HexKey, now: Long = Clock.System.now().epochSeconds): List = + statusesFrom(database.confederationDao().getEventsForConfederation(confederationId), signed(database, confederationId), now) - /** [statusesOf], from rows and signed kind:0s already read: what a flow's emission is handed. */ - fun statusesFrom(rows: List, profiles: Profiles, now: Long): List { + /** [statusesOf], from rows and signed events already read: what a flow's emission is handed. */ + fun statusesFrom(rows: List, signed: Signed, now: Long): List { val byChange = rows.groupBy { it.proposalId } - return rows.filter { it.kind == ConfederationKinds.PROFILE_CHANGE } + return rows.filter { it.kind == ConfederationKinds.CHANGE } .mapNotNull { row -> - val change = ConfederationProfileStatements.parseChange(row.toEvent()) ?: return@mapNotNull null - statusOf(change, byChange[change.id].orEmpty(), profiles, now) + val change = ConfederationChangeStatements.parseChange(row.toEvent()) ?: return@mapNotNull null + statusOf(change, byChange[change.id].orEmpty(), signed, now) } - .sortedWith(compareByDescending { it.change.createdAt }.thenByDescending { it.change.id }) + .sortedWith(compareByDescending { it.change.createdAt }.thenByDescending { it.change.id }) } private fun statusOf( - change: ConfederationProfileStatements.Change, + change: ConfederationChangeStatements.Change, rows: List, - profiles: Profiles, + signed: Signed, now: Long, - ): ConfederationProfileChangeStatus { + ): ConfederationChangeStatus { val events = rows.map { it.toEvent() } - return ConfederationProfileChangeStatus.of( + return ConfederationChangeStatus.of( change = change, - answers = events.mapNotNull { if (it.kind == ConfederationKinds.PROFILE_CHANGE) null else ConfederationProfileStatements.parseAnswer(it) }, - vouchers = events.filter { it.kind == ConfederationKinds.VOUCHER }.mapNotNull(ConfederationProfileStatements::parseVoucher), - newestProfile = profiles.newest, - published = change.profileId in profiles.signedIds, + answers = events.mapNotNull { if (it.kind == ConfederationKinds.CHANGE) null else ConfederationChangeStatements.parseAnswer(it) }, + vouchers = events.filter { it.kind == ConfederationKinds.VOUCHER }.mapNotNull(ConfederationChangeStatements::parseVoucher), + newestOfKind = when (change.kind) { + MetadataEvent.KIND -> signed.profiles.newest + ConfederationKinds.CHARTER -> signed.charter + else -> null + }, + published = change.eventId in signed.ids, now = now, ) } + /** + * What the confederation has signed that this device holds, as far as a proposal's state needs + * it: every id, of a profile, a post or a charter; its profiles; and its charter, if any. + */ + class Signed(val ids: Set, val profiles: Profiles, val charter: Pair?) + + suspend fun signed(database: GizaDatabase, confederationId: HexKey): Signed = signedFrom( + confederationId, + database.confederationDao().getEventsForConfederation(confederationId), + database.confederationDao().getChartersOf(confederationId), + profiles(database, confederationId), + ) + + /** [signed], from rows already read: the confederation's own, and the charters it authored. */ + fun signedFrom(confederationId: HexKey, rows: List, charterRows: List, profiles: Profiles): Signed { + val posts = rows.filter { it.kind == com.vitorpamplona.quartz.nip10Notes.TextNoteEvent.KIND && it.pubKey == confederationId }.map { it.id } + val charters = charterRows.map { it.toEvent() }.filter { GroupKeyStateEvent.isSignedByRoom(it, confederationId) } + val charter = charters.minWithOrNull(compareBy({ it.createdAt }, { it.id }))?.let { it.createdAt to it.id } + return Signed(profiles.signedIds + posts + charters.map { it.id }, profiles, charter) + } + /** The kind:0s a confederation has signed that this device holds: their ids, and the newest. */ class Profiles(val signedIds: Set, val newest: Pair?, val newestProfile: GroupNostrProfile?) { companion object { @@ -346,13 +387,55 @@ object ConfederationProfileManager { // ---- proposing ------------------------------------------------------------------------------- - /** What the form says when a profile will not fit one statement to every group (Phase 0, check 3). */ - fun tooLongFor(groups: Int): String = "This profile is too long to send to $groups groups. Shorten its about." + /** + * Why [userPublicKey] cannot put a proposal for [confederationId] to the group of [chatRoomId], + * or null when they can (D2): the group is one of the confederation's and can sign, they are its + * admin and hold its announced inbox key, and every other group has an inbox to be asked through. + */ + suspend fun changeProblem(database: GizaDatabase, chatRoomId: String, userPublicKey: HexKey, confederationId: HexKey): ChangeProblem? { + val membership = membership(database, confederationId) ?: return ChangeProblem.NoRecord + if (!membership.includes(chatRoomId)) return ChangeProblem.NotMember + val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return ChangeProblem.NotMember + if (room.chatRoom.mlsGroupState == null || room.chatRoom.leftGroupAt != null) return ChangeProblem.CannotSign + if (!FrostSigningManager.canSign(database, chatRoomId)) return ChangeProblem.CannotSign + if (RoomAdmins.of(database, chatRoomId)?.admins?.contains(userPublicKey) != true) return ChangeProblem.NotAdmin + if (ConfederationManager.announcedInboxKey(database, chatRoomId, userPublicKey) == null) return ChangeProblem.NoInbox + membership.othersThan(chatRoomId).firstOrNull { !InboxReplies.hasAnnouncedKey(database, it) }?.let { + return ChangeProblem.GroupWithoutInbox(ConfederationManager.nameOf(database, it)) + } + return null + } /** - * Proposes, in [localChatRoom], that its group propose a new profile for [confederationId]: a kind:0 - * with [tags] and [content], editing the newest one this device holds (D2). The group's quorum signs - * one seal per member group and the voucher that makes it the group's endorsement (D5). + * The proposal a signing attempt was signing, read from the event it names: a line written before + * lines named the proposal carries the attempt's id. Null when [attemptId] is no attempt, or its + * event came from no proposal this device holds. + */ + suspend fun proposalOfAttempt(database: GizaDatabase, attemptId: String): HexKey? { + val attempt = database.confederationCeremonyDao().getAttempt(attemptId) ?: return null + val eventId = Event.fromJsonOrNull(attempt.eventJson)?.id ?: return null + return proposalOfEvent(database, attempt.confederationId, eventId) + } + + /** The proposal of [eventId] for [confederationId] to sign, where this device holds it. */ + suspend fun proposalOfEvent(database: GizaDatabase, confederationId: HexKey, eventId: HexKey): HexKey? = + database.confederationDao().getEventsForConfederation(confederationId) + .firstOrNull { it.kind == ConfederationKinds.CHANGE && ConfederationChangeStatements.parseChange(it.toEvent())?.eventId == eventId }?.id + + /** + * What a form says when what it proposes will not fit one statement to every group (Phase 0, + * check 3): the whole event rides in every group's seal. + */ + fun tooLongFor(groups: Int, kind: Int = MetadataEvent.KIND): String = when (kind) { + MetadataEvent.KIND -> "This profile is too long to send to $groups groups. Shorten its about." + else -> "This post is too long to send to $groups groups. Shorten it." + } + + /** + * Proposes, in [localChatRoom], that its group propose that [confederationId] sign an event of + * [kind] with [tags] and [content] (D2): a kind:0 edits the newest profile this device holds. The + * group's quorum signs one seal per member group and the voucher that makes it the group's + * endorsement (D5). */ suspend fun proposeChange( database: GizaDatabase, @@ -363,23 +446,46 @@ object ConfederationProfileManager { content: String, createdAt: Long = Clock.System.now().epochSeconds, expiresAt: Long = createdAt + ConfederationKinds.DEFAULT_CHANGE_EXPIRY_SECONDS, + kind: Int = MetadataEvent.KIND, ): FrostSigningSession { val group = localChatRoom.chatRoom.id val membership = membership(database, confederationId) ?: throw IllegalStateException("This device holds no record of that confederation") check(membership.includes(group)) { "This group is not one of ${membership.name}'s" } - val base = profiles(database, confederationId).newest?.second - val rumor = ConfederationProfileStatements.change( - group, membership.othersThan(group), confederationId, membership.threshold, base, tags, content, createdAt, expiresAt, + val base = if (kind == MetadataEvent.KIND) profiles(database, confederationId).newest?.second else null + val rumor = ConfederationChangeStatements.change( + group, membership.othersThan(group), confederationId, membership.threshold, base, tags, content, createdAt, expiresAt, kind, ) - val change = ConfederationProfileStatements.parseChange(rumor) ?: throw IllegalStateException("That profile cannot be proposed") + val change = ConfederationChangeStatements.parseChange(rumor) ?: throw IllegalStateException("That cannot be proposed") return ConfederationManager.proposeStatement( database, localChatRoom, userPublicKey, rumor, change.addressees, invitation = null, - extra = listOf(ConfederationProfileStatements.voucherTemplate(change, createdAt)), - tooLarge = { tooLongFor(change.groups.size) }, + extra = listOf(ConfederationChangeStatements.voucherTemplate(change, createdAt)), + tooLarge = { tooLongFor(change.groups.size, kind) }, ) } + /** + * The charter [confederationId] would sign, as [membership] knows it: its groups and threshold, + * under its name. What a group proposes when the confederation has none. + */ + suspend fun charterTemplate(database: GizaDatabase, confederationId: HexKey): Pair>, String>? { + val membership = membership(database, confederationId) ?: return null + return ConfederationCharterEvent.assembleTags(membership.name, membership.groups, membership.threshold) to + ConfederationCharterEvent.content(membership.name, membership.groups.size) + } + + /** Proposes, in [localChatRoom], that the confederation sign its charter (docs/confederation-proposals.md). */ + suspend fun proposeCharter( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + confederationId: HexKey, + createdAt: Long = Clock.System.now().epochSeconds, + ): FrostSigningSession { + val (tags, content) = charterTemplate(database, confederationId) ?: throw IllegalStateException("This device holds no record of that confederation") + return proposeChange(database, localChatRoom, userPublicKey, confederationId, tags, content, createdAt, kind = ConfederationKinds.CHARTER) + } + /** Proposes that this group endorse [changeId], vouching for its kind:0 (D3, D5). */ suspend fun proposeEndorsement( database: GizaDatabase, @@ -390,11 +496,11 @@ object ConfederationProfileManager { ): FrostSigningSession { val group = localChatRoom.chatRoom.id val (change, invitation) = heldChange(database, changeId, group) - val rumor = ConfederationProfileStatements.endorsement(group, change, createdAt) + val rumor = ConfederationChangeStatements.endorsement(group, change, createdAt) return ConfederationManager.proposeStatement( database, localChatRoom, userPublicKey, rumor, change.othersThan(group), invitation, - extra = listOf(ConfederationProfileStatements.voucherTemplate(change, createdAt)), - tooLarge = { tooLongFor(change.groups.size) }, + extra = listOf(ConfederationChangeStatements.voucherTemplate(change, createdAt)), + tooLarge = { tooLongFor(change.groups.size, change.kind) }, ) } @@ -409,15 +515,15 @@ object ConfederationProfileManager { ): FrostSigningSession { val group = localChatRoom.chatRoom.id val (change, invitation) = heldChange(database, changeId, group) - val rumor = ConfederationProfileStatements.objection(group, change, reason, createdAt) + val rumor = ConfederationChangeStatements.objection(group, change, reason, createdAt) return ConfederationManager.proposeStatement(database, localChatRoom, userPublicKey, rumor, change.othersThan(group), invitation) } /** The change [changeId] and the seal that carried it to [group]: null for a change this group made. */ - private suspend fun heldChange(database: GizaDatabase, changeId: HexKey, group: HexKey): Pair { - val row = database.confederationDao().getEvent(changeId)?.takeIf { it.kind == ConfederationKinds.PROFILE_CHANGE } + private suspend fun heldChange(database: GizaDatabase, changeId: HexKey, group: HexKey): Pair { + val row = database.confederationDao().getEvent(changeId)?.takeIf { it.kind == ConfederationKinds.CHANGE } ?: throw IllegalStateException("This device does not hold that change") - val change = ConfederationProfileStatements.parseChange(row.toEvent()) ?: throw IllegalStateException("That change is not well formed") + val change = ConfederationChangeStatements.parseChange(row.toEvent()) ?: throw IllegalStateException("That change is not well formed") check(change.names(group)) { "That change is not addressed to this group" } return change to row.sealJson } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRefusal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRefusal.kt index ec8fb0e0..398ccbeb 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRefusal.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRefusal.kt @@ -92,10 +92,10 @@ object ConfederationRefusal { * the seals of the change or endorsement it vouches for (docs/confederation-profile.md, D11). */ private fun isOwnKind(kind: Int): Boolean = - ConfederationKinds.isConfederationKind(kind) || kind in ConfederationKinds.PROFILE_CHANGE_KINDS || kind == ConfederationKinds.VOUCHER + ConfederationKinds.isConfederationKind(kind) || kind in ConfederationKinds.CHANGE_KINDS || kind == ConfederationKinds.VOUCHER private fun isSealedKind(kind: Int): Boolean = - ConfederationStatements.isStatementKind(kind) || kind in ConfederationKinds.PROFILE_CHANGE_KINDS + ConfederationStatements.isStatementKind(kind) || kind in ConfederationKinds.CHANGE_KINDS /** * Why this device, as [userPublicKey], declines to sign [events] for the room [chatRoomId], or @@ -111,13 +111,13 @@ object ConfederationRefusal { now: Long = Clock.System.now().epochSeconds, ): String? { if (!involves(events, carried)) return null - if (events.any { ConfederationKinds.isConfederationKind(it.kind) || it.kind in ConfederationKinds.PROFILE_CHANGE_KINDS }) return PUBLIC + if (events.any { ConfederationKinds.isConfederationKind(it.kind) || it.kind in ConfederationKinds.CHANGE_KINDS }) return PUBLIC // The seals, then at most what is signed beside them: a profile change's voucher. val seals = events.takeWhile { it.kind == InboxSeal.KIND } val extras = events.drop(seals.size) if (seals.isEmpty() || extras.any { it.kind != ConfederationKinds.VOUCHER }) return SHAPE val rumor = carried.rumor?.takeIf { isSealedKind(it.kind) } ?: return SHAPE - if (extras.isNotEmpty() && rumor.kind !in ConfederationKinds.PROFILE_CHANGE_KINDS) return SHAPE + if (extras.isNotEmpty() && rumor.kind !in ConfederationKinds.CHANGE_KINDS) return SHAPE if (!rumor.pubKey.equals(chatRoomId, ignoreCase = true)) return NOT_LISTED val read = when (val result = InboxRefusal.readSealed(database, chatRoomId, userPublicKey, seals, manifest, ::isSealedKind)) { @@ -128,8 +128,8 @@ object ConfederationRefusal { // Every recipient is a group, reached at the key its own 10044 announced. if (read.manifest.seals.filterIndexed { index, _ -> index != read.manifest.groupCopy }.any { it.announcement == null }) return NO_INBOX if (rumor.createdAt !in (now - STATEMENT_SLACK_SECONDS)..(now + STATEMENT_SLACK_SECONDS)) return TIME - if (rumor.kind in ConfederationKinds.PROFILE_CHANGE_KINDS) { - return ConfederationProfileRefusal.of(database, chatRoomId, userPublicKey, rumor, extras, carried, now) + if (rumor.kind in ConfederationKinds.CHANGE_KINDS) { + return ConfederationChangeRefusal.of(database, chatRoomId, userPublicKey, rumor, extras, carried, now) } return when (rumor.kind) { @@ -208,7 +208,7 @@ object ConfederationRefusal { val carried = Carried.from(database.confederationDao().getSigning(sessionId)) if (!involves(events, carried)) return emptyList() val rumor = carried.rumor ?: return emptyList() - if (rumor.kind in ConfederationKinds.PROFILE_CHANGE_KINDS) return ConfederationProfileRefusal.notes(database, chatRoomId, rumor) + if (rumor.kind in ConfederationKinds.CHANGE_KINDS) return ConfederationChangeRefusal.notes(database, chatRoomId, rumor) val proposal = ConfederationStatements.parseProposal(rumor) ?: ConfederationStatements.parseAnswer(rumor)?.let { ConfederationManager.proposal(database, it.proposalId) } ?: return emptyList() 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 e00bdf97..e4881f3c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt @@ -46,7 +46,7 @@ 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.ConfederationKinds -import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatements import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder.Plan @@ -56,8 +56,11 @@ import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents * A confederation signing an event as itself, one person per device (docs/confederation.md, * Phase 14), over upstream's Option A signing, in the confederation's own Marmot room. * - * Every role holder is asked, as a FROST member is: approving says this person's roles will sign. - * The proposer, who coordinates, fixes the selection from the first yeses -- at least `T` groups, + * Nobody is asked. What the confederation signs its groups have already decided, each by its own + * quorum, and each group that endorsed it signed a voucher (docs/confederation-profile.md, D5; + * docs/confederation-proposals.md): a role holder's device says yes for each of their seats whose + * group vouched and no for the rest. An event without vouchers from `T` groups is refused, whatever + * its kind. The proposer, who coordinates, fixes the selection from the first yeses -- at least `T` groups, * at least `t_g` admins in each -- and then each selected role makes a nonce, confirms the * transcript and the event, and gives its partial. Everything that takes no secret is computed on * every device from the public messages, so each device builds the signature itself and checks it @@ -85,17 +88,23 @@ 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, its posts and its charter (Phase 15). */ - val SIGNABLE_KINDS: Set = setOf(MetadataEvent.KIND, TextNoteEvent.KIND, ConfederationCharterEvent.KIND) + val SIGNABLE_KINDS: Set = ConfederationKinds.SIGNABLE - const val RESTARTED = "A device restarted while signing, so this attempt cannot finish. Propose it again" + const val RESTARTED = "A device restarted while signing, so this attempt cannot finish. It will be started again" - /** A kind:0 asked for without enough of its groups' vouchers (docs/confederation-profile.md, D5). */ - const val THROUGH_GROUPS = "A confederation's profile changes through its groups, and not enough of them have endorsed this one" + /** + * Anything asked for without enough of its groups' vouchers (docs/confederation-profile.md, D5; + * docs/confederation-proposals.md). + */ + const val THROUGH_GROUPS = "A confederation signs only what its groups propose, and not enough of them have endorsed this" /** A kind:0 older than one the confederation has already signed: relays would keep the newer. */ const val SUPERSEDED = "The confederation has signed a newer profile since" - /** Two attempts over the same kind:0: the one whose id sorts first goes on (D6). */ + /** A charter when the confederation has signed one already. */ + const val CHARTERED = "The confederation has signed its charter already" + + /** Two attempts over the same event: the one whose id sorts first goes on (D6). */ const val CROSSED = "Another attempt is signing this change" // ---- what a confederation is on this device ------------------------------------------------ @@ -141,31 +150,36 @@ object ConfederationSigningManager { /** Why this device would not sign [event] for [held]'s confederation, or null. */ private suspend fun refusalOf(database: GizaDatabase, held: Held, event: Event): String? = - basicRefusalOf(held, event) ?: if (event.kind == MetadataEvent.KIND) profileRefusalOf(database, held, event) else null + basicRefusalOf(held, event) ?: groupsRefusalOf(database, held, event) /** - * A kind:0 is signed only on its groups' word: vouchers from at least `T` member groups, each for - * exactly this kind:0 and not expired, and no newer profile signed since (docs/confederation-profile.md, D5). + * Everything is signed only on its groups' word: vouchers from at least `T` member groups, each + * for exactly this event and not expired (docs/confederation-profile.md, D5). And nothing that + * would change nothing: no profile older than one signed since, no second charter. */ - private suspend fun profileRefusalOf(database: GizaDatabase, held: Held, event: Event): String? { + private suspend fun groupsRefusalOf(database: GizaDatabase, held: Held, event: Event): String? { if (vouchedGroups(database, held, event.id).size < held.plan.proposal.threshold) return THROUGH_GROUPS - val newest = ConfederationProfileManager.profiles(database, held.confederation.id).newest - if (newest != null && newest.second != event.id && (newest.first > event.createdAt || (newest.first == event.createdAt && newest.second < event.id))) return SUPERSEDED + val signed = ConfederationProfileManager.signed(database, held.confederation.id) + if (event.kind == MetadataEvent.KIND) { + val newest = signed.profiles.newest + if (newest != null && newest.second != event.id && (newest.first > event.createdAt || (newest.first == event.createdAt && newest.second < event.id))) return SUPERSEDED + } + if (event.kind == ConfederationCharterEvent.KIND && signed.charter != null && signed.charter.second != event.id) return CHARTERED return null } - /** The member groups whose unexpired voucher for [profileId] this device holds. */ - internal suspend fun vouchedGroups(database: GizaDatabase, held: Held, profileId: HexKey, now: Long = Clock.System.now().epochSeconds): Set = - vouchersFor(database, held, profileId, now).map { it.pubKey }.toSet() + /** The member groups whose unexpired voucher for [eventId] this device holds. */ + internal suspend fun vouchedGroups(database: GizaDatabase, held: Held, eventId: HexKey, now: Long = Clock.System.now().epochSeconds): Set = + vouchersFor(database, held, eventId, now).map { it.pubKey }.toSet() - /** The vouchers for [profileId] this device holds, one per member group, unexpired. */ - internal suspend fun vouchersFor(database: GizaDatabase, held: Held, profileId: HexKey, now: Long = Clock.System.now().epochSeconds): List = + /** The vouchers for [eventId] this device holds, one per member group, unexpired. */ + internal suspend fun vouchersFor(database: GizaDatabase, held: Held, eventId: HexKey, now: Long = Clock.System.now().epochSeconds): List = database.confederationDao().getEventsForConfederation(held.confederation.id) .filter { it.kind == ConfederationKinds.VOUCHER } .map { it.toEvent() } .filter { voucher -> - val parsed = ConfederationProfileStatements.parseVoucher(voucher) - parsed != null && parsed.profileId == profileId && parsed.expiresAt >= now && voucher.pubKey in held.plan.groups + val parsed = ConfederationChangeStatements.parseVoucher(voucher) + parsed != null && parsed.eventId == eventId && parsed.expiresAt >= now && voucher.pubKey in held.plan.groups } .distinctBy { it.pubKey } @@ -187,19 +201,13 @@ object ConfederationSigningManager { (charter.threshold == null || charter.threshold == held.plan.proposal.threshold) } - /** 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, held.plan.proposal.threshold), - ConfederationCharterEvent.content(held.confederation.name, held.plan.groups.size), - ) - } - // ---- proposing ------------------------------------------------------------------------- - /** Proposes that [confederationId] sign one event. Proposing is the proposer's approval. */ + /** + * Starts [confederationId]'s signing of one event its groups have endorsed: [vouchers] from at + * least `T` of them, carried on the proposal. Who starts it is `ConfederationChangeFollowThrough`'s + * to say (D6); nobody is asked. + */ suspend fun propose( database: GizaDatabase, confederationId: HexKey, @@ -209,8 +217,8 @@ object ConfederationSigningManager { content: String, nostrPrivateKey: ByteArray, createdAt: Long = Clock.System.now().epochSeconds, - /** For a kind:0: the groups' vouchers it is signed on, carried on the proposal (D5). */ - vouchers: List = emptyList(), + /** The groups' vouchers it is signed on, carried on the proposal (D5). */ + vouchers: List, ): ConfederationSigningAttempt = mutex.withLock { val roomId = confederationId val held = held(database, roomId) ?: throw IllegalStateException("This device holds no record of this confederation") @@ -232,27 +240,21 @@ object ConfederationSigningManager { stage = ConfederationSigningStage.SELECTING, ) database.confederationCeremonyDao().upsertAttempt(attempt) - if (event.kind == MetadataEvent.KIND) { - val carried = vouchersFor(database, held, event.id) - announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED, profileLine(database, carried)) - broadcast(database, sender, attempt, ConfederationSigningEvents.PROPOSAL, event.toJson(), carried.map { arrayOf(ConfederationSigningEvents.VOUCHER_TAG, it.toJson()) }) - publishAvailabilityByGroup(database, sender, attempt, held, carried.map { it.pubKey }.toSet()) - settleCrossing(database, sender, held, attempt, event.id) - } else { - announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED, "A proposal for the confederation to sign: ${describe(event)}") - broadcast(database, sender, attempt, ConfederationSigningEvents.PROPOSAL, event.toJson()) - publishAvailability(database, sender, attempt, held, available = true) - } + val carried = vouchersFor(database, held, event.id) + announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED, endorsedLine(database, event, carried)) + broadcast(database, sender, attempt, ConfederationSigningEvents.PROPOSAL, event.toJson(), carried.map { arrayOf(ConfederationSigningEvents.VOUCHER_TAG, it.toJson()) }) + publishAvailabilityByGroup(database, sender, attempt, held, carried.map { it.pubKey }.toSet()) + settleCrossing(database, sender, held, attempt, event.id) advance(database, sender, attempt.id) database.confederationCeremonyDao().getAttempt(attempt.id)!! } - /** The line a profile's signing writes in the confederation's room: whose word it is signed on. */ - private suspend fun profileLine(database: GizaDatabase, vouchers: List): String = - "Signing the profile endorsed by " + vouchers.map { ConfederationManager.nameOf(database, it.pubKey) }.joinToString() + /** The line a signing writes in each seat group's room: what is signed, and whose word it is signed on. */ + private suspend fun endorsedLine(database: GizaDatabase, event: Event, vouchers: List): String = + "Signing ${describe(event)}, endorsed by " + vouchers.map { ConfederationManager.nameOf(database, it.pubKey) }.joinToString() /** - * Two attempts over one kind:0 -- two people in the order who both thought it their turn -- end in + * Two attempts over one event -- two people in the order who both thought it their turn -- end in * the one whose id sorts first, on every device; the others are ended out loud (D6). */ private suspend fun settleCrossing(database: GizaDatabase, sender: Sender, held: Held, attempt: ConfederationSigningAttempt, eventId: HexKey) { @@ -272,7 +274,7 @@ object ConfederationSigningManager { * room-removal.md, D7). Several of the group's role holders send the same one; receivers keep one. */ suspend fun postVoucher(database: GizaDatabase, userPublicKey: HexKey, voucher: Event) { - val parsed = ConfederationProfileStatements.parseVoucher(voucher) ?: return + val parsed = ConfederationChangeStatements.parseVoucher(voucher) ?: return val held = held(database, parsed.confederation) ?: return if (held.plan.seatsOf(userPublicKey).none { it.group == voucher.pubKey }) return // Into the group's own room, where the group's role holders are (D2); its admins carry it on (D4). @@ -364,7 +366,7 @@ object ConfederationSigningManager { // A group's own signed word, whoever carried it. val held = held(database, confederationId) ?: return@withLock if (signed.pubKey !in held.plan.groups) return@withLock - if (ConfederationProfileStatements.parseVoucher(signed)?.confederation != held.confederation.id) return@withLock + if (ConfederationChangeStatements.parseVoucher(signed)?.confederation != held.confederation.id) return@withLock ConfederationProfileManager.recordVoucher(database, signed) return@withLock } @@ -437,19 +439,13 @@ object ConfederationSigningManager { return database.confederationCeremonyDao().getAttempt(attemptId) } database.confederationCeremonyDao().upsertAttempt(attempt) - if (event.kind == MetadataEvent.KIND) { - // Nobody is asked: each seat's group has already said, by its voucher or by not giving - // one (docs/confederation-profile.md, D5). - val vouchers = vouchersFor(database, held, event.id) - announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED, profileLine(database, vouchers)) - publishAvailabilityByGroup(database, sender, attempt, held, vouchers.map { it.pubKey }.toSet()) - replayStoredMessages(database, held, attempt) - settleCrossing(database, sender, held, attempt, event.id) - return database.confederationCeremonyDao().getAttempt(attemptId) - } - // This person answers it, as a person: their line asks them (D9). - announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_ASKED, "The confederation asks you to sign ${describe(event)}") + // Nobody is asked: each seat's group has already said, by its voucher or by not giving one + // (docs/confederation-profile.md, D5; docs/confederation-proposals.md). + val vouchers = vouchersFor(database, held, event.id) + announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED, endorsedLine(database, event, vouchers)) + publishAvailabilityByGroup(database, sender, attempt, held, vouchers.map { it.pubKey }.toSet()) replayStoredMessages(database, held, attempt) + settleCrossing(database, sender, held, attempt, event.id) return database.confederationCeremonyDao().getAttempt(attemptId) } @@ -502,35 +498,6 @@ object ConfederationSigningManager { return true } - // ---- the member's say -------------------------------------------------------------------- - - fun isAwaitingApproval(attempt: ConfederationSigningAttempt): Boolean = - attempt.isRunning && attempt.approvedAt == null && attempt.declinedAt == null - - suspend fun approve(database: GizaDatabase, attemptId: String, nostrPrivateKey: ByteArray) = mutex.withLock { - val attempt = database.confederationCeremonyDao().getAttempt(attemptId)?.takeIf(::isAwaitingApproval) ?: return@withLock - val sender = Sender(nostrPrivateKey) - val held = held(database, attempt.confederationId) ?: return@withLock - // Checked again: what is signed has to be what this device would sign now. - refusalOf(database, held, Event.fromJson(attempt.eventJson))?.let { why -> - update(database, attempt) { it.copy(declinedAt = Clock.System.now(), failureReason = why) } - publishAvailability(database, sender, attempt, held, available = false) - return@withLock - } - update(database, attempt) { it.copy(approvedAt = Clock.System.now()) } - publishAvailability(database, sender, attempt, held, available = true) - advance(database, sender, attemptId) - } - - suspend fun decline(database: GizaDatabase, attemptId: String, nostrPrivateKey: ByteArray) = mutex.withLock { - val attempt = database.confederationCeremonyDao().getAttempt(attemptId)?.takeIf(::isAwaitingApproval) ?: return@withLock - val sender = Sender(nostrPrivateKey) - val held = held(database, attempt.confederationId) ?: return@withLock - update(database, attempt) { it.copy(declinedAt = Clock.System.now()) } - publishAvailability(database, sender, attempt, held, available = false) - advance(database, sender, attemptId) - } - /** * After a restart: an attempt this device sent nonces in and has not finished cannot finish * now, since the nonces went with the process. Ends each out loud. Others are moved on. @@ -694,7 +661,7 @@ object ConfederationSigningManager { // A profile its groups decided: filed under the confederation beside the change it came from, // and owed to relays by the device that started the signing (docs/confederation-profile.md, D7). if (signed.kind == MetadataEvent.KIND) { - val changeId = vouchersFor(database, held, signed.id, now = 0).firstNotNullOfOrNull { ConfederationProfileStatements.parseVoucher(it)?.changeId } + val changeId = vouchersFor(database, held, signed.id, now = 0).firstNotNullOfOrNull { ConfederationChangeStatements.parseVoucher(it)?.changeId } ConfederationProfileManager.recordProfile(database, signed, changeId) // Owed by every device that signed it, not only the one that started it: the same event // from several devices is one event to a relay, and nobody waits on one phone (D7, as built). @@ -880,9 +847,8 @@ object ConfederationSigningManager { // 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, - // An ask is to this device's owner, so it is theirs, as a FROST ask is (NotificationClassifier.NEEDS_YOU). - senderPublicKey = if (type == ChatMessage.TYPE_CONFEDERATION_SIGNING_ASKED) attempt.userPublicKey else attempt.proposerPublicKey, - isUserMessage = type == ChatMessage.TYPE_CONFEDERATION_SIGNING_ASKED, + senderPublicKey = attempt.proposerPublicKey, + isUserMessage = false, giftWrapPayloadId = null, marmotGroupEventId = null, marmotInnerEventId = null, 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 58e81b12..a723ede1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt @@ -121,7 +121,7 @@ object GroupInboxManager { } // A formed confederation's groups deciding its profile: the confederation's to file, as // the formation's statements are (docs/confederation-profile.md, D2 and D3). - if (rumor.kind in ConfederationKinds.PROFILE_CHANGE_KINDS) { + if (rumor.kind in ConfederationKinds.CHANGE_KINDS) { ConfederationProfileManager.recordStatement(database, rumor, opened.seal, roomId) database.groupInboxDao().markOpened(wrap.id, key.generation) return null diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt index a35a345b..d641855a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt @@ -233,7 +233,7 @@ object InboxReplies { val rumor = InboxSeal.rumorInside(copy.content, InboxReplyManifest.selfConversationKey(key.secretKey!!.hexToByteArray()), roomId) ?: return // A confederation's statement is the confederation's to file, not a conversation in the // inbox (docs/confederation-without-coordinator.md, D7). - if (ConfederationStatements.isStatementKind(rumor.kind) || rumor.kind in ConfederationKinds.PROFILE_CHANGE_KINDS) return + if (ConfederationStatements.isStatementKind(rumor.kind) || rumor.kind in ConfederationKinds.CHANGE_KINDS) return val participants = InboxConversation.participantsOf(rumor, roomId) database.groupInboxDao().insertMessage( GroupInboxMessage( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileStatements.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationChangeStatements.kt similarity index 71% rename from composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileStatements.kt rename to composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationChangeStatements.kt index 2907f955..959e1323 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileStatements.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationChangeStatements.kt @@ -10,36 +10,44 @@ import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler import mobi.giza.compose.nostr.confederation.tags.ConfederationThresholdTag /** - * What a formed confederation's groups say to each other about its profile - * (docs/confederation-profile.md, D2, D3 and D5). + * What a formed confederation's groups say to each other about something it would sign + * (docs/confederation-profile.md, D2, D3 and D5; docs/confederation-proposals.md): a new profile, + * a post, or its charter. Whatever it is, it goes the same way -- one group proposes it, the others + * endorse or object, each by its own quorum, and the confederation signs it once `T` have vouched. * * ``` - * 9435 rumor a group proposing a new profile - * content: the unsigned kind:0, as JSON, its id included and its signature empty + * 9435 rumor a group proposing that the confederation sign an event + * content: the unsigned event, as JSON, its id included and its signature empty: + * a kind:0, a kind:1 or a 9434, authored by the confederation * tags: ["p", ] …, ["confederation", ], - * ["threshold", ""], ["base", ] (absent when none), - * ["expiration", ""] + * ["threshold", ""], ["base", ] (a kind:0's only, and + * absent when there is none), ["expiration", ""] * 9436 rumor a group endorsing it content: empty * 9437 rumor a group objecting to it, or content: a reason, or nothing * the proposing group withdrawing it * tags (both): ["p", ] …, ["confederation", ], - * ["e", ], ["profile", ] - * 9438 signed a group vouching for the kind:0, signed by its quorum in the same session as its + * ["e", ], ["profile", ] + * 9438 signed a group vouching for the event, signed by its quorum in the same session as its * 9435 or 9436 and never published - * tags: ["confederation", ], ["profile", ], ["e", ], + * tags: ["confederation", ], ["profile", ], ["e", ], * ["expiration", ""] * ``` * - * The kind:0 is dated when it is proposed and its `created_at` is the 9435's own, so its id is - * fixed before anyone answers, and every answer, voucher and signing attempt names that id. + * The `profile` tag names the proposed event whatever its kind: it was named when only profiles + * went this way, and a voucher is a signed event, so renaming it would leave older devices unable + * to read newer vouchers. + * + * The event is dated when it is proposed and its `created_at` is the 9435's own, so its id is fixed + * before anyone answers, and every answer, voucher and signing attempt names that id. * * Parsing is all or nothing, as for the formation's statements: whether the groups agree is - * [ConfederationProfileChangeStatus]'s to compute and whether a device signs is the refusal's. + * [ConfederationChangeStatus]'s to compute and whether a device signs is the refusal's. */ -object ConfederationProfileStatements { +object ConfederationChangeStatements { const val CONFEDERATION_TAG = "confederation" const val BASE_TAG = "base" - const val PROFILE_TAG = "profile" + /** Names the proposed event, of whatever kind; see the note above on why it says `profile`. */ + const val EVENT_TAG = "profile" const val EXPIRATION_TAG = "expiration" /** A proposed change, as [parseChange] reads it from its rumor. */ @@ -53,16 +61,20 @@ object ConfederationProfileStatements { val addressees: List, /** How many groups must endorse it: the confederation's outer threshold, as the proposer states it. */ val threshold: Int, - /** The kind:0 this edits, or null for the confederation's first. */ + /** The kind:0 this edits, or null for the confederation's first, and for anything but a kind:0. */ val base: HexKey?, val expiresAt: Long, - /** The kind:0 the confederation would sign: unsigned, its id computed. */ - val profile: Event, + /** The event the confederation would sign: unsigned, its id computed. */ + val event: Event, ) { /** Every member group, the proposer first. */ val groups: List get() = listOf(proposingGroup) + addressees - val profileId: HexKey get() = profile.id + val eventId: HexKey get() = event.id + + val kind: Kind get() = event.kind + + val isProfile: Boolean get() = event.kind == MetadataEvent.KIND fun names(group: HexKey): Boolean = group in groups @@ -79,7 +91,7 @@ object ConfederationProfileStatements { val createdAt: Long, val changeId: HexKey, val confederation: HexKey, - val profileId: HexKey, + val eventId: HexKey, val addressees: List, /** An objection's or a withdrawal's reason; empty for an endorsement. */ val reason: String, @@ -88,7 +100,7 @@ object ConfederationProfileStatements { /** Whether this answers [change], addressed to every other group it names. */ fun answers(change: Change): Boolean = - changeId == change.id && profileId == change.profileId && confederation == change.confederation && + changeId == change.id && eventId == change.eventId && confederation == change.confederation && change.names(group) && addressees.toSet() == change.othersThan(group).toSet() } @@ -98,25 +110,26 @@ object ConfederationProfileStatements { val group: HexKey, val createdAt: Long, val confederation: HexKey, - val profileId: HexKey, + val eventId: HexKey, val changeId: HexKey, val expiresAt: Long, ) { - /** Whether this vouches for exactly [change]'s kind:0. */ + /** Whether this vouches for exactly [change]'s event. */ fun vouchesFor(change: Change): Boolean = - changeId == change.id && profileId == change.profileId && confederation == change.confederation && + changeId == change.id && eventId == change.eventId && confederation == change.confederation && expiresAt == change.expiresAt && change.names(group) } // ---- building -------------------------------------------------------------------------------- - /** The unsigned kind:0 [confederation] would sign, with its id. */ - fun unsignedProfile(confederation: HexKey, createdAt: Long, tags: Array>, content: String): Event = - Event(EventHasher.hashId(confederation, createdAt, MetadataEvent.KIND, tags, content), confederation, createdAt, MetadataEvent.KIND, tags, content, "") + /** The unsigned event of [kind] that [confederation] would sign, with its id. */ + fun unsigned(confederation: HexKey, createdAt: Long, kind: Kind, tags: Array>, content: String): Event = + Event(EventHasher.hashId(confederation, createdAt, kind, tags, content), confederation, createdAt, kind, tags, content, "") /** - * The 9435 [group] would send to [others], proposing that [confederation] sign a kind:0 with - * [profileTags] and [profileContent], dated [createdAt] like the rumor itself. + * The 9435 [group] would send to [others], proposing that [confederation] sign an event of + * [kind] with [eventTags] and [eventContent], dated [createdAt] like the rumor itself. [base] + * is for a kind:0 only. */ fun change( group: HexKey, @@ -124,19 +137,22 @@ object ConfederationProfileStatements { confederation: HexKey, threshold: Int, base: HexKey?, - profileTags: Array>, - profileContent: String, + eventTags: Array>, + eventContent: String, createdAt: Long, expiresAt: Long, + kind: Kind = MetadataEvent.KIND, ): Event { - val profile = unsignedProfile(confederation, createdAt, profileTags, profileContent) + require(kind in ConfederationKinds.SIGNABLE) { "A confederation does not sign events of kind $kind" } + require(base == null || kind == MetadataEvent.KIND) { "Only a profile edits a base" } + val event = unsigned(confederation, createdAt, kind, eventTags, eventContent) val tags = others.filter { it != group }.distinct().map { arrayOf("p", it) } + listOfNotNull( arrayOf(CONFEDERATION_TAG, confederation), ConfederationThresholdTag.assemble(threshold.toString()), base?.let { arrayOf(BASE_TAG, it) }, arrayOf(EXPIRATION_TAG, expiresAt.toString()), ) - return rumor(group, ConfederationKinds.PROFILE_CHANGE, tags.toTypedArray(), profile.toJson(), createdAt) + return rumor(group, ConfederationKinds.CHANGE, tags.toTypedArray(), event.toJson(), createdAt) } fun endorsement(group: HexKey, change: Change, createdAt: Long): Event = @@ -150,18 +166,18 @@ object ConfederationProfileStatements { val tags = change.othersThan(group).map { arrayOf("p", it) } + listOf( arrayOf(CONFEDERATION_TAG, change.confederation), arrayOf("e", change.id), - arrayOf(PROFILE_TAG, change.profileId), + arrayOf(EVENT_TAG, change.eventId), ) return rumor(group, kind, tags.toTypedArray(), content, createdAt) } - /** What a group signs beside its seals to vouch for [change]'s kind:0. The signer sets the author. */ + /** What a group signs beside its seals to vouch for [change]'s event. The signer sets the author. */ fun voucherTemplate(change: Change, createdAt: Long): EventTemplate = EventTemplate( createdAt, ConfederationKinds.VOUCHER, arrayOf( arrayOf(CONFEDERATION_TAG, change.confederation), - arrayOf(PROFILE_TAG, change.profileId), + arrayOf(EVENT_TAG, change.eventId), arrayOf("e", change.id), arrayOf(EXPIRATION_TAG, change.expiresAt.toString()), ), @@ -175,7 +191,7 @@ object ConfederationProfileStatements { /** The change in [rumor], or null if it is not a well-formed one. */ fun parseChange(rumor: Event): Change? = runCatching { - if (rumor.kind != ConfederationKinds.PROFILE_CHANGE) return null + if (rumor.kind != ConfederationKinds.CHANGE) return null if (!ConfederationKinds.isPublicKey(rumor.pubKey)) return null val addressees = addresseesOf(rumor.tags) ?: return null if (rumor.pubKey in addressees) return null @@ -194,10 +210,11 @@ object ConfederationProfileStatements { if (expiresAt <= rumor.createdAt) return null if (rumor.tags.any { it.isNotEmpty() && it[0] == "e" }) return null - val profile = Event.fromJsonOrNull(rumor.content) ?: return null - if (profile.kind != MetadataEvent.KIND || profile.pubKey != confederation) return null - if (profile.createdAt != rumor.createdAt || profile.sig.isNotEmpty()) return null - if (profile.id != EventHasher.hashId(profile.pubKey, profile.createdAt, profile.kind, profile.tags, profile.content)) return null + val event = Event.fromJsonOrNull(rumor.content) ?: return null + if (event.kind !in ConfederationKinds.SIGNABLE || event.pubKey != confederation) return null + if (base != null && event.kind != MetadataEvent.KIND) return null + if (event.createdAt != rumor.createdAt || event.sig.isNotEmpty()) return null + if (event.id != EventHasher.hashId(event.pubKey, event.createdAt, event.kind, event.tags, event.content)) return null Change( id = rumor.id, @@ -208,7 +225,7 @@ object ConfederationProfileStatements { threshold = threshold, base = base, expiresAt = expiresAt, - profile = profile, + event = event, ) }.getOrNull() @@ -220,7 +237,7 @@ object ConfederationProfileStatements { if (rumor.pubKey in addressees) return null val confederation = single(rumor.tags, CONFEDERATION_TAG)?.takeIf(ConfederationKinds::isPublicKey) ?: return null val changeId = single(rumor.tags, "e")?.takeIf(ConfederationKinds::isHex32) ?: return null - val profileId = single(rumor.tags, PROFILE_TAG)?.takeIf(ConfederationKinds::isHex32) ?: return null + val eventId = single(rumor.tags, EVENT_TAG)?.takeIf(ConfederationKinds::isHex32) ?: return null if (rumor.kind == ConfederationKinds.ENDORSEMENT && rumor.content.isNotEmpty()) return null Answer( id = rumor.id, @@ -229,7 +246,7 @@ object ConfederationProfileStatements { createdAt = rumor.createdAt, changeId = changeId, confederation = confederation, - profileId = profileId, + eventId = eventId, addressees = addressees, reason = rumor.content, ) @@ -244,15 +261,15 @@ object ConfederationProfileStatements { if (!ConfederationKinds.isPublicKey(event.pubKey)) return null if (event.tags.size != 4) return null val confederation = single(event.tags, CONFEDERATION_TAG)?.takeIf(ConfederationKinds::isPublicKey) ?: return null - val profileId = single(event.tags, PROFILE_TAG)?.takeIf(ConfederationKinds::isHex32) ?: return null + val eventId = single(event.tags, EVENT_TAG)?.takeIf(ConfederationKinds::isHex32) ?: return null val changeId = single(event.tags, "e")?.takeIf(ConfederationKinds::isHex32) ?: return null val expiresAt = single(event.tags, EXPIRATION_TAG)?.toLongOrNull() ?: return null - Voucher(event.id, event.pubKey, event.createdAt, confederation, profileId, changeId, expiresAt) + Voucher(event.id, event.pubKey, event.createdAt, confederation, eventId, changeId, expiresAt) }.getOrNull() /** The change a statement is about: its own id for a change, its `e` for an answer. */ fun changeIdOf(rumor: Event): HexKey? = when (rumor.kind) { - ConfederationKinds.PROFILE_CHANGE -> parseChange(rumor)?.id + ConfederationKinds.CHANGE -> parseChange(rumor)?.id else -> parseAnswer(rumor)?.changeId } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileChangeStatus.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationChangeStatus.kt similarity index 50% rename from composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileChangeStatus.kt rename to composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationChangeStatus.kt index 067a392d..48d5f36c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileChangeStatus.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationChangeStatus.kt @@ -1,12 +1,15 @@ package mobi.giza.compose.nostr.confederation import com.vitorpamplona.quartz.nip01Core.core.HexKey -import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements.Answer -import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements.Change -import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements.Voucher +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatements.Answer +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatements.Change +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatements.Voucher -/** Where a proposed change to a confederation's profile stands (docs/confederation-profile.md, D4). */ -enum class ConfederationProfileChangeState { +/** + * Where a proposal for a confederation to sign something stands (docs/confederation-profile.md, D4; + * docs/confederation-proposals.md): a new profile, a post or its charter. + */ +enum class ConfederationChangeState { /** Waiting on groups to answer. */ OPEN, @@ -16,7 +19,10 @@ enum class ConfederationProfileChangeState { /** The confederation signed it, and this device holds it signed. */ PUBLISHED, - /** A newer profile is held: relays keep only the newest, so this one would change nothing. */ + /** + * Something that replaces it is signed: a newer profile, which relays keep instead, or another + * charter. A post is never superseded. + */ SUPERSEDED, /** So many groups objected that it can no longer reach the threshold. */ @@ -29,11 +35,11 @@ enum class ConfederationProfileChangeState { EXPIRED, } -/** What each group has said about a change. */ -enum class ConfederationProfileAnswer { PROPOSED, ENDORSED, OBJECTED, WAITING } +/** What each group has said about a proposal. */ +enum class ConfederationChangeAnswer { PROPOSED, ENDORSED, OBJECTED, WAITING } /** - * A change and everything said about it, and the state that follows, computed whenever it is read: + * A proposal and everything said about it, and the state that follows, computed whenever it is read: * every device that holds the same statements computes the same thing. * * One answer counts per group: its first, by `created_at` and then id, and only if dated by the @@ -41,26 +47,26 @@ enum class ConfederationProfileAnswer { PROPOSED, ENDORSED, OBJECTED, WAITING } * of it (docs/confederation.md, D8). The proposing group's own 9435 is its endorsement, and its 9437 * a withdrawal. */ -data class ConfederationProfileChangeStatus( +data class ConfederationChangeStatus( val change: Change, /** Each answering group's counted answer. */ val answers: Map, - /** Each group's voucher for this kind:0, where this device holds one. */ + /** Each group's voucher for this event, where this device holds one. */ val vouchers: Map, - val state: ConfederationProfileChangeState, + val state: ConfederationChangeState, ) { /** The groups that endorsed it, the proposer first. */ val endorsers: List - get() = change.groups.filter { answerOf(it) == ConfederationProfileAnswer.PROPOSED || answerOf(it) == ConfederationProfileAnswer.ENDORSED } + get() = change.groups.filter { answerOf(it) == ConfederationChangeAnswer.PROPOSED || answerOf(it) == ConfederationChangeAnswer.ENDORSED } - val objectors: List get() = change.groups.filter { answerOf(it) == ConfederationProfileAnswer.OBJECTED } + val objectors: List get() = change.groups.filter { answerOf(it) == ConfederationChangeAnswer.OBJECTED } - fun answerOf(group: HexKey): ConfederationProfileAnswer = when { - group == change.proposingGroup -> ConfederationProfileAnswer.PROPOSED + fun answerOf(group: HexKey): ConfederationChangeAnswer = when { + group == change.proposingGroup -> ConfederationChangeAnswer.PROPOSED else -> when (answers[group]?.isEndorsement) { - true -> ConfederationProfileAnswer.ENDORSED - false -> ConfederationProfileAnswer.OBJECTED - null -> ConfederationProfileAnswer.WAITING + true -> ConfederationChangeAnswer.ENDORSED + false -> ConfederationChangeAnswer.OBJECTED + null -> ConfederationChangeAnswer.WAITING } } @@ -69,22 +75,23 @@ data class ConfederationProfileChangeStatus( /** The proposer's withdrawal, if it made one. */ val withdrawal: Answer? get() = answers[change.proposingGroup] - val isOpen: Boolean get() = state == ConfederationProfileChangeState.OPEN + val isOpen: Boolean get() = state == ConfederationChangeState.OPEN companion object { /** * The status of [change] given what this device holds: [answers] and [vouchers] about it, the - * newest signed kind:0 of the confederation it holds ([newestProfile], by `created_at` and id), - * and whether it holds [change]'s own kind:0 signed ([published]). + * newest signed event of its kind the confederation has that would replace it ([newestOfKind], + * by `created_at` and id: a kind:0, or a charter), and whether it holds [change]'s own event + * signed ([published]). */ fun of( change: Change, answers: List, vouchers: List, - newestProfile: Pair?, + newestOfKind: Pair?, published: Boolean, now: Long, - ): ConfederationProfileChangeStatus { + ): ConfederationChangeStatus { val counted = answers .filter { it.answers(change) && it.createdAt <= change.expiresAt } .filter { it.group != change.proposingGroup || !it.isEndorsement } @@ -96,20 +103,26 @@ data class ConfederationProfileChangeStatus( val endorsing = 1 + counted.values.count { it.isEndorsement && it.group != change.proposingGroup } val objecting = counted.values.count { !it.isEndorsement && it.group != change.proposingGroup } val groups = change.groups.size - val newer = newestProfile?.let { (createdAt, id) -> - id != change.profileId && (createdAt > change.createdAt || (createdAt == change.createdAt && id < change.profileId)) + val newer = newestOfKind?.let { (createdAt, id) -> + when (change.kind) { + // Relays keep the newest kind:0 only, so an older one signed now would change nothing. + 0 -> id != change.eventId && (createdAt > change.createdAt || (createdAt == change.createdAt && id < change.eventId)) + // A confederation has one charter: once one is signed, another says nothing new. + ConfederationKinds.CHARTER -> id != change.eventId + else -> false + } } == true val state = when { - published -> ConfederationProfileChangeState.PUBLISHED - counted.containsKey(change.proposingGroup) -> ConfederationProfileChangeState.WITHDRAWN - newer -> ConfederationProfileChangeState.SUPERSEDED - change.isExpiredAt(now) -> ConfederationProfileChangeState.EXPIRED - endorsing >= change.threshold -> ConfederationProfileChangeState.ENDORSED - groups - objecting < change.threshold -> ConfederationProfileChangeState.DECLINED - else -> ConfederationProfileChangeState.OPEN + published -> ConfederationChangeState.PUBLISHED + counted.containsKey(change.proposingGroup) -> ConfederationChangeState.WITHDRAWN + newer -> ConfederationChangeState.SUPERSEDED + change.isExpiredAt(now) -> ConfederationChangeState.EXPIRED + endorsing >= change.threshold -> ConfederationChangeState.ENDORSED + groups - objecting < change.threshold -> ConfederationChangeState.DECLINED + else -> ConfederationChangeState.OPEN } - return ConfederationProfileChangeStatus(change, counted, vouched, state) + return ConfederationChangeStatus(change, counted, vouched, state) } } } 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 fd9b788f..8ae0217c 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 @@ -26,11 +26,12 @@ object ConfederationKinds { val ALL: Set = setOf(PROPOSAL, ACCEPTANCE, REJECTION, WITHDRAWAL, CHARTER) /** - * A formed confederation's groups deciding its profile (docs/confederation-profile.md): a group - * proposing a change, and every other group endorsing or objecting to it. Rumors only, sealed - * group to group like the proposal's statements; never on a relay, so never in [ALL]. + * A formed confederation's groups deciding what it signs (docs/confederation-profile.md, + * docs/confederation-proposals.md): a group proposing an event -- a profile, a post, the + * charter -- and every other group endorsing or objecting to it. Rumors only, sealed group to + * group like the proposal's statements; never on a relay, so never in [ALL]. */ - const val PROFILE_CHANGE: Kind = 9435 + const val CHANGE: Kind = 9435 const val ENDORSEMENT: Kind = 9436 const val OBJECTION: Kind = 9437 @@ -41,10 +42,16 @@ object ConfederationKinds { */ const val VOUCHER: Kind = 9438 - /** The statements of a profile change. The voucher is not one: it is signed, not sealed. */ - val PROFILE_CHANGE_KINDS: Set = setOf(PROFILE_CHANGE, ENDORSEMENT, OBJECTION) + /** The statements of a proposal. The voucher is not one: it is signed, not sealed. */ + val CHANGE_KINDS: Set = setOf(CHANGE, ENDORSEMENT, OBJECTION) - /** How long a profile change stays open by default, and at most (D2). */ + /** + * What a confederation signs, and so what a 9435 may carry: its profile (kind:0), its posts + * (kind:1) and its charter ([CHARTER]). + */ + val SIGNABLE: Set = setOf(0, 1, CHARTER) + + /** How long a proposal stays open by default, and at most (D2). */ const val DEFAULT_CHANGE_EXPIRY_SECONDS: Long = 3L * 24 * 60 * 60 const val MAX_CHANGE_EXPIRY_SECONDS: Long = 7L * 24 * 60 * 60 diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationClassifier.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationClassifier.kt index 50011d06..52d29f6b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationClassifier.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationClassifier.kt @@ -33,8 +33,6 @@ object NotificationClassifier { * session's own key), so unlike the other two categories they are not dropped for being ours. */ val NEEDS_YOU: Set = setOf( - // The confederation asking for this person's answer, for their seats (docs/confederation-room-removal.md, D9). - Line.TYPE_CONFEDERATION_SIGNING_ASKED, Line.TYPE_DKG_APPROVAL_NEEDED_HOST_KEY, Line.TYPE_DKG_APPROVAL_NEEDED_ROUND_1, Line.TYPE_DKG_APPROVAL_NEEDED_ROUND_2, @@ -106,6 +104,8 @@ object NotificationClassifier { Line.TYPE_CONFEDERATION_CEREMONY_COMPLETE, Line.TYPE_CONFEDERATION_CEREMONY_FAILED, Line.TYPE_CONFEDERATION_SIGNING_PROPOSED, + // No longer written: nobody is asked what the groups decide (docs/confederation-proposals.md). + Line.TYPE_CONFEDERATION_SIGNING_ASKED, Line.TYPE_CONFEDERATION_SIGNING_FAILED, Line.TYPE_CONFEDERATION_PROFILE_ENDORSED, Line.TYPE_CONFEDERATION_PROFILE_OBJECTED, 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 0f63acfd..145bced8 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -171,11 +171,18 @@ interface ChatRepository { /** What [chatRoomId]'s screen says about its direct messages, to [userPublicKey]. docs/group-threshold-ecdh.md. */ suspend fun groupDmRow(chatRoomId: String, userPublicKey: HexKey): mobi.giza.compose.ui.view.state.GroupDmRow? = null - /** Whether this device holds a seat in [confederationId], and so can propose what it signs. docs/confederation.md, Phase 15. */ - suspend fun canSignAsConfederation(confederationId: HexKey): Boolean = false + /** + * Whether the signed-in identity can put a proposal for [confederationId] to sign something to + * [chatRoomId]'s group: an admin of a member group, holding its inbox key. docs/confederation-proposals.md. + */ + suspend fun canSignAsConfederation(chatRoomId: String, confederationId: HexKey): Boolean = false - /** Proposes that [confederationId] sign one event. The attempt's id. docs/confederation-room-removal.md, D9. */ - suspend fun proposeAsConfederation(confederationId: HexKey, kind: Kind, tags: Array>, content: String): String = + /** + * Proposes, in [localChatRoom], that its group propose that [confederationId] sign one event: the + * group's quorum signs it to every member group, which endorse or object (docs/confederation-proposals.md). + * The group's signing session's id. + */ + suspend fun proposeAsConfederation(localChatRoom: LocalChatRoom, confederationId: HexKey, kind: Kind, tags: Array>, content: String): String = throw UnsupportedOperationException("No confederation here") /** Who [confederationId] says it is, and its name: the byline over a post the confederation is to sign. */ 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 29edab31..88384d71 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt @@ -9,14 +9,12 @@ 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 import mobi.giza.compose.managers.ConfederationManager import mobi.giza.compose.nostr.confederation.ConfederationStatus -import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatus import mobi.giza.compose.managers.ConfederationProfileManager import mobi.giza.compose.nostr.GroupNostrProfile import mobi.giza.compose.nostr.GroupPost @@ -100,29 +98,24 @@ 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> /** - * Every change to [confederationId]'s profile this device holds, newest first, with where each - * stands, as it changes. docs/confederation-profile.md, D4. + * Every proposal for [confederationId] to sign something this device holds -- a profile, a post, + * its charter -- newest first, with where each stands, as it changes. docs/confederation-profile.md, + * D4; docs/confederation-proposals.md. */ - fun observeProfileChanges(confederationId: HexKey): Flow> = flowOf(emptyList()) + fun observeChanges(confederationId: HexKey): Flow> = flowOf(emptyList()) - /** One change to a confederation's profile, as it changes; null while this device does not hold it. */ - fun observeProfileChange(changeId: HexKey): Flow = flowOf(null) + /** One proposal, as it changes; null while this device does not hold it. */ + fun observeChange(changeId: HexKey): Flow = flowOf(null) + + /** + * The proposal [id] names: itself, or -- for a signing attempt's id, which a line about a signing + * carries -- the proposal the attempt was signing, where this device holds it. + */ + suspend fun proposalIdOf(id: String): HexKey = id /** Every formed confederation this device knows of, by record or charter: whose kind:0 the relays are asked for (D7). */ fun observeKnownConfederations(): Flow> = flowOf(emptyList()) @@ -145,29 +138,27 @@ interface ConfederationRepository { /** The proposal the confederation was formed from, where this device holds it. */ suspend fun formingProposalOf(confederationId: HexKey): HexKey? = null - /** Whether [userPublicKey] holds a seat in the confederation, and so can propose what it signs and answer for it. */ - suspend fun holdsSeat(confederationId: HexKey, userPublicKey: HexKey): Boolean = false - - /** [userPublicKey]'s attempts at the confederation signing something, newest first (docs/confederation-room-removal.md, D9). */ - fun observeSigningAttempts(confederationId: HexKey, userPublicKey: HexKey): Flow> = flowOf(emptyList()) - /** Whether this device holds a charter the confederation has signed. */ fun observeCharterSigned(confederationId: HexKey): Flow = flowOf(false) - /** Proposes that the confederation sign its charter: its groups, under its name. The attempt's id. */ - suspend fun proposeCharter(confederationId: HexKey): String = throw UnsupportedOperationException("No confederation here") + /** + * Proposes, in [localChatRoom], that its group propose the confederation's charter: its groups + * and threshold, under its name (docs/confederation-proposals.md). The group's signing session. + */ + suspend fun proposeCharter(localChatRoom: LocalChatRoom, userPublicKey: HexKey, confederationId: HexKey): FrostSigningSession = + throw UnsupportedOperationException("No confederation here") /** - * Why [userPublicKey] cannot put a change to [confederationId]'s profile to the group of - * [chatRoomId], or null when they can (D2). + * Why [userPublicKey] cannot put a proposal for [confederationId] -- a profile, a post, its + * charter -- to the group of [chatRoomId], or null when they can (D2). */ - suspend fun profileChangeProblem(chatRoomId: String, userPublicKey: HexKey, confederationId: HexKey): ProfileChangeProblem? = - ProfileChangeProblem.NoRecord + suspend fun changeProblem(chatRoomId: String, userPublicKey: HexKey, confederationId: HexKey): ChangeProblem? = + ChangeProblem.NoRecord /** The member groups of [confederationId] this device is in whose statements [userPublicKey] can put to them. */ suspend fun proposingGroupsFor(userPublicKey: HexKey, confederationId: HexKey): List = emptyList() - /** What the change edits, read where this device holds it: the base, else the newest profile held. */ + /** What a proposed profile edits, read where this device holds it: the base, else the newest profile held. */ suspend fun profileBaseOf(changeId: HexKey): UserMetadata? = null suspend fun proposeProfileChange( @@ -178,18 +169,18 @@ interface ConfederationRepository { content: String, ): FrostSigningSession = throw UnsupportedOperationException("No confederation here") - suspend fun proposeProfileEndorsement(localChatRoom: LocalChatRoom, userPublicKey: HexKey, changeId: HexKey): FrostSigningSession = + suspend fun proposeEndorsement(localChatRoom: LocalChatRoom, userPublicKey: HexKey, changeId: HexKey): FrostSigningSession = throw UnsupportedOperationException("No confederation here") /** An objection; from the group that proposed the change, its withdrawal. */ - suspend fun proposeProfileObjection(localChatRoom: LocalChatRoom, userPublicKey: HexKey, changeId: HexKey, reason: String): FrostSigningSession = + suspend fun proposeObjection(localChatRoom: LocalChatRoom, userPublicKey: HexKey, changeId: HexKey, reason: String): FrostSigningSession = throw UnsupportedOperationException("No confederation here") - /** A session in [chatRoomId]'s group over an answer to [changeId] that has not finished, if any: one at a time. */ - fun observePendingProfileAnswer(chatRoomId: String, changeId: HexKey): Flow = flowOf(null) + /** A session in [chatRoomId]'s group over an answer to proposal [changeId] that has not finished, if any: one at a time. */ + fun observePendingChangeAnswer(chatRoomId: String, changeId: HexKey): Flow = flowOf(null) - /** A session in [chatRoomId]'s group proposing a change to [confederationId]'s profile that has not finished, if any. */ - fun observePendingProfileChange(chatRoomId: String, confederationId: HexKey): Flow = flowOf(null) + /** A session in [chatRoomId]'s group proposing something for [confederationId] to sign that has not finished, if any. */ + fun observePendingChange(chatRoomId: String, confederationId: HexKey): Flow = flowOf(null) companion object { /** Holds nothing and proposes nothing: for screens and tests with no confederation behind them. */ @@ -228,32 +219,27 @@ interface ConfederationRepository { override suspend fun joinablePlan(proposalId: HexKey): ConfederationRosterBuilder.Plan? = null 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 } } } -/** Why a member cannot put a change to a confederation's profile to their group (docs/confederation-profile.md, D2). */ -sealed interface ProfileChangeProblem { +/** Why a member cannot put a proposal for a confederation to their group (docs/confederation-profile.md, D2). */ +sealed interface ChangeProblem { /** This device knows neither the confederation's record nor its charter. */ - data object NoRecord : ProfileChangeProblem + data object NoRecord : ChangeProblem /** This group is not one of the confederation's. */ - data object NotMember : ProfileChangeProblem + data object NotMember : ChangeProblem /** The room is closed, or this device holds no share of the group's key. */ - data object CannotSign : ProfileChangeProblem + data object CannotSign : ChangeProblem /** The member is not one of the group's admins. */ - data object NotAdmin : ProfileChangeProblem + data object NotAdmin : ChangeProblem /** This device does not hold the inbox key the group has announced. */ - data object NoInbox : ProfileChangeProblem + data object NoInbox : ChangeProblem /** Another member group has announced no inbox, so it cannot be asked. */ - data class GroupWithoutInbox(val name: String) : ProfileChangeProblem + data class GroupWithoutInbox(val name: String) : ChangeProblem } 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 d6187d5c..eea602db 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt @@ -173,11 +173,12 @@ object ProposedEvent { ConfederationKinds.WITHDRAWAL -> Summary(label = "Withdrawing a confederation proposal", detail = event.content) - // What makes a group's change to its confederation's profile, or its endorsement of - // one, something the confederation can act on (docs/confederation-profile.md, D5). + // What makes a group's proposal for its confederation to sign something -- a profile, a + // post, its charter -- or its endorsement of one, something the confederation can act on + // (docs/confederation-profile.md, D5; docs/confederation-proposals.md). ConfederationKinds.VOUCHER -> Summary( - label = "Endorsing a new profile for a confederation", - detail = "Lets the confederation's admins sign it once enough groups endorse it", + label = "Endorsing a proposal for a confederation to sign", + detail = "Lets the confederation sign it once enough groups endorse it", ) // A Bennu wallet's: declined on arrival, and said as what it is rather than 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 1ec3defd..ef5ce8e6 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,7 +41,6 @@ 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 @@ -160,19 +159,15 @@ fun AddGroupPostScreen( // when a quorum signs -- so landing // on the list it is not in would // read as a failure. + // A confederation's post is the group's + // proposal first, so it is the group's + // session either way. onNavigateToRouteAndPopUpInclusive.invoke( - if (addGroupPostViewModel.isConfederation) { - ConfederationSigningRoute( - activeUserPublicKey = activeUserPublicKey, - attemptId = sessionId - ) - } else { - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - } + 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 f122666f..2c3e6eb2 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 @@ -54,7 +54,6 @@ import mobi.giza.compose.resources.open_the_confederation 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.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 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 ce1816ab..73542e25 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 @@ -53,8 +53,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.ConfederationProfileChangeRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationChangeRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRoute import mobi.giza.compose.ui.composable.navigation.routes.ChatRoomDetailRoute import mobi.giza.compose.ui.composable.navigation.routes.DkgRitualRoute @@ -247,14 +246,9 @@ fun ChatRoomMessagingScreen( ) ) }, - onOpenConfederationSigning = { attemptId -> + onOpenConfederationChange = { changeId -> onNavigateToRoute.invoke( - ConfederationSigningRoute(activeUserPublicKey = activeUserPublicKey, attemptId = attemptId) - ) - }, - onOpenConfederationProfileChange = { changeId -> - onNavigateToRoute.invoke( - ConfederationProfileChangeRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, changeId = changeId) + ConfederationChangeRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, changeId = changeId) ) }, onOpenConfederation = { confederationId -> diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileChangeScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationChangeScreen.kt similarity index 76% rename from composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileChangeScreen.kt rename to composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationChangeScreen.kt index 491ce713..6d6b0d4e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileChangeScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationChangeScreen.kt @@ -39,8 +39,8 @@ import androidx.lifecycle.viewmodel.compose.viewModel import com.vitorpamplona.quartz.nip01Core.core.HexKey import kotlin.time.Instant import mobi.giza.compose.extensions.toFormattedTimeAndDateString -import mobi.giza.compose.nostr.confederation.ConfederationProfileAnswer -import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState +import mobi.giza.compose.nostr.confederation.ConfederationChangeAnswer +import mobi.giza.compose.nostr.confederation.ConfederationChangeState import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.ConfederationRepository import mobi.giza.compose.resources.Res @@ -63,15 +63,19 @@ import mobi.giza.compose.resources.object_to_the_change import mobi.giza.compose.resources.open_the_signing_session import mobi.giza.compose.resources.open_until import mobi.giza.compose.resources.picture_url -import mobi.giza.compose.resources.profile_change +import mobi.giza.compose.resources.proposal +import mobi.giza.compose.resources.proposal_overline +import mobi.giza.compose.resources.proposal_charter_explained +import mobi.giza.compose.resources.what_it_would_sign +import mobi.giza.compose.nostr.confederation.ConfederationKinds import mobi.giza.compose.resources.profile_field_becomes import mobi.giza.compose.resources.profile_field_empty import mobi.giza.compose.resources.profile_field_was import mobi.giza.compose.resources.reason_optional -import mobi.giza.compose.resources.this_device_does_not_hold_that_change +import mobi.giza.compose.resources.this_device_does_not_hold_that_proposal import mobi.giza.compose.resources.waiting_for_the_group_to_sign_its_answer import mobi.giza.compose.resources.website -import mobi.giza.compose.resources.withdraw_the_change +import mobi.giza.compose.resources.withdraw_the_proposal 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 @@ -85,31 +89,32 @@ import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition import mobi.giza.compose.ui.composable.widgets.rememberNotifier import mobi.giza.compose.ui.theme.readableContent import mobi.giza.compose.ui.theme.spacing -import mobi.giza.compose.ui.view.model.ConfederationProfileChangeViewModel -import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState -import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState.FieldName +import mobi.giza.compose.ui.view.model.ConfederationChangeViewModel +import mobi.giza.compose.ui.view.state.ConfederationChangeUIState +import mobi.giza.compose.ui.view.state.ConfederationChangeUIState.FieldName import org.jetbrains.compose.resources.stringResource /** - * One proposed change to a confederation's profile, seen from one of its groups - * (docs/confederation-profile.md, D3): what it would change, field by field, how every group has - * answered, and this group's answer. Answering is a group signature, so each button opens a signing - * session and the screen goes to it. + * One proposal for a confederation to sign something, seen from one of its groups + * (docs/confederation-profile.md, D3; docs/confederation-proposals.md): what it would sign -- a + * profile field by field, a post's words, the charter -- how every group has answered, and this + * group's answer. Answering is a group signature, so each button opens a signing session and the + * screen goes to it. */ @OptIn(ExperimentalMaterial3Api::class) @Composable -fun ConfederationProfileChangeScreen( +fun ConfederationChangeScreen( activeUserPublicKey: HexKey, chatRoomId: String, changeId: HexKey, - initialUIState: ConfederationProfileChangeUIState = ConfederationProfileChangeUIState.Loading, + initialUIState: ConfederationChangeUIState = ConfederationChangeUIState.Loading, chatRepository: ChatRepository, confederationRepository: ConfederationRepository, onNavigateToRoute: (Route) -> Unit, onNavigateBack: () -> Unit, ) { - val viewModel: ConfederationProfileChangeViewModel = viewModel( - factory = ConfederationProfileChangeViewModel.factory( + val viewModel: ConfederationChangeViewModel = viewModel( + factory = ConfederationChangeViewModel.factory( activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, changeId = changeId, @@ -119,7 +124,7 @@ fun ConfederationProfileChangeScreen( ) ) LaunchedEffect(true) { - if (initialUIState == ConfederationProfileChangeUIState.Loading) viewModel.initiate() + if (initialUIState == ConfederationChangeUIState.Loading) viewModel.initiate() } val notify = rememberNotifier(rememberCoroutineScope()) @@ -136,23 +141,23 @@ fun ConfederationProfileChangeScreen( modifier = Modifier.imePadding(), topBar = { TopAppBar( - title = { Text(text = stringResource(Res.string.profile_change), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + title = { Text(text = stringResource(Res.string.proposal), maxLines = 1, overflow = TextOverflow.Ellipsis) }, navigationIcon = { NavigateBackButton(onNavigateBack) }, ) }, ) { padding -> ScreenStateTransition(state) { uiState -> when (val current = uiState) { - is ConfederationProfileChangeUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = current.message, onRetry = null) + is ConfederationChangeUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = current.message, onRetry = null) - ConfederationProfileChangeUIState.Loading -> LoadingDataIndicator(modifier = Modifier.padding(padding)) + ConfederationChangeUIState.Loading -> LoadingDataIndicator(modifier = Modifier.padding(padding)) - ConfederationProfileChangeUIState.NotHeld -> EmptyState( + ConfederationChangeUIState.NotHeld -> EmptyState( modifier = Modifier.padding(padding), - message = stringResource(Res.string.this_device_does_not_hold_that_change), + message = stringResource(Res.string.this_device_does_not_hold_that_proposal), ) - is ConfederationProfileChangeUIState.Loaded -> Column( + is ConfederationChangeUIState.Loaded -> Column( modifier = Modifier.padding(padding).readableContent().fillMaxSize() .verticalScroll(rememberScrollState()) .padding(MaterialTheme.spacing.screenMargin), @@ -162,7 +167,10 @@ fun ConfederationProfileChangeScreen( val nameOf = { key: HexKey -> current.names[key] ?: key.take(12) } Text(text = current.confederationName, style = MaterialTheme.typography.headlineSmall) - Text(text = changeStateLabel(current.status.state), style = MaterialTheme.typography.labelLarge) + Text( + text = stringResource(Res.string.proposal_overline, proposalKindLabel(change.kind), changeStateLabel(current.status)), + style = MaterialTheme.typography.labelLarge, + ) Text(text = stringResource(Res.string.confederation_proposed_by, nameOf(change.proposingGroup))) Text(text = stringResource(Res.string.n_of_m_endorsements, current.status.endorsers.size, change.threshold)) Text( @@ -171,10 +179,21 @@ fun ConfederationProfileChangeScreen( color = MaterialTheme.colorScheme.onSurfaceVariant, ) - // What it would change. + // What it would sign: a profile as a difference from the one it edits, anything + // else as itself. HorizontalDivider() - if (current.differences.isEmpty()) { - Text(stringResource(Res.string.no_field_changes)) + Text(text = stringResource(Res.string.what_it_would_sign), style = MaterialTheme.typography.titleSmall) + when { + change.isProfile && current.differences.isEmpty() -> Text(stringResource(Res.string.no_field_changes)) + change.kind == ConfederationKinds.CHARTER -> ListItem( + leadingContent = { Icon(proposalIcon(change.kind), contentDescription = Decorative) }, + headlineContent = { Text(proposalHeadline(change)) }, + supportingContent = { Text(stringResource(Res.string.proposal_charter_explained)) }, + ) + !change.isProfile -> ListItem( + leadingContent = { Icon(proposalIcon(change.kind), contentDescription = Decorative) }, + headlineContent = { Text(change.event.content) }, + ) } current.differences.forEach { field -> val empty = stringResource(Res.string.profile_field_empty) @@ -203,9 +222,9 @@ fun ConfederationProfileChangeScreen( leadingContent = { Icon( imageVector = when (answer) { - ConfederationProfileAnswer.PROPOSED, ConfederationProfileAnswer.ENDORSED -> Icons.Default.CheckCircle - ConfederationProfileAnswer.OBJECTED -> Icons.Default.Block - ConfederationProfileAnswer.WAITING -> Icons.Default.HourglassEmpty + ConfederationChangeAnswer.PROPOSED, ConfederationChangeAnswer.ENDORSED -> Icons.Default.CheckCircle + ConfederationChangeAnswer.OBJECTED -> Icons.Default.Block + ConfederationChangeAnswer.WAITING -> Icons.Default.HourglassEmpty }, contentDescription = Decorative, ) @@ -215,10 +234,10 @@ fun ConfederationProfileChangeScreen( Text( stringResource( when (answer) { - ConfederationProfileAnswer.PROPOSED -> Res.string.answer_proposed - ConfederationProfileAnswer.ENDORSED -> Res.string.answer_endorsed - ConfederationProfileAnswer.OBJECTED -> Res.string.answer_objected - ConfederationProfileAnswer.WAITING -> Res.string.answer_waiting + ConfederationChangeAnswer.PROPOSED -> Res.string.answer_proposed + ConfederationChangeAnswer.ENDORSED -> Res.string.answer_endorsed + ConfederationChangeAnswer.OBJECTED -> Res.string.answer_objected + ConfederationChangeAnswer.WAITING -> Res.string.answer_waiting } ) + (current.status.answers[group]?.reason?.takeIf { it.isNotBlank() }?.let { ": $it" } ?: "") ) @@ -227,7 +246,7 @@ fun ConfederationProfileChangeScreen( } // Once enough groups have endorsed it: who the signing is still waiting on. - if (current.status.state == ConfederationProfileChangeState.ENDORSED) { + if (current.status.state == ConfederationChangeState.ENDORSED) { val unvouched = current.status.endorsers.filter { it !in current.status.vouchers.keys } if (unvouched.isNotEmpty()) { Text( @@ -275,7 +294,7 @@ fun ConfederationProfileChangeScreen( modifier = Modifier.fillMaxWidth(), enabled = !current.isActing, onClick = { viewModel.objectTo("", onSuccess = toSession, onFailure = { notify(couldNotAnswer) }) }, - ) { Text(stringResource(Res.string.withdraw_the_change)) } + ) { Text(stringResource(Res.string.withdraw_the_proposal)) } } } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationScreen.kt index e45394a1..fb87b444 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationScreen.kt @@ -34,11 +34,11 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import mobi.giza.compose.extensions.toFormattedTimeAndDateString import mobi.giza.compose.extensions.toNpub -import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState -import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus +import mobi.giza.compose.nostr.confederation.ConfederationChangeState +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatus import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.ConfederationRepository -import mobi.giza.compose.repository.ProfileChangeProblem +import mobi.giza.compose.repository.ChangeProblem import mobi.giza.compose.resources.Res import mobi.giza.compose.resources.change_declined import mobi.giza.compose.resources.change_endorsed @@ -57,10 +57,7 @@ import mobi.giza.compose.resources.how_it_was_formed import mobi.giza.compose.resources.n_admins_hold_its_key import mobi.giza.compose.resources.n_of_m_endorsements import mobi.giza.compose.resources.no_name_on_this_profile -import mobi.giza.compose.resources.no_profile_changes_yet -import mobi.giza.compose.resources.only_admins_see_profile_changes import mobi.giza.compose.resources.open_the_signing_session -import mobi.giza.compose.resources.profile_changes import mobi.giza.compose.resources.profile_problem_cannot_sign import mobi.giza.compose.resources.profile_problem_group_without_inbox import mobi.giza.compose.resources.profile_problem_no_inbox @@ -69,7 +66,7 @@ import mobi.giza.compose.resources.profile_problem_not_admin import mobi.giza.compose.resources.profile_problem_not_member import mobi.giza.compose.resources.this_device_knows_nothing_of_that_confederation import mobi.giza.compose.resources.waiting_for_the_group_to_sign_its_answer -import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProfileChangeRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationChangeRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProposalRoute import mobi.giza.compose.ui.composable.navigation.routes.EditConfederationProfileRoute import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute @@ -87,20 +84,11 @@ import mobi.giza.compose.ui.theme.readableContent import mobi.giza.compose.ui.theme.spacing import mobi.giza.compose.ui.view.model.ConfederationViewModel import mobi.giza.compose.ui.view.state.ConfederationUIState -import mobi.giza.compose.database.model.ConfederationSigningStage -import mobi.giza.compose.text.ProposedEvent import mobi.giza.compose.nostr.GroupPost import androidx.compose.runtime.rememberCoroutineScope import mobi.giza.compose.ui.composable.widgets.rememberNotifier -import mobi.giza.compose.ui.composable.navigation.routes.ConfederationSigningRoute import mobi.giza.compose.ui.composable.navigation.routes.AddGroupPostRoute import mobi.giza.compose.resources.could_not_propose_the_charter -import mobi.giza.compose.resources.signing_failed -import mobi.giza.compose.resources.signing_complete -import mobi.giza.compose.resources.signing_in_progress -import mobi.giza.compose.resources.waiting_for_your_answer -import mobi.giza.compose.resources.nothing_is_being_signed -import mobi.giza.compose.resources.confederation_signing_attempts import mobi.giza.compose.resources.propose_the_charter import mobi.giza.compose.resources.the_charter_names_the_groups import mobi.giza.compose.resources.confederation_charter_none @@ -109,15 +97,38 @@ import mobi.giza.compose.resources.confederation_charter import mobi.giza.compose.resources.confederation_has_posted_nothing import mobi.giza.compose.resources.add_post import mobi.giza.compose.resources.posts +import mobi.giza.compose.resources.proposals +import mobi.giza.compose.resources.only_admins_see_proposals +import mobi.giza.compose.resources.no_proposals_yet +import mobi.giza.compose.resources.confederation_charter_proposed +import mobi.giza.compose.resources.change_posted +import mobi.giza.compose.resources.change_superseded_charter +import mobi.giza.compose.resources.proposal_kind_profile +import mobi.giza.compose.resources.proposal_kind_post +import mobi.giza.compose.resources.proposal_kind_charter +import mobi.giza.compose.resources.proposal_charter_headline +import mobi.giza.compose.resources.proposal_overline +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatements +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import androidx.compose.material.icons.filled.AccountCircle +import androidx.compose.ui.graphics.vector.ImageVector import org.jetbrains.compose.resources.stringResource /** - * A formed confederation, seen from one of its member groups (docs/confederation-profile.md, D1): - * its profile, the groups it is made of, and the changes to its profile, with the way to propose one. + * A formed confederation, seen from one of its member groups (docs/confederation-profile.md, D1; + * docs/confederation-proposals.md): its profile, the groups it is made of, the proposals for it to + * sign something, its posts and its charter. + * + * Whatever the confederation signs -- a new profile, a post, its charter -- goes one way: an admin + * proposes it from their group, the group's quorum signs the proposal to every member group, the + * others endorse or object by theirs, and the confederation signs once enough have endorsed. So every + * way to propose here is open to the same people, and leads to the group's signing session. * * Every member of a member group can open it. Members who are not admins hold none of the groups' - * statements, so for them it shows what is public -- the charter's groups and the signed profile -- - * and says why the changes are missing rather than showing none. + * statements, so for them it shows what is public -- the charter's groups, the signed profile and + * posts -- and says why the proposals are missing rather than showing none. */ @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -149,6 +160,7 @@ fun ConfederationScreen( // Read out here: both are composable and an onClick lambda is not. val notify = rememberNotifier(rememberCoroutineScope()) val couldNotProposeCharter = stringResource(Res.string.could_not_propose_the_charter) + val toSession: (String) -> Unit = { sessionId -> onNavigateToRoute(FrostSigningRoute(activeUserPublicKey, chatRoomId, sessionId)) } Scaffold( snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, @@ -180,12 +192,6 @@ fun ConfederationScreen( Text(text = stringResource(Res.string.confederation_profile), style = MaterialTheme.typography.titleSmall) ConfederationProfileCard(current) - current.pendingSessionId?.let { sessionId -> - Text(text = stringResource(Res.string.waiting_for_the_group_to_sign_its_answer)) - TextButton(onClick = { onNavigateToRoute(FrostSigningRoute(activeUserPublicKey, chatRoomId, sessionId)) }) { - Text(stringResource(Res.string.open_the_signing_session)) - } - } if (current.readsChanges) { Button( modifier = Modifier.fillMaxWidth(), @@ -233,29 +239,35 @@ fun ConfederationScreen( ) } - // The changes to its profile: only the groups' admins hold them. + // What it has been asked to sign, of every kind: only the groups' admins hold them. HorizontalDivider() - Text(text = stringResource(Res.string.profile_changes), style = MaterialTheme.typography.titleSmall) + Text(text = stringResource(Res.string.proposals), style = MaterialTheme.typography.titleSmall) + // A proposal this group is signing now, of whatever kind: one at a time. + current.pendingSessionId?.let { sessionId -> + Text(text = stringResource(Res.string.waiting_for_the_group_to_sign_its_answer)) + TextButton(onClick = { toSession(sessionId) }) { + Text(stringResource(Res.string.open_the_signing_session)) + } + } when { - !current.readsChanges -> EmptyState(message = stringResource(Res.string.only_admins_see_profile_changes)) - current.changes.isEmpty() -> EmptyState(message = stringResource(Res.string.no_profile_changes_yet)) + !current.readsChanges -> EmptyState(message = stringResource(Res.string.only_admins_see_proposals)) + current.changes.isEmpty() -> EmptyState(message = stringResource(Res.string.no_proposals_yet)) else -> current.changes.forEach { change -> - ProfileChangeCard( + ProposalCard( status = change, proposer = current.names[change.change.proposingGroup] ?: change.change.proposingGroup.take(12), - onClick = { onNavigateToRoute(ConfederationProfileChangeRoute(activeUserPublicKey, chatRoomId, change.change.id)) }, + onClick = { onNavigateToRoute(ConfederationChangeRoute(activeUserPublicKey, chatRoomId, change.change.id)) }, ) } } - // Its posts, and the way to propose one for a member who holds a seat - // (docs/confederation-room-removal.md, D9). + // Its posts, and the way to propose one: a proposal from this group like any other. HorizontalDivider() Text(text = stringResource(Res.string.posts), style = MaterialTheme.typography.titleSmall) - if (current.holdsSeat) { + if (current.readsChanges) { Button( modifier = Modifier.fillMaxWidth(), - enabled = identityCanSign, + enabled = current.canEdit && identityCanSign, onClick = { onNavigateToRoute(AddGroupPostRoute(activeUserPublicKey, chatRoomId, relayHint = null, confederationId = confederationId)) }, ) { Icon(Icons.Default.Edit, contentDescription = Decorative) @@ -268,25 +280,21 @@ fun ConfederationScreen( current.posts.forEach { post -> ConfederationPostCard(post) } } - // Its charter: the public statement of the groups it is made of. + // Its charter: the public statement of the groups it is made of, proposed like the rest. HorizontalDivider() Text(text = stringResource(Res.string.confederation_charter), style = MaterialTheme.typography.titleSmall) when { current.charterSigned -> Text(stringResource(Res.string.confederation_charter_signed)) - current.holdsSeat -> { + current.charterProposed -> Text(stringResource(Res.string.confederation_charter_proposed)) + current.readsChanges -> { Text( text = stringResource(Res.string.the_charter_names_the_groups), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) TextButton( - enabled = identityCanSign, - onClick = { - viewModel.proposeCharter( - onSuccess = { attemptId -> onNavigateToRoute(ConfederationSigningRoute(activeUserPublicKey = activeUserPublicKey, attemptId = attemptId)) }, - onFailure = { notify(couldNotProposeCharter) }, - ) - }, + enabled = current.canEdit && identityCanSign, + onClick = { viewModel.proposeCharter(onSuccess = toSession, onFailure = { notify(couldNotProposeCharter) }) }, ) { Text(stringResource(Res.string.propose_the_charter)) } @@ -294,22 +302,6 @@ fun ConfederationScreen( else -> Text(stringResource(Res.string.confederation_charter_none)) } - // What it is signing, and what it asked this person: a seat's work. - if (current.holdsSeat) { - HorizontalDivider() - Text(text = stringResource(Res.string.confederation_signing_attempts), style = MaterialTheme.typography.titleSmall) - if (current.attempts.isEmpty()) { - EmptyState(message = stringResource(Res.string.nothing_is_being_signed)) - } else { - current.attempts.forEach { attempt -> - SigningAttemptCard( - attempt = attempt, - onClick = { onNavigateToRoute(ConfederationSigningRoute(activeUserPublicKey = activeUserPublicKey, attemptId = attempt.id)) }, - ) - } - } - } - HorizontalDivider() current.formingProposalId?.let { proposalId -> TextButton(onClick = { onNavigateToRoute(ConfederationProposalRoute(activeUserPublicKey, chatRoomId, proposalId)) }) { @@ -338,30 +330,6 @@ private fun ConfederationPostCard(post: GroupPost) { } } -@Composable -private fun SigningAttemptCard(attempt: ConfederationUIState.Attempt, onClick: () -> Unit) { - val summary = attempt.event?.let { ProposedEvent.summarize(it) } - Card(modifier = Modifier.fillMaxWidth(), onClick = onClick) { - ListItem( - overlineContent = { - Text( - stringResource( - when { - attempt.stage == ConfederationSigningStage.COMPLETE -> Res.string.signing_complete - attempt.stage == ConfederationSigningStage.FAILED -> Res.string.signing_failed - attempt.awaitingYou -> Res.string.waiting_for_your_answer - else -> Res.string.signing_in_progress - } - ) - ) - }, - headlineContent = { Text(text = summary?.label.orEmpty(), maxLines = 1, overflow = TextOverflow.Ellipsis) }, - supportingContent = summary?.detail?.let { detail -> { Text(text = detail, maxLines = 2, overflow = TextOverflow.Ellipsis) } }, - trailingContent = { Icon(Icons.Default.ChevronRight, contentDescription = Decorative) }, - ) - } -} - @Composable private fun ConfederationProfileCard(state: ConfederationUIState.Loaded) { val profile = state.profile @@ -397,13 +365,14 @@ private fun ConfederationProfileCard(state: ConfederationUIState.Loaded) { } } +/** One proposal: what it would have the confederation sign, where it stands, who proposed it and how far it has got. */ @Composable -private fun ProfileChangeCard(status: ConfederationProfileChangeStatus, proposer: String, onClick: () -> Unit) { - val name = mobi.giza.compose.managers.ConfederationProfileRefusal.metadataOf(status.change.profile)?.anyName()?.takeIf { it.isNotBlank() } +private fun ProposalCard(status: ConfederationChangeStatus, proposer: String, onClick: () -> Unit) { Card(modifier = Modifier.fillMaxWidth(), onClick = onClick) { ListItem( - headlineContent = { Text(text = name ?: stringResource(Res.string.no_name_on_this_profile), maxLines = 1, overflow = TextOverflow.Ellipsis) }, - overlineContent = { Text(changeStateLabel(status.state)) }, + leadingContent = { Icon(proposalIcon(status.change.kind), contentDescription = Decorative) }, + headlineContent = { Text(text = proposalHeadline(status.change), maxLines = 2, overflow = TextOverflow.Ellipsis) }, + overlineContent = { Text(stringResource(Res.string.proposal_overline, proposalKindLabel(status.change.kind), changeStateLabel(status))) }, supportingContent = { Column { Text(stringResource(Res.string.confederation_proposed_by, proposer)) @@ -425,24 +394,50 @@ private fun ProfileChangeCard(status: ConfederationProfileChangeStatus, proposer } @Composable -internal fun changeStateLabel(state: ConfederationProfileChangeState): String = stringResource( - when (state) { - ConfederationProfileChangeState.OPEN -> Res.string.change_open - ConfederationProfileChangeState.ENDORSED -> Res.string.change_endorsed - ConfederationProfileChangeState.PUBLISHED -> Res.string.change_published - ConfederationProfileChangeState.SUPERSEDED -> Res.string.change_superseded - ConfederationProfileChangeState.DECLINED -> Res.string.change_declined - ConfederationProfileChangeState.WITHDRAWN -> Res.string.change_withdrawn - ConfederationProfileChangeState.EXPIRED -> Res.string.change_expired +internal fun changeStateLabel(status: ConfederationChangeStatus): String = stringResource( + when (status.state) { + ConfederationChangeState.OPEN -> Res.string.change_open + ConfederationChangeState.ENDORSED -> Res.string.change_endorsed + ConfederationChangeState.PUBLISHED -> if (status.change.kind == TextNoteEvent.KIND) Res.string.change_posted else Res.string.change_published + ConfederationChangeState.SUPERSEDED -> + if (status.change.kind == ConfederationKinds.CHARTER) Res.string.change_superseded_charter else Res.string.change_superseded + ConfederationChangeState.DECLINED -> Res.string.change_declined + ConfederationChangeState.WITHDRAWN -> Res.string.change_withdrawn + ConfederationChangeState.EXPIRED -> Res.string.change_expired } ) +/** What kind of thing a proposal would have the confederation sign. */ @Composable -internal fun problemText(problem: ProfileChangeProblem): String = when (problem) { - ProfileChangeProblem.NoRecord -> stringResource(Res.string.profile_problem_no_record) - ProfileChangeProblem.NotMember -> stringResource(Res.string.profile_problem_not_member) - ProfileChangeProblem.CannotSign -> stringResource(Res.string.profile_problem_cannot_sign) - ProfileChangeProblem.NotAdmin -> stringResource(Res.string.profile_problem_not_admin) - ProfileChangeProblem.NoInbox -> stringResource(Res.string.profile_problem_no_inbox) - is ProfileChangeProblem.GroupWithoutInbox -> stringResource(Res.string.profile_problem_group_without_inbox, problem.name) +internal fun proposalKindLabel(kind: Int): String = stringResource( + when (kind) { + MetadataEvent.KIND -> Res.string.proposal_kind_profile + ConfederationKinds.CHARTER -> Res.string.proposal_kind_charter + else -> Res.string.proposal_kind_post + } +) + +internal fun proposalIcon(kind: Int): ImageVector = when (kind) { + MetadataEvent.KIND -> Icons.Default.AccountCircle + ConfederationKinds.CHARTER -> Icons.Default.Groups + else -> Icons.Default.Edit +} + +/** A proposal in a line: a profile by the name it would give, a post by its words, the charter as itself. */ +@Composable +internal fun proposalHeadline(change: ConfederationChangeStatements.Change): String = when (change.kind) { + MetadataEvent.KIND -> mobi.giza.compose.managers.ConfederationChangeRefusal.metadataOf(change.event)?.anyName()?.takeIf { it.isNotBlank() } + ?: stringResource(Res.string.no_name_on_this_profile) + ConfederationKinds.CHARTER -> stringResource(Res.string.proposal_charter_headline) + else -> change.event.content +} + +@Composable +internal fun problemText(problem: ChangeProblem): String = when (problem) { + ChangeProblem.NoRecord -> stringResource(Res.string.profile_problem_no_record) + ChangeProblem.NotMember -> stringResource(Res.string.profile_problem_not_member) + ChangeProblem.CannotSign -> stringResource(Res.string.profile_problem_cannot_sign) + ChangeProblem.NotAdmin -> stringResource(Res.string.profile_problem_not_admin) + ChangeProblem.NoInbox -> stringResource(Res.string.profile_problem_no_inbox) + is ChangeProblem.GroupWithoutInbox -> stringResource(Res.string.profile_problem_group_without_inbox, problem.name) } 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 deleted file mode 100644 index d35e1fc6..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationSigningScreen.kt +++ /dev/null @@ -1,190 +0,0 @@ -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 com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -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_approved_for -import mobi.giza.compose.resources.answer_declined_for -import mobi.giza.compose.resources.answer_no -import mobi.giza.compose.resources.answer_not_yet_endorsed_by -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.ConfederationSigningAnswer -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() - val isProfile = current.event.kind == MetadataEvent.KIND - current.answers.forEach { answer -> AnswerItem(answer, isProfile) } - } - } - } - } -} - -/** - * One role holder's answer. Somebody seated in several groups answers for each, so a yes for one - * group and a no for another is said group by group, not folded into either. On a profile the no - * is no one's refusal: the seat's group had not endorsed it when the signing began. - */ -@Composable -private fun AnswerItem(answer: ConfederationSigningAnswer, isProfile: Boolean) { - val approved = answer.approvedFor.isNotEmpty() - val declined = answer.declinedFor.isNotEmpty() - ListItem( - leadingContent = { - Icon( - imageVector = when { - !answer.hasSaid -> Icons.Default.HourglassEmpty - approved -> Icons.Default.CheckCircle - else -> Icons.Default.Block - }, - contentDescription = Decorative, - ) - }, - headlineContent = { Text(answer.name, maxLines = 1, overflow = TextOverflow.Ellipsis) }, - supportingContent = { - when { - !answer.hasSaid -> Text(stringResource(Res.string.answer_waiting)) - !declined -> Text(stringResource(Res.string.answer_yes)) - !approved && !isProfile -> Text(stringResource(Res.string.answer_no)) - else -> Column { - if (approved) Text(stringResource(Res.string.answer_approved_for, answer.approvedFor.joinToString())) - Text( - stringResource( - if (isProfile) Res.string.answer_not_yet_endorsed_by else Res.string.answer_declined_for, - answer.declinedFor.joinToString(), - ) - ) - } - } - }, - ) -} 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 109b8fd1..c3291e2f 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 @@ -12,13 +12,11 @@ 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.ConfederationRoute import mobi.giza.compose.ui.composable.navigation.routes.EditConfederationProfileRoute -import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProfileChangeRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationChangeRoute import mobi.giza.compose.ui.composable.ConfederationScreen import mobi.giza.compose.ui.composable.EditConfederationProfileScreen -import mobi.giza.compose.ui.composable.ConfederationProfileChangeScreen +import mobi.giza.compose.ui.composable.ConfederationChangeScreen 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 @@ -1401,10 +1399,10 @@ fun GizaNavHost( onNavigateBack = { navController.popBackStack() } ) } - composable { backStackEntry -> - val route = backStackEntry.toRoute() + composable { backStackEntry -> + val route = backStackEntry.toRoute() - ConfederationProfileChangeScreen( + ConfederationChangeScreen( activeUserPublicKey = route.activeUserPublicKey, chatRoomId = route.chatRoomId, changeId = route.changeId, @@ -1414,15 +1412,6 @@ 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/ConfederationRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationRoute.kt index 38e6766e..005eb5c4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationRoute.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationRoute.kt @@ -24,7 +24,7 @@ data class EditConfederationProfileRoute( /** One proposed change to a confederation's profile, and this group's answer to it (D3). */ @Serializable -data class ConfederationProfileChangeRoute( +data class ConfederationChangeRoute( val activeUserPublicKey: String, val chatRoomId: String, val changeId: String, 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 deleted file mode 100644 index 82b3c028..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationSigningRoute.kt +++ /dev/null @@ -1,10 +0,0 @@ -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 46d21e4c..092d8d39 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 @@ -127,9 +127,9 @@ fun ChatTranscript( */ onOpenSigning: (sessionId: String?) -> Unit, /** Opens a confederation's request to sign: docs/confederation.md, Phase 15. */ - onOpenConfederationSigning: (attemptId: String) -> Unit = {}, /** Opens a change to a confederation's profile: docs/confederation-profile.md, D8. */ - onOpenConfederationProfileChange: (changeId: String) -> Unit = {}, + /** A confederation's proposal, by its id, or by the id of an attempt at signing it. */ + onOpenConfederationChange: (changeId: String) -> Unit = {}, /** Opens a confederation, from the line saying it has a new profile. */ onOpenConfederation: (confederationId: String) -> Unit = {}, /** Opens the room's proposals, all of them, whatever their state. */ @@ -384,25 +384,27 @@ 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. + // The confederation signing what its groups endorsed: it opens the + // proposal, which says where the signing stands. Nobody is asked + // here; an ask from before that was so opens the same way. + // docs/confederation-proposals.md. if (localChatMessage.chatMessage.messageType == ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED || localChatMessage.chatMessage.messageType == ChatMessage.TYPE_CONFEDERATION_SIGNING_ASKED ) { RitualNotice( localChatMessage = localChatMessage, - isAnswered = false, + isAnswered = true, isSettled = true, onClick = { - localChatMessage.chatMessage.frostSigningSessionId?.let(onOpenConfederationSigning) + localChatMessage.chatMessage.frostSigningSessionId?.let(onOpenConfederationChange) }, opens = null, ) return@items } - // A change to a confederation's profile, or the profile it ended in: - // each opens what it is about. docs/confederation-profile.md, D8. + // A proposal for a confederation to sign something, or the profile it + // ended in: each opens what it is about. docs/confederation-profile.md, D8. if (localChatMessage.chatMessage.messageType in ChatMessage.CONFEDERATION_PROFILE_TYPES) { val target = localChatMessage.chatMessage.frostSigningSessionId RitualNotice( @@ -414,7 +416,7 @@ fun ChatTranscript( if (localChatMessage.chatMessage.messageType == ChatMessage.TYPE_CONFEDERATION_PROFILE_PUBLISHED) { onOpenConfederation(it) } else { - onOpenConfederationProfileChange(it) + onOpenConfederationChange(it) } } }, 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 966797ae..ff47a27d 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 @@ -39,7 +39,11 @@ class AddGroupPostViewModel( val chatRoomId: String, val activeUserPublicKey: HexKey, val relayHint: String?, - /** A confederation the group is in, to sign the post instead of the group (docs/confederation-room-removal.md, D9). */ + /** + * A confederation the group is in, to propose the post to instead of the group signing it + * (docs/confederation-proposals.md): the group's quorum proposes it, and the confederation signs + * once enough of its groups have endorsed it. + */ val confederationId: HexKey? = null, initialAddGroupPostUIState: AddGroupPostUIState, val chatRepository: ChatRepository, @@ -70,7 +74,7 @@ class AddGroupPostViewModel( // The same condition the group detail screen, or the confederation's, gates // the entry point on. canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && - if (confederationId != null) chatRepository.canSignAsConfederation(confederationId) else frostSigningRepository.canSign(chatRoomId), + if (confederationId != null) chatRepository.canSignAsConfederation(chatRoomId, confederationId) else frostSigningRepository.canSign(chatRoomId), postingAs = byline?.second, ) } @@ -114,10 +118,10 @@ class AddGroupPostViewModel( viewModelScope.launch(Dispatchers.IO) { val session = runCatching { - // A confederation signs through its own signing, not the group's FROST - // key: docs/confederation.md, Phase 15. + // A confederation's post is this group's proposal to every member group, + // signed by its quorum like any statement: docs/confederation-proposals.md. if (confederationId != null) { - chatRepository.proposeAsConfederation(confederationId, template.kind, template.tags, template.content) + chatRepository.proposeAsConfederation(localChatRoom, confederationId, template.kind, template.tags, template.content) } else { frostSigningRepository.proposeSigning( localChatRoom = localChatRoom, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationProfileChangeViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationChangeViewModel.kt similarity index 60% rename from composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationProfileChangeViewModel.kt rename to composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationChangeViewModel.kt index 41693e6a..97b8fdb6 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationProfileChangeViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationChangeViewModel.kt @@ -17,55 +17,62 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.managers.ConfederationProfileRefusal +import mobi.giza.compose.managers.ConfederationChangeRefusal import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.ConfederationRepository -import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState -import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState.Field -import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState.FieldName +import mobi.giza.compose.ui.view.state.ConfederationChangeUIState +import mobi.giza.compose.ui.view.state.ConfederationChangeUIState.Field +import mobi.giza.compose.ui.view.state.ConfederationChangeUIState.FieldName /** - * One change to a confederation's profile from one of its groups, and the group's answer to it - * (docs/confederation-profile.md, D3). Answering is a group signature, so each button opens a - * signing session and the screen goes to it; one answer at a time. + * One proposal for a confederation to sign something -- a profile, a post, its charter -- from one of + * its groups, and the group's answer to it (docs/confederation-profile.md, D3; + * docs/confederation-proposals.md). Answering is a group signature, so each button opens a signing + * session and the screen goes to it; one answer at a time. + * + * [requestedId] may be a signing attempt's id, from a line written before lines named the proposal: the + * repository reads it as the proposal the attempt was signing. */ -class ConfederationProfileChangeViewModel( +class ConfederationChangeViewModel( val activeUserPublicKey: HexKey, val chatRoomId: String, - val changeId: HexKey, - initialUIState: ConfederationProfileChangeUIState, + /** The proposal's id, or a signing attempt's: see the class's note. */ + val requestedId: HexKey, + initialUIState: ConfederationChangeUIState, val chatRepository: ChatRepository, val confederationRepository: ConfederationRepository, ) : ViewModel() { private val logger = Logger.withTag(TAG) private val state = MutableStateFlow(initialUIState) - val uiState: StateFlow = state.asStateFlow() + val uiState: StateFlow = state.asStateFlow() fun initiate() { viewModelScope.launch(Dispatchers.IO) { val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) ?: run { - state.value = ConfederationProfileChangeUIState.Error("Couldn't find the group") + state.value = ConfederationChangeUIState.Error("Couldn't find the group") return@launch } val canAnswer = GroupStatementCapability.roomIsOpen(localChatRoom) && chatRepository.canSign(chatRoomId) && confederationRepository.isAdmin(chatRoomId, activeUserPublicKey) && confederationRepository.holdsAnnouncedInbox(chatRoomId, activeUserPublicKey) + val changeId = confederationRepository.proposalIdOf(requestedId) val base = confederationRepository.profileBaseOf(changeId) combine( - confederationRepository.observeProfileChange(changeId), - confederationRepository.observePendingProfileAnswer(chatRoomId, changeId), + confederationRepository.observeChange(changeId), + confederationRepository.observePendingChangeAnswer(chatRoomId, changeId), ) { status, pending -> status to pending }.collect { (status, pending) -> if (status == null) { - state.value = ConfederationProfileChangeUIState.NotHeld + state.value = ConfederationChangeUIState.NotHeld return@collect } - val acting = (state.value as? ConfederationProfileChangeUIState.Loaded)?.isActing == true - state.value = ConfederationProfileChangeUIState.Loaded( + val acting = (state.value as? ConfederationChangeUIState.Loaded)?.isActing == true + state.value = ConfederationChangeUIState.Loaded( localChatRoom = localChatRoom, status = status, confederationName = confederationRepository.membership(status.change.confederation)?.name ?: "", - differences = differences(base, ConfederationProfileRefusal.metadataOf(status.change.profile)), + // Only a profile is a difference from something; a post or a charter is shown as itself. + differences = if (status.change.isProfile) differences(base, ConfederationChangeRefusal.metadataOf(status.change.event)) else emptyList(), names = status.change.groups.associateWith { confederationRepository.nameOf(it, chatRoomId) }, canAnswer = canAnswer, pendingSessionId = pending?.id, @@ -76,33 +83,33 @@ class ConfederationProfileChangeViewModel( } fun endorse(onSuccess: (String) -> Unit, onFailure: () -> Unit) = act(onSuccess, onFailure) { loaded -> - confederationRepository.proposeProfileEndorsement(loaded.localChatRoom, activeUserPublicKey, changeId) + confederationRepository.proposeEndorsement(loaded.localChatRoom, activeUserPublicKey, loaded.status.change.id) } /** An objection, with [reason]; from the group that proposed the change, its withdrawal. */ fun objectTo(reason: String, onSuccess: (String) -> Unit, onFailure: () -> Unit) = act(onSuccess, onFailure) { loaded -> - confederationRepository.proposeProfileObjection(loaded.localChatRoom, activeUserPublicKey, changeId, reason.trim()) + confederationRepository.proposeObjection(loaded.localChatRoom, activeUserPublicKey, loaded.status.change.id, reason.trim()) } private fun act( onSuccess: (String) -> Unit, onFailure: () -> Unit, - propose: suspend (ConfederationProfileChangeUIState.Loaded) -> FrostSigningSession, + propose: suspend (ConfederationChangeUIState.Loaded) -> FrostSigningSession, ) { - val loaded = state.value as? ConfederationProfileChangeUIState.Loaded ?: return + val loaded = state.value as? ConfederationChangeUIState.Loaded ?: return if (loaded.isActing) return - state.update { (it as? ConfederationProfileChangeUIState.Loaded)?.copy(isActing = true) ?: it } + state.update { (it as? ConfederationChangeUIState.Loaded)?.copy(isActing = true) ?: it } viewModelScope.launch(Dispatchers.IO) { val session = runCatching { propose(loaded) } - .onFailure { logger.e("Could not ask $chatRoomId to answer $changeId", it) } + .onFailure { logger.e("Could not ask $chatRoomId to answer ${loaded.status.change.id}", it) } .getOrNull() - state.update { (it as? ConfederationProfileChangeUIState.Loaded)?.copy(isActing = false) ?: it } + state.update { (it as? ConfederationChangeUIState.Loaded)?.copy(isActing = false) ?: it } viewModelScope.launch(Dispatchers.Main) { if (session != null) onSuccess(session.id) else onFailure() } } } companion object { - private const val TAG = "ConfederationProfileChangeViewModel" + private const val TAG = "ConfederationChangeViewModel" /** The fields a person edits that differ between [before] and [after]. */ fun differences(before: UserMetadata?, after: UserMetadata?): List { @@ -120,12 +127,12 @@ class ConfederationProfileChangeViewModel( activeUserPublicKey: HexKey, chatRoomId: String, changeId: HexKey, - initialUIState: ConfederationProfileChangeUIState = ConfederationProfileChangeUIState.Loading, + initialUIState: ConfederationChangeUIState = ConfederationChangeUIState.Loading, chatRepository: ChatRepository, confederationRepository: ConfederationRepository, ): ViewModelProvider.Factory = viewModelFactory { initializer { - ConfederationProfileChangeViewModel(activeUserPublicKey, chatRoomId, changeId, initialUIState, chatRepository, confederationRepository) + ConfederationChangeViewModel(activeUserPublicKey, chatRoomId, changeId, initialUIState, chatRepository, confederationRepository) } } } 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 deleted file mode 100644 index 1f38f485..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationSigningViewModel.kt +++ /dev/null @@ -1,97 +0,0 @@ -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.ConfederationSigningAnswer -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 - // Per group, not per person: somebody seated in several groups can say yes for one and - // no for another, and is neither simply approving nor simply declining. - val said = messages.filter { it.kind == ConfederationSigningEvents.AVAILABILITY }.mapNotNull { message -> - ConfederationRitualEvents.decodeByGroup(message.payload)?.let { message.senderPublicKey to it } - }.toMap() - val groupNames = plan?.groups.orEmpty().associateWith { confederationRepository.nameOf(it) } - val answers = plan?.people.orEmpty().map { person -> - val byGroup = said[person].orEmpty() - val inRosterOrder = plan?.groups.orEmpty().filter { it in byGroup } - ConfederationSigningAnswer( - name = confederationRepository.nameOf(person), - approvedFor = inRosterOrder.filter { byGroup[it] == ConfederationSigningEvents.YES }.map(groupNames::getValue), - declinedFor = inRosterOrder.filter { byGroup[it] != ConfederationSigningEvents.YES }.map(groupNames::getValue), - ) - } - 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/ConfederationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationViewModel.kt index d8f6f391..7626fb26 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationViewModel.kt @@ -1,8 +1,5 @@ package mobi.giza.compose.ui.view.model -import com.vitorpamplona.quartz.nip01Core.core.Event -import mobi.giza.compose.managers.ConfederationSigningManager -import mobi.giza.compose.database.model.ConfederationSigningAttempt import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope @@ -22,8 +19,8 @@ import mobi.giza.compose.ui.view.state.ConfederationUIState /** * A formed confederation from one of its member groups (docs/confederation-profile.md, D1): its - * profile, its groups, and the changes to its profile. Watched, since a change, an answer and a newly - * signed profile all arrive while the screen is open. + * profile, its groups, the proposals for it to sign something, its posts and its charter. Watched, + * since a proposal, an answer and a newly signed event all arrive while the screen is open. */ class ConfederationViewModel( val activeUserPublicKey: HexKey, @@ -52,20 +49,18 @@ class ConfederationViewModel( ConfederationUIState.Group(group, names.getValue(group), holders[group].orEmpty().map { confederationRepository.nameOf(it) }) } val readsChanges = confederationRepository.isAdmin(chatRoomId, activeUserPublicKey) - val problem = confederationRepository.profileChangeProblem(chatRoomId, activeUserPublicKey, confederationId) + val problem = confederationRepository.changeProblem(chatRoomId, activeUserPublicKey, confederationId) val formingProposalId = confederationRepository.formingProposalOf(confederationId) - val holdsSeat = confederationRepository.holdsSeat(confederationId, activeUserPublicKey) combine( combine( confederationRepository.observeProfile(confederationId), - confederationRepository.observeProfileChanges(confederationId), - confederationRepository.observePendingProfileChange(chatRoomId, confederationId), + confederationRepository.observeChanges(confederationId), + confederationRepository.observePendingChange(chatRoomId, confederationId), ) { profile, changes, pending -> Triple(profile, changes, pending) }, confederationRepository.observePosts(confederationId), confederationRepository.observeCharterSigned(confederationId), - confederationRepository.observeSigningAttempts(confederationId, activeUserPublicKey), - ) { profileAndChanges, posts, charterSigned, attempts -> Quad(profileAndChanges, posts, charterSigned, attempts) }.collect { (profileAndChanges, posts, charterSigned, attempts) -> + ) { profileAndChanges, posts, charterSigned -> Triple(profileAndChanges, posts, charterSigned) }.collect { (profileAndChanges, posts, charterSigned) -> val (profile, changes, pending) = profileAndChanges state.value = ConfederationUIState.Loaded( localChatRoom = localChatRoom, @@ -80,43 +75,26 @@ class ConfederationViewModel( pendingSessionId = pending?.id, formingProposalId = formingProposalId, posts = posts, - holdsSeat = holdsSeat, charterSigned = charterSigned, - attempts = attemptsToShow(attempts), names = names, ) } } } - /** Proposes that the confederation sign its charter; the attempt's id to [onSuccess]. */ - fun proposeCharter(onSuccess: (attemptId: String) -> Unit, onFailure: () -> Unit) { + /** + * Proposes, from this group, that the confederation sign its charter (docs/confederation-proposals.md): + * the group's signing session's id to [onSuccess], since the group signs the proposal first. + */ + fun proposeCharter(onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { + val loaded = state.value as? ConfederationUIState.Loaded ?: return viewModelScope.launch(Dispatchers.IO) { - val attemptId = runCatching { confederationRepository.proposeCharter(confederationId) }.getOrNull() - launch(Dispatchers.Main) { if (attemptId != null) onSuccess(attemptId) else onFailure() } + val session = runCatching { confederationRepository.proposeCharter(loaded.localChatRoom, activeUserPublicKey, confederationId) }.getOrNull() + launch(Dispatchers.Main) { if (session != null) onSuccess(session.id) else onFailure() } } } - private data class Quad(val first: A, val second: B, val third: C, val fourth: D) - companion object { - /** How many ended attempts the screen keeps under the running ones. */ - const val ENDED_SHOWN = 5 - - /** Running first, the ones waiting on this person before the rest; then the newest few that ended. */ - internal fun attemptsToShow(attempts: List): List { - val items = attempts.map { attempt -> - ConfederationUIState.Attempt( - id = attempt.id, - event = Event.fromJsonOrNull(attempt.eventJson), - stage = attempt.stage, - awaitingYou = ConfederationSigningManager.isAwaitingApproval(attempt), - ) to attempt - } - val running = items.filter { it.second.isRunning }.sortedWith(compareBy({ !it.first.awaitingYou }, { -it.second.createdAt.epochSeconds })) - val ended = items.filter { !it.second.isRunning }.sortedByDescending { it.second.updatedAt }.take(ENDED_SHOWN) - return (running + ended).map { it.first } - } fun factory( activeUserPublicKey: HexKey, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditConfederationProfileViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditConfederationProfileViewModel.kt index c22f972a..474b7483 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditConfederationProfileViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditConfederationProfileViewModel.kt @@ -53,7 +53,7 @@ class EditConfederationProfileViewModel( profile = confederationRepository.observeProfile(confederationId).first(), proposingGroups = groups, names = membership.groups.associateWith { confederationRepository.nameOf(it) }, - problem = if (groups.isEmpty()) confederationRepository.profileChangeProblem(chatRoomId, activeUserPublicKey, confederationId) else null, + problem = if (groups.isEmpty()) confederationRepository.changeProblem(chatRoomId, activeUserPublicKey, confederationId) else null, selectedGroup = groups.firstOrNull(), ) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationProfileChangeUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationChangeUIState.kt similarity index 70% rename from composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationProfileChangeUIState.kt rename to composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationChangeUIState.kt index fd3dfad9..58f47dc1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationProfileChangeUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationChangeUIState.kt @@ -2,14 +2,14 @@ package mobi.giza.compose.ui.view.state import com.vitorpamplona.quartz.nip01Core.core.HexKey import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState -import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus +import mobi.giza.compose.nostr.confederation.ConfederationChangeState +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatus /** One change to a confederation's profile, seen from one of its groups (docs/confederation-profile.md, D3). */ -sealed interface ConfederationProfileChangeUIState { +sealed interface ConfederationChangeUIState { data class Loaded( val localChatRoom: LocalChatRoom, - val status: ConfederationProfileChangeStatus, + val status: ConfederationChangeStatus, val confederationName: String, /** Each field that would change, as (field, before, after). */ val differences: List, @@ -19,9 +19,9 @@ sealed interface ConfederationProfileChangeUIState { /** An answer this group is being asked to sign, not yet signed: one at a time. */ val pendingSessionId: String? = null, val isActing: Boolean = false, - ) : ConfederationProfileChangeUIState { + ) : ConfederationChangeUIState { private val roomId get() = localChatRoom.chatRoom.id - private val live get() = status.state == ConfederationProfileChangeState.OPEN || status.state == ConfederationProfileChangeState.ENDORSED + private val live get() = status.state == ConfederationChangeState.OPEN || status.state == ConfederationChangeState.ENDORSED /** Another group's change this group has not answered, still open. */ val canEndorseOrObject: Boolean @@ -37,9 +37,9 @@ sealed interface ConfederationProfileChangeUIState { data class Field(val name: FieldName, val before: String?, val after: String?) - data object NotHeld : ConfederationProfileChangeUIState + data object NotHeld : ConfederationChangeUIState - data class Error(val message: String) : ConfederationProfileChangeUIState + data class Error(val message: String) : ConfederationChangeUIState - data object Loading : ConfederationProfileChangeUIState + data object Loading : ConfederationChangeUIState } 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 deleted file mode 100644 index f1233e09..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationSigningUIState.kt +++ /dev/null @@ -1,34 +0,0 @@ -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, with their answer for each group they hold a role in. */ - val answers: List, - val roleCount: Int, - val groupCount: Int, - val isActing: Boolean = false, - ) : ConfederationSigningUIState - - data object NotHeld : ConfederationSigningUIState - - data object Loading : ConfederationSigningUIState -} - -/** - * One role holder's answer, by group: a person seated in several groups answers for each of them, - * and the answers can differ -- on a profile, each follows whether that group had endorsed it when - * the signing began. Both lists empty while they have not said. - */ -data class ConfederationSigningAnswer( - val name: String, - val approvedFor: List = emptyList(), - val declinedFor: List = emptyList(), -) { - val hasSaid: Boolean get() = approvedFor.isNotEmpty() || declinedFor.isNotEmpty() -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationUIState.kt index bf27b6c6..cea88b30 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationUIState.kt @@ -1,13 +1,13 @@ package mobi.giza.compose.ui.view.state -import com.vitorpamplona.quartz.nip01Core.core.Event -import mobi.giza.compose.database.model.ConfederationSigningStage +import mobi.giza.compose.nostr.confederation.ConfederationChangeState +import mobi.giza.compose.nostr.confederation.ConfederationKinds import mobi.giza.compose.nostr.GroupPost import com.vitorpamplona.quartz.nip01Core.core.HexKey import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.nostr.GroupNostrProfile -import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus -import mobi.giza.compose.repository.ProfileChangeProblem +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatus +import mobi.giza.compose.repository.ChangeProblem /** A formed confederation, seen from one of its member groups (docs/confederation-profile.md, D1). */ sealed interface ConfederationUIState { @@ -20,32 +20,36 @@ sealed interface ConfederationUIState { val groups: List, /** The newest profile the confederation has signed that this device holds. */ val profile: GroupNostrProfile? = null, - /** The changes to its profile this device holds, newest first: an admin's device holds them, nobody else's. */ - val changes: List = emptyList(), + /** + * The proposals for it to sign something -- a profile, a post, its charter -- this device holds, + * newest first: an admin's device holds them, nobody else's (docs/confederation-proposals.md). + */ + val changes: List = emptyList(), /** Whether this member reads the groups' statements: one of the group's admins. */ val readsChanges: Boolean = false, - /** Why this member cannot propose a change from this group, or null when they can. */ - val problem: ProfileChangeProblem? = null, - /** A change this group is being asked to propose, not yet signed. */ + /** Why this member cannot put a proposal to this group, or null when they can. */ + val problem: ChangeProblem? = null, + /** A proposal this group is being asked to make, not yet signed: one at a time. */ val pendingSessionId: String? = null, /** The proposal the confederation was formed from, where this device holds it. */ val formingProposalId: HexKey? = null, /** The posts it has signed that this device holds, newest first. */ val posts: List = emptyList(), - /** Whether this person holds a seat, and so can propose what it signs (docs/confederation-room-removal.md, D9). */ - val holdsSeat: Boolean = false, /** Whether this device holds the charter it has signed. */ val charterSigned: Boolean = false, - /** This person's attempts at it signing something, running first, then the last few ended. */ - val attempts: List = emptyList(), /** How to name each group. */ val names: Map = emptyMap(), ) : ConfederationUIState { + /** Whether this member can put a proposal to the group now: nothing stands in the way, and none is being signed. */ val canEdit: Boolean get() = problem == null && pendingSessionId == null - } - /** One attempt at the confederation signing something: what, how far it is, and whether it waits on this person. */ - data class Attempt(val id: String, val event: Event?, val stage: ConfederationSigningStage, val awaitingYou: Boolean) + /** A charter proposal still open or being signed: a second would only cross it. */ + val charterProposed: Boolean + get() = changes.any { + it.change.kind == ConfederationKinds.CHARTER && + (it.state == ConfederationChangeState.OPEN || it.state == ConfederationChangeState.ENDORSED) + } + } /** A member group, with the admins who hold its roles where this device knows them. */ data class Group(val publicKey: HexKey, val name: String, val roleHolders: List) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/EditConfederationProfileUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/EditConfederationProfileUIState.kt index 1be68c43..c7e0e572 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/EditConfederationProfileUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/EditConfederationProfileUIState.kt @@ -2,7 +2,7 @@ package mobi.giza.compose.ui.view.state import com.vitorpamplona.quartz.nip01Core.core.HexKey import mobi.giza.compose.nostr.GroupNostrProfile -import mobi.giza.compose.repository.ProfileChangeProblem +import mobi.giza.compose.repository.ChangeProblem /** The form for a change to a confederation's profile (docs/confederation-profile.md, D2). */ sealed interface EditConfederationProfileUIState { @@ -17,7 +17,7 @@ sealed interface EditConfederationProfileUIState { val proposingGroups: List, val names: Map, /** Why the group it was opened from cannot propose, when no group can. */ - val problem: ProfileChangeProblem?, + val problem: ChangeProblem?, val selectedGroup: HexKey?, val isActing: Boolean = false, ) : EditConfederationProfileUIState diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationChangeStatementsTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationChangeStatementsTest.kt new file mode 100644 index 00000000..b90a8ad4 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationChangeStatementsTest.kt @@ -0,0 +1,194 @@ +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.crypto.EventHasher +import fr.acinq.bitcoin.PrivateKey +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import mobi.giza.compose.extensions.toHex + +/** What a formed confederation's groups say about its profile, and where a change stands (docs/confederation-profile.md, Phase 1). */ +class ConfederationChangeStatementsTest { + private fun npub(n: Int): HexKey = PrivateKey(ByteArray(32).also { it[0] = 0x17; it[31] = n.toByte() }).publicKey().xOnly().value.toHex() + + private val agora = npub(1) + private val polis = npub(2) + private val ekklesia = npub(3) + private val atlas = npub(9) + private val now = 1_790_000_000L + private val expiry = now + ConfederationKinds.DEFAULT_CHANGE_EXPIRY_SECONDS + + private fun changeRumor( + by: HexKey = agora, + others: List = listOf(polis, ekklesia), + threshold: Int = 2, + base: HexKey? = "ba".repeat(32), + content: String = """{"name":"Atlas"}""", + createdAt: Long = now, + ): Event = ConfederationChangeStatements.change(by, others, atlas, threshold, base, emptyArray(), content, createdAt, expiry) + + private val change get() = ConfederationChangeStatements.parseChange(changeRumor())!! + + private fun rebuilt(rumor: Event, tags: Array> = rumor.tags, content: String = rumor.content): Event = + Event(EventHasher.hashId(rumor.pubKey, rumor.createdAt, rumor.kind, tags, content), rumor.pubKey, rumor.createdAt, rumor.kind, tags, content, "") + + // ---- the wire ------------------------------------------------------------------------------- + + @Test + fun `a change carries the kind 0 the confederation would sign, dated and named before anyone answers`() { + val rumor = changeRumor() + val parsed = assertNotNull(ConfederationChangeStatements.parseChange(rumor)) + assertEquals(listOf(agora, polis, ekklesia), parsed.groups) + assertEquals(atlas, parsed.confederation) + assertEquals(2, parsed.threshold) + assertEquals("ba".repeat(32), parsed.base) + assertEquals(atlas, parsed.event.pubKey) + assertEquals(0, parsed.event.kind) + assertEquals(rumor.createdAt, parsed.event.createdAt) + assertEquals("", rumor.sig, "a rumor") + assertEquals("", parsed.event.sig, "and its kind:0 unsigned") + assertEquals(EventHasher.hashId(atlas, now, 0, emptyArray(), """{"name":"Atlas"}"""), parsed.eventId) + } + + @Test + fun `a post or a charter goes the same way, with no base, and nothing else does`() { + val post = ConfederationChangeStatements.change(agora, listOf(polis, ekklesia), atlas, 2, null, emptyArray(), "Three groups, one voice", now, now + 1000, kind = 1) + assertEquals(1, ConfederationChangeStatements.parseChange(post)?.kind) + assertEquals("Three groups, one voice", ConfederationChangeStatements.parseChange(post)?.event?.content) + val charter = ConfederationChangeStatements.change( + agora, listOf(polis, ekklesia), atlas, 2, null, + ConfederationCharterEvent.assembleTags("Atlas", listOf(agora, polis, ekklesia), 2), ConfederationCharterEvent.content("Atlas", 3), now, now + 1000, + kind = ConfederationKinds.CHARTER, + ) + assertEquals(ConfederationKinds.CHARTER, ConfederationChangeStatements.parseChange(charter)?.kind) + kotlin.test.assertFailsWith { + ConfederationChangeStatements.change(agora, listOf(polis, ekklesia), atlas, 2, null, emptyArray(), "long form", now, now + 1000, kind = 30023) + } + kotlin.test.assertFailsWith("only a profile has a base") { + ConfederationChangeStatements.change(agora, listOf(polis, ekklesia), atlas, 2, "ba".repeat(32), emptyArray(), "a post", now, now + 1000, kind = 1) + } + } + + @Test + fun `a first profile has no base`() { + assertNull(ConfederationChangeStatements.parseChange(changeRumor(base = null))!!.base) + } + + @Test + fun `a change is refused whole when any part of it is wrong`() { + val rumor = changeRumor() + fun without(name: String) = rebuilt(rumor, rumor.tags.filter { it[0] != name }.toTypedArray()) + assertNull(ConfederationChangeStatements.parseChange(without("confederation"))) + assertNull(ConfederationChangeStatements.parseChange(without("threshold"))) + assertNull(ConfederationChangeStatements.parseChange(without("expiration"))) + assertNull(ConfederationChangeStatements.parseChange(without("p")), "a change to nobody") + + // The kind:0 is the confederation's, dated as the rumor, unsigned, with its own id. + val profile = ConfederationChangeStatements.parseChange(rumor)!!.event + fun withProfile(p: Event) = rebuilt(rumor, content = p.toJson()) + assertNull(ConfederationChangeStatements.parseChange(withProfile(ConfederationChangeStatements.unsigned(polis, now, 0, emptyArray(), "{}"))), "someone else's profile") + assertNull(ConfederationChangeStatements.parseChange(withProfile(ConfederationChangeStatements.unsigned(atlas, now + 1, 0, emptyArray(), "{}"))), "dated otherwise") + assertNull(ConfederationChangeStatements.parseChange(withProfile(Event("00".repeat(32), atlas, now, 0, emptyArray(), "{}", ""))), "an id that is not its hash") + assertNull(ConfederationChangeStatements.parseChange(withProfile(Event(profile.id, atlas, now, 0, profile.tags, profile.content, "ab".repeat(64)))), "already signed") + assertNull(ConfederationChangeStatements.parseChange(withProfile(ConfederationChangeStatements.unsigned(atlas, now, 0, emptyArray(), "{}").let { Event(EventHasher.hashId(atlas, now, 1, emptyArray(), "{}"), atlas, now, 1, emptyArray(), "{}", "") })), "a post that claims to edit a profile") + + assertNull(ConfederationChangeStatements.parseChange(changeRumor(threshold = 4)), "more groups than it names") + assertNull(ConfederationChangeStatements.parseChange(changeRumor(threshold = 1)), "a threshold of one") + assertEquals(listOf(polis), ConfederationChangeStatements.parseChange(changeRumor(others = listOf(polis, agora)))!!.addressees, "naming itself is tidied away") + val selfNamed = rebuilt(rumor, rumor.tags + arrayOf(arrayOf("p", agora))) + assertNull(ConfederationChangeStatements.parseChange(selfNamed), "and refused when it arrives that way") + } + + @Test + fun `answers name the change and its kind 0, and go to every other group`() { + val endorsement = ConfederationChangeStatements.endorsement(polis, change, now + 5) + val parsed = assertNotNull(ConfederationChangeStatements.parseAnswer(endorsement)) + assertTrue(parsed.isEndorsement) + assertEquals(change.id, parsed.changeId) + assertEquals(change.eventId, parsed.eventId) + assertEquals(setOf(agora, ekklesia), parsed.addressees.toSet()) + assertTrue(parsed.answers(change)) + + val objection = assertNotNull(ConfederationChangeStatements.parseAnswer(ConfederationChangeStatements.objection(ekklesia, change, "Too long", now + 5))) + assertFalse(objection.isEndorsement) + assertEquals("Too long", objection.reason) + + // An endorsement says nothing but that it endorses. + assertNull(ConfederationChangeStatements.parseAnswer(rebuilt(endorsement, content = "and also"))) + // To fewer groups than the change names, it does not answer it. + val partial = rebuilt(endorsement, endorsement.tags.filter { !(it[0] == "p" && it[1] == ekklesia) }.toTypedArray()) + assertFalse(ConfederationChangeStatements.parseAnswer(partial)!!.answers(change)) + } + + @Test + fun `a voucher names the change, its kind 0 and its expiry, and nothing else`() { + val template = ConfederationChangeStatements.voucherTemplate(change, now + 5) + val voucher = Event(EventHasher.hashId(polis, template.createdAt, template.kind, template.tags, template.content), polis, template.createdAt, template.kind, template.tags, template.content, "") + val parsed = assertNotNull(ConfederationChangeStatements.parseVoucher(voucher)) + assertTrue(parsed.vouchesFor(change)) + assertEquals(ConfederationKinds.VOUCHER, voucher.kind) + + val other = ConfederationChangeStatements.parseChange(changeRumor(content = """{"name":"Other"}"""))!! + assertFalse(parsed.vouchesFor(other), "a voucher is for one kind:0") + assertNull(ConfederationChangeStatements.parseVoucher(Event(voucher.id, polis, voucher.createdAt, voucher.kind, voucher.tags + arrayOf(arrayOf("x", "y")), "", ""))) + } + + @Test + fun `none of the new kinds is public`() { + (ConfederationKinds.CHANGE_KINDS + ConfederationKinds.VOUCHER).forEach { + assertFalse(it in ConfederationKinds.ALL, "$it would be subscribed to and broadcast") + assertTrue(it in 1000..9999) + } + } + + // ---- the state ------------------------------------------------------------------------------ + + private fun statusOf( + vararg answers: Event, + newest: Pair? = null, + published: Boolean = false, + at: Long = now + 60, + change: ConfederationChangeStatements.Change = this.change, + ) = ConfederationChangeStatus.of(change, answers.mapNotNull(ConfederationChangeStatements::parseAnswer), emptyList(), newest, published, at) + + private fun endorse(by: HexKey, at: Long = now + 5) = ConfederationChangeStatements.endorsement(by, change, at) + private fun objectTo(by: HexKey, at: Long = now + 5) = ConfederationChangeStatements.objection(by, change, "", at) + + @Test + fun `the proposer is the first endorsement, and the threshold's worth of groups endorses it`() { + assertEquals(ConfederationChangeState.OPEN, statusOf().state) + val endorsed = statusOf(endorse(polis)) + assertEquals(ConfederationChangeState.ENDORSED, endorsed.state) + assertEquals(listOf(agora, polis), endorsed.endorsers) + assertEquals(ConfederationChangeAnswer.WAITING, endorsed.answerOf(ekklesia)) + } + + @Test + fun `an objection is counted, but blocks only when the threshold is out of reach`() { + assertEquals(ConfederationChangeState.OPEN, statusOf(objectTo(polis)).state, "Ekklesia can still make it two") + assertEquals(ConfederationChangeState.ENDORSED, statusOf(objectTo(polis), endorse(ekklesia)).state, "two of three is the rule") + assertEquals(ConfederationChangeState.DECLINED, statusOf(objectTo(polis), objectTo(ekklesia)).state) + } + + @Test + fun `a group's first answer is its answer, and only one dated by the expiry counts`() { + val status = statusOf(objectTo(polis, now + 5), endorse(polis, now + 9)) + assertEquals(ConfederationChangeAnswer.OBJECTED, status.answerOf(polis)) + assertEquals(ConfederationChangeState.OPEN, statusOf(endorse(polis, expiry + 1), at = now + 60).state, "too late to count") + } + + @Test + fun `withdrawn, published, superseded and expired`() { + assertEquals(ConfederationChangeState.WITHDRAWN, statusOf(objectTo(agora)).state) + assertEquals(ConfederationChangeState.PUBLISHED, statusOf(endorse(polis), published = true).state) + assertEquals(ConfederationChangeState.SUPERSEDED, statusOf(endorse(polis), newest = (now + 1) to "ff".repeat(32)).state) + assertEquals(ConfederationChangeState.ENDORSED, statusOf(endorse(polis), newest = (now - 1) to "ff".repeat(32)).state, "an older profile is what it replaces") + assertEquals(ConfederationChangeState.EXPIRED, statusOf(at = expiry + 1).state) + assertEquals(ConfederationChangeState.EXPIRED, statusOf(endorse(polis), at = expiry + 1).state, "nothing signs past the expiry") + } +} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileStatementsTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileStatementsTest.kt deleted file mode 100644 index 21026ca3..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileStatementsTest.kt +++ /dev/null @@ -1,175 +0,0 @@ -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.crypto.EventHasher -import fr.acinq.bitcoin.PrivateKey -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertTrue -import mobi.giza.compose.extensions.toHex - -/** What a formed confederation's groups say about its profile, and where a change stands (docs/confederation-profile.md, Phase 1). */ -class ConfederationProfileStatementsTest { - private fun npub(n: Int): HexKey = PrivateKey(ByteArray(32).also { it[0] = 0x17; it[31] = n.toByte() }).publicKey().xOnly().value.toHex() - - private val agora = npub(1) - private val polis = npub(2) - private val ekklesia = npub(3) - private val atlas = npub(9) - private val now = 1_790_000_000L - private val expiry = now + ConfederationKinds.DEFAULT_CHANGE_EXPIRY_SECONDS - - private fun changeRumor( - by: HexKey = agora, - others: List = listOf(polis, ekklesia), - threshold: Int = 2, - base: HexKey? = "ba".repeat(32), - content: String = """{"name":"Atlas"}""", - createdAt: Long = now, - ): Event = ConfederationProfileStatements.change(by, others, atlas, threshold, base, emptyArray(), content, createdAt, expiry) - - private val change get() = ConfederationProfileStatements.parseChange(changeRumor())!! - - private fun rebuilt(rumor: Event, tags: Array> = rumor.tags, content: String = rumor.content): Event = - Event(EventHasher.hashId(rumor.pubKey, rumor.createdAt, rumor.kind, tags, content), rumor.pubKey, rumor.createdAt, rumor.kind, tags, content, "") - - // ---- the wire ------------------------------------------------------------------------------- - - @Test - fun `a change carries the kind 0 the confederation would sign, dated and named before anyone answers`() { - val rumor = changeRumor() - val parsed = assertNotNull(ConfederationProfileStatements.parseChange(rumor)) - assertEquals(listOf(agora, polis, ekklesia), parsed.groups) - assertEquals(atlas, parsed.confederation) - assertEquals(2, parsed.threshold) - assertEquals("ba".repeat(32), parsed.base) - assertEquals(atlas, parsed.profile.pubKey) - assertEquals(0, parsed.profile.kind) - assertEquals(rumor.createdAt, parsed.profile.createdAt) - assertEquals("", rumor.sig, "a rumor") - assertEquals("", parsed.profile.sig, "and its kind:0 unsigned") - assertEquals(EventHasher.hashId(atlas, now, 0, emptyArray(), """{"name":"Atlas"}"""), parsed.profileId) - } - - @Test - fun `a first profile has no base`() { - assertNull(ConfederationProfileStatements.parseChange(changeRumor(base = null))!!.base) - } - - @Test - fun `a change is refused whole when any part of it is wrong`() { - val rumor = changeRumor() - fun without(name: String) = rebuilt(rumor, rumor.tags.filter { it[0] != name }.toTypedArray()) - assertNull(ConfederationProfileStatements.parseChange(without("confederation"))) - assertNull(ConfederationProfileStatements.parseChange(without("threshold"))) - assertNull(ConfederationProfileStatements.parseChange(without("expiration"))) - assertNull(ConfederationProfileStatements.parseChange(without("p")), "a change to nobody") - - // The kind:0 is the confederation's, dated as the rumor, unsigned, with its own id. - val profile = ConfederationProfileStatements.parseChange(rumor)!!.profile - fun withProfile(p: Event) = rebuilt(rumor, content = p.toJson()) - assertNull(ConfederationProfileStatements.parseChange(withProfile(ConfederationProfileStatements.unsignedProfile(polis, now, emptyArray(), "{}"))), "someone else's profile") - assertNull(ConfederationProfileStatements.parseChange(withProfile(ConfederationProfileStatements.unsignedProfile(atlas, now + 1, emptyArray(), "{}"))), "dated otherwise") - assertNull(ConfederationProfileStatements.parseChange(withProfile(Event("00".repeat(32), atlas, now, 0, emptyArray(), "{}", ""))), "an id that is not its hash") - assertNull(ConfederationProfileStatements.parseChange(withProfile(Event(profile.id, atlas, now, 0, profile.tags, profile.content, "ab".repeat(64)))), "already signed") - assertNull(ConfederationProfileStatements.parseChange(withProfile(ConfederationProfileStatements.unsignedProfile(atlas, now, emptyArray(), "{}").let { Event(EventHasher.hashId(atlas, now, 1, emptyArray(), "{}"), atlas, now, 1, emptyArray(), "{}", "") })), "a post, not a profile") - - assertNull(ConfederationProfileStatements.parseChange(changeRumor(threshold = 4)), "more groups than it names") - assertNull(ConfederationProfileStatements.parseChange(changeRumor(threshold = 1)), "a threshold of one") - assertEquals(listOf(polis), ConfederationProfileStatements.parseChange(changeRumor(others = listOf(polis, agora)))!!.addressees, "naming itself is tidied away") - val selfNamed = rebuilt(rumor, rumor.tags + arrayOf(arrayOf("p", agora))) - assertNull(ConfederationProfileStatements.parseChange(selfNamed), "and refused when it arrives that way") - } - - @Test - fun `answers name the change and its kind 0, and go to every other group`() { - val endorsement = ConfederationProfileStatements.endorsement(polis, change, now + 5) - val parsed = assertNotNull(ConfederationProfileStatements.parseAnswer(endorsement)) - assertTrue(parsed.isEndorsement) - assertEquals(change.id, parsed.changeId) - assertEquals(change.profileId, parsed.profileId) - assertEquals(setOf(agora, ekklesia), parsed.addressees.toSet()) - assertTrue(parsed.answers(change)) - - val objection = assertNotNull(ConfederationProfileStatements.parseAnswer(ConfederationProfileStatements.objection(ekklesia, change, "Too long", now + 5))) - assertFalse(objection.isEndorsement) - assertEquals("Too long", objection.reason) - - // An endorsement says nothing but that it endorses. - assertNull(ConfederationProfileStatements.parseAnswer(rebuilt(endorsement, content = "and also"))) - // To fewer groups than the change names, it does not answer it. - val partial = rebuilt(endorsement, endorsement.tags.filter { !(it[0] == "p" && it[1] == ekklesia) }.toTypedArray()) - assertFalse(ConfederationProfileStatements.parseAnswer(partial)!!.answers(change)) - } - - @Test - fun `a voucher names the change, its kind 0 and its expiry, and nothing else`() { - val template = ConfederationProfileStatements.voucherTemplate(change, now + 5) - val voucher = Event(EventHasher.hashId(polis, template.createdAt, template.kind, template.tags, template.content), polis, template.createdAt, template.kind, template.tags, template.content, "") - val parsed = assertNotNull(ConfederationProfileStatements.parseVoucher(voucher)) - assertTrue(parsed.vouchesFor(change)) - assertEquals(ConfederationKinds.VOUCHER, voucher.kind) - - val other = ConfederationProfileStatements.parseChange(changeRumor(content = """{"name":"Other"}"""))!! - assertFalse(parsed.vouchesFor(other), "a voucher is for one kind:0") - assertNull(ConfederationProfileStatements.parseVoucher(Event(voucher.id, polis, voucher.createdAt, voucher.kind, voucher.tags + arrayOf(arrayOf("x", "y")), "", ""))) - } - - @Test - fun `none of the new kinds is public`() { - (ConfederationKinds.PROFILE_CHANGE_KINDS + ConfederationKinds.VOUCHER).forEach { - assertFalse(it in ConfederationKinds.ALL, "$it would be subscribed to and broadcast") - assertTrue(it in 1000..9999) - } - } - - // ---- the state ------------------------------------------------------------------------------ - - private fun statusOf( - vararg answers: Event, - newest: Pair? = null, - published: Boolean = false, - at: Long = now + 60, - change: ConfederationProfileStatements.Change = this.change, - ) = ConfederationProfileChangeStatus.of(change, answers.mapNotNull(ConfederationProfileStatements::parseAnswer), emptyList(), newest, published, at) - - private fun endorse(by: HexKey, at: Long = now + 5) = ConfederationProfileStatements.endorsement(by, change, at) - private fun objectTo(by: HexKey, at: Long = now + 5) = ConfederationProfileStatements.objection(by, change, "", at) - - @Test - fun `the proposer is the first endorsement, and the threshold's worth of groups endorses it`() { - assertEquals(ConfederationProfileChangeState.OPEN, statusOf().state) - val endorsed = statusOf(endorse(polis)) - assertEquals(ConfederationProfileChangeState.ENDORSED, endorsed.state) - assertEquals(listOf(agora, polis), endorsed.endorsers) - assertEquals(ConfederationProfileAnswer.WAITING, endorsed.answerOf(ekklesia)) - } - - @Test - fun `an objection is counted, but blocks only when the threshold is out of reach`() { - assertEquals(ConfederationProfileChangeState.OPEN, statusOf(objectTo(polis)).state, "Ekklesia can still make it two") - assertEquals(ConfederationProfileChangeState.ENDORSED, statusOf(objectTo(polis), endorse(ekklesia)).state, "two of three is the rule") - assertEquals(ConfederationProfileChangeState.DECLINED, statusOf(objectTo(polis), objectTo(ekklesia)).state) - } - - @Test - fun `a group's first answer is its answer, and only one dated by the expiry counts`() { - val status = statusOf(objectTo(polis, now + 5), endorse(polis, now + 9)) - assertEquals(ConfederationProfileAnswer.OBJECTED, status.answerOf(polis)) - assertEquals(ConfederationProfileChangeState.OPEN, statusOf(endorse(polis, expiry + 1), at = now + 60).state, "too late to count") - } - - @Test - fun `withdrawn, published, superseded and expired`() { - assertEquals(ConfederationProfileChangeState.WITHDRAWN, statusOf(objectTo(agora)).state) - assertEquals(ConfederationProfileChangeState.PUBLISHED, statusOf(endorse(polis), published = true).state) - assertEquals(ConfederationProfileChangeState.SUPERSEDED, statusOf(endorse(polis), newest = (now + 1) to "ff".repeat(32)).state) - assertEquals(ConfederationProfileChangeState.ENDORSED, statusOf(endorse(polis), newest = (now - 1) to "ff".repeat(32)).state, "an older profile is what it replaces") - assertEquals(ConfederationProfileChangeState.EXPIRED, statusOf(at = expiry + 1).state) - assertEquals(ConfederationProfileChangeState.EXPIRED, statusOf(endorse(polis), at = expiry + 1).state, "nothing signs past the expiry") - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileNetworkJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileNetworkJvmTest.kt index f9f23b1f..dc673203 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileNetworkJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileNetworkJvmTest.kt @@ -26,7 +26,9 @@ 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.confederation.ConfederationKinds -import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatements +import mobi.giza.compose.database.model.ConfederationSigningAttempt +import mobi.giza.compose.nostr.confederation.ConfederationChangeState import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents @@ -122,14 +124,14 @@ class ConfederationProfileNetworkJvmTest { private suspend fun pumpConfederationRoom() = network.pumpConfederation() private suspend fun sweepEverywhere() = - network.everyDevice.flatMap { ConfederationProfileFollowThrough.sweep(it.db, it.publicKey, it.secret) } + network.everyDevice.flatMap { ConfederationChangeFollowThrough.sweep(it.db, it.publicKey, it.secret) } private suspend fun proposeName(name: String): HexKey { network.signed(agora) { device -> ConfederationProfileManager.proposeChange(device.db, device.room(), device.publicKey, confederation.id, emptyArray(), """{"name":"$name","display_name":"$name"}""").id } return agora.devices[0].db.confederationDao().getEventsForConfederation(confederation.id) - .filter { it.kind == ConfederationKinds.PROFILE_CHANGE }.maxBy { it.eventCreatedAt }.id + .filter { it.kind == ConfederationKinds.CHANGE }.maxBy { it.eventCreatedAt }.id } private suspend fun states(changeId: HexKey) = network.everyDevice.map { ConfederationProfileManager.status(it.db, changeId)?.state }.toSet() @@ -137,12 +139,12 @@ class ConfederationProfileNetworkJvmTest { @Test fun `a change proposed by one group, endorsed by another, is signed and read everywhere`() = runBlocking { val changeId = proposeName("Atlas of the Coast") - assertEquals(setOf(ConfederationProfileChangeState.OPEN), states(changeId), "every admin of every group holds it") + assertEquals(setOf(ConfederationChangeState.OPEN), states(changeId), "every admin of every group holds it") pumpConfederationRoom() assertEquals(emptyList(), sweepEverywhere(), "one group's voucher is not enough to start anything") network.signed(polis) { ConfederationProfileManager.proposeEndorsement(it.db, it.room(), it.publicKey, changeId).id } - assertEquals(setOf(ConfederationProfileChangeState.ENDORSED), states(changeId)) + assertEquals(setOf(ConfederationChangeState.ENDORSED), states(changeId)) pumpConfederationRoom() val started = sweepEverywhere() @@ -152,8 +154,8 @@ class ConfederationProfileNetworkJvmTest { network.everyDevice.forEach { device -> val attempt = device.db.confederationCeremonyDao().getAttempts(confederation.id, device.publicKey).single() assertEquals(ConfederationSigningStage.COMPLETE, attempt.stage, "${device.name}: ${attempt.failureReason}") - assertTrue(!ConfederationSigningManager.isAwaitingApproval(attempt), "${device.name} was not asked") - assertEquals(ConfederationProfileChangeState.PUBLISHED, ConfederationProfileManager.status(device.db, changeId)?.state, device.name) + assertTrue(attempt.approvedAt != null || attempt.declinedAt != null, "${device.name} was not asked: its device answered for its seats") + assertEquals(ConfederationChangeState.PUBLISHED, ConfederationProfileManager.status(device.db, changeId)?.state, device.name) assertEquals("Atlas of the Coast", ConfederationProfileManager.profiles(device.db, confederation.id).newestProfile?.name(), device.name) } @@ -187,52 +189,68 @@ class ConfederationProfileNetworkJvmTest { val changeId = proposeName("Not Atlas") network.signed(ekklesia) { ConfederationProfileManager.proposeObjection(it.db, it.room(), it.publicKey, changeId, "Keep the name").id } network.signed(agora) { ConfederationProfileManager.proposeObjection(it.db, it.room(), it.publicKey, changeId).id } - assertEquals(setOf(ConfederationProfileChangeState.WITHDRAWN), states(changeId)) + assertEquals(setOf(ConfederationChangeState.WITHDRAWN), states(changeId)) pumpConfederationRoom() assertEquals(emptyList(), sweepEverywhere()) network.everyDevice.forEach { assertEquals(null, ConfederationProfileManager.profiles(it.db, confederation.id).newestProfile) } } - // ---- docs/confederation-room-removal.md, Phase 8: a post, end to end, with no room anywhere ---------- + // ---- docs/confederation-proposals.md: a post, end to end, the way a profile goes ---------- + + /** The proposal Agora's quorum just signed for the confederation to sign an event of [kind]. */ + private suspend fun latestProposal(kind: Int): HexKey = + agora.devices[0].db.confederationDao().getEventsForConfederation(confederation.id) + .filter { it.kind == ConfederationKinds.CHANGE && ConfederationChangeStatements.parseChange(it.toEvent())?.kind == kind } + .maxBy { it.eventCreatedAt }.id + + /** Agora proposes an event of [kind] with [propose], Polis endorses it, and the confederation signs it with nobody asked. */ + private suspend fun proposedAndSigned(kind: Int, propose: suspend (GroupInboxHarness.Device) -> String): Pair { + network.signed(agora, propose = propose) + val changeId = latestProposal(kind) + assertEquals(setOf(ConfederationChangeState.OPEN), states(changeId)) + network.signed(polis) { ConfederationProfileManager.proposeEndorsement(it.db, it.room(), it.publicKey, changeId).id } + assertEquals(setOf(ConfederationChangeState.ENDORSED), states(changeId)) + pumpConfederationRoom() + val started = sweepEverywhere() + assertEquals(1, started.size, "the first in the order starts the signing, and only they do") + pumpConfederationRoom() + return changeId to started.single() + } @Test - fun `a post proposed by one role holder is asked of the others in their groups' rooms, signed, and owed to relays`() = runBlocking { - val proposer = agora.devices[0] - val attempt = ConfederationSigningManager.propose( - proposer.db, confederation.id, proposer.publicKey, com.vitorpamplona.quartz.nip10Notes.TextNoteEvent.KIND, emptyArray(), - "Three groups, one voice", proposer.secret, - ) - pumpConfederationRoom() - - // Every other role holder is asked, in their own group's room, by a line that is theirs. - network.groups.forEach { group -> - group.devices.filter { it !== proposer }.forEach { device -> - val asked = device.db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId).map { it.chatMessage } - .filter { it.messageType == ChatMessage.TYPE_CONFEDERATION_SIGNING_ASKED && it.frostSigningSessionId == attempt.id } - assertEquals(1, asked.size, "${device.name} is asked in ${group.name}'s room") - ConfederationSigningManager.approve(device.db, attempt.id, device.secret) - } + fun `a post proposed by one group and endorsed by another is signed with nobody asked, and owed to relays`() = runBlocking { + val (changeId, started) = proposedAndSigned(com.vitorpamplona.quartz.nip10Notes.TextNoteEvent.KIND) { device -> + ConfederationProfileManager.proposeChange( + device.db, device.room(), device.publicKey, confederation.id, emptyArray(), "Three groups, one voice", + kind = com.vitorpamplona.quartz.nip10Notes.TextNoteEvent.KIND, + ).id } - pumpConfederationRoom() network.everyDevice.forEach { device -> assertEquals(null, device.db.chatRoomDao().findChatRoomById(confederation.id), "${device.name} holds no room of the confederation's") - val done = device.db.confederationCeremonyDao().getAttempt(attempt.id) - assertEquals(ConfederationSigningStage.COMPLETE, done?.stage, "${device.name}: ${done?.failureReason}") - val signed = Event.fromJson(done!!.signedEventJson!!) + val done = device.db.confederationCeremonyDao().getAttempts(confederation.id, device.publicKey).single() + assertEquals(ConfederationSigningStage.COMPLETE, done.stage, "${device.name}: ${done.failureReason}") + val signed = Event.fromJson(done.signedEventJson!!) assertEquals("Three groups, one voice", device.db.confederationDao().getEvent(signed.id)?.toEvent()?.content, "filed as the confederation's post") assertTrue(device.db.confederationDao().observeUnpublished().first().any { it.id == signed.id }, "${device.name} owes it to relays") + assertEquals(ConfederationChangeState.PUBLISHED, ConfederationProfileManager.status(device.db, changeId)?.state, device.name) } + network.groups.forEach { group -> + group.devices.forEach { device -> + val lines = device.db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId).map { it.chatMessage } + assertTrue(lines.none { it.messageType == ChatMessage.TYPE_CONFEDERATION_SIGNING_ASKED }, "${device.name} was not asked") + assertTrue(lines.any { it.messageType == ChatMessage.TYPE_CONFEDERATION_PROFILE_PROPOSED && it.content.contains("a post for") }, "${device.name}: ${lines.map { it.content }}") + } + } + assertTrue(started.userPublicKey in network.everyDevice.map { it.publicKey }) } - /** The confederation's charter, signed the direct way its charter still is: proposed by one role holder, approved by the rest. */ + /** The confederation's charter, the way everything it signs goes: proposed by Agora, endorsed by Polis, signed with nobody asked. */ private suspend fun signCharter(): Event { - val proposer = agora.devices[0] - val (kind, tags, content) = assertNotNull(ConfederationSigningManager.charterTemplate(proposer.db, confederation.id)) - val attempt = ConfederationSigningManager.propose(proposer.db, confederation.id, proposer.publicKey, kind, tags, content, proposer.secret) - pumpConfederationRoom() - network.everyDevice.filter { it !== proposer }.forEach { ConfederationSigningManager.approve(it.db, attempt.id, it.secret) } - pumpConfederationRoom() - return Event.fromJson(assertNotNull(proposer.db.confederationCeremonyDao().getAttempt(attempt.id)?.signedEventJson, "the charter is signed")) + val (_, started) = proposedAndSigned(ConfederationKinds.CHARTER) { device -> + ConfederationProfileManager.proposeCharter(device.db, device.room(), device.publicKey, confederation.id).id + } + val starter = network.everyDevice.first { it.publicKey == started.userPublicKey } + return Event.fromJson(assertNotNull(starter.db.confederationCeremonyDao().getAttempt(started.id)?.signedEventJson, "the charter is signed")) } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileReceiveJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileReceiveJvmTest.kt index 00a36bab..3d79bf07 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileReceiveJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileReceiveJvmTest.kt @@ -25,7 +25,7 @@ import mobi.giza.compose.managers.ConfederationStatementFixture.npub import mobi.giza.compose.managers.ConfederationStatementFixture.seal import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent import mobi.giza.compose.nostr.confederation.ConfederationKinds -import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatements import mobi.giza.compose.notifications.NotificationClassifier /** @@ -65,10 +65,10 @@ class ConfederationProfileReceiveJvmTest { return Event(id, pubKey, template.createdAt, template.kind, template.tags, template.content, Nip01Crypto.sign(id.hexToByteArray(), by.value.toByteArray()).toHex()) } - private val changeRumor: Event = ConfederationProfileStatements.change( + private val changeRumor: Event = ConfederationChangeStatements.change( npub(agora), listOf(npub(polis), npub(ekklesia)), atlas, 2, null, emptyArray(), """{"name":"Atlas"}""", now, now + 1000, ) - private val change: ConfederationProfileStatements.Change = ConfederationProfileStatements.parseChange(changeRumor)!! + private val change: ConfederationChangeStatements.Change = ConfederationChangeStatements.parseChange(changeRumor)!! private suspend fun lines(room: PrivateKey) = db.chatMessageDao().getChatMessagesByChatRoomId(npub(room)) .map { it.chatMessage }.filter { it.messageType in ChatMessage.CONFEDERATION_PROFILE_TYPES } @@ -89,7 +89,7 @@ class ConfederationProfileReceiveJvmTest { @Test fun `an answer that arrives before its change gets its line when the change does`() = runBlocking { - val objection = ConfederationProfileStatements.objection(npub(ekklesia), change, "Not that name", now + 5) + val objection = ConfederationChangeStatements.objection(npub(ekklesia), change, "Not that name", now + 5) ConfederationProfileManager.recordStatement(db, objection, seal(ekklesia, objection), npub(polis)) assertEquals(emptyList(), lines(polis)) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileStatementJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileStatementJvmTest.kt index ded3e132..3ad5d597 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileStatementJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileStatementJvmTest.kt @@ -21,8 +21,8 @@ import mobi.giza.compose.database.model.FrostSigningSession import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent import mobi.giza.compose.nostr.confederation.ConfederationKinds -import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState -import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements +import mobi.giza.compose.nostr.confederation.ConfederationChangeState +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatements import mobi.giza.compose.nostr.frost.FrostSigningEvents /** @@ -69,7 +69,7 @@ class ConfederationProfileStatementJvmTest { network.signed(agora, except) { device -> ConfederationProfileManager.proposeChange(device.db, device.room(), device.publicKey, atlas, emptyArray(), content).id } - return agora.devices[0].db.confederationDao().getEventsForConfederation(atlas).single { it.kind == ConfederationKinds.PROFILE_CHANGE }.id + return agora.devices[0].db.confederationDao().getEventsForConfederation(atlas).single { it.kind == ConfederationKinds.CHANGE }.id } private suspend fun states(changeId: HexKey) = network.everyDevice.map { ConfederationProfileManager.status(it.db, changeId)?.state }.toSet() @@ -79,11 +79,11 @@ class ConfederationProfileStatementJvmTest { @Test fun `a change reaches every admin of every group, and the proposer's quorum vouches for it`() = runBlocking { val changeId = proposeChange() - assertEquals(setOf(ConfederationProfileChangeState.OPEN), states(changeId)) + assertEquals(setOf(ConfederationChangeState.OPEN), states(changeId)) network.everyDevice.forEach { device -> val status = assertNotNull(ConfederationProfileManager.status(device.db, changeId), "on ${device.name}") assertEquals(listOf(agora.roomId), status.endorsers) - assertEquals("Atlas of the Coast", ConfederationProfileRefusal.metadataOf(status.change.profile)?.anyName()) + assertEquals("Atlas of the Coast", ConfederationChangeRefusal.metadataOf(status.change.event)?.anyName()) } // Agora's voucher, signed in the same session, is on Agora's devices and nobody else's. agora.devices.forEach { assertEquals(setOf(agora.roomId), ConfederationProfileManager.status(it.db, changeId)!!.vouchers.keys) } @@ -96,7 +96,7 @@ class ConfederationProfileStatementJvmTest { fun `a second group's endorsement makes it endorsed everywhere`() = runBlocking { val changeId = proposeChange() network.signed(polis) { ConfederationProfileManager.proposeEndorsement(it.db, it.room(), it.publicKey, changeId).id } - assertEquals(setOf(ConfederationProfileChangeState.ENDORSED), states(changeId)) + assertEquals(setOf(ConfederationChangeState.ENDORSED), states(changeId)) polis.devices.forEach { assertEquals(setOf(polis.roomId), ConfederationProfileManager.status(it.db, changeId)!!.vouchers.keys) } } @@ -104,9 +104,9 @@ class ConfederationProfileStatementJvmTest { fun `two objections out of three decline it, and the proposer can withdraw one still open`() = runBlocking { val changeId = proposeChange() network.signed(polis) { ConfederationProfileManager.proposeObjection(it.db, it.room(), it.publicKey, changeId, "Too long").id } - assertEquals(setOf(ConfederationProfileChangeState.OPEN), states(changeId)) + assertEquals(setOf(ConfederationChangeState.OPEN), states(changeId)) network.signed(agora) { ConfederationProfileManager.proposeObjection(it.db, it.room(), it.publicKey, changeId).id } - assertEquals(setOf(ConfederationProfileChangeState.WITHDRAWN), states(changeId)) + assertEquals(setOf(ConfederationChangeState.WITHDRAWN), states(changeId)) } @Test @@ -165,56 +165,56 @@ class ConfederationProfileStatementJvmTest { val newer = signed(atlasKey, EventTemplate(now - 30, 0, emptyArray(), """{"name":"Atlas"}""")) ConfederationProfileManager.recordProfile(signer.db, newer) val session = propose { ConfederationProfileManager.proposeChange(it.db, it.room(), it.publicKey, atlas, emptyArray(), profile) } - assertDeclined(signer, agora.roomId, session.id, ConfederationProfileRefusal.STALE) + assertDeclined(signer, agora.roomId, session.id, ConfederationChangeRefusal.STALE) } @Test fun `a device that has never heard of the confederation declines`() = runBlocking { signer.db.confederationDao().getCharters(atlas).forEach { signer.db.confederationDao().deleteEvent(it.id) } val session = propose { ConfederationProfileManager.proposeChange(it.db, it.room(), it.publicKey, atlas, emptyArray(), profile) } - assertDeclined(signer, agora.roomId, session.id, ConfederationProfileRefusal.UNKNOWN_CONFEDERATION) + assertDeclined(signer, agora.roomId, session.id, ConfederationChangeRefusal.UNKNOWN_CONFEDERATION) } @Test fun `a profile nothing could show is declined`() = runBlocking { val session = propose { ConfederationProfileManager.proposeChange(it.db, it.room(), it.publicKey, atlas, emptyArray(), "not a profile") } - assertDeclined(signer, agora.roomId, session.id, ConfederationProfileRefusal.UNREADABLE) + assertDeclined(signer, agora.roomId, session.id, ConfederationChangeRefusal.UNREADABLE) } @Test fun `a voucher for anything but exactly the change is declined`() = runBlocking { val session = propose { device -> - val rumor = ConfederationProfileStatements.change( + val rumor = ConfederationChangeStatements.change( agora.roomId, listOf(polis.roomId, ekklesia.roomId), atlas, 2, null, emptyArray(), profile, now, now + 1000, ) - val other = ConfederationProfileStatements.parseChange( - ConfederationProfileStatements.change(agora.roomId, listOf(polis.roomId, ekklesia.roomId), atlas, 2, null, emptyArray(), "{}", now, now + 1000), + val other = ConfederationChangeStatements.parseChange( + ConfederationChangeStatements.change(agora.roomId, listOf(polis.roomId, ekklesia.roomId), atlas, 2, null, emptyArray(), "{}", now, now + 1000), )!! ConfederationManager.proposeStatement( device.db, device.room(), device.publicKey, rumor, listOf(polis.roomId, ekklesia.roomId), invitation = null, - extra = listOf(ConfederationProfileStatements.voucherTemplate(other, now)), + extra = listOf(ConfederationChangeStatements.voucherTemplate(other, now)), ) } - assertDeclined(signer, agora.roomId, session.id, ConfederationProfileRefusal.VOUCHER) + assertDeclined(signer, agora.roomId, session.id, ConfederationChangeRefusal.VOUCHER) } @Test fun `a change with no voucher is declined`() = runBlocking { val session = propose { device -> - val rumor = ConfederationProfileStatements.change( + val rumor = ConfederationChangeStatements.change( agora.roomId, listOf(polis.roomId, ekklesia.roomId), atlas, 2, null, emptyArray(), profile, now, now + 1000, ) ConfederationManager.proposeStatement(device.db, device.room(), device.publicKey, rumor, listOf(polis.roomId, ekklesia.roomId), invitation = null) } - assertDeclined(signer, agora.roomId, session.id, ConfederationProfileRefusal.VOUCHER) + assertDeclined(signer, agora.roomId, session.id, ConfederationChangeRefusal.VOUCHER) } @Test fun `a voucher asked for on its own is declined`() = runBlocking { - val change = ConfederationProfileStatements.parseChange( - ConfederationProfileStatements.change(agora.roomId, listOf(polis.roomId, ekklesia.roomId), atlas, 2, null, emptyArray(), profile, now, now + 1000), + val change = ConfederationChangeStatements.parseChange( + ConfederationChangeStatements.change(agora.roomId, listOf(polis.roomId, ekklesia.roomId), atlas, 2, null, emptyArray(), profile, now, now + 1000), )!! - val session = propose { FrostSigningManager.proposeSigningBatch(it.db, it.room(), it.publicKey, listOf(ConfederationProfileStatements.voucherTemplate(change, now))) } + val session = propose { FrostSigningManager.proposeSigningBatch(it.db, it.room(), it.publicKey, listOf(ConfederationChangeStatements.voucherTemplate(change, now))) } assertDeclined(signer, agora.roomId, session.id, ConfederationRefusal.SHAPE) } @@ -224,12 +224,12 @@ class ConfederationProfileStatementJvmTest { network.signed(polis) { ConfederationProfileManager.proposeObjection(it.db, it.room(), it.publicKey, changeId).id } val again = ConfederationProfileManager.proposeEndorsement(polis.devices[0].db, polis.devices[0].room(), polis.devices[0].publicKey, changeId) polis.harness.pump() - assertDeclined(polis.devices[1], polis.roomId, again.id, ConfederationProfileRefusal.ANSWERED) + assertDeclined(polis.devices[1], polis.roomId, again.id, ConfederationChangeRefusal.ANSWERED) network.signed(ekklesia) { ConfederationProfileManager.proposeObjection(it.db, it.room(), it.publicKey, changeId).id } - assertEquals(setOf(ConfederationProfileChangeState.DECLINED), states(changeId)) + assertEquals(setOf(ConfederationChangeState.DECLINED), states(changeId)) val late = ConfederationProfileManager.proposeObjection(agora.devices[0].db, agora.devices[0].room(), agora.devices[0].publicKey, changeId) agora.harness.pump() - assertDeclined(agora.devices[1], agora.roomId, late.id, ConfederationProfileRefusal.CLOSED) + assertDeclined(agora.devices[1], agora.roomId, late.id, ConfederationChangeRefusal.CLOSED) } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileStorageJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileStorageJvmTest.kt index d4db316c..57e13edf 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileStorageJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileStorageJvmTest.kt @@ -24,8 +24,8 @@ import mobi.giza.compose.managers.ConfederationStatementFixture.key import mobi.giza.compose.managers.ConfederationStatementFixture.npub import mobi.giza.compose.managers.ConfederationStatementFixture.seal import mobi.giza.compose.nostr.confederation.ConfederationKinds -import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState -import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements +import mobi.giza.compose.nostr.confederation.ConfederationChangeState +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatements /** A confederation's profile changes, filed and read back (docs/confederation-profile.md, Phase 1). */ class ConfederationProfileStorageJvmTest { @@ -41,7 +41,7 @@ class ConfederationProfileStorageJvmTest { private val atlas = npub(atlasKey) private val now = Clock.System.now().epochSeconds - private fun changeRumor(content: String = """{"name":"Atlas"}""", createdAt: Long = now) = ConfederationProfileStatements.change( + private fun changeRumor(content: String = """{"name":"Atlas"}""", createdAt: Long = now) = ConfederationChangeStatements.change( npub(agora), listOf(npub(polis), npub(ekklesia)), atlas, 2, null, emptyArray(), content, createdAt, createdAt + ConfederationKinds.DEFAULT_CHANGE_EXPIRY_SECONDS, ) @@ -59,8 +59,8 @@ class ConfederationProfileStorageJvmTest { val rumor = changeRumor() assertTrue(file(agora, rumor)) assertFalse(file(agora, rumor), "a second copy is the same one") - val change = ConfederationProfileStatements.parseChange(rumor)!! - assertTrue(file(polis, ConfederationProfileStatements.endorsement(npub(polis), change, now + 1))) + val change = ConfederationChangeStatements.parseChange(rumor)!! + assertTrue(file(polis, ConfederationChangeStatements.endorsement(npub(polis), change, now + 1))) val row = assertNotNull(db.confederationDao().getEvent(rumor.id)) assertEquals(atlas, row.confederationId) @@ -68,7 +68,7 @@ class ConfederationProfileStorageJvmTest { assertEquals(2, db.confederationDao().getEventsForConfederation(atlas).size) assertEquals(emptyList(), db.confederationDao().getProposals(), "not a formation proposal") - assertEquals(ConfederationProfileChangeState.ENDORSED, ConfederationProfileManager.status(db, rumor.id)?.state) + assertEquals(ConfederationChangeState.ENDORSED, ConfederationProfileManager.status(db, rumor.id)?.state) } @Test @@ -80,8 +80,8 @@ class ConfederationProfileStorageJvmTest { @Test fun `a voucher is filed only if its group's key signed it`() = runBlocking { - val change = ConfederationProfileStatements.parseChange(changeRumor())!! - val voucher = signed(polis, ConfederationProfileStatements.voucherTemplate(change, now + 1)) + val change = ConfederationChangeStatements.parseChange(changeRumor())!! + val voucher = signed(polis, ConfederationChangeStatements.voucherTemplate(change, now + 1)) assertTrue(ConfederationProfileManager.recordVoucher(db, voucher)) val forged = Event(voucher.id, npub(ekklesia), voucher.createdAt, voucher.kind, voucher.tags, voucher.content, voucher.sig) @@ -98,19 +98,19 @@ class ConfederationProfileStorageJvmTest { val newer = changeRumor("""{"name":"Atlas of the Coast"}""", createdAt = now) file(agora, older) file(agora, newer) - val profile = ConfederationProfileStatements.parseChange(newer)!!.profile + val profile = ConfederationChangeStatements.parseChange(newer)!!.event val signedProfile = signed(atlasKey, EventTemplate(profile.createdAt, profile.kind, profile.tags, profile.content)) assertEquals(profile.id, signedProfile.id) assertTrue(ConfederationProfileManager.recordProfile(db, signedProfile, newer.id), "filed with no room for the confederation") assertFalse(ConfederationProfileManager.recordProfile(db, Event(signedProfile.id, atlas, signedProfile.createdAt, 0, signedProfile.tags, signedProfile.content, "00".repeat(64)))) val states = ConfederationProfileManager.statusesOf(db, atlas).associate { it.change.id to it.state } - assertEquals(ConfederationProfileChangeState.PUBLISHED, states[newer.id]) - assertEquals(ConfederationProfileChangeState.SUPERSEDED, states[older.id]) + assertEquals(ConfederationChangeState.PUBLISHED, states[newer.id]) + assertEquals(ConfederationChangeState.SUPERSEDED, states[older.id]) assertEquals(listOf(newer.id, older.id), ConfederationProfileManager.statusesOf(db, atlas).map { it.change.id }, "newest first") val repository = DatabaseConfederationRepository(db, this) - assertEquals(listOf(newer.id, older.id), repository.observeProfileChanges(atlas).first().map { it.change.id }) - assertEquals(ConfederationProfileChangeState.SUPERSEDED, repository.observeProfileChange(older.id).first()?.state) + assertEquals(listOf(newer.id, older.id), repository.observeChanges(atlas).first().map { it.change.id }) + assertEquals(ConfederationChangeState.SUPERSEDED, repository.observeChange(older.id).first()?.state) } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSharedSeatsSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSharedSeatsSigningJvmTest.kt index 5534c7b3..c51fd020 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSharedSeatsSigningJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSharedSeatsSigningJvmTest.kt @@ -21,7 +21,7 @@ import mobi.giza.compose.database.model.ConfederationSigningStage 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.ConfederationProfileStatements +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatements import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents @@ -94,12 +94,34 @@ class ConfederationSharedSeatsSigningJvmTest { } } + /** [group]'s voucher for [change], as its quorum signs it. */ + private fun voucher(change: ConfederationChangeStatements.Change, group: Int): Event { + val template = ConfederationChangeStatements.voucherTemplate(change, now - 3) + val id = EventHasher.hashId(groups[group], template.createdAt, template.kind, template.tags, template.content) + return Event(id, groups[group], template.createdAt, template.kind, template.tags, template.content, + Nip01Crypto.sign(id.hexToByteArray(), network.groupKeys[group].value.toByteArray()).toHex()) + } + + /** + * A post every group endorsed (docs/confederation-proposals.md): Agora's proposal and every + * group's voucher on every device, and the signing started by [proposer] on their word. + */ + private fun proposePost(proposer: Device) = runBlocking { + val content = "Words from groups that share admins" + val rumor = ConfederationChangeStatements.change(groups[0], groups.drop(1), confederation.id, 2, null, emptyArray(), content, now - 5, now + 1000, TextNoteEvent.KIND) + val change = ConfederationChangeStatements.parseChange(rumor)!! + val vouchers = groups.indices.map { voucher(change, it) } + devices.values.forEach { d -> + ConfederationProfileManager.recordStatement(d.db, rumor, ConfederationStatementFixture.seal(network.groupKeys[0], rumor), null) + vouchers.forEach { ConfederationProfileManager.recordVoucher(d.db, it) } + } + ConfederationSigningManager.propose(proposer.db, confederation.id, proposer.person, TextNoteEvent.KIND, emptyArray(), content, proposer.nsec, change.event.createdAt, vouchers) + } + @Test fun `someone seated in every group writes each message into every group's room`() { val proposer = devices.getValue(npub(11)) - runBlocking { - ConfederationSigningManager.propose(proposer.db, confederation.id, proposer.person, TextNoteEvent.KIND, emptyArray(), "Words from groups that share admins", proposer.nsec) - } + proposePost(proposer) groups.forEach { group -> val written = runBlocking { proposer.db.marmotInnerEventDao().getByChatRoomAndKinds(group, listOf(ConfederationSigningEvents.CARRIED)) } .filter { it.publicKey == proposer.person } @@ -118,11 +140,7 @@ class ConfederationSharedSeatsSigningJvmTest { @Test fun `a post is signed when the selection takes only some of a person's seats`() { val proposer = devices.getValue(npub(11)) - val attempt = runBlocking { - ConfederationSigningManager.propose(proposer.db, confederation.id, proposer.person, TextNoteEvent.KIND, emptyArray(), "Words from groups that share admins", proposer.nsec) - } - pump() - runBlocking { listOf(12, 13, 14).map { devices.getValue(npub(it)) }.forEach { ConfederationSigningManager.approve(it.db, attempt.id, it.nsec) } } + val attempt = proposePost(proposer) pump() stages(attempt.id).forEach { (person, a) -> assertEquals(ConfederationSigningStage.COMPLETE, a?.stage, "${person.take(6)}: ${a?.failureReason}") } @@ -137,9 +155,9 @@ class ConfederationSharedSeatsSigningJvmTest { @Test fun `a profile two groups vouched for is signed, and the third group's admins answer for each of their groups`() { - val rumor = ConfederationProfileStatements.change(groups[0], groups.drop(1), confederation.id, 2, null, emptyArray(), """{"name":"Atlas"}""", now - 5, now + 1000) - val change = ConfederationProfileStatements.parseChange(rumor)!! - val endorsement = ConfederationProfileStatements.endorsement(groups[1], change, now - 4) + val rumor = ConfederationChangeStatements.change(groups[0], groups.drop(1), confederation.id, 2, null, emptyArray(), """{"name":"Atlas"}""", now - 5, now + 1000) + val change = ConfederationChangeStatements.parseChange(rumor)!! + val endorsement = ConfederationChangeStatements.endorsement(groups[1], change, now - 4) runBlocking { devices.values.forEach { d -> ConfederationProfileManager.recordStatement(d.db, rumor, ConfederationStatementFixture.seal(network.groupKeys[0], rumor), null) @@ -147,10 +165,7 @@ class ConfederationSharedSeatsSigningJvmTest { } // Agora's and Polis's vouchers; Ekklesia's has not come by the time the signing starts. listOf(0 to 12, 1 to 14).forEach { (group, poster) -> - val template = ConfederationProfileStatements.voucherTemplate(change, now - 3) - val id = EventHasher.hashId(groups[group], template.createdAt, template.kind, template.tags, template.content) - val voucher = Event(id, groups[group], template.createdAt, template.kind, template.tags, template.content, - Nip01Crypto.sign(id.hexToByteArray(), network.groupKeys[group].value.toByteArray()).toHex()) + val voucher = voucher(change, group) val device = devices.getValue(npub(poster)) ConfederationProfileManager.recordVoucher(device.db, voucher) ConfederationSigningManager.postVoucher(device.db, device.person, voucher) @@ -158,7 +173,7 @@ class ConfederationSharedSeatsSigningJvmTest { } pump() val started = runBlocking { - devices.values.sortedBy { it.person }.flatMap { ConfederationProfileFollowThrough.sweep(it.db, it.person, it.nsec) } + devices.values.sortedBy { it.person }.flatMap { ConfederationChangeFollowThrough.sweep(it.db, it.person, it.nsec) } } assertEquals(1, started.size) pump() 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 86a06640..17892288 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt @@ -35,8 +35,8 @@ 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 -import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState -import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements +import mobi.giza.compose.nostr.confederation.ConfederationChangeState +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatements import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.minutes @@ -44,9 +44,9 @@ import kotlin.time.Duration.Companion.seconds /** * A confederation signing as itself, one person per device (docs/confederation.md, Phase 14): a - * confederation formed across nine devices, then a proposal in its room, approvals, and Option A - * signing with every signer's nonce held in memory -- ending, on every device, in the same event, - * signed as the room's id. + * confederation formed across nine devices, then something its groups endorsed -- vouched for, each + * by its quorum (docs/confederation-proposals.md) -- and Option A signing with every signer's nonce + * held in memory, nobody asked, ending on every device in the same event, signed as its id. */ class ConfederationSigningJvmTest { private fun secret(n: Int) = PrivateKey(ByteArray(32).also { it[0] = 0x71; it[31] = n.toByte() }) @@ -138,22 +138,30 @@ class ConfederationSigningJvmTest { } } - private fun propose(kind: Int = TextNoteEvent.KIND, content: String = "The first words of a group of groups") = runBlocking { - ConfederationSigningManager.propose(proposer.db, confederation.id, proposer.person, kind, emptyArray(), content, proposer.nsec) - } - - private fun approve(attemptId: String, who: List) = runBlocking { - who.map { devices.getValue(npub(secret(it))) }.forEach { ConfederationSigningManager.approve(it.db, attemptId, it.nsec) } + /** + * Agora proposes that the confederation sign an event of [kind], the groups in [vouching] vouch + * for it -- their vouchers held on every device, as their inboxes and rooms would carry them -- + * and [by] starts the signing on their word, as the follow-through would. + */ + private fun propose( + kind: Int = TextNoteEvent.KIND, + content: String = "The first words of a group of groups", + tags: Array> = emptyArray(), + vouching: List = listOf(0, 1, 2), + by: Device = proposer, + ) = runBlocking { + val change = endorsedChange(content, endorsers = vouching.filter { it != 0 }, kind = kind, tags = tags) + val vouchers = vouching.map { voucher(change, it) } + devices.values.forEach { d -> vouchers.forEach { ConfederationProfileManager.recordVoucher(d.db, it) } } + ConfederationSigningManager.propose(by.db, confederation.id, by.person, kind, tags, content, by.nsec, change.event.createdAt, vouchers) } private fun attempts(attemptId: String) = runBlocking { devices.values.associate { it.person to it.db.confederationCeremonyDao().getAttempt(attemptId) } } @Test - fun `the confederation signs a post, and every device holds it signed as the room`() { + fun `the confederation signs a post its groups endorsed, and every device holds it signed as itself`() { val attempt = propose() pump() - approve(attempt.id, people - 11) - pump() attempts(attempt.id).forEach { (person, a) -> assertEquals(ConfederationSigningStage.COMPLETE, a?.stage, "${person.take(6)}: ${a?.failureReason}") } val signed = attempts(attempt.id).values.map { Event.fromJson(it!!.signedEventJson!!) } @@ -167,23 +175,38 @@ class ConfederationSigningJvmTest { } } - // ---- docs/confederation-profile.md, Phase 5: a profile on its groups' word ------------------ + // ---- docs/confederation-profile.md, Phase 5, and docs/confederation-proposals.md: on its groups' word ---- @Test - fun `a profile proposed in the room directly is refused, since it changes through its groups`() { - val failure = assertFailsWith { propose(kind = MetadataEvent.KIND, content = """{"name":"Atlas"}""") } + fun `anything asked for without its groups' vouchers is refused, whatever its kind`() { + listOf(MetadataEvent.KIND to """{"name":"Atlas"}""", TextNoteEvent.KIND to "Straight to the signers").forEach { (kind, content) -> + val failure = assertFailsWith { + runBlocking { ConfederationSigningManager.propose(proposer.db, confederation.id, proposer.person, kind, emptyArray(), content, proposer.nsec, vouchers = emptyList()) } + } + assertEquals(ConfederationSigningManager.THROUGH_GROUPS, failure.message) + } + } + + @Test + fun `one group's voucher is not enough for a post`() { + val failure = assertFailsWith { propose(vouching = listOf(0)) } assertEquals(ConfederationSigningManager.THROUGH_GROUPS, failure.message) } private val now get() = Clock.System.now().epochSeconds - /** Agora proposes a profile and Polis endorses it, every device holding both, as their inboxes would. */ - private fun endorsedChange(content: String = """{"name":"Atlas","about":"A group of groups"}""", endorsers: List = listOf(1)): ConfederationProfileStatements.Change = runBlocking { - val rumor = ConfederationProfileStatements.change( - groups[0], groups.drop(1), confederation.id, 2, null, emptyArray(), content, now - 5, now + 1000, + /** Agora proposes an event -- a profile unless [kind] says otherwise -- and [endorsers] endorse it, every device holding all of it, as their inboxes would. */ + private fun endorsedChange( + content: String = """{"name":"Atlas","about":"A group of groups"}""", + endorsers: List = listOf(1), + kind: Int = MetadataEvent.KIND, + tags: Array> = emptyArray(), + ): ConfederationChangeStatements.Change = runBlocking { + val rumor = ConfederationChangeStatements.change( + groups[0], groups.drop(1), confederation.id, 2, null, tags, content, now - 5, now + 1000, kind, ) - val change = ConfederationProfileStatements.parseChange(rumor)!! - val answers = endorsers.map { i -> network.groupKeys[i] to ConfederationProfileStatements.endorsement(groups[i], change, now - 4) } + val change = ConfederationChangeStatements.parseChange(rumor)!! + val answers = endorsers.map { i -> network.groupKeys[i] to ConfederationChangeStatements.endorsement(groups[i], change, now - 4) } devices.values.forEach { d -> ConfederationProfileManager.recordStatement(d.db, rumor, ConfederationStatementFixture.seal(network.groupKeys[0], rumor), null) answers.forEach { (key, answer) -> ConfederationProfileManager.recordStatement(d.db, answer, ConfederationStatementFixture.seal(key, answer), null) } @@ -191,13 +214,18 @@ class ConfederationSigningJvmTest { change } - /** [group]'s voucher for [change], as its quorum signs it, posted into the room by its role holder [poster]. */ - private fun vouch(change: ConfederationProfileStatements.Change, group: Int, poster: Int) = runBlocking { - val template = ConfederationProfileStatements.voucherTemplate(change, now - 3) + /** [group]'s voucher for [change], as its quorum signs it. */ + private fun voucher(change: ConfederationChangeStatements.Change, group: Int): Event { + val template = ConfederationChangeStatements.voucherTemplate(change, now - 3) val key = network.groupKeys[group] val id = com.vitorpamplona.quartz.nip01Core.crypto.EventHasher.hashId(groups[group], template.createdAt, template.kind, template.tags, template.content) - val voucher = Event(id, groups[group], template.createdAt, template.kind, template.tags, template.content, + return Event(id, groups[group], template.createdAt, template.kind, template.tags, template.content, com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto.sign(id.hexToByteArray(), key.value.toByteArray()).toHex()) + } + + /** [group]'s voucher for [change], posted into the room by its role holder [poster]. */ + private fun vouch(change: ConfederationChangeStatements.Change, group: Int, poster: Int) = runBlocking { + val voucher = voucher(change, group) val device = devices.getValue(npub(secret(poster))) ConfederationProfileManager.recordVoucher(device.db, voucher) ConfederationSigningManager.postVoucher(device.db, device.person, voucher) @@ -207,13 +235,13 @@ class ConfederationSigningJvmTest { private val order get() = devices.values.sortedBy { it.person } private fun sweep(at: Instant = Clock.System.now(), who: List = order) = runBlocking { - who.flatMap { ConfederationProfileFollowThrough.sweep(it.db, it.person, it.nsec, at) } + who.flatMap { ConfederationChangeFollowThrough.sweep(it.db, it.person, it.nsec, at) } } - private fun profileAttempts(change: ConfederationProfileStatements.Change) = runBlocking { + private fun profileAttempts(change: ConfederationChangeStatements.Change) = runBlocking { devices.values.associate { d -> d.person to d.db.confederationCeremonyDao().getAttempts(confederation.id, d.person) - .filter { Event.fromJson(it.eventJson).id == change.profileId } + .filter { Event.fromJson(it.eventJson).id == change.eventId } } } @@ -231,7 +259,7 @@ class ConfederationSigningJvmTest { profileAttempts(change).forEach { (person, list) -> val attempt = list.single() assertEquals(ConfederationSigningStage.COMPLETE, attempt.stage, "${person.take(6)}: ${attempt.failureReason}") - assertTrue(!ConfederationSigningManager.isAwaitingApproval(attempt), "nobody is asked") + assertTrue(attempt.approvedAt != null || attempt.declinedAt != null, "nobody is asked: each device answered for its seats") } runBlocking { // Ekklesia did not vouch, so its admins' seats said no. @@ -241,7 +269,7 @@ class ConfederationSigningJvmTest { assertEquals(mapOf(groups[2] to ConfederationSigningEvents.NO), ConfederationRitualEvents.decodeByGroup(said!!.payload)) } devices.values.forEach { d -> - assertEquals(ConfederationProfileChangeState.PUBLISHED, ConfederationProfileManager.status(d.db, change.id)?.state, "on ${d.person.take(6)}") + assertEquals(ConfederationChangeState.PUBLISHED, ConfederationProfileManager.status(d.db, change.id)?.state, "on ${d.person.take(6)}") assertEquals("Atlas", ConfederationProfileManager.profiles(d.db, confederation.id).newestProfile?.name()) } assertEquals(1, started.single().let { a -> devices.values.first { it.person == a.userPublicKey } }.db.confederationDao().observeUnpublished().first() @@ -295,12 +323,12 @@ class ConfederationSigningJvmTest { vouch(change, group = 0, poster = 11) vouch(change, group = 1, poster = 21) pump() - val vouchers = runBlocking { ConfederationSigningManager.vouchersFor(proposer.db, ConfederationSigningManager.held(proposer.db, confederation.id)!!, change.profileId) } + val vouchers = runBlocking { ConfederationSigningManager.vouchersFor(proposer.db, ConfederationSigningManager.held(proposer.db, confederation.id)!!, change.eventId) } val a = order[0] val b = order[1] val attempts = listOf(a, b).map { d -> runBlocking { - ConfederationSigningManager.propose(d.db, confederation.id, d.person, 0, change.profile.tags, change.profile.content, d.nsec, change.profile.createdAt, vouchers) + ConfederationSigningManager.propose(d.db, confederation.id, d.person, 0, change.event.tags, change.event.content, d.nsec, change.event.createdAt, vouchers) } } pump() @@ -317,22 +345,21 @@ class ConfederationSigningJvmTest { } @Test - fun `enough willing admins in enough groups is all it takes`() { - val attempt = propose(TextNoteEvent.KIND, "The first words of a group of groups") + fun `two groups' vouchers sign a post, and the third group's seats say no`() { + val attempt = propose(vouching = listOf(0, 1)) pump() - // Two groups of three, two admins in each: Agora (11, 12) and Polis (21, 22). Nobody else answers. - approve(attempt.id, listOf(12, 21, 22)) - pump() - listOf(11, 12, 21, 22, 33).forEach { n -> - assertEquals(ConfederationSigningStage.COMPLETE, attempts(attempt.id).getValue(npub(secret(n)))?.stage) + attempts(attempt.id).forEach { (person, a) -> assertEquals(ConfederationSigningStage.COMPLETE, a?.stage, "${person.take(6)}: ${a?.failureReason}") } + runBlocking { + listOf(31, 32, 33).forEach { n -> + val said = proposer.db.confederationCeremonyDao().getSigningMessage(attempt.id, npub(secret(n)), ConfederationSigningEvents.AVAILABILITY) + assertEquals(mapOf(groups[2] to ConfederationSigningEvents.NO), ConfederationRitualEvents.decodeByGroup(said!!.payload)) + } } } @Test fun `a device that loses its nonces mid-attempt ends it for everybody`() { val attempt = propose() - pump() - approve(attempt.id, people - 11) pump(hold = { it.kind == ConfederationSigningEvents.NONCES }) ConfederationSigningManager.forgetSignersForTest() // every device restarts pump() @@ -342,19 +369,6 @@ class ConfederationSigningJvmTest { } } - @Test - fun `when too many decline, the proposer says so and it ends`() { - val attempt = propose() - pump() - runBlocking { - listOf(21, 22, 31, 32).map { devices.getValue(npub(secret(it))) }.forEach { ConfederationSigningManager.decline(it.db, attempt.id, it.nsec) } - } - pump() - val ended = attempts(attempt.id).getValue(proposer.person) - assertEquals(ConfederationSigningStage.FAILED, ended?.stage) - assertTrue(ended!!.failureReason!!.startsWith("Not enough admins"), ended.failureReason) - } - // ---- docs/confederation-room-removal.md, Phase 2: every message signed by its author ---------- /** A yes for [n]'s seats in [attemptId], signed by [signer], in an envelope as [n]'s device would send it. */ @@ -376,10 +390,16 @@ class ConfederationSigningJvmTest { on.db.confederationCeremonyDao().getSigningMessage(attemptId, npub(secret(by)), ConfederationSigningEvents.AVAILABILITY) } + /** Polis's 21, never online: whatever answer of theirs a test hands over is the only one. */ + private val quiet get() = devices.getValue(npub(secret(21))) + + /** The proposer's session held back: the attempt stays running, so an answer is still filed when it comes. */ + private val running: (Event) -> Boolean = { it.kind == ConfederationSigningEvents.SESSION } + @Test fun `a message changed after it was signed is dropped by whoever receives it`() { val attempt = propose() - pump() + pump(away = setOf(quiet), hold = running) val receiver = devices.getValue(npub(secret(31))) val changed = envelope(attempt.id, 21) { Event(it.id, it.pubKey, it.createdAt, it.kind, it.tags, it.content.replace("yes", "no"), it.sig) } runBlocking { ConfederationSigningManager.process(receiver.db, receiver.db.chatRoomDao().findChatRoomById(groups[2])!!, changed, receiver.person, receiver.nsec) } @@ -392,7 +412,7 @@ class ConfederationSigningJvmTest { @Test fun `a message signed by someone who holds no seat is dropped, and so is one signed for someone else`() { val attempt = propose() - pump() + pump(away = setOf(quiet), hold = running) val receiver = devices.getValue(npub(secret(31))) val outsider = PrivateKey(ByteArray(32).also { it[0] = 0x72; it[31] = 9 }) runBlocking { @@ -415,8 +435,6 @@ class ConfederationSigningJvmTest { fun `every role holder's messages are also in their own group's room`() { val attempt = propose() pump() - approve(attempt.id, people - 11) - pump() attempts(attempt.id).values.forEach { assertEquals(ConfederationSigningStage.COMPLETE, it?.stage, it?.failureReason) } devices.values.forEach { d -> val seatGroups = runBlocking { ConfederationSigningManager.held(d.db, confederation.id)!!.plan.seatsOf(d.person).map { it.group }.distinct() } @@ -467,8 +485,6 @@ class ConfederationSigningJvmTest { fun `no device holds a room of the confederation's, and the post is still signed everywhere`() { val attempt = propose() pump() - approve(attempt.id, people - 11) - pump() attempts(attempt.id).forEach { (person, a) -> assertEquals(ConfederationSigningStage.COMPLETE, a?.stage, "${person.take(6)}: ${a?.failureReason}") } devices.values.forEach { d -> assertEquals(null, runBlocking { d.db.chatRoomDao().findChatRoomById(confederation.id) }) } } @@ -477,8 +493,6 @@ class ConfederationSigningJvmTest { fun `each group's messages cross once, carried by its first admin`() { val attempt = propose() pump() - approve(attempt.id, people - 11) - pump() attempts(attempt.id).values.forEach { assertEquals(ConfederationSigningStage.COMPLETE, it?.stage, it?.failureReason) } admins.forEachIndexed { i, members -> val first = members.map { npub(secret(it)) }.min() @@ -490,9 +504,7 @@ class ConfederationSigningJvmTest { fun `with a group's first admin away, the next one carries twenty seconds later`() { val agoraFirst = devices.getValue(admins[0].map { npub(secret(it)) }.min()) val proposerHere = if (agoraFirst === proposer) devices.getValue(npub(secret(21))) else proposer - val attempt = runBlocking { ConfederationSigningManager.propose(proposerHere.db, confederation.id, proposerHere.person, TextNoteEvent.KIND, emptyArray(), "Said while one admin is away", proposerHere.nsec) } - pump(away = setOf(agoraFirst)) - approve(attempt.id, people.filter { npub(secret(it)) != agoraFirst.person && npub(secret(it)) != proposerHere.person }) + val attempt = propose(content = "Said while one admin is away", by = proposerHere) pump(away = setOf(agoraFirst)) // Two groups are enough to sign, so the post is signed; but Agora's answers have not left Agora. val agoraRest = admins[0].map { devices.getValue(npub(secret(it))) }.filter { it !== agoraFirst } @@ -518,13 +530,11 @@ class ConfederationSigningJvmTest { val demoted = devices.getValue(npub(secret(13))) assertTrue(runBlocking { demoted.db.inboxKeyDao().getKeys(groups[0], demoted.person) }.none { it.secretKey != null }, "no inbox key for a demoted founder") + // Agora's yes is 11's and 13's: 12 is away, so 13's seat is chosen. + val away = devices.getValue(npub(secret(12))) val attempt = propose() - pump() - // Agora's yes is 11's and 13's: 12 says no, so 13's seat is chosen. - runBlocking { ConfederationSigningManager.decline(devices.getValue(npub(secret(12))).db, attempt.id, devices.getValue(npub(secret(12))).nsec) } - approve(attempt.id, listOf(13, 21, 22, 23, 31, 32, 33)) - pump() - stagesOf(attempt.id).forEach { (who, said) -> assertEquals(ConfederationSigningStage.COMPLETE, said?.first, "$who: ${said?.second}") } + pump(away = setOf(away)) + stagesOf(attempt.id, devices.values.filter { it !== away }).forEach { (who, said) -> assertEquals(ConfederationSigningStage.COMPLETE, said?.first, "$who: ${said?.second}") } val session = runBlocking { proposer.db.confederationCeremonyDao().getSigningMessage(attempt.id, proposer.person, ConfederationSigningEvents.SESSION) } assertNotNull(runBlocking { proposer.db.confederationCeremonyDao().getSigningMessage(attempt.id, demoted.person, ConfederationSigningEvents.PARTIALS) }, "13's partial reached the proposer: ${session?.payload}") } @@ -536,14 +546,12 @@ class ConfederationSigningJvmTest { val removed = devices.getValue(npub(secret(13))) val attempt = propose() pump() - approve(attempt.id, people - 11 - 13) - pump() assertEquals(null, runBlocking { removed.db.confederationCeremonyDao().getAttempt(attempt.id) }, "out of Agora's room, out of the confederation's signing") stagesOf(attempt.id, devices.values.filter { it !== removed }).forEach { (who, said) -> assertEquals(ConfederationSigningStage.COMPLETE, said?.first, "$who: ${said?.second}") } } @Test - fun `a confederation signs only its profile and its posts`() { + fun `a confederation signs only its profile, its posts and its charter`() { assertFailsWith { propose(kind = 30023, content = "long form") } assertFailsWith { propose(kind = TextNoteEvent.KIND, content = " ") } } @@ -553,51 +561,29 @@ class ConfederationSigningJvmTest { // ---- docs/confederation-room-removal.md, Phase 6: the confederation's screen takes over ---------- @Test - fun `a post is asked of each role holder in their own group's room, and the ask is theirs`() = runBlocking { + fun `a post is asked of nobody, and each role holder's room says whose word it is signed on`() = runBlocking { val attempt = propose() pump() - val polis = devices.getValue(npub(secret(21))) - val asked = polis.db.chatMessageDao().getChatMessagesByChatRoomId(groups[1]).map { it.chatMessage } - .single { it.messageType == mobi.giza.compose.database.model.ChatMessage.TYPE_CONFEDERATION_SIGNING_ASKED } - assertEquals(attempt.id, asked.frostSigningSessionId, "the line opens the attempt") - assertTrue(asked.isUserMessage, "an ask is to this device's owner") - assertEquals(polis.person, asked.senderPublicKey) - assertTrue(mobi.giza.compose.database.model.ChatMessage.TYPE_CONFEDERATION_SIGNING_ASKED in mobi.giza.compose.notifications.NotificationClassifier.NEEDS_YOU) - val proposerLines = proposer.db.chatMessageDao().getChatMessagesByChatRoomId(groups[0]).map { it.chatMessage.messageType } - assertTrue(mobi.giza.compose.database.model.ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED in proposerLines, "the proposer is told, not asked: $proposerLines") - assertTrue(mobi.giza.compose.database.model.ChatMessage.TYPE_CONFEDERATION_SIGNING_ASKED !in proposerLines) + devices.values.forEach { d -> + val group = groups[admins.indexOfFirst { members -> members.any { npub(secret(it)) == d.person } }] + val lines = d.db.chatMessageDao().getChatMessagesByChatRoomId(group).map { it.chatMessage } + assertTrue(lines.none { it.messageType == mobi.giza.compose.database.model.ChatMessage.TYPE_CONFEDERATION_SIGNING_ASKED }, "${d.person.take(6)} was not asked") + val signing = lines.single { it.messageType == mobi.giza.compose.database.model.ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED && it.frostSigningSessionId == attempt.id } + assertTrue(signing.content.startsWith("Signing a post, endorsed by"), signing.content) + assertTrue(!signing.isUserMessage) + } } @Test fun `a signed post is owed to relays by every device that signed it`() = runBlocking { val attempt = propose() pump() - approve(attempt.id, people - 11) - pump() val signed = Event.fromJson(attempts(attempt.id).getValue(proposer.person)!!.signedEventJson!!) devices.values.forEach { d -> assertTrue(d.db.confederationDao().observeUnpublished().first().any { it.id == signed.id }, "${d.person.take(6)} owes it") } } - @Test - fun `the confederation's screen lists what is waiting on you first, then what is running, then the last few ended`() { - fun attempt(id: Char, stage: ConfederationSigningStage, approved: Boolean, at: Long) = mobi.giza.compose.database.model.ConfederationSigningAttempt( - id = id.toString().repeat(64), confederationId = confederation.id, proposerPublicKey = proposer.person, userPublicKey = proposer.person, - eventJson = "{}", stage = stage, approvedAt = if (approved) Instant.fromEpochSeconds(at) else null, - createdAt = Instant.fromEpochSeconds(at), updatedAt = Instant.fromEpochSeconds(at), - ) - val shown = mobi.giza.compose.ui.view.model.ConfederationViewModel.attemptsToShow( - listOf(attempt('a', ConfederationSigningStage.NONCES, approved = true, at = 30)) + - attempt('b', ConfederationSigningStage.SELECTING, approved = false, at = 10) + - (0 until 7).map { attempt('c' + it, ConfederationSigningStage.COMPLETE, approved = true, at = 100L + it) } - ) - assertEquals(listOf('b', 'a'), shown.take(2).map { it.id.first() }, "waiting on you, then running") - assertTrue(shown[0].awaitingYou) - assertEquals(2 + mobi.giza.compose.ui.view.model.ConfederationViewModel.ENDED_SHOWN, shown.size) - assertEquals('c' + 6, shown[2].id.first(), "the newest ended first") - } - @Test fun `once formed, the key ceremony's room leads to the confederation`() = runBlocking { val device = devices.getValue(npub(secret(11))) @@ -616,10 +602,8 @@ class ConfederationSigningJvmTest { 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, confederation.id, proposer.person, kind, tags, content, proposer.nsec) } - pump() - approve(attempt.id, people - 11) + val (tags, content) = runBlocking { assertNotNull(ConfederationProfileManager.charterTemplate(proposer.db, confederation.id)) } + val attempt = propose(kind = ConfederationCharterEvent.KIND, content = content, tags = tags) pump() attempts(attempt.id).values.forEach { assertEquals(ConfederationSigningStage.COMPLETE, it?.stage, it?.failureReason) } @@ -643,7 +627,7 @@ class ConfederationSigningJvmTest { val wrong = ConfederationCharterEvent.assembleTags(confederation.name, groups.take(2)) assertFailsWith { runBlocking { - ConfederationSigningManager.propose(proposer.db, confederation.id, proposer.person, ConfederationCharterEvent.KIND, wrong, "x", proposer.nsec) + ConfederationSigningManager.propose(proposer.db, confederation.id, proposer.person, ConfederationCharterEvent.KIND, wrong, "x", proposer.nsec, vouchers = emptyList()) } } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileScreensJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileScreensJvmTest.kt index 6e6ebaeb..275044d8 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileScreensJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileScreensJvmTest.kt @@ -23,19 +23,22 @@ import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.extensions.toHex import mobi.giza.compose.managers.ConfederationStatementFixture import mobi.giza.compose.nostr.GroupNostrProfile -import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus -import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatus +import mobi.giza.compose.nostr.confederation.ConfederationChangeStatements import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.ConfederationRepository -import mobi.giza.compose.repository.ProfileChangeProblem +import mobi.giza.compose.repository.ChangeProblem import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost import mobi.giza.compose.ui.theme.GizaTheme -import mobi.giza.compose.ui.view.model.ConfederationProfileChangeViewModel -import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState +import mobi.giza.compose.ui.view.model.ConfederationChangeViewModel +import mobi.giza.compose.ui.view.state.ConfederationChangeUIState import mobi.giza.compose.ui.view.state.ConfederationUIState import mobi.giza.compose.ui.view.state.EditConfederationProfileUIState -/** A confederation's screen, its profile form and a change to its profile, as a member meets them (docs/confederation-profile.md, Phase 4). */ +/** + * A confederation's screen, its profile form and a proposal for it to sign something, as a member + * meets them (docs/confederation-profile.md, Phase 4; docs/confederation-proposals.md). + */ @OptIn(ExperimentalTestApi::class) class ConfederationProfileScreensJvmTest { private val agora = ConfederationStatementFixture.npub(1) @@ -55,22 +58,22 @@ class ConfederationProfileScreensJvmTest { GroupNostrProfile.of(GroupSignedEvent.fromEvent(event, chatRoomId = atlas), atlas)!! } - private fun change(by: String, content: String = """{"name":"Atlas of the Coast","about":"Two groups"}""") = - ConfederationProfileStatements.parseChange( - ConfederationProfileStatements.change(by, listOf(if (by == agora) polis else agora), atlas, 2, signedProfile.signedEvent.id, emptyArray(), content, now, now + 1000) + private fun change(by: String, content: String = """{"name":"Atlas of the Coast","about":"Two groups"}""", kind: Int = 0) = + ConfederationChangeStatements.parseChange( + ConfederationChangeStatements.change( + by, listOf(if (by == agora) polis else agora), atlas, 2, signedProfile.signedEvent.id.takeIf { kind == 0 }, emptyArray(), content, now, now + 1000, kind, + ) )!! - private fun status(change: ConfederationProfileStatements.Change) = - ConfederationProfileChangeStatus.of(change, emptyList(), emptyList(), null, published = false, now = now + 1) + private fun status(change: ConfederationChangeStatements.Change) = + ConfederationChangeStatus.of(change, emptyList(), emptyList(), null, published = false, now = now + 1) private fun loaded( readsChanges: Boolean = true, - problem: ProfileChangeProblem? = null, - changes: List = emptyList(), + problem: ChangeProblem? = null, + changes: List = emptyList(), posts: List = emptyList(), - holdsSeat: Boolean = false, charterSigned: Boolean = false, - attempts: List = emptyList(), ) = ConfederationUIState.Loaded( localChatRoom = localChatRoom, confederationId = atlas, @@ -86,15 +89,13 @@ class ConfederationProfileScreensJvmTest { problem = problem, names = mapOf(agora to "This group", polis to "Polis"), posts = posts, - holdsSeat = holdsSeat, charterSigned = charterSigned, - attempts = attempts, ) // ---- the confederation's screen ---------------------------------------------------------------- @Test - fun `an admin sees the profile, the groups with who holds their roles, the changes and the way to edit`() = renderConfederation( + fun `an admin sees the profile, the groups with who holds their roles, the proposals and the way to edit`() = renderConfederation( loaded(changes = listOf(status(change(by = polis)))) ) { onNodeWithText("Two groups").assertIsDisplayed() @@ -102,26 +103,30 @@ class ConfederationProfileScreensJvmTest { onNodeWithText("2 admins hold its key").assertIsDisplayed() onNodeWithText("alice, bob").assertIsDisplayed() onNodeWithText("2 of 2 groups to act").assertIsDisplayed() + onNodeWithText("Proposals").assertIsDisplayed() onNodeWithText("Atlas of the Coast").assertIsDisplayed() + onNodeWithText("Profile · Open").assertIsDisplayed() onNodeWithText("Proposed by Polis").assertIsDisplayed() onNodeWithText("Endorsed by 1 of the 2 groups it needs").assertIsDisplayed() onNodeWithText("Edit profile").assertIsEnabled() } @Test - fun `a member who is not an admin sees what is public, and why the changes are missing`() = renderConfederation(loaded(readsChanges = false)) { + fun `a member who is not an admin sees what is public, and why the proposals are missing`() = renderConfederation(loaded(readsChanges = false)) { onNodeWithText("Two groups").assertIsDisplayed() - onNodeWithText("Only the group's admins see proposed changes.").assertIsDisplayed() + onNodeWithText("Only the group's admins see proposals.").assertIsDisplayed() onAllNodesWithText("Edit profile").assertCountEquals(0) } @Test - fun `an admin who cannot propose is told why`() = renderConfederation(loaded(problem = ProfileChangeProblem.GroupWithoutInbox("Polis"))) { + fun `an admin who cannot propose is told why, and can propose nothing`() = renderConfederation(loaded(problem = ChangeProblem.GroupWithoutInbox("Polis"))) { onNodeWithText("Polis has no inbox, so it cannot be asked").assertIsDisplayed() onNodeWithText("Edit profile").assertIsNotEnabled() + onNodeWithText("Add post").assertIsNotEnabled() + onNodeWithText("Propose the charter").assertIsNotEnabled() } - // ---- docs/confederation-room-removal.md, Phase 6: posts, the charter, and signing ------------------ + // ---- docs/confederation-proposals.md: posts and the charter are proposals too ------------------ private val post = mobi.giza.compose.nostr.GroupPost( mobi.giza.compose.database.model.GroupSignedEvent( @@ -131,25 +136,40 @@ class ConfederationProfileScreensJvmTest { ) ) - private val asked = ConfederationUIState.Attempt( - id = "s".repeat(64), - event = com.vitorpamplona.quartz.nip01Core.core.Event("e".repeat(64), atlas, 1, 1, emptyArray(), "Words for the record", ""), - stage = mobi.giza.compose.database.model.ConfederationSigningStage.SELECTING, - awaitingYou = true, - ) - @Test - fun `someone who holds a seat sees the posts, can add one, can propose the charter, and sees what waits on them`() = - renderConfederation(loaded(posts = listOf(post), holdsSeat = true, attempts = listOf(asked))) { + fun `an admin sees the posts, and proposes one or the charter from the group, with no signing of their own to answer`() = + renderConfederation(loaded(posts = listOf(post))) { onNodeWithText("The first words of a group of groups").assertIsDisplayed() onNodeWithText("Add post").assertIsEnabled() - onNodeWithText("Propose the charter").assertIsDisplayed() - onNodeWithText("Waiting for your answer").assertIsDisplayed() + onNodeWithText("Propose the charter").assertIsEnabled() + onAllNodesWithText("Signing").assertCountEquals(0) + onAllNodesWithText("Waiting for your answer").assertCountEquals(0) onAllNodesWithText("Open the confederation's room").assertCountEquals(0) } @Test - fun `a member who holds no seat reads the posts and the charter, and is offered nothing to sign`() = + fun `a post and the charter are listed among the proposals, by what they would sign`() = renderConfederation( + loaded(changes = listOf(status(change(by = polis, content = "Words for the record", kind = 1)), status(charterChange()))) + ) { + onNodeWithText("Words for the record").assertIsDisplayed() + onNodeWithText("Post · Open").assertIsDisplayed() + onNodeWithText("The confederation's charter").assertIsDisplayed() + onNodeWithText("Charter · Open").assertIsDisplayed() + onNodeWithText("The charter has been proposed, and is signed once enough groups endorse it").assertIsDisplayed() + onAllNodesWithText("Propose the charter").assertCountEquals(0) + } + + private fun charterChange() = ConfederationChangeStatements.parseChange( + ConfederationChangeStatements.change( + agora, listOf(polis), atlas, 2, null, + mobi.giza.compose.nostr.confederation.ConfederationCharterEvent.assembleTags("Atlas", listOf(agora, polis), 2), + mobi.giza.compose.nostr.confederation.ConfederationCharterEvent.content("Atlas", 2), now, now + 1000, + mobi.giza.compose.nostr.confederation.ConfederationKinds.CHARTER, + ) + )!! + + @Test + fun `a member who is not an admin reads the posts and the charter, and is offered nothing to propose`() = renderConfederation(loaded(readsChanges = false, charterSigned = true)) { onNodeWithText("The confederation has posted nothing yet").assertIsDisplayed() onNodeWithText("The confederation has signed its charter, naming its groups").assertIsDisplayed() @@ -159,19 +179,19 @@ class ConfederationProfileScreensJvmTest { } @Test - fun `with no charter and no seat, it says there is none`() = renderConfederation(loaded()) { + fun `with no charter, a member who is not an admin is told there is none`() = renderConfederation(loaded(readsChanges = false)) { onNodeWithText("The confederation has no charter yet").assertIsDisplayed() } - // ---- a change ---------------------------------------------------------------------------------- + // ---- a proposal -------------------------------------------------------------------------------- - private fun changeState(change: ConfederationProfileStatements.Change, pending: String? = null) = ConfederationProfileChangeUIState.Loaded( + private fun changeState(change: ConfederationChangeStatements.Change, pending: String? = null) = ConfederationChangeUIState.Loaded( localChatRoom = localChatRoom, status = status(change), confederationName = "Atlas", - differences = ConfederationProfileChangeViewModel.differences( + differences = if (!change.isProfile) emptyList() else ConfederationChangeViewModel.differences( signedProfile.metadata, - mobi.giza.compose.managers.ConfederationProfileRefusal.metadataOf(change.profile), + mobi.giza.compose.managers.ConfederationChangeRefusal.metadataOf(change.event), ), names = mapOf(agora to "This group", polis to "Polis"), canAnswer = true, @@ -186,12 +206,23 @@ class ConfederationProfileScreensJvmTest { onNodeWithText("Proposed it").assertIsDisplayed() onNodeWithText("Endorse").assertIsDisplayed() onNodeWithText("Object").assertIsDisplayed() - onAllNodesWithText("Withdraw the change").assertCountEquals(0) + onAllNodesWithText("Withdraw the proposal").assertCountEquals(0) } @Test - fun `this group's own change can be withdrawn, not endorsed`() = renderChange(changeState(change(by = agora))) { - onNodeWithText("Withdraw the change").assertIsDisplayed() + fun `another group's post is shown as its words, and answered the same way`() = + renderChange(changeState(change(by = polis, content = "Words for the record", kind = 1))) { + onNodeWithText("Proposal").assertIsDisplayed() + onNodeWithText("Post · Open").assertIsDisplayed() + onNodeWithText("Words for the record").assertIsDisplayed() + onAllNodesWithText("Was:", substring = true).assertCountEquals(0) + onNodeWithText("Endorse").assertIsDisplayed() + onNodeWithText("Object").assertIsDisplayed() + } + + @Test + fun `this group's own proposal can be withdrawn, not endorsed`() = renderChange(changeState(change(by = agora))) { + onNodeWithText("Withdraw the proposal").assertIsDisplayed() onAllNodesWithText("Endorse").assertCountEquals(0) } @@ -233,8 +264,8 @@ class ConfederationProfileScreensJvmTest { ) } - private fun renderChange(state: ConfederationProfileChangeUIState, assertions: ComposeUiTest.() -> Unit) = render(assertions) { - ConfederationProfileChangeScreen( + private fun renderChange(state: ConfederationChangeUIState, assertions: ComposeUiTest.() -> Unit) = render(assertions) { + ConfederationChangeScreen( activeUserPublicKey = "a".repeat(64), chatRoomId = agora, changeId = "c".repeat(64), initialUIState = state, chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, confederationRepository = ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY, onNavigateToRoute = {}, onNavigateBack = {}, 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 58fefd6c..e2a765d9 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 @@ -24,10 +24,6 @@ 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.ConfederationSigningAnswer -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 @@ -343,94 +339,4 @@ class ConfederationScreensJvmTest { } assertions() } - - private fun signing( - stage: ConfederationSigningStage, - approved: Boolean, - failure: String? = null, - kind: Int = 1, - answers: List = listOf( - ConfederationSigningAnswer("Ana", approvedFor = listOf("Agora")), - ConfederationSigningAnswer("Bo"), - ConfederationSigningAnswer("Cy", declinedFor = listOf("Polis")), - ), - ) = 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, kind, emptyArray(), - if (kind == 0) """{"name":"Atlas"}""" else "The first words of a group of groups", "", - ), - answers = answers, - 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 `somebody seated in several groups is shown answering for each, not as declining`() = - renderSigning( - signing( - ConfederationSigningStage.NONCES, approved = true, - answers = listOf(ConfederationSigningAnswer("Ana", approvedFor = listOf("Agora", "Polis"), declinedFor = listOf("Ekklesia"))), - ) - ) { - onNodeWithText("Approved for Agora, Polis").assertIsDisplayed() - onNodeWithText("Declined for Ekklesia").assertIsDisplayed() - onAllNodesWithText("Declined").assertCountEquals(0) - } - - @Test - fun `on a profile, a group that had not endorsed it yet is not a refusal`() = - renderSigning( - signing( - ConfederationSigningStage.NONCES, approved = true, kind = 0, - answers = listOf( - ConfederationSigningAnswer("Ana", approvedFor = listOf("Agora"), declinedFor = listOf("Ekklesia")), - ConfederationSigningAnswer("Cy", declinedFor = listOf("Ekklesia")), - ), - ) - ) { - onNodeWithText("Approved for Agora").assertIsDisplayed() - onAllNodesWithText("Not for Ekklesia, which had not endorsed it when signing began").assertCountEquals(2) - onAllNodesWithText("Declined", substring = true).assertCountEquals(0) - } - - @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/README.md b/docs/README.md index ecbd5d39..4263482c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -19,6 +19,7 @@ the [retired](./retired/) notes now. | [confederation-without-coordinator.md](./confederation-without-coordinator.md) | a confederation nobody coordinates: a phased plan, built but for its device run and behind flags that are off in release. The proposal and every answer travel as NIP-17 messages between the groups' NIP-4E inboxes, each sealed by its group's quorum, so every admin of every group reads every admin list and computes the outcome, and the key ceremony derives its room and session seed and computes the coordinator's broadcast on every device. Covers why a group could be the DKG's coordinator and does not need to be, why the admin lists stop being a payload encrypted to one person, why a confederation names at most twelve groups, how a group that says different things to different groups is caught, and who makes the confederation's room when nobody is in charge | | [confederation-profile.md](./confederation-profile.md) | a formed confederation's nostr profile, decided by its groups: a phased plan, built but for its device run and behind flags that are off in release. The confederation gets its own screen, reached from each member group's screen, and an edit there is a statement by the editing group, sealed by its quorum and sent to every member group's inbox, which the others endorse or object to by their own quorums. Once `T` groups have endorsed, each group's signed voucher is a role holder's consent, so the confederation signs and publishes the profile with nobody asked again. Covers why the rule is `T` of `N`, why a transferable voucher is needed beside the non-transferable seals, who starts the signing, and how the confederation's room and the key ceremony's room come to say what they are | | [confederation-room-removal.md](./confederation-room-removal.md) | taking away the confederation's own Marmot room: a phased plan, built but for its device run and behind flags that are off in release. A role holder's signing messages go into their own group's room, each group's admins carry them between groups through the inboxes, one at a time in order, and the posts, charter and signing attempts the room offered move to the confederation's screen. Covers why the nested signing still has to cross between groups every round, why each message becomes a signed event so it can be carried, why a demoted founder keeps signing and a removed one stops, and dropping the rooms already on devices while refusing a Welcome back into one | +| [confederation-proposals.md](./confederation-proposals.md) | everything a formed confederation signs -- its profile, its posts, its charter -- decided by its groups the way its profile already was, behind flags that are off in release. A post or the charter is a 9435 like a profile change, endorsed or objected to by each group's quorum, and signed with nobody asked once `T` groups have vouched; the per-person approve and decline, and the Signing screen, are gone. The confederation's screen lists them all as Proposals | | [confederation-upstream.md](./confederation-upstream.md) | the work below Giza that unblocks the confederation's Parts B and C: a phased plan, not built, across secp256k1-zkp, secp256k1-kmp and bitcoin-kmp. Covers why the one-process DKG and signing cannot simply be exposed step by step (the coordinator derives everyone's key state, acknowledgment is signed before the share is stored, nonce randomness is derived from the session id), why every DKG step can stay stateless, the storage contract a device follows, and Prefractal as an all-groups-must-sign path that needs no upstream work | | [automatic-key-ceremony.md](./automatic-key-ceremony.md) | joining is the only approval: a phased plan, built but for its device session, that makes a key ceremony run by itself after a member joins. Covers why contributing and confirming were never decisions a person could add to, the resume sweep that replaces the tap, the coordinator's follow-up steps and the one key state a device can sign without asking, and why abandon stays | | [ceremony-creation.md](./ceremony-creation.md) | one place to start a key ceremony — how joining a subgroup's ceremony opened a second one for the parent room, the screen that showed a ceremony and offered to start one in the same button, and the removal of the nip30303 documents, whose kinds collided with the ceremony's, leaving the member chronicle with nothing to carry and nothing to say | diff --git a/docs/confederation-profile.md b/docs/confederation-profile.md index 914a3050..dfc90da2 100644 --- a/docs/confederation-profile.md +++ b/docs/confederation-profile.md @@ -740,7 +740,7 @@ and the one-minute sweep are guesses until a device run says otherwise. ## Out of scope -- Moving posts (kind:1) and the charter (9434) onto group statements. +- Moving posts (kind:1) and the charter (9434) onto group statements. **Since done:** [confederation-proposals.md](./confederation-proposals.md). - Governance of the confederation's room and roster: admins added later, admins removed. - A role holder's per-confederation setting to be asked each time (appendix). - Threshold-ECDH member groups, as in the coordinator-free plan. diff --git a/docs/confederation-proposals.md b/docs/confederation-proposals.md new file mode 100644 index 00000000..56d8d4ea --- /dev/null +++ b/docs/confederation-proposals.md @@ -0,0 +1,117 @@ +# Everything a confederation signs, decided by its groups + +A formed confederation signs three things: its profile (kind:0), its posts (kind:1) and its +charter (9434). [confederation-profile.md](./confederation-profile.md) put the profile on a path +where the **groups** decide. One group proposes, the others endorse or object, each by its own +quorum, and the confederation signs once `T` groups have vouched, with nobody asked again. Posts and +the charter stayed on the older path, listed there under *Out of scope*: one role holder started a +signing attempt, and every other role holder approved or declined it **as a person**, on the +confederation's **Signing** screen. + +This change moves posts and the charter onto the profile's path and closes the older one. The +confederation's screen calls the result **Proposals**. + +Written against `4b36ce21`, on 2026-11-23, behind `ExperimentalFeatures.confederation` and +`ExperimentalFeatures.groupInbox`, both off in release. Nothing here has run on a device. Paths +starting `K/` are under `composeApp/src/commonMain/kotlin/mobi/giza/compose/`. + +--- + +## What was wrong + +- **Two answers to one question.** "Should the confederation sign this?" was decided by groups for a + profile and by people for a post. A role holder who would never have got their group's quorum + could still sign a post for the confederation, which is the problem confederation-profile.md + fixed for profiles. +- **Two screens for one thing.** Profile changes listed what the groups had said. The Signing + section listed signing attempts and their per-person answers. A post never appeared under + profile changes, and a profile's signing appeared under Signing as an attempt nobody could answer. +- **The ask went to the wrong people.** Only role holders, the admins at formation, were asked about + a post. An admin who joined a group later was never asked. A demoted founder still was. + +--- + +## Decisions + +### P1. A 9435 carries any event the confederation signs + +`ConfederationChangeStatements` (formerly `ConfederationProfileStatements`) builds and parses a +9435 whose content is an unsigned kind:0, kind:1 or 9434 authored by the confederation +(`ConfederationKinds.SIGNABLE`). The `base` tag is for a kind:0 only. A post or charter that carries +one is refused at parse time. + +The `profile` tag on 9436, 9437 and 9438 keeps its name, and now names the proposed event whatever its +kind. A voucher is a signed event, so renaming the tag would leave devices on either side of the change +unable to read each other's vouchers. The constant is `EVENT_TAG = "profile"`, with a note. + +### P2. What a group's signer refuses, by kind + +`ConfederationChangeRefusal.changeRefusal`: + +| kind | refused when | +|---|---| +| kind:0 | unreadable, or not editing the newest profile held (as before) | +| kind:1 | blank: `BLANK_POST` | +| 9434 | not naming exactly the confederation's groups, name and threshold (`UNTRUE_CHARTER`), or a charter is already signed (`CHARTERED`) | + +### P3. Nothing is signed without `T` groups' vouchers + +`ConfederationSigningManager.refusalOf` asks for vouchers from `T` groups for **every** kind, not +only a kind:0 (`THROUGH_GROUPS`). `propose` takes its vouchers as a required argument. An attempt +over any kind asks nobody: each device says yes for each of its seats whose group vouched and no for +the rest (`publishAvailabilityByGroup`). `approve`, `decline`, `isAwaitingApproval` and +`charterTemplate` are gone from the signing manager. `ChatMessage.TYPE_CONFEDERATION_SIGNING_ASKED` +is no longer written and has left `NotificationClassifier.NEEDS_YOU`. The constant stays, because a +device may hold such lines. + +`ConfederationChangeFollowThrough` (formerly `…ProfileFollowThrough`) already swept every 9435. It +now starts the signing of a post or a charter by the same order and backoff as a profile. + +### P4. Where a proposal stands, by kind + +`ConfederationChangeStatus.of` takes `newestOfKind` in place of `newestProfile`: + +- a kind:0 is `SUPERSEDED` by a newer signed profile, as before; +- a charter is `SUPERSEDED` once any other charter is signed; +- a post is never superseded. + +`PUBLISHED` means the device holds the event signed, whatever its kind +(`ConfederationProfileManager.Signed`). A charter is filed under its author rather than the +confederation's column, so `observeChanges` watches the charters beside the confederation's rows. + +### P5. The screens + +- **`ConfederationScreen`.** "Profile changes" is now **Proposals**. It lists every kind, each card + headed by its kind and state ("Post · Open"). **Add post** and **Propose the charter** are offered + to the same people as **Edit profile**: an admin of this group who holds its inbox key, with every + other group reachable (`ChangeProblem`, formerly `ProfileChangeProblem`). Both open the group's + signing session. The **Signing** section is gone. While a charter proposal is open, the charter + section says so instead of offering a second one. +- **`ConfederationChangeScreen`** (formerly `…ProfileChangeScreen`), titled **Proposal**. Under + "What it would sign" it shows a profile as its field-by-field difference, a post as its words, and + the charter as itself. Endorse, Object and Withdraw are unchanged. +- **`ConfederationSigningScreen`** is deleted, with its view model, state and route. A signing line in + a group's room now opens the proposal. A line written before this change carries an attempt's id, + and `ConfederationRepository.proposalIdOf` reads that id as the proposal the attempt was signing. +- **`AddGroupPostScreen`** with a `confederationId` proposes from the group + (`ChatRepository.proposeAsConfederation(localChatRoom, …)`) and goes to the group's FROST session. + +--- + +## Who is asked what, now for everything + +| step | who is asked | automatic after that | +|---|---|---| +| propose (a profile, a post, the charter) | one admin of group A, on the confederation's screen; then A's quorum | the seals to every group, A's voucher | +| B answers | one admin of B; then B's quorum | B's voucher | +| `T` groups have vouched | nobody | the first role holder in order starts the signing; every seat answers by its group's voucher | +| signed | nobody | filed, owed to relays, a line in every member group's room | + +--- + +## Not done + +- No device run, as for the plans before it. +- Older devices running a build from before this change will decline a 9435 that carries a post or + a charter (`SHAPE`), out loud. That is the intended failure while both builds exist, and both + flags are off in release.