diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index b6c68bbc..ad569820 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -114,7 +114,6 @@
Rotate shares without them?
They are out of the room, but their share of the group key still helps sign until the shares are rotated without them. Rotating asks every remaining member to take part. Shares held before the rotation stop working once every device has deleted them.
Rotate shares
- Rotate the shares?
Taking part: %1$s
Left out until they are brought back: %1$s
Left out for good: %1$s
@@ -147,7 +146,15 @@
The last rotation ended: %1$s
Help bring a member back
Sent to the group
- Share rotation proposed; every remaining member is asked to take part
+ A rotation is in progress
+ Waiting for the group to sign the new shares before another rotation
+ This device is catching up with the group's latest rotation
+ Removal sent. They still hold a share; rotate without them once the group has signed the current shares.
+ Ask the group to sign the new shares
+ Asked the group to sign the new shares
+ See the proposal
+ Share rotation proposed; every other member is asked to take part
+ Rotate the group's shares?
Library
Lightning invoice
Open in a wallet app
@@ -499,4 +506,16 @@
Waiting on %1$s since %2$s.
If they have stopped answering, any member can abandon the ceremony. No key is made, and the group can start again.
Open the room
+ Admin
+ Founding members aren't admins
+ %1$s took part in the key ceremony that made this group, but this room doesn't list them as admins.
+ Make them admins
+ Asked the group to make them admins
+ Not every founding member was invited
+ %1$s took part in the key ceremony that made this group, but the invitation to this room never went out.
+ Invite them
+ Invited them to the room
+ Some of them haven't published a key package yet
+ Admin room
+ Every member of this group is an admin there.
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt
index e0d28947..9f98ea80 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt
@@ -7,6 +7,7 @@ import com.vitorpamplona.crypto.random.RandomInstance
import com.vitorpamplona.marmot.appComponents.AppComponentIds
import com.vitorpamplona.marmot.foundation.appEvents.MarmotAppEvent
import com.vitorpamplona.marmot.groups.MlsGroupManager
+import com.vitorpamplona.marmot.appComponents.AdminPolicyV1
import com.vitorpamplona.marmot.groups.currentAdminIdentities
import com.vitorpamplona.marmot.groups.currentGroupState
import com.vitorpamplona.marmot.groups.isLocalAdmin
@@ -862,6 +863,31 @@ abstract class MarmotOutboundDao(
publishGatedCommit(localChatRoom) { manager, id -> manager.stageRemoveMember(id, leafIndex) }
}
+ /**
+ * Adds [publicKeys] to a current-profile room's admin policy, as an admin.
+ *
+ * Additions only. The policy committed is the one the group holds now plus
+ * these -- never a list built somewhere else -- so an admin already there is
+ * never dropped by it. One commit for all of them, through the publish gate
+ * like every other governance change. Nothing to do when every one is already
+ * listed. docs/robust-group-admins.md, Phase 3.
+ */
+ @Transaction
+ open suspend fun addAdmins(localChatRoom: LocalChatRoom, publicKeys: Set) {
+ require(localChatRoom.chatRoom.marmotProfile() == MarmotProfile.CURRENT) { "Only a current-profile room can change its admins" }
+ val group = database.marmotEngine.groupFor(localChatRoom.routingId)
+ ?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}")
+
+ val current = group.currentAdminIdentities()
+ val added = publicKeys - current
+ if (added.isEmpty()) return
+
+ val policy = AdminPolicyV1.ofHex(current + added).encode()
+ publishGatedCommit(localChatRoom) { manager, id ->
+ manager.stageAppDataUpdate(id, AdminPolicyV1.COMPONENT_ID, policy)
+ }
+ }
+
/**
* Disbands a current-profile room, as an admin.
*
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt
index 80a643f1..7facdce2 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt
@@ -60,6 +60,8 @@ import mobi.giza.compose.exceptions.MarmotMissingKeyPackageBundleException
import mobi.giza.compose.exceptions.MarmotMissingNostrGroupDataExtension
import mobi.giza.compose.exceptions.MarmotNotMemberOfChatGroupException
import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.managers.AdminFlags
+import mobi.giza.compose.managers.FoundingAdmins
import mobi.giza.compose.managers.ChillDkgRitualManager
import mobi.giza.compose.managers.ShareRefreshManager
import mobi.giza.compose.managers.ShareRepairManager
@@ -899,6 +901,17 @@ abstract class NostrDao(
participants
)
+ // The admins, from the group context this device
+ // was welcomed into. Without it a joiner's rows
+ // flagged nobody until some later commit arrived,
+ // which in a robust group's admin room may be
+ // never -- docs/robust-group-admins.md, Phase 2.
+ AdminFlags.reconcile(
+ database = database,
+ chatRoomId = nostrGroupId,
+ mlsGroup = group,
+ )
+
// Save ChatRoom Relays...
participants.filter { it.participantPublicKey != userPublicKey }.forEach { participant ->
val publicKey = participant.participantPublicKey
@@ -960,6 +973,17 @@ abstract class NostrDao(
chatRoomId = nostrGroupId
)
+ // And with the state on file, whether the room
+ // names every member of that ceremony as an
+ // admin -- this device's own record against the
+ // creator's list. docs/robust-group-admins.md,
+ // Phase 3.
+ FoundingAdmins.announceIfMissing(
+ database = database,
+ chatRoomId = nostrGroupId,
+ userPublicKey = userPublicKey,
+ )
+
// Where is the decoded welcome message...
// TODO: Sync GroupEvents/Messages...
// database.chatMessageDao().upsert(
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 a0907524..ef1c736b 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
@@ -577,6 +577,14 @@ data class ChatMessage(
*/
const val TYPE_CHANGE_REJECTED = "changeRejected"
+ /**
+ * The admin room this device was welcomed into does not name every member
+ * of the ceremony that made its key as an admin. Derived at the Welcome
+ * from this device's own record of the ceremony, never received, and
+ * written once. docs/robust-group-admins.md, Phase 3.
+ */
+ const val TYPE_FOUNDING_ADMINS_MISSING = "foundingAdminsMissing"
+
/**
* Every membership line, for the one check the transcript dispatches on.
*
@@ -591,6 +599,7 @@ data class ChatMessage(
TYPE_MEMBER_LEFT,
TYPE_GROUP_DISBANDED,
TYPE_CHANGE_REJECTED,
+ TYPE_FOUNDING_ADMINS_MISSING,
)
const val TYPE_UNDECRYPTABLE_OUTER_LAYER = "undecryptableOuterLayer"
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 cf1e27a4..30dc919f 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
@@ -10,6 +10,9 @@ import com.vitorpamplona.quartz.nip01Core.core.Kind
import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import mobi.giza.compose.managers.AdminFlags
+import mobi.giza.compose.managers.FoundingAdmins
+import mobi.giza.compose.managers.SharedKeyDerivation
import mobi.giza.compose.managers.CeremonyFollowThrough
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate
@@ -28,10 +31,12 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.combine
import mobi.giza.compose.database.GENESIS_AT
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.ChatMessage
import mobi.giza.compose.database.model.ChatRoom
+import mobi.giza.compose.database.model.DkgSession
import mobi.giza.compose.database.model.GiftWrapPayload
import mobi.giza.compose.database.model.GroupKeyState
import mobi.giza.compose.database.model.GroupSignedEvent
@@ -45,6 +50,7 @@ import mobi.giza.compose.database.model.types.MarmotReindexReport
import mobi.giza.compose.identity.Identity
import mobi.giza.compose.identity.toKeyPair
import mobi.giza.compose.managers.ShareRefreshManager
+import mobi.giza.compose.managers.RotationHold
import mobi.giza.compose.ui.view.state.SharesSummary
import mobi.giza.compose.ui.view.state.RotationPreview
import mobi.giza.compose.database.model.types.ShareStanding
@@ -52,7 +58,6 @@ import mobi.giza.compose.database.model.types.ShareRepairStage
import mobi.giza.compose.database.model.types.ShareRefreshStage
import mobi.giza.compose.database.model.types.ShareRefreshApprovalStep
import mobi.giza.compose.database.model.types.DkgRitualStage
-import mobi.giza.compose.database.model.DkgSession
import mobi.giza.compose.managers.ShareGenerations
import mobi.giza.compose.managers.ShareRepairManager
import mobi.giza.compose.ExperimentalFeatures
@@ -77,27 +82,61 @@ class DatabaseChatRepository(
val logger = Logger.withTag(TAG)
override suspend fun createMarmotGroup(
- groupId: String,
- name: String,
- purpose: String,
- adminPublicKeys: Set,
- userPublicKey: HexKey,
+ ceremony: DkgSession,
+ ceremonyRoom: LocalChatRoom,
keyPair: KeyPair,
- path: List,
parentChatRoomId: HexKey?,
- ): MarmotGroupCreation.Outcome = MarmotGroupCreation.create(
+ ): MarmotGroupCreation.Outcome = MarmotGroupCreation.createFor(
database = database,
chatRepository = this,
- groupId = groupId,
- name = name,
- purpose = purpose,
- adminPublicKeys = adminPublicKeys,
- userPublicKey = userPublicKey,
+ ceremony = ceremony,
+ ceremonyRoom = ceremonyRoom,
keyPair = keyPair,
- path = path,
parentChatRoomId = parentChatRoomId,
)
+ override suspend fun finishFoundingInvite(
+ ceremony: DkgSession,
+ ceremonyRoom: LocalChatRoom,
+ ): MarmotGroupCreation.FoundingInvite = MarmotGroupCreation.finishFoundingInvite(
+ database = database,
+ chatRepository = this,
+ ceremony = ceremony,
+ ceremonyRoom = ceremonyRoom,
+ )
+
+ override suspend fun finishFoundingInvite(chatRoomId: String): MarmotGroupCreation.FoundingInvite {
+ val (ceremony, ceremonyRoom) = FoundingAdmins.ceremonyOf(database, chatRoomId)
+ ?: return MarmotGroupCreation.FoundingInvite.NothingToDo
+ return finishFoundingInvite(ceremony, ceremonyRoom)
+ }
+
+ override suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set = try {
+ FoundingAdmins.ceremonyOf(database, localChatRoom.chatRoom.id)
+ ?.let { (ceremony, ceremonyRoom) ->
+ MarmotGroupCreation.uninvitedFounders(database, localChatRoom, ceremony, ceremonyRoom)
+ }
+ .orEmpty()
+ } catch (e: Throwable) {
+ logger.e("Error reading who ${localChatRoom.chatRoom.id}'s founding invite missed", e)
+ emptySet()
+ }
+
+ override suspend fun adminRoomOf(chatRoomId: String): String? = try {
+ // The room's own ceremony, not a subgroup's it hosted: a subgroup's key
+ // makes the subgroup's room, which is not this group's admin room.
+ database.dkgSessionDao().getLatestSessionFor(chatRoomId, parentChatRoomId = null)
+ ?.takeIf { it.stage == DkgRitualStage.COMPLETE }
+ ?.thresholdPublicKey
+ ?.let { SharedKeyDerivation.marmotGroupId(it) }
+ ?.takeIf { it != chatRoomId && database.chatRoomDao().findChatRoomById(it) != null }
+ } catch (e: Throwable) {
+ logger.e("Error finding the admin room of $chatRoomId", e)
+ null
+ }
+
+ override suspend fun reconcileAdminFlags(): Int = AdminFlags.reconcileAll(database)
+
override suspend fun followThroughCeremonies(keyPair: KeyPair) =
CeremonyFollowThrough.observe(database = database, chatRepository = this, keyPair = keyPair)
@@ -651,6 +690,19 @@ class DatabaseChatRepository(
database.marmotOutboundDao().removeMember(localChatRoom, memberPublicKey)
}
+ override suspend fun addAdmins(localChatRoom: LocalChatRoom, publicKeys: Set) {
+ database.marmotOutboundDao().addAdmins(localChatRoom, publicKeys)
+ }
+
+ override suspend fun foundingAdmins(chatRoomId: String): FoundingAdmins.Check = try {
+ FoundingAdmins.check(database, chatRoomId)
+ } catch (e: Throwable) {
+ // A room whose check threw is shown without the warning rather than not
+ // at all; the check is a label on the room, not a gate in front of it.
+ logger.e("Error checking the founding admins of $chatRoomId", e)
+ FoundingAdmins.Check.CannotCheck
+ }
+
override suspend fun holdsShare(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): Boolean =
ExperimentalFeatures.shareRefresh &&
runCatching { ShareRefreshManager.liveIdOf(database, localChatRoom, memberPublicKey) != null }.getOrDefault(false)
@@ -716,7 +768,19 @@ class DatabaseChatRepository(
SharesSummary.Member(entry.memberPublicKey, nameOf(entry.memberPublicKey), entry.standing, entry.memberPublicKey == me)
},
pending = if (ExperimentalFeatures.shareRefresh) pending else emptyList(),
- canRotate = ExperimentalFeatures.shareRefresh && shares.secretShare != null && runningRefresh == null,
+ rotation = if (!ExperimentalFeatures.shareRefresh || shares.secretShare == null) {
+ SharesSummary.Rotation.Unavailable
+ } else {
+ when (val hold = ShareRefreshManager.rotationHold(database, localChatRoom, key)) {
+ null -> SharesSummary.Rotation.Available
+ is RotationHold.Running -> SharesSummary.Rotation.Held(SharesSummary.Rotation.Reason.ROTATION_RUNNING)
+ is RotationHold.AwaitingKeyState -> SharesSummary.Rotation.Held(
+ SharesSummary.Rotation.Reason.AWAITING_SIGNATURES,
+ canAskForSignature = hold.signingSessionId == null,
+ )
+ is RotationHold.Behind -> SharesSummary.Rotation.Held(SharesSummary.Rotation.Reason.BEHIND)
+ }
+ },
canAskToBeRepaired = ExperimentalFeatures.shareRefresh && mine?.standing == ShareStanding.STALE && !repairing,
running = running.takeIf { ExperimentalFeatures.shareRefresh },
lastFailure = refreshes.firstOrNull()?.takeIf { it.stage == ShareRefreshStage.FAILED }?.failureReason
@@ -753,6 +817,12 @@ class DatabaseChatRepository(
)
}
+ override fun observeSharesInputs(chatRoomId: String): Flow = combine(
+ database.groupKeyStateDao().observeByChatRoomId(chatRoomId),
+ database.frostSigningSessionDao().observeSessionsForChatRoom(chatRoomId),
+ database.shareRefreshDao().observeSessionsForRoom(chatRoomId),
+ ) { _, _, _ -> }
+
private fun failureOf(t: Throwable?): String? = t?.let { it.message ?: it::class.simpleName ?: "Unknown error" }
private fun privateKeyOrNull(): Pair? {
@@ -793,6 +863,12 @@ class DatabaseChatRepository(
}.exceptionOrNull())
}
+ override suspend fun proposeKeyState(localChatRoom: LocalChatRoom): String? {
+ val (me, _) = privateKeyOrNull() ?: return "This identity cannot sign"
+ val key = shareKeyOf(localChatRoom) ?: return "This group has no shared key"
+ return failureOf(runCatching { ShareRefreshManager.proposeOwedKeyState(database, localChatRoom, me, key) }.exceptionOrNull())
+ }
+
override suspend fun abandonRotation(localChatRoom: LocalChatRoom, sessionId: String): String? =
failureOf(runCatching { ShareRefreshManager.abandon(database, localChatRoom, sessionId) }.exceptionOrNull())
@@ -855,4 +931,4 @@ class DatabaseChatRepository(
companion object {
const val TAG = "DatabaseChatRepository"
}
-}
\ No newline at end of file
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt
new file mode 100644
index 00000000..85a9156c
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt
@@ -0,0 +1,86 @@
+package mobi.giza.compose.managers
+
+import co.touchlab.kermit.Logger
+import com.vitorpamplona.marmot.groups.currentAdminIdentities
+import com.vitorpamplona.mls.group.MlsGroup
+import kotlin.time.Clock
+import mobi.giza.compose.database.GizaDatabase
+
+/**
+ * `Participant.adminAt`, kept in line with the group's own admin policy.
+ *
+ * The policy is the truth -- `AdminPolicyV1` on the current profile,
+ * `MarmotGroupData.admin_pubkeys` on the legacy one -- and it is what the library
+ * enforces and what `isLocalAdmin()` reads. The column is this device's cache of
+ * it, for the screens that label members. A cache with three writers drifted:
+ * the creator caught its rows up by hand, a commit reconciled them, and the
+ * Welcome wrote none at all, so on every device but the creator's a robust
+ * group's admin room showed no admins until some later commit happened to
+ * arrive. docs/robust-group-admins.md, G2 and D2.
+ *
+ * So there is one writer, and every path that changes what the policy says or
+ * which rows exist calls it: the room's creation, the Welcome, and every commit.
+ *
+ * Flags only, never membership. Removing the rows of members the tree no longer
+ * holds is `MarmotInboundManager.processGroupMembershipChanges`'s job, on a
+ * commit; doing it here would turn a best-effort step -- a partly failed invite
+ * at creation, say -- into a partial membership.
+ */
+object AdminFlags {
+ private val logger = Logger.withTag("AdminFlags")
+
+ /**
+ * Flags the rows of [chatRoomId] that [mlsGroup]'s admin policy names and
+ * clears the rest. Reads the rows fresh, so it can run straight after an
+ * upsert that added some.
+ *
+ * @return how many rows changed.
+ */
+ suspend fun reconcile(database: GizaDatabase, chatRoomId: String, mlsGroup: MlsGroup): Int {
+ val admins = mlsGroup.currentAdminIdentities()
+ val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return 0
+ val now = Clock.System.now()
+
+ val changed = room.localParticipants.map { it.participant }.mapNotNull { participant ->
+ val named = participant.participantPublicKey in admins
+ when {
+ named && participant.adminAt == null -> participant.copy(adminAt = now)
+ !named && participant.adminAt != null -> participant.copy(adminAt = null)
+ else -> null
+ }
+ }
+
+ if (changed.isNotEmpty()) {
+ logger.d("$chatRoomId: ${changed.size} admin flag(s) brought in line with the group")
+ database.participantDao().upsert(changed)
+ }
+ return changed.size
+ }
+
+ /**
+ * [reconcile] for every room this device holds MLS state for and is still in.
+ *
+ * Run once per start, for the rooms made before the Welcome wrote any flags:
+ * a joiner's rows there flag nobody until some commit arrives, and in a
+ * robust group's admin room one may never arrive. No stored "done" flag -- a
+ * room whose rows already agree is a read and no write, so a second run costs
+ * one decode per room and a preference would only be one more thing to keep
+ * right. docs/robust-group-admins.md, Phase 6.
+ *
+ * One room that will not decode is logged and passed over, not fatal to the
+ * rest.
+ *
+ * @return how many rows changed, across every room.
+ */
+ suspend fun reconcileAll(database: GizaDatabase): Int =
+ database.chatRoomDao().getChatRoomIdsWithMlsState().sumOf { chatRoomId ->
+ runCatching {
+ val group = database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.toMlsGroup()
+ ?: return@runCatching 0
+ reconcile(database, chatRoomId, group)
+ }.getOrElse {
+ logger.e("Could not bring $chatRoomId's admin flags in line", it)
+ 0
+ }
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt
index 85846d44..430c9e06 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt
@@ -30,7 +30,9 @@ import mobi.giza.compose.repository.ChatRepository
* 1. a subgroup's parent certifies the room the key derives -- proposed here, and
* signed by the parent's own quorum, which stays their decision;
* 2. the group signs what that room will sign with, its key state;
- * 3. the room is created and the members welcomed into it.
+ * 3. the room is created and the members welcomed into it;
+ * 4. a room whose founding invite never went out has it finished
+ * (docs/robust-group-admins.md, Phase 4).
*
* None of the three proposals asks anybody anything: each is a request to the
* group, and the coordinator agreed to make it when they opened the ceremony. So
@@ -62,7 +64,7 @@ object CeremonyFollowThrough {
/** What one call to [takeNextStep] did. */
sealed interface Step {
- /** Not this device's to do, or nothing left: not the coordinator, not finished, or the room exists. */
+ /** Not this device's to do, or nothing left: not the coordinator, not finished, or the room exists with its founders. */
data object NothingToDo : Step
/** Waiting on signatures somebody else gives. */
@@ -74,6 +76,12 @@ object CeremonyFollowThrough {
/** The room exists now. */
data class Created(val chatRoomId: String) : Step
+ /**
+ * The room existed without its founders, whose invite never went out, and
+ * now they have been invited; [notAdded] could not be.
+ */
+ data class Invited(val chatRoomId: String, val notAdded: List) : Step
+
/** The room cannot be created until these members' devices publish a key package. */
data class BlockedOn(val missing: List) : Step
@@ -166,11 +174,24 @@ object CeremonyFollowThrough {
val thresholdPublicKey = current.thresholdPublicKey ?: return@withLock Step.NothingToDo
val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey)
- if (database.chatRoomDao().findChatRoomById(roomId) != null) return@withLock Step.NothingToDo
-
val ceremonyRoom = database.chatRoomDao().findChatRoomById(current.chatRoomId)
?: return@withLock Step.Stuck("The room ceremony ${current.id} ran in is gone")
+ // 4. The room exists: finish its founding invite if it never went out.
+ // Only a room still at epoch 0 has anything to finish, so nobody who
+ // left is ever invited back -- see `MarmotGroupCreation.uninvitedFounders`.
+ if (database.chatRoomDao().findChatRoomById(roomId) != null) {
+ return@withLock when (val invite = chatRepository.finishFoundingInvite(current, ceremonyRoom)) {
+ MarmotGroupCreation.FoundingInvite.NothingToDo -> Step.NothingToDo
+ is MarmotGroupCreation.FoundingInvite.Sent -> {
+ logger.i("Ceremony ${current.id}: invited ${invite.invited.size} founder(s) to $roomId")
+ Step.Invited(roomId, invite.notAdded)
+ }
+ is MarmotGroupCreation.FoundingInvite.BlockedOn -> Step.BlockedOn(invite.missing)
+ is MarmotGroupCreation.FoundingInvite.Failed -> Step.Stuck(invite.reason)
+ }
+ }
+
val participants = ChillDkgRitualManager.participantsOf(current, ceremonyRoom)
val parent = current.parentChatRoomId
@@ -240,14 +261,13 @@ object CeremonyFollowThrough {
}
}
- // 3. The room, with everyone the ceremony was run with as its admins.
+ // 3. The room, with everyone the ceremony was run with as its admins --
+ // which `MarmotGroupCreation.createFor` reads off the ceremony itself, so
+ // there is no list here to get wrong (docs/robust-group-admins.md, Phase 1).
when (
val outcome = chatRepository.createMarmotGroup(
- groupId = roomId,
- name = roomName(current),
- purpose = roomPurpose(current),
- adminPublicKeys = participants,
- userPublicKey = current.userPublicKey,
+ ceremony = current,
+ ceremonyRoom = ceremonyRoom,
keyPair = keyPair,
// Verified by the time it is written: the key state this room was
// gated on carries the certificate, and `stateFrom` refused it
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt
new file mode 100644
index 00000000..b0b5c836
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt
@@ -0,0 +1,128 @@
+package mobi.giza.compose.managers
+
+import com.vitorpamplona.marmot.groups.currentAdminIdentities
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.model.ChatMessage
+import mobi.giza.compose.database.model.DkgSession
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent
+
+/**
+ * Whether a key-backed room's admin policy names every one of its founding
+ * members. docs/robust-group-admins.md, Phase 3.
+ *
+ * The founding members are the participants of the ceremony that made the room's
+ * key (D1). Every one of their devices built that set from the proposal it agreed
+ * to, so each can check the room it was welcomed into against its own record
+ * rather than trusting the device that happened to create it -- a bug, an older
+ * build, or a Bennu peer could all have listed fewer. A subgroup has a second
+ * record of the same set: the birth certificate its parent's quorum signed, which
+ * names its admins.
+ *
+ * Nothing is refused on a mismatch. The room's address is the key, and there is
+ * no second room to go to; a warning that names who is missing is what can be
+ * acted on, by any admin, with [missingFrom]'s answer.
+ */
+object FoundingAdmins {
+
+ /** Enough of a key to tell two members apart when no profile is stored. */
+ private const val SHORTENED_PUBLIC_KEY_LENGTH = 12
+
+ sealed interface Check {
+ /** No key behind the room -- a convenient group, run by its creator. */
+ data object NotKeyBacked : Check
+
+ /**
+ * A key-backed room this device holds no ceremony for: a member added
+ * after the founding, or a reinstall. It is not one of the founders, and
+ * has nothing of its own to check the room against.
+ */
+ data object CannotCheck : Check
+
+ data object Matches : Check
+
+ /** Founding members the room's admin policy does not name. */
+ data class Missing(val publicKeys: Set) : Check
+ }
+
+ suspend fun check(database: GizaDatabase, chatRoomId: String): Check {
+ val state = database.groupKeyStateDao().getByChatRoomId(chatRoomId) ?: return Check.NotKeyBacked
+ val group = database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.toMlsGroup()
+ ?: return Check.CannotCheck
+ val ceremony = database.dkgSessionDao().getSessionById(state.dkgSessionId)
+
+ val founders = foundersOf(database, ceremony).orEmpty() + certifiedAdmins(state.birthCertificateJson)
+ if (founders.isEmpty()) return Check.CannotCheck
+
+ val missing = founders - group.currentAdminIdentities()
+ return if (missing.isEmpty()) Check.Matches else Check.Missing(missing)
+ }
+
+ /**
+ * Checks the room this device was just welcomed into, and says so in its
+ * transcript when founding members are missing from its admins. Once, at the
+ * Welcome: the detail screen repeats the check on every visit, and a line per
+ * visit would be the same news told again.
+ *
+ * A whole sentence naming who is missing, like the membership lines it sits
+ * among, so nothing prefixes a sender's name to it.
+ */
+ suspend fun announceIfMissing(database: GizaDatabase, chatRoomId: String, userPublicKey: HexKey): Check {
+ val check = check(database, chatRoomId)
+ if (check !is Check.Missing) return check
+
+ val names = check.publicKeys.map { publicKey ->
+ database.profileDao().getProfileByPublicKey(publicKey)?.humanReadableNameOrPubkey()
+ ?: publicKey.take(SHORTENED_PUBLIC_KEY_LENGTH)
+ }.sorted()
+
+ database.chatMessageDao().upsert(
+ ChatMessage(
+ content = "This room was created without ${names.joinToString(", ")} as " +
+ (if (names.size == 1) "an admin" else "admins") +
+ ", though they took part in the key ceremony. An admin can add them back from the room's details.",
+ messageType = ChatMessage.TYPE_FOUNDING_ADMINS_MISSING,
+ chatRoomId = chatRoomId,
+ senderPublicKey = userPublicKey,
+ isUserMessage = true,
+ giftWrapPayloadId = null,
+ marmotGroupEventId = null,
+ marmotInnerEventId = null,
+ )
+ )
+ return check
+ }
+
+ /**
+ * The ceremony that made [chatRoomId]'s key, as this device holds it, and the
+ * room it ran in -- or null where this device holds no key state for the room,
+ * no record of that ceremony, or no longer the room it ran in.
+ */
+ suspend fun ceremonyOf(database: GizaDatabase, chatRoomId: String): Pair? {
+ val state = database.groupKeyStateDao().getByChatRoomId(chatRoomId) ?: return null
+ val ceremony = database.dkgSessionDao().getSessionById(state.dkgSessionId) ?: return null
+ val ceremonyRoom = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return null
+ return ceremony to ceremonyRoom
+ }
+
+ /** The ceremony's participants, or null when this device holds no record of them. */
+ private suspend fun foundersOf(database: GizaDatabase, ceremony: DkgSession?): Set? {
+ ceremony ?: return null
+ ceremony.participantPublicKeySet()?.let { return it }
+ val ceremonyRoom = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return null
+ return ChillDkgRitualManager.participantsOf(ceremony, ceremonyRoom)
+ }
+
+ /**
+ * The admins a subgroup's parent certified it with, or nothing for a group
+ * with no parent. Only read off a state that `GroupKeyStateManager.stateFrom`
+ * kept, which it does only for a certificate that checked out.
+ */
+ private fun certifiedAdmins(birthCertificateJson: String?): Set =
+ birthCertificateJson
+ ?.let { Event.fromJsonOrNull(it) }
+ ?.let { SubgroupBirthCertificateEvent.parseAdminPublicKeys(it.tags).toSet() }
+ .orEmpty()
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt
index 0875dc3c..2f8c4570 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt
@@ -4,14 +4,16 @@ import co.touchlab.kermit.Logger
import mobi.giza.compose.nostr.MarmotProfile
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import com.vitorpamplona.mls.group.MlsGroup
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
-import kotlin.time.Clock
import kotlinx.coroutines.withTimeoutOrNull
import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.model.Participant
+import mobi.giza.compose.database.model.DkgSession
import mobi.giza.compose.database.model.MarmotKeyPackage
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.extensions.toHex
@@ -177,8 +179,16 @@ object MarmotGroupCreation {
// there is a row to file it against.
GroupKeyStateManager.adopt(database, groupId)
+ // Read again now the routing is on file. The row above predates it, and a
+ // room with no routing row is addressed by its own id -- so on the current
+ // profile the invite went to a second copy of the group the engine adopted
+ // under the room id, and the copy at the real address still held only its
+ // creator. Every later invite then took the founding path: no commit, and
+ // nobody already in the room told. docs/robust-group-admins.md, Phase 4.
+ val routedRoom = chatRepository.getChatRoomByIdentifier(groupId) ?: localChatRoom
+
val notAdded = runCatching {
- chatRepository.addMembers(localChatRoom = localChatRoom, peers = addable)
+ chatRepository.addMembers(localChatRoom = routedRoom, peers = addable)
}.onFailure {
logger.e("Failed to add members to $groupId", it)
}.getOrElse { addable.map { (publicKey, _) -> publicKey } }
@@ -187,7 +197,7 @@ object MarmotGroupCreation {
logger.w("$groupId created without ${notAdded.size} member(s): $notAdded")
}
- stampAdmins(database, groupId, adminPublicKeys)
+ flagAdmins(database, groupId)
return Outcome.Created(
room = chatRepository.getChatRoomByIdentifier(groupId) ?: localChatRoom,
@@ -195,49 +205,181 @@ object MarmotGroupCreation {
)
}
+ /**
+ * Creates the room [ceremony]'s key derives, with the ceremony's participants
+ * as its admins.
+ *
+ * The only way the app makes such a room, and the reason [create] takes a list
+ * of admins nobody outside this file supplies. The founding members of a
+ * robust group are the participants of the ceremony that made its key --
+ * every one of their devices built that set from the proposal it agreed to --
+ * and a room's epoch-0 admin list is fixed for good at an address derived from
+ * the key. Two callers computing it was two chances to compute it differently.
+ * See docs/robust-group-admins.md, D1 and Phase 1.
+ *
+ * The room's id, name and description come off the ceremony too, so the
+ * coordinator's device creating it on its own and a member pressing the
+ * button make the same room.
+ *
+ * [ceremonyRoom] is the room the ceremony ran in: the participant set falls
+ * back to its members for a ceremony that predates its own participant list,
+ * as [ChillDkgRitualManager.participantsOf] does everywhere.
+ *
+ * A device that was not in the ceremony is refused. It holds no key state for
+ * the room and no share of the key, and listing itself as the room's
+ * creator would put an admin into the room the group never chose.
+ */
+ suspend fun createFor(
+ database: GizaDatabase,
+ chatRepository: ChatRepository,
+ ceremony: DkgSession,
+ ceremonyRoom: LocalChatRoom,
+ keyPair: KeyPair,
+ parentChatRoomId: HexKey? = null,
+ keyPackageLookupTimeout: Long = KEY_PACKAGE_LOOKUP_TIMEOUT,
+ profile: MarmotProfile = MarmotProfile.DEFAULT_FOR_NEW_ROOMS,
+ ): Outcome {
+ val thresholdPublicKey = ceremony.thresholdPublicKey
+ ?: return Outcome.Failed("This ceremony has no key yet.")
+
+ val founders = ChillDkgRitualManager.participantsOf(ceremony, ceremonyRoom)
+ if (ceremony.participantPublicKeySet() == null) {
+ logger.w("Ceremony ${ceremony.id} predates its participant list; its room's members are its founders")
+ }
+
+ if (ceremony.userPublicKey !in founders) {
+ logger.e("Not creating the room for ${ceremony.id}: ${ceremony.userPublicKey} was not in it")
+ return Outcome.Failed("Only someone who took part in the key ceremony can create its room.")
+ }
+
+ return create(
+ database = database,
+ chatRepository = chatRepository,
+ groupId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey),
+ name = CeremonyFollowThrough.roomName(ceremony),
+ purpose = CeremonyFollowThrough.roomPurpose(ceremony),
+ adminPublicKeys = founders,
+ userPublicKey = ceremony.userPublicKey,
+ keyPair = keyPair,
+ parentChatRoomId = parentChatRoomId,
+ keyPackageLookupTimeout = keyPackageLookupTimeout,
+ profile = profile,
+ )
+ }
+
+ /** What [finishFoundingInvite] did. */
+ sealed interface FoundingInvite {
+ /** Every founding member holds a leaf, or the room is past its founding. */
+ data object NothingToDo : FoundingInvite
+
+ /** The founders who were missing were invited; [notAdded] could not be. */
+ data class Sent(val chatRoomId: String, val invited: List, val notAdded: List) : FoundingInvite
+
+ /** Some founders have no published key package, so nobody was invited. */
+ data class BlockedOn(val missing: List) : FoundingInvite
+
+ data class Failed(val reason: String) : FoundingInvite
+ }
+
+ /**
+ * The founding members of [room] its founding invite never reached: listed as
+ * admins, holding no leaf, in a room nothing has been committed to since it was
+ * made.
+ *
+ * Only at epoch 0. A room is created at epoch 0 and its founding invite is the
+ * commit that leaves it -- so a room still there is one whose invite failed
+ * outright, and nobody in it has left or been removed, because either would
+ * have been a commit. Past epoch 0 a founder without a leaf might be one who
+ * left, and inviting them back is not this function's to decide
+ * (docs/robust-group-admins.md, Out of scope).
+ *
+ * A device holds a room at epoch 0 only if it made it: everybody else's copy
+ * comes from a Welcome, which is already past the founding commit.
+ */
+ suspend fun uninvitedFounders(
+ database: GizaDatabase,
+ room: LocalChatRoom,
+ ceremony: DkgSession,
+ ceremonyRoom: LocalChatRoom,
+ ): Set {
+ val group = liveGroupOf(database, room) ?: return emptySet()
+ if (group.epoch != 0L) return emptySet()
+
+ val holdingLeaves = Participant.fromMlsGroup(group, room.chatRoom.id, null).map { it.participantPublicKey }.toSet()
+ return ChillDkgRitualManager.participantsOf(ceremony, ceremonyRoom) - holdingLeaves
+ }
+
+ /**
+ * Invites the founding members [room]'s founding invite never reached -- see
+ * [uninvitedFounders] -- in one commit, as [create] would have.
+ *
+ * Every key package first, as at creation: a founder who cannot be invited yet
+ * holds the rest back rather than leaving the room to a second, partial
+ * founding. docs/robust-group-admins.md, Phase 4.
+ */
+ suspend fun finishFoundingInvite(
+ database: GizaDatabase,
+ chatRepository: ChatRepository,
+ ceremony: DkgSession,
+ ceremonyRoom: LocalChatRoom,
+ keyPackageLookupTimeout: Long = KEY_PACKAGE_LOOKUP_TIMEOUT,
+ ): FoundingInvite {
+ val thresholdPublicKey = ceremony.thresholdPublicKey ?: return FoundingInvite.NothingToDo
+ val groupId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey)
+ val room = chatRepository.getChatRoomByIdentifier(groupId) ?: return FoundingInvite.NothingToDo
+
+ val uninvited = uninvitedFounders(database, room, ceremony, ceremonyRoom)
+ if (uninvited.isEmpty()) return FoundingInvite.NothingToDo
+
+ val keyPackages = keyPackagesFor(chatRepository, uninvited.toList(), keyPackageLookupTimeout, room.chatRoom.marmotProfile())
+ val missing = keyPackages.filter { it.second == null }.map { it.first }
+ if (missing.isNotEmpty()) {
+ logger.w("Not finishing $groupId's founding invite: no key package for $missing")
+ return FoundingInvite.BlockedOn(missing)
+ }
+ val addable = keyPackages.mapNotNull { (publicKey, keyPackage) -> keyPackage?.let { publicKey to it } }
+
+ val notAdded = runCatching {
+ chatRepository.addMembers(localChatRoom = room, peers = addable)
+ }.onFailure {
+ logger.e("Failed to finish $groupId's founding invite", it)
+ }.getOrElse { return FoundingInvite.Failed(it.message ?: "Couldn't invite them. Please try again.") }
+
+ flagAdmins(database, groupId)
+ logger.i("Finished $groupId's founding invite: ${addable.size - notAdded.size} invited, ${notAdded.size} not")
+ return FoundingInvite.Sent(groupId, addable.map { it.first }, notAdded)
+ }
+
+ /** The room's live group: the row's on the legacy profile, the engine's on the current one. */
+ private suspend fun liveGroupOf(database: GizaDatabase, room: LocalChatRoom): MlsGroup? =
+ when (room.chatRoom.marmotProfile()) {
+ MarmotProfile.LEGACY -> room.chatRoom.toMlsGroup()
+ MarmotProfile.CURRENT -> database.marmotEngine.groupFor(room.routingId)
+ }
+
/**
* Writes `adminAt` on the rows of the members this room was created with as
* admins.
*
- * The creating device never learns this any other way, which is a bug older
- * than subgroups and easy to miss. `Participant.adminAt` is written in exactly
- * one place -- `MarmotInboundManager.processGroupMembershipChanges`, on an
- * arriving commit -- while the rows a creator makes come from
- * `getOrCreateChatRoom` and `addMembers`, neither of which sets it. So on the
- * device that made the room, every participant reads as a non-admin until some
- * *other* member sends a commit it processes: a room whose epoch-0 context
- * names three admins had none of them flagged, on the one device certain to be
- * one.
+ * The creating device never learns this any other way: its rows come from
+ * `getOrCreateChatRoom` and `addMembers`, neither of which sets the flag, and
+ * no commit arrives to reconcile them -- a room whose epoch-0 context named
+ * three admins had none of them flagged on the one device certain to be one.
*
- * This is the same list already baked into `MarmotGroupData` a few lines
- * above, so nothing new is being asserted -- the row is being caught up with
- * the group context it was created from. `processGroupMembershipChanges`
- * reconciles it against the MLS tree from then on and will agree.
- *
- * Only flags are written. That function also *removes* participants missing
- * from the tree, and running the whole reconciliation here would soft-delete
+ * Through [AdminFlags.reconcile], off the group this device just made, rather
+ * than off [create]'s own list: the policy is what every other device reads,
+ * and one writer is how the two cannot disagree (docs/robust-group-admins.md,
+ * D2). Only flags are written. A membership reconciliation here would remove
* the rows of anyone `addMembers` could not reach -- turning a partial invite
- * into a partial membership. Widening a flag is safe; narrowing membership on
- * a best-effort step is not.
+ * into a partial membership.
*
* Swallowed on failure, like `adopt` above it: the room is made and usable,
- * and what a missing flag costs is a button not being offered rather than
- * anything being wrong.
+ * and what a missing flag costs is a label rather than anything being wrong.
*/
- private suspend fun stampAdmins(
- database: GizaDatabase,
- groupId: String,
- adminPublicKeys: Set
- ) {
+ private suspend fun flagAdmins(database: GizaDatabase, groupId: String) {
runCatching {
- val room = database.chatRoomDao().findChatRoomById(groupId) ?: return
-
- val stamped = room.localParticipants
- .map { it.participant }
- .filter { it.participantPublicKey in adminPublicKeys && it.adminAt == null }
- .map { it.copy(adminAt = Clock.System.now()) }
-
- if (stamped.isNotEmpty()) database.participantDao().upsert(stamped)
+ val group = database.chatRoomDao().findChatRoomById(groupId)?.chatRoom?.toMlsGroup() ?: return
+ AdminFlags.reconcile(database, groupId, group)
}.onFailure {
logger.e("Created $groupId but could not flag its admins", it)
}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt
index af9fac92..e10d30d6 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt
@@ -3,7 +3,6 @@ package mobi.giza.compose.managers
import co.touchlab.kermit.Logger
import com.vitorpamplona.marmot.GroupEventResult
import com.vitorpamplona.marmot.foundation.appEvents.MarmotAppEvent
-import com.vitorpamplona.marmot.groups.currentAdminIdentities
import com.vitorpamplona.marmot.groups.currentGroupState
import com.vitorpamplona.marmot.mip03GroupMessages.GroupEventEncryption
import com.vitorpamplona.mls.codec.TlsReader
@@ -136,7 +135,6 @@ object MarmotInboundManager {
announceAdditions: Boolean = true,
) {
logger.d("processGroupMembershipChanges")
- val adminPublicKeys = mlsGroup.currentAdminIdentities()
val commitedGroupMembers = Participant.fromMlsGroup(
mlsGroup = mlsGroup,
@@ -153,35 +151,13 @@ object MarmotInboundManager {
}
logger.d("excludedParticipants: $excludedParticipants")
val existingParticipantPublicKeys = localChatRoom.localParticipants.map { it.participant.participantPublicKey }
+ // Admin flags are not written here: `AdminFlags.reconcile` below reads the
+ // rows this function leaves and flags them from the group's policy, the
+ // same call the Welcome and the room's creation make.
val newParticipants = commitedGroupMembers.filter { committedGroupMember ->
existingParticipantPublicKeys.contains(committedGroupMember.participantPublicKey).not()
- }.map { newParticipant ->
- newParticipant.copy(
- adminAt = if (adminPublicKeys.contains(newParticipant.participantPublicKey)) {
- Clock.System.now()
- } else {
- null
- }
- )
}
logger.d("newParticipants: $newParticipants")
- val removedAdmins = localChatRoom.localParticipants.filter { localParticipant ->
- localParticipant.participant.adminAt != null && !adminPublicKeys.contains(localParticipant.participant.participantPublicKey)
- }.map { localParticipant ->
- localParticipant.participant.copy(
- adminAt = null
- )
- }
- logger.d("removedAdmins: $removedAdmins")
-
- val graduatedAdmins = localChatRoom.localParticipants.filter { localParticipant ->
- localParticipant.participant.adminAt == null && adminPublicKeys.contains(localParticipant.participant.participantPublicKey)
- }.map { localParticipant ->
- localParticipant.participant.copy(
- adminAt = Clock.System.now()
- )
- }
- logger.d("graduatedAdmins: $graduatedAdmins")
// Placeholder profiles for new participants...
newParticipants.forEach { newParticipant ->
@@ -246,10 +222,9 @@ object MarmotInboundManager {
)
}
// Handle membership changes...
- database.participantDao().upsert(removedAdmins)
database.participantDao().delete(excludedParticipants)
database.participantDao().upsert(newParticipants)
- database.participantDao().upsert(graduatedAdmins)
+ AdminFlags.reconcile(database, localChatRoom.chatRoom.id, mlsGroup)
val userPublicKey = localChatRoom.chatRoom.userPublicKey
val disbanded = mlsGroup.currentGroupState().isDisbanded
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/RotationHold.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/RotationHold.kt
new file mode 100644
index 00000000..f7047f3a
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/RotationHold.kt
@@ -0,0 +1,29 @@
+package mobi.giza.compose.managers
+
+/**
+ * Why this device must not propose a share rotation now
+ * (docs/rotation-waits-for-key-state.md). [ShareRefreshManager.rotationHold]
+ * answers it; [reason] is the refusal the propose paths give.
+ */
+sealed interface RotationHold {
+ val reason: String
+
+ /** A refresh of the key is still running here. */
+ data class Running(val refreshId: String) : RotationHold {
+ override val reason get() = "a rotation is still running"
+ }
+
+ /**
+ * The group has not signed the key state at [generation] -- the proof that
+ * the shares the last rotation dealt can sign -- or a key-state proposal is
+ * open, [signingSessionId] when this device holds it.
+ */
+ data class AwaitingKeyState(val generation: Int, val signingSessionId: String?) : RotationHold {
+ override val reason get() = "the group has not yet signed the key state at generation $generation"
+ }
+
+ /** The group signs at a generation this device has not reached: it missed a certificate. */
+ data class Behind(val groupGeneration: Int, val localGeneration: Int) : RotationHold {
+ override val reason get() = "the group is at generation $groupGeneration and this device at $localGeneration"
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt
index 84e1370a..835f5e2b 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt
@@ -22,6 +22,7 @@ import kotlinx.coroutines.CancellationException
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.ChatMessage
import mobi.giza.compose.database.model.DkgSession
+import mobi.giza.compose.database.model.FrostSigningSession
import mobi.giza.compose.database.model.KeyShareGeneration
import mobi.giza.compose.database.model.KeyShareMember
import mobi.giza.compose.database.model.MarmotInnerEvent
@@ -36,6 +37,7 @@ import mobi.giza.compose.database.model.types.ShareRefreshStage
import mobi.giza.compose.database.model.types.ShareStanding
import mobi.giza.compose.ExperimentalFeatures
import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
import mobi.giza.compose.nostr.frost.ShareRefreshEvents
/**
@@ -166,7 +168,7 @@ object ShareRefreshManager {
return Preview(
takingPart = plan.recipients.mapNotNull { memberOf[it] },
withheld = plan.withheld.mapNotNull { (id, standing) -> memberOf[id]?.let { it to standing } }.toMap(),
- refusal = plan.refusal ?: running(database, key)?.let { "a rotation of this key is already running" },
+ refusal = plan.refusal ?: rotationHold(database, localChatRoom, key)?.reason,
)
}
@@ -179,7 +181,13 @@ object ShareRefreshManager {
* device deals at once, and its owner is not asked again. That is safe only
* because the proposal is made from a dialog that named everyone it leaves
* out ([preview]) -- proposing is agreeing to withhold whoever the form
- * showed, never whoever it defaulted to unseen.
+ * showed, never whoever it defaulted to unseen. Every other recipient is
+ * asked the one thing, to take part (docs/rotate-shares-single-approval.md,
+ * which also made storing the new share automatic for everyone, and
+ * docs/rotation-waits-for-key-state.md, Phase 4).
+ *
+ * Refused while [rotationHold] holds: a rotation stacked on a generation the
+ * group has not yet signed is what D6 exists to prevent.
*/
suspend fun proposeRefresh(
database: GizaDatabase,
@@ -194,6 +202,7 @@ object ShareRefreshManager {
require(isKeysRoom(database, localChatRoom, key)) { "${localChatRoom.chatRoom.id} is not the room key ${key.id} signs as" }
running(database, key)?.let { return it }
+ rotationHold(database, localChatRoom, key)?.let { throw IllegalStateException("Cannot rotate yet: ${it.reason}") }
val shares = ShareGenerations.active(database, key)
val (recipients, allWithheld, refused) = plan(key, shares, userPublicKey, withheld)
@@ -259,6 +268,73 @@ object ShareRefreshManager {
return proposeRefresh(database, localChatRoom, userPublicKey, nostrPrivateKey, key, mapOf(id to ShareStanding.RETIRED))
}
+ /**
+ * Why this device must not propose a rotation of [key] now, or null when it may
+ * (docs/rotation-waits-for-key-state.md). The Shares section and [proposeRefresh]
+ * both read this, so the button and the protocol cannot disagree.
+ *
+ * A rotation is not over when its refresh is: it is over when the group has
+ * signed the key state at the new generation, the first signature the new
+ * shares make and what every device waits on before deleting the old ones
+ * (D6). Rotating again before then stacks a second unproven generation on the
+ * first, and leaves the first one's key-state proposal to fail under its
+ * signers.
+ *
+ * Checked on the proposer's device only. A recipient a few seconds behind on
+ * the signature would refuse out loud and end a rotation that was fine.
+ */
+ suspend fun rotationHold(database: GizaDatabase, localChatRoom: LocalChatRoom, key: DkgSession): RotationHold? {
+ running(database, key)?.let { return RotationHold.Running(it.id) }
+
+ val active = ShareGenerations.active(database, key).generation
+ val signed = GroupKeyStateManager.keyStateFor(database, localChatRoom.chatRoom.id)
+ ?.takeIf { it.dkgSessionId == key.id }
+ ?.generation ?: 0
+ if (signed > active) return RotationHold.Behind(groupGeneration = signed, localGeneration = active)
+
+ val open = openKeyStateSession(database, key)
+ if (signed < active || open != null) return RotationHold.AwaitingKeyState(active, open?.id)
+ return null
+ }
+
+ /**
+ * Asks the group to sign the key state it owes for the generation the last
+ * rotation produced, when nobody here is asking -- the coordinator's proposal
+ * failed, or its device is gone. Anyone may (docs/frost-share-refresh.md,
+ * Phase 8); without it a lost coordinator holds every later rotation for good
+ * (docs/rotation-waits-for-key-state.md, R4).
+ */
+ suspend fun proposeOwedKeyState(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, key: DkgSession): FrostSigningSession {
+ val hold = rotationHold(database, localChatRoom, key)
+ check(hold is RotationHold.AwaitingKeyState && hold.signingSessionId == null) {
+ "The group is not waiting on anyone to ask for its key state"
+ }
+ // The refresh that produced the generation, named on the state as the
+ // coordinator would have named it.
+ val refreshId = database.shareRefreshDao().getSessionsForKey(key.id)
+ .firstOrNull { it.stage == ShareRefreshStage.COMPLETE && it.baseGeneration + 1 == hold.generation }
+ ?.id
+ return GroupKeyStateManager.proposeGeneration(database, localChatRoom, userPublicKey, key, refreshId)
+ }
+
+ /**
+ * A key-state signing session of [key] still open on this device -- a
+ * rotation's, a rebind's, or the ceremony's first -- unless this device has
+ * declined it. A session fails only once enough members decline, so one this
+ * device has refused can sit open for as long as the others stay quiet; it
+ * does not hold this device's hand for that long.
+ */
+ private suspend fun openKeyStateSession(database: GizaDatabase, key: DkgSession): FrostSigningSession? {
+ val dao = database.frostSigningSessionDao()
+ return dao.getOpenSessionsForKey(key.id)
+ .filter { it.signDeclinedAt == null }
+ .firstOrNull { session ->
+ dao.getItems(session.id).singleOrNull()
+ ?.let { Event.fromJsonOrNull(it.unsignedEventJson) }
+ ?.kind == GroupKeyStateEvent.KIND
+ }
+ }
+
/** A refresh of [key] still running on this device, if there is one. One at a time per key. */
private suspend fun running(database: GizaDatabase, key: DkgSession): ShareRefreshSession? =
database.shareRefreshDao().getSessionsForKey(key.id).firstOrNull {
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 57eac81f..6447ccfd 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt
@@ -7,8 +7,10 @@ import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
import com.vitorpamplona.quartz.nip17Dm.messages.ChatMessageEvent
import com.vitorpamplona.quartz.nip17Dm.settings.DmRelayListEvent
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.flow
import mobi.giza.compose.database.model.ChatRoom
+import mobi.giza.compose.database.model.DkgSession
import mobi.giza.compose.database.model.GiftWrapPayload
import mobi.giza.compose.database.model.GroupKeyState
import mobi.giza.compose.database.model.GroupSignedEvent
@@ -17,8 +19,8 @@ import mobi.giza.compose.database.model.Participant
import mobi.giza.compose.database.model.intermdiate.LocalChatMessage
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.database.model.types.MarmotReindexReport
+import mobi.giza.compose.managers.FoundingAdmins
import mobi.giza.compose.managers.MarmotGroupCreation
-import mobi.giza.compose.managers.SharedKeyDerivation
import mobi.giza.compose.managers.SubgroupManager
import mobi.giza.compose.nostr.MarmotProfile
import mobi.giza.compose.ui.view.state.SharesSummary
@@ -197,29 +199,61 @@ interface ChatRepository {
): List
/**
- * Creates a Marmot room at an id the group's key derives, with
- * [adminPublicKeys] as its admins, and welcomes them into it.
+ * Creates the Marmot room [ceremony]'s key derives, with everyone the ceremony
+ * was run with as its admins, and welcomes them into it.
*
* Two flows want exactly this: the admin room a group opens after its
* ceremony, and a subgroup. See `MarmotGroupCreation`, which holds the rules
* -- every key package before anything exists, the admins baked into epoch 0,
* and the key state filed before the members are added.
*
+ * Takes the ceremony rather than a list of admins on purpose. The room's id
+ * is derived, so its epoch-0 admin list is fixed at that address for good, and
+ * the founding members of a robust group are exactly the ceremony's
+ * participants -- so the one place that set is read is the one place a room is
+ * made. [ceremonyRoom] is the room the ceremony ran in, read only for a
+ * ceremony that predates its own participant list. See
+ * docs/robust-group-admins.md, Phase 1.
+ *
* Refuses rather than half-creates: the id is derived, so a partly created
* room occupies that address permanently and there is no second id to retry
* with.
*/
suspend fun createMarmotGroup(
- groupId: String,
- name: String,
- purpose: String,
- adminPublicKeys: Set,
- userPublicKey: HexKey,
+ ceremony: DkgSession,
+ ceremonyRoom: LocalChatRoom,
keyPair: KeyPair,
- path: List = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH,
parentChatRoomId: HexKey? = null,
): MarmotGroupCreation.Outcome
+ /**
+ * Invites the founding members [ceremony]'s room never reached, when its
+ * founding invite never went out. See `MarmotGroupCreation.finishFoundingInvite`
+ * and docs/robust-group-admins.md, Phase 4.
+ */
+ suspend fun finishFoundingInvite(ceremony: DkgSession, ceremonyRoom: LocalChatRoom): MarmotGroupCreation.FoundingInvite
+
+ /** [finishFoundingInvite] for the room [chatRoomId], through the ceremony its key state names. */
+ suspend fun finishFoundingInvite(chatRoomId: String): MarmotGroupCreation.FoundingInvite
+
+ /** The founders [localChatRoom]'s founding invite never reached; empty when there are none to reach. */
+ suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set
+
+ /**
+ * The admin room [chatRoomId]'s own key ceremony made, if this device holds
+ * it: where the members of a robust group's NIP-17 room are admins. Null for
+ * a room with no finished ceremony of its own, and for one whose admin room
+ * this device does not hold.
+ */
+ suspend fun adminRoomOf(chatRoomId: String): String?
+
+ /**
+ * Brings every Marmot room's admin flags in line with its group's policy, for
+ * the rooms joined before the Welcome wrote any. Once per start. See
+ * `AdminFlags.reconcileAll` and docs/robust-group-admins.md, Phase 6.
+ */
+ suspend fun reconcileAdminFlags(): Int
+
/**
* Takes every key ceremony [keyPair] coordinated from a key to a working room,
* until cancelled: asks the group to sign its key state (a subgroup's parent to
@@ -269,6 +303,21 @@ interface ChatRepository {
*/
suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey)
+ /**
+ * Adds [publicKeys] to a current-profile room's admin policy, as an admin of
+ * it: one commit through the publish gate, additions only. The repair for a
+ * room missing founding members from its admins -- see [foundingAdmins] and
+ * docs/robust-group-admins.md, Phase 3.
+ */
+ suspend fun addAdmins(localChatRoom: LocalChatRoom, publicKeys: Set)
+
+ /**
+ * Whether [chatRoomId]'s admin policy names every member of the ceremony that
+ * made its key, as this device's own record of that ceremony has them. See
+ * `FoundingAdmins`.
+ */
+ suspend fun foundingAdmins(chatRoomId: String): FoundingAdmins.Check
+
/**
* Whether [memberPublicKey] holds a live share of the room's key, and so
* whether a removal leaves them able to help sign until the shares are
@@ -285,6 +334,14 @@ interface ChatRepository {
/** The room's key as the Shares section shows it, or null when the room has none. */
suspend fun sharesSummary(localChatRoom: LocalChatRoom): SharesSummary?
+ /**
+ * Emits whenever something [sharesSummary] reads for [chatRoomId] may have
+ * changed -- the key state the group signed, a signing session, a refresh --
+ * so the section follows the group without being reopened
+ * (docs/rotation-waits-for-key-state.md, Phase 3).
+ */
+ fun observeSharesInputs(chatRoomId: String): Flow
+
/** Proposes rotating every share of the room's key. Null on success, or why not. */
suspend fun rotateShares(localChatRoom: LocalChatRoom): String?
@@ -298,6 +355,13 @@ interface ChatRepository {
/** Answers what [approval] asks. Null on success, or why not. */
suspend fun approveShares(localChatRoom: LocalChatRoom, approval: SharesSummary.PendingApproval): String?
+ /**
+ * Asks the group to sign the key state at the generation the last rotation
+ * produced, when nobody here is asking (docs/rotation-waits-for-key-state.md, R4).
+ * Null when the request went out, or why it did not.
+ */
+ suspend fun proposeKeyState(localChatRoom: LocalChatRoom): String?
+
/** Ends the rotation [sessionId] for everyone. Null on success, or why not. */
suspend fun abandonRotation(localChatRoom: LocalChatRoom, sessionId: String): String?
@@ -447,19 +511,27 @@ interface ChatRepository {
): List = peers.map { it.first }
override suspend fun createMarmotGroup(
- groupId: String,
- name: String,
- purpose: String,
- adminPublicKeys: Set,
- userPublicKey: HexKey,
+ ceremony: DkgSession,
+ ceremonyRoom: LocalChatRoom,
keyPair: KeyPair,
- path: List,
parentChatRoomId: HexKey?,
): MarmotGroupCreation.Outcome =
MarmotGroupCreation.Outcome.Failed("No database")
override suspend fun followThroughCeremonies(keyPair: KeyPair) = Unit
+ override suspend fun finishFoundingInvite(ceremony: DkgSession, ceremonyRoom: LocalChatRoom) =
+ MarmotGroupCreation.FoundingInvite.NothingToDo
+
+ override suspend fun finishFoundingInvite(chatRoomId: String) =
+ MarmotGroupCreation.FoundingInvite.NothingToDo
+
+ override suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set = emptySet()
+
+ override suspend fun adminRoomOf(chatRoomId: String): String? = null
+
+ override suspend fun reconcileAdminFlags(): Int = 0
+
override suspend fun sendChatMessage(
text: String,
@@ -494,18 +566,27 @@ interface ChatRepository {
override suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) = Unit
+ override suspend fun addAdmins(localChatRoom: LocalChatRoom, publicKeys: Set) = Unit
+
+ override suspend fun foundingAdmins(chatRoomId: String): FoundingAdmins.Check =
+ FoundingAdmins.Check.NotKeyBacked
+
override suspend fun holdsShare(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): Boolean = false
override suspend fun rotateSharesWithout(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): String? = null
override suspend fun sharesSummary(localChatRoom: LocalChatRoom): SharesSummary? = null
+ override fun observeSharesInputs(chatRoomId: String): Flow = emptyFlow()
+
override suspend fun rotateShares(localChatRoom: LocalChatRoom): String? = null
override suspend fun rotationPreview(localChatRoom: LocalChatRoom, without: HexKey?): RotationPreview? = null
override suspend fun approveShares(localChatRoom: LocalChatRoom, approval: SharesSummary.PendingApproval): String? = null
+ override suspend fun proposeKeyState(localChatRoom: LocalChatRoom): String? = null
+
override suspend fun abandonRotation(localChatRoom: LocalChatRoom, sessionId: String): String? = null
override suspend fun askToBeRepaired(localChatRoom: LocalChatRoom): String? = null
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 10b8e07b..9dec1a94 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
@@ -14,6 +14,9 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
+import mobi.giza.compose.managers.MarmotGroupCreation
+import androidx.compose.material3.CardDefaults
+import androidx.compose.material.icons.filled.AdminPanelSettings
import androidx.compose.material.icons.filled.Key
import androidx.compose.material.icons.filled.AccountTree
import androidx.compose.material.icons.filled.Autorenew
@@ -81,6 +84,18 @@ import mobi.giza.compose.ui.view.model.ChatRoomDetailViewModel
import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import mobi.giza.compose.ui.theme.spacing
+import mobi.giza.compose.resources.every_member_of_this_group_administers_it_there
+import mobi.giza.compose.resources.admin_room
+import mobi.giza.compose.resources.founding_members_have_no_key_package
+import mobi.giza.compose.resources.founding_members_invited
+import mobi.giza.compose.resources.invite_them
+import mobi.giza.compose.resources.s_took_part_in_the_key_ceremony_but_were_not_invited
+import mobi.giza.compose.resources.not_every_founding_member_was_invited
+import mobi.giza.compose.resources.founding_members_made_admins_requested
+import mobi.giza.compose.resources.make_them_admins
+import mobi.giza.compose.resources.s_took_part_in_the_key_ceremony_but_are_not_admins
+import mobi.giza.compose.resources.founding_members_are_not_admins
+import mobi.giza.compose.resources.admin
import mobi.giza.compose.resources.run_by_members
import mobi.giza.compose.resources.parent_group
import mobi.giza.compose.resources.a_subgroup
@@ -121,9 +136,16 @@ import androidx.compose.foundation.layout.Row
import mobi.giza.compose.resources.share_rotation_requested
import mobi.giza.compose.resources.not_now
import mobi.giza.compose.resources.rotate_shares
+import mobi.giza.compose.resources.rotation_held_running
+import mobi.giza.compose.resources.rotate_shares_confirm_title
+import mobi.giza.compose.resources.rotation_held_awaiting_signatures
+import mobi.giza.compose.resources.rotation_held_behind
+import mobi.giza.compose.resources.rotation_held_after_removal
+import mobi.giza.compose.resources.ask_the_group_to_sign_the_new_shares
+import mobi.giza.compose.resources.key_state_requested
+import mobi.giza.compose.resources.see_the_proposal
import mobi.giza.compose.resources.rotate_shares_without_body
import mobi.giza.compose.resources.rotate_shares_without_title
-import mobi.giza.compose.resources.rotate_shares_title
import mobi.giza.compose.resources.rotation_cannot_start
import mobi.giza.compose.resources.rotation_left_out_for_good
import mobi.giza.compose.resources.rotation_left_out_until_brought_back
@@ -132,7 +154,6 @@ import mobi.giza.compose.resources.rotation_taking_part
import mobi.giza.compose.resources.rotation_no_key
import mobi.giza.compose.ui.view.state.RotationPreview
import androidx.compose.runtime.remember
-import androidx.compose.material3.CardDefaults
import mobi.giza.compose.resources.waiting_on_s_since_s
import mobi.giza.compose.resources.rotation_ended
import mobi.giza.compose.resources.abandon_rotation_body
@@ -210,6 +231,11 @@ fun ChatRoomDetailScreen(
val rotationRequested = stringResource(Res.string.share_rotation_requested)
val sharesActionSent = stringResource(Res.string.shares_action_sent)
val noKeyToRotate = stringResource(Res.string.rotation_no_key)
+ val keyStateRequested = stringResource(Res.string.key_state_requested)
+ val rotationHeldAfterRemoval = stringResource(Res.string.rotation_held_after_removal)
+ val madeAdminsRequested = stringResource(Res.string.founding_members_made_admins_requested)
+ val foundersInvited = stringResource(Res.string.founding_members_invited)
+ val foundersHaveNoKeyPackage = stringResource(Res.string.founding_members_have_no_key_package)
// Offered after removing a member who still holds a share of the room's key:
// the removal took them out of the room, not out of the key
@@ -274,9 +300,10 @@ fun ChatRoomDetailScreen(
chatRoomDetailViewModel.rotationProposal?.let { proposal ->
AlertDialog(
onDismissRequest = { chatRoomDetailViewModel.dismissRotationProposal() },
- title = { Text(stringResource(Res.string.rotate_shares_title)) },
+ title = { Text(stringResource(Res.string.rotate_shares_confirm_title)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) {
+ Text(stringResource(Res.string.shares_rotation_caveat))
Text(stringResource(Res.string.rotation_taking_part, proposal.preview.takingPart.joinToString(", ")))
RotationLeftOut(proposal.preview)
val refusal = proposal.preview.refusal
@@ -443,6 +470,94 @@ fun ChatRoomDetailScreen(
}
}
+ // The founding members, where the room is not as the
+ // ceremony that made its key left it: founders its
+ // policy does not list as admins, or founders its
+ // founding invite never reached. Under the key and the
+ // parent, because it is about the same thing -- who the
+ // group that made this room is. docs/robust-group-admins.md,
+ // Phase 5.
+ if (chatRoomDetailUIState.missingFoundingAdmins.isNotEmpty()) {
+ item {
+ FoundingMembersCard(
+ title = stringResource(Res.string.founding_members_are_not_admins),
+ body = stringResource(
+ Res.string.s_took_part_in_the_key_ceremony_but_are_not_admins,
+ chatRoomDetailUIState.founderNamesFor(chatRoomDetailUIState.missingFoundingAdmins),
+ ),
+ // An admin of a room the app governs: the
+ // repair is a commit only they can make.
+ actionLabel = stringResource(Res.string.make_them_admins)
+ .takeIf { chatRoomDetailUIState.canGovern },
+ isActionPending = chatRoomDetailViewModel.isActionPending.value,
+ onAction = {
+ chatRoomDetailViewModel.addMissingFoundingAdmins(
+ localChatRoom = chatRoomDetailUIState.localChatRoom,
+ missing = chatRoomDetailUIState.missingFoundingAdmins,
+ ) { failure -> notify(failure ?: madeAdminsRequested) }
+ },
+ )
+ }
+ }
+
+ if (chatRoomDetailUIState.uninvitedFounders.isNotEmpty()) {
+ item {
+ FoundingMembersCard(
+ title = stringResource(Res.string.not_every_founding_member_was_invited),
+ body = stringResource(
+ Res.string.s_took_part_in_the_key_ceremony_but_were_not_invited,
+ chatRoomDetailUIState.founderNamesFor(chatRoomDetailUIState.uninvitedFounders),
+ ),
+ actionLabel = stringResource(Res.string.invite_them),
+ isActionPending = chatRoomDetailViewModel.isActionPending.value,
+ onAction = {
+ chatRoomDetailViewModel.inviteFounders(chatRoomId) { invite ->
+ notify(
+ when (invite) {
+ is MarmotGroupCreation.FoundingInvite.BlockedOn -> foundersHaveNoKeyPackage
+ is MarmotGroupCreation.FoundingInvite.Failed -> invite.reason
+ else -> foundersInvited
+ }
+ )
+ }
+ },
+ )
+ }
+ }
+
+ // A robust group's NIP-17 room has no admins of its own;
+ // its members are admins of the room its key made.
+ chatRoomDetailUIState.adminRoomId?.let { adminRoomId ->
+ item {
+ Card(
+ modifier = Modifier.fillMaxWidth(),
+ onClick = {
+ onNavigateToRoute.invoke(
+ ChatRoomDetailRoute(
+ activeUserPublicKey = activeUserPublicKey,
+ chatRoomId = adminRoomId,
+ relayHint = relayHint
+ )
+ )
+ }
+ ) {
+ ListItem(
+ leadingContent = {
+ Icon(Icons.Default.AdminPanelSettings, contentDescription = Decorative)
+ },
+ trailingContent = {
+ Icon(Icons.Default.ChevronRight, contentDescription = Decorative)
+ },
+ headlineContent = {
+ Text(text = stringResource(Res.string.admin_room))
+ },
+ supportingContent = {
+ Text(text = stringResource(Res.string.every_member_of_this_group_administers_it_there))
+ }
+ )
+ }
+ }
+ }
item {
chatRoomDetailUIState.localChatRoom.chatRoom.description?.let {
Text(
@@ -537,6 +652,7 @@ fun ChatRoomDetailScreen(
Row(horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) {
if (approval.kind != SharesSummary.PendingApproval.Kind.REPAIR_HELP) {
TextButton(
+ enabled = !chatRoomDetailViewModel.isActionPending.value,
onClick = {
chatRoomDetailViewModel.abandonRotation(chatRoomDetailUIState.localChatRoom, approval.sessionId) { failure ->
notify(failure ?: sharesActionSent)
@@ -547,6 +663,7 @@ fun ChatRoomDetailScreen(
}
}
FilledTonalButton(
+ enabled = !chatRoomDetailViewModel.isActionPending.value,
onClick = {
chatRoomDetailViewModel.approveShares(chatRoomDetailUIState.localChatRoom, approval) { failure ->
notify(failure ?: sharesActionSent)
@@ -559,7 +676,9 @@ fun ChatRoomDetailScreen(
}
)
}
- if (shares.canRotate || shares.canAskToBeRepaired) {
+ val rotation = shares.rotation
+ val actionPending = chatRoomDetailViewModel.isActionPending.value
+ if (rotation != SharesSummary.Rotation.Unavailable || shares.canAskToBeRepaired) {
item {
Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) {
Text(
@@ -567,8 +686,12 @@ fun ChatRoomDetailScreen(
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
- if (shares.canRotate) {
+ if (rotation != SharesSummary.Rotation.Unavailable) {
+ // Disabled rather than hidden while the last rotation is
+ // unfinished, with the reason beneath it
+ // (docs/rotation-waits-for-key-state.md, Phase 2).
FilledTonalButton(
+ enabled = rotation == SharesSummary.Rotation.Available && !actionPending,
onClick = {
chatRoomDetailViewModel.previewRotation(chatRoomDetailUIState.localChatRoom) {
notify(noKeyToRotate)
@@ -578,8 +701,50 @@ fun ChatRoomDetailScreen(
Text(stringResource(Res.string.rotate_shares))
}
}
+ if (rotation is SharesSummary.Rotation.Held) {
+ Text(
+ text = stringResource(
+ when (rotation.reason) {
+ SharesSummary.Rotation.Reason.ROTATION_RUNNING -> Res.string.rotation_held_running
+ SharesSummary.Rotation.Reason.AWAITING_SIGNATURES -> Res.string.rotation_held_awaiting_signatures
+ SharesSummary.Rotation.Reason.BEHIND -> Res.string.rotation_held_behind
+ }
+ ),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ if (rotation.canAskForSignature) {
+ // Nobody is asking for the key state the group owes:
+ // the coordinator's proposal failed, or its device is
+ // gone. Anyone may ask again (frost-share-refresh.md, Phase 8).
+ TextButton(
+ enabled = !actionPending,
+ onClick = {
+ chatRoomDetailViewModel.proposeKeyState(chatRoomDetailUIState.localChatRoom) { failure ->
+ notify(failure ?: keyStateRequested)
+ }
+ }
+ ) {
+ Text(stringResource(Res.string.ask_the_group_to_sign_the_new_shares))
+ }
+ } else if (rotation.reason == SharesSummary.Rotation.Reason.AWAITING_SIGNATURES) {
+ TextButton(
+ onClick = {
+ onNavigateToRoute.invoke(
+ ProposalListRoute(
+ activeUserPublicKey = activeUserPublicKey,
+ chatRoomId = chatRoomId
+ )
+ )
+ }
+ ) {
+ Text(stringResource(Res.string.see_the_proposal))
+ }
+ }
+ }
if (shares.canAskToBeRepaired) {
TextButton(
+ enabled = !actionPending,
onClick = {
chatRoomDetailViewModel.askToBeRepaired(chatRoomDetailUIState.localChatRoom) { failure ->
notify(failure ?: sharesActionSent)
@@ -830,8 +995,8 @@ fun ChatRoomDetailScreen(
chatRoomDetailViewModel.removeMember(
localChatRoom = chatRoomDetailUIState.localChatRoom,
memberPublicKey = memberPublicKey,
- ) { failure ->
- notify(failure ?: removalRequested)
+ ) { failure, rotationHeld ->
+ notify(failure ?: if (rotationHeld) rotationHeldAfterRemoval else removalRequested)
}
}
) {
@@ -853,10 +1018,21 @@ fun ChatRoomDetailScreen(
)
},
supportingContent = {
- localParticipant.profile?.about?.let {
- Text(
- text = it
- )
+ Column {
+ // From the group's admin policy, through
+ // `AdminFlags` -- docs/robust-group-admins.md.
+ if (localParticipant.participant.adminAt != null) {
+ Text(
+ text = stringResource(Res.string.admin),
+ style = MaterialTheme.typography.labelMedium,
+ color = MaterialTheme.colorScheme.primary,
+ )
+ }
+ localParticipant.profile?.about?.let {
+ Text(
+ text = it
+ )
+ }
}
}
@@ -1532,3 +1708,60 @@ private fun RotationRunningCard(running: SharesSummary.Running, onAbandon: () ->
}
}
}
+
+/**
+ * Something about this room's founding members that is not as the ceremony
+ * left it -- founders it does not list as admins, or founders its invite never
+ * reached -- and, where this device can, the one action that repairs it.
+ *
+ * On the error container: the room works, but not as the group that made it
+ * agreed, and that is worth more than a supporting line. docs/robust-group-admins.md,
+ * Phase 5.
+ */
+@Composable
+private fun FoundingMembersCard(
+ title: String,
+ body: String,
+ actionLabel: String?,
+ isActionPending: Boolean,
+ onAction: () -> Unit,
+) {
+ Card(
+ modifier = Modifier.fillMaxWidth(),
+ colors = CardDefaults.cardColors(
+ containerColor = MaterialTheme.colorScheme.errorContainer,
+ contentColor = MaterialTheme.colorScheme.onErrorContainer,
+ )
+ ) {
+ Column(
+ modifier = Modifier.padding(MaterialTheme.spacing.containerPadding),
+ verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap),
+ ) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap),
+ ) {
+ Icon(Icons.Default.AdminPanelSettings, contentDescription = Decorative)
+ Text(text = title, style = MaterialTheme.typography.titleSmall)
+ }
+
+ Text(text = body, style = MaterialTheme.typography.bodyMedium)
+
+ actionLabel?.let { label ->
+ TextButton(
+ onClick = onAction,
+ enabled = !isActionPending,
+ colors = ButtonDefaults.textButtonColors(
+ contentColor = MaterialTheme.colorScheme.onErrorContainer
+ ),
+ ) {
+ Text(label)
+ }
+ }
+ }
+ }
+}
+
+/** The founders [publicKeys] names, as the screen calls them, in a stable order. */
+private fun ChatRoomDetailUIState.Loaded.founderNamesFor(publicKeys: Set): String =
+ publicKeys.map { founderNames[it] ?: it }.sorted().joinToString(", ")
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt
index c2d7f2b1..0a503e3a 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt
@@ -16,8 +16,13 @@ import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.IO
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.launch
+import mobi.giza.compose.managers.FoundingAdmins
+import mobi.giza.compose.managers.MarmotGroupCreation
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.database.model.types.MarmotReindexReport
import mobi.giza.compose.managers.WalletRefusal
@@ -98,6 +103,14 @@ class ChatRoomDetailViewModel(
?.let { Event.fromJsonOrNull(it) }
?.let(WalletRefusal::isGuarded) == true
+ // The founding members, against what the ceremony that made the
+ // room's key said: who the policy leaves out, and who the founding
+ // invite never reached. docs/robust-group-admins.md, Phases 3 and 4.
+ val missingFoundingAdmins = (chatRepository.foundingAdmins(chatRoomId) as? FoundingAdmins.Check.Missing)
+ ?.publicKeys
+ .orEmpty()
+ val uninvitedFounders = chatRepository.uninvitedFounders(localChatRoom)
+
ChatRoomDetailUIState.Loaded(
localChatRoom = localChatRoom,
groupKeyState = groupKeyState,
@@ -109,8 +122,39 @@ class ChatRoomDetailViewModel(
canGovern = canGovern,
isDisbanded = isDisbanded,
shares = chatRepository.sharesSummary(localChatRoom),
+ missingFoundingAdmins = missingFoundingAdmins,
+ uninvitedFounders = uninvitedFounders,
+ founderNames = (missingFoundingAdmins + uninvitedFounders).associateWith { publicKey ->
+ nostrRepository.getProfileWithPublicKey(publicKey)?.humanReadableNameOrPubkey()
+ ?: publicKey.take(SHORTENED_PUBLIC_KEY_LENGTH)
+ },
+ adminRoomId = if (localChatRoom.chatRoom.mlsGroupState == null) chatRepository.adminRoomOf(chatRoomId) else null,
)
}
+ localChatRoom?.let { observeShares(it.chatRoom.id) }
+ }
+ }
+
+ private var sharesObserver: Job? = null
+
+ /**
+ * Keeps the Shares section following the group: a key state signed, a
+ * proposal declined, a refresh moved on by another device, all while this
+ * screen is open (docs/rotation-waits-for-key-state.md, Phase 3). Only the
+ * section is read again -- the rest of the screen has its own paths.
+ */
+ @OptIn(FlowPreview::class)
+ private fun observeShares(roomId: String) {
+ if (sharesObserver != null) return
+ sharesObserver = viewModelScope.launch(Dispatchers.IO) {
+ chatRepository.observeSharesInputs(roomId)
+ // A signing session writes a row per message; read once it settles.
+ .debounce(SHARES_SETTLE_MILLIS)
+ .collect {
+ val loaded = chatRoomDetailUIState as? ChatRoomDetailUIState.Loaded ?: return@collect
+ val shares = chatRepository.sharesSummary(loaded.localChatRoom)
+ (chatRoomDetailUIState as? ChatRoomDetailUIState.Loaded)?.let { chatRoomDetailUIState = it.copy(shares = shares) }
+ }
}
}
@@ -119,22 +163,65 @@ class ChatRoomDetailViewModel(
* applied when a relay accepts it, so the member's row stays until then; the
* line saying they were removed is there at once.
*/
- fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey, onDone: (String?) -> Unit = {}) {
+ fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey, onDone: (failure: String?, rotationHeld: Boolean) -> Unit = { _, _ -> }) {
viewModelScope.launch(Dispatchers.IO) {
// Asked before the removal, while they are still in the room's roster.
val heldShare = chatRepository.holdsShare(localChatRoom, memberPublicKey)
val failure = runCatching { chatRepository.removeMember(localChatRoom, memberPublicKey) }
.exceptionOrNull()
- // Who else the rotation would leave out, for the offer to name.
- val preview = if (failure == null && heldShare) chatRepository.rotationPreview(localChatRoom, memberPublicKey) else null
+ // Offered only when a rotation could start now; while the last one is
+ // unfinished the offer would only be refused
+ // (docs/rotation-waits-for-key-state.md, Phase 2). Who else it would
+ // leave out, for the offer to name.
+ val rotation = if (failure == null && heldShare) chatRepository.sharesSummary(localChatRoom)?.rotation else null
+ val preview = if (rotation == SharesSummary.Rotation.Available) chatRepository.rotationPreview(localChatRoom, memberPublicKey) else null
initiateChatRoomDetail()
viewModelScope.launch(Dispatchers.Main) {
- onDone(failure?.message)
+ onDone(failure?.message, rotation is SharesSummary.Rotation.Held)
// The removal takes them out of the room, not out of the key: they
// can still help sign until the shares are rotated without them.
// A second act, offered rather than folded in -- it needs every
// remaining holder (docs/frost-share-refresh.md, Phase 9).
- if (failure == null && heldShare) rotationOffer = RotationOffer(localChatRoom, memberPublicKey, preview)
+ if (rotation == SharesSummary.Rotation.Available) rotationOffer = RotationOffer(localChatRoom, memberPublicKey, preview)
+ }
+ }
+ }
+
+ /**
+ * Adds the founding members the room's admin policy is missing, as an admin,
+ * and reloads the screen. One commit, applied when a relay accepts it, so the
+ * warning stays until then. docs/robust-group-admins.md, Phase 3.
+ */
+ fun addMissingFoundingAdmins(localChatRoom: LocalChatRoom, missing: Set, onDone: (String?) -> Unit = {}) {
+ if (isActionPending.value) return
+ isActionPending.value = true
+ viewModelScope.launch(Dispatchers.IO) {
+ val failure = runCatching { chatRepository.addAdmins(localChatRoom, missing) }.exceptionOrNull()
+ initiateChatRoomDetail()
+ viewModelScope.launch(Dispatchers.Main) {
+ isActionPending.value = false
+ onDone(failure?.message)
+ }
+ }
+ }
+
+ /**
+ * Finishes the room's founding invite, and reloads the screen. Reports null
+ * when it went out, or why not -- naming the founders still without a key
+ * package, since only they can publish one. docs/robust-group-admins.md,
+ * Phase 4.
+ */
+ fun inviteFounders(chatRoomId: String, onDone: (MarmotGroupCreation.FoundingInvite) -> Unit = {}) {
+ // Waits on relays for key packages, so a second tap would ask twice.
+ if (isActionPending.value) return
+ isActionPending.value = true
+ viewModelScope.launch(Dispatchers.IO) {
+ val invite = runCatching { chatRepository.finishFoundingInvite(chatRoomId) }
+ .getOrElse { MarmotGroupCreation.FoundingInvite.Failed(it.message ?: "Couldn't invite them. Please try again.") }
+ initiateChatRoomDetail()
+ viewModelScope.launch(Dispatchers.Main) {
+ isActionPending.value = false
+ onDone(invite)
}
}
}
@@ -145,9 +232,17 @@ class ChatRoomDetailViewModel(
* goes on with in the background, so done means sent, not finished.
*/
private fun sharesAction(onDone: (String?) -> Unit, action: suspend () -> String?) {
+ // One at a time: the section's buttons read this, so a second tap while the
+ // first is on its way does nothing rather than reporting twice.
+ if (isActionPending.value) return
+ isActionPending.value = true
viewModelScope.launch(Dispatchers.IO) {
- val failure = action()
- initiateChatRoomDetail()
+ val failure = try {
+ action()
+ } finally {
+ initiateChatRoomDetail()
+ viewModelScope.launch(Dispatchers.Main) { isActionPending.value = false }
+ }
viewModelScope.launch(Dispatchers.Main) { onDone(failure) }
}
}
@@ -185,6 +280,9 @@ class ChatRoomDetailViewModel(
fun approveShares(localChatRoom: LocalChatRoom, approval: SharesSummary.PendingApproval, onDone: (String?) -> Unit) =
sharesAction(onDone) { chatRepository.approveShares(localChatRoom, approval) }
+ fun proposeKeyState(localChatRoom: LocalChatRoom, onDone: (String?) -> Unit) =
+ sharesAction(onDone) { chatRepository.proposeKeyState(localChatRoom) }
+
fun abandonRotation(localChatRoom: LocalChatRoom, sessionId: String, onDone: (String?) -> Unit) =
sharesAction(onDone) { chatRepository.abandonRotation(localChatRoom, sessionId) }
@@ -304,6 +402,12 @@ class ChatRoomDetailViewModel(
companion object {
private const val TAG = "ChatRoomDetailViewModel"
+ /** How long the Shares section's inputs have to be still before it is read again. */
+ internal const val SHARES_SETTLE_MILLIS = 250L
+
+ /** Enough of a key to tell two founders apart when no profile is stored. */
+ private const val SHORTENED_PUBLIC_KEY_LENGTH = 12
+
fun factory(
activeUserPublicKey: HexKey,
chatRoomId: String,
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModel.kt
index 4bca2b1a..115dd582 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModel.kt
@@ -53,7 +53,6 @@ import mobi.giza.compose.database.model.intermdiate.LocalFrostSigningSession
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlin.time.Instant
-import mobi.giza.compose.managers.CeremonyFollowThrough
/**
* Watches one ChillDKG ritual, and the steps that follow it.
@@ -522,7 +521,7 @@ class DkgRitualViewModel(
val loaded = dkgRitualUIState as? DkgRitualUIState.Loaded ?: return
val session = loaded.session
- val thresholdPublicKey = session.thresholdPublicKey ?: return
+ if (session.thresholdPublicKey == null) return
// The screen offers nothing until the group has signed, so this is a
// guard rather than a path anybody takes.
@@ -535,43 +534,24 @@ class DkgRitualViewModel(
}
val keyPair = KeyPair(privKey = nostrPrivateKey.value.toByteArray())
- val groupId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey)
-
- // Everyone the ceremony was run with, this device included. These are the
- // admins: the whole point of the room is that the members who hold shares of
- // the key can all act in it.
- //
- // Off the ceremony rather than off the room, because for a subgroup the
- // room is the parent's and its roster is the wrong set entirely.
- val members = ChillDkgRitualManager.participantsOf(session, loaded.localChatRoom)
-
- // A subgroup is called what the coordinator called it; an admin room is
- // called after the group it administers, because it has no name of its
- // own to be given. Either way the bare name goes down and
- // `MarmotGroupCreation` puts it under `MarmotGroupName`, so a NIP-17 room
- // called `Ekklesia` stands up a Marmot room called `#Ekklesia`.
- // The same name and description the coordinator's device uses when it
- // creates the room on its own -- see `CeremonyFollowThrough` -- so the two
- // ways of making it cannot make two different rooms.
- val subgroupParent = loaded.parentChatRoomId
-
- val name = CeremonyFollowThrough.roomName(session)
isActionPending.value = true
adminGroupBlockedOn.value = emptyList()
viewModelScope.launch(Dispatchers.IO) {
+ // The room, its name and its admins all come off the ceremony, inside
+ // `MarmotGroupCreation.createFor` -- the same call the coordinator's
+ // device makes on its own in `CeremonyFollowThrough`, so the two ways of
+ // making it cannot make two different rooms. Nothing here names an
+ // admin: docs/robust-group-admins.md, Phase 1.
val outcome = chatRepository.createMarmotGroup(
- groupId = groupId,
- name = name,
- purpose = CeremonyFollowThrough.roomPurpose(session),
- adminPublicKeys = members,
- userPublicKey = activeUserPublicKey,
+ ceremony = session,
+ ceremonyRoom = loaded.localChatRoom,
keyPair = keyPair,
// Verified by the time it is written: the key state this room was
// gated on carries the certificate, and `stateFrom` refused it
// otherwise.
- parentChatRoomId = subgroupParent
+ parentChatRoomId = loaded.parentChatRoomId
)
isActionPending.value = false
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SelectChatRoomTypeViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SelectChatRoomTypeViewModel.kt
index 0d4c290f..3a884bed 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SelectChatRoomTypeViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SelectChatRoomTypeViewModel.kt
@@ -94,6 +94,12 @@ class SelectChatRoomTypeViewModel(
/**
* Everyone who administers the group under [ChatRoomType.ROBUST]: the picked
* members plus the creator.
+ *
+ * Counted here only to offer a quorum. The admins themselves are read off
+ * the ceremony this screen opens -- `ChillDkgRitualManager.proposeRitual`
+ * builds its participants by the same rule, the room's members plus the
+ * creator -- and `MarmotGroupCreation.createFor` makes the admin room from
+ * those. See docs/robust-group-admins.md, Phase 1.
*/
val adminCount: Int = (memberPublicKeys + activeUserPublicKey).distinct().size
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt
index 9985c278..0cb4d9b5 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt
@@ -248,6 +248,13 @@ class SynchronizationViewModel(
// (docs/rotate-shares-single-approval.md, Phase 3).
runCatching { nostrRepository.resumeRunningCeremonies(keyPair) }
.onFailure { logger.e("Could not resume running key ceremonies", it) }
+ // The rooms joined before the Welcome wrote admin flags
+ // flag nobody until some commit arrives, and a robust
+ // group's admin room may never get one. Caught up here,
+ // once a start; a room already right is read, not
+ // written. docs/robust-group-admins.md, Phase 6.
+ runCatching { chatRepository.reconcileAdminFlags() }
+ .onFailure { logger.e("Could not bring admin flags in line", it) }
launch(Dispatchers.IO) { observePendingBroadcastNostrEventRequests(keyPair) }
// Runs until cancelled rather than draining a queue, but it
// belongs here for the same reason the pumps do: it needs the
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt
index 5b7b8511..a7fe3b32 100755
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt
@@ -84,6 +84,33 @@ sealed interface ChatRoomDetailUIState {
* room has no key (docs/frost-share-refresh.md, Phase 11).
*/
val shares: SharesSummary? = null,
+ /**
+ * Members of the ceremony that made this room's key whom its admin policy
+ * does not name -- empty when it names them all, and when this device has
+ * no record of the ceremony to check against. Read through
+ * `FoundingAdmins.check`; docs/robust-group-admins.md, Phase 3.
+ */
+ val missingFoundingAdmins: Set = emptySet(),
+ /**
+ * Founding members this room's founding invite never reached -- only ever
+ * non-empty on the device that made the room, while it is still at epoch 0.
+ * See `MarmotGroupCreation.uninvitedFounders`; docs/robust-group-admins.md,
+ * Phase 4.
+ */
+ val uninvitedFounders: Set = emptySet(),
+ /**
+ * What to call the founders the two sets above name. They need not be in
+ * this room -- an uninvited one is not, by definition -- so the room's own
+ * rows cannot be asked.
+ */
+ val founderNames: Map = emptyMap(),
+ /**
+ * The admin room this group's ceremony made, when this is the group's
+ * NIP-17 room and this device holds it. A NIP-17 room has no admins of its
+ * own; this is where its members are admins. docs/robust-group-admins.md,
+ * Phase 5.
+ */
+ val adminRoomId: String? = null,
): ChatRoomDetailUIState
data class Error(
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt
index af7dbc63..06c4c1e0 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt
@@ -13,8 +13,8 @@ data class SharesSummary(
val generation: Int,
val members: List,
val pending: List,
- /** This device holds a live share and no rotation is running: it may propose one. */
- val canRotate: Boolean,
+ /** Whether this device may propose a rotation, and if not, what it waits on. */
+ val rotation: Rotation,
/** This device's own id is stale and nothing is bringing it back yet. */
val canAskToBeRepaired: Boolean,
/** A rotation under way, from its one approval until the group signs the new generation. */
@@ -24,6 +24,27 @@ data class SharesSummary(
) {
data class Member(val publicKey: HexKey, val name: String, val standing: ShareStanding, val isSelf: Boolean)
+ /**
+ * The rotate action, as the section shows it (docs/rotation-waits-for-key-state.md).
+ * [ShareRefreshManager.rotationHold][mobi.giza.compose.managers.ShareRefreshManager.rotationHold]
+ * decides it, the same function proposing asks, so the button and the protocol agree.
+ */
+ sealed interface Rotation {
+ /** No live share here, or a build without the feature: no button. */
+ data object Unavailable : Rotation
+
+ data object Available : Rotation
+
+ /**
+ * The button, disabled, and why. [canAskForSignature]: the group owes the
+ * key state at this generation and nobody here is asking for it, so this
+ * device can.
+ */
+ data class Held(val reason: Reason, val canAskForSignature: Boolean = false) : Rotation
+
+ enum class Reason { ROTATION_RUNNING, AWAITING_SIGNATURES, BEHIND }
+ }
+
/**
* Something this device's owner is being asked, and the session it is for.
* A rotation's carries who it leaves out, because agreeing to that is what
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt
index 5ff9d1fc..25e9ad7c 100644
--- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt
@@ -15,6 +15,7 @@ import kotlinx.coroutines.runBlocking
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.builder.getRoomDatabase
import mobi.giza.compose.database.model.DkgSession
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.database.model.GroupSignedEvent
import mobi.giza.compose.database.model.types.DkgApprovalStep
import mobi.giza.compose.database.model.types.DkgRitualStage
@@ -49,21 +50,22 @@ class CeremonyFollowThroughJvmTest {
/** The room creations asked for, and what the next one answers. */
private val created = mutableListOf>>()
private var outcome: (String) -> MarmotGroupCreation.Outcome = { MarmotGroupCreation.Outcome.Failed("unset") }
+ private var foundingInvite: MarmotGroupCreation.FoundingInvite = MarmotGroupCreation.FoundingInvite.NothingToDo
private val chatRepository = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY {
override suspend fun createMarmotGroup(
- groupId: String,
- name: String,
- purpose: String,
- adminPublicKeys: Set,
- userPublicKey: HexKey,
+ ceremony: DkgSession,
+ ceremonyRoom: LocalChatRoom,
keyPair: KeyPair,
- path: List,
parentChatRoomId: HexKey?,
): MarmotGroupCreation.Outcome {
+ val groupId = SharedKeyDerivation.marmotGroupId(ceremony.thresholdPublicKey!!)
+ val adminPublicKeys = ChillDkgRitualManager.participantsOf(ceremony, ceremonyRoom)
created += groupId to adminPublicKeys
return outcome(groupId)
}
+
+ override suspend fun finishFoundingInvite(ceremony: DkgSession, ceremonyRoom: LocalChatRoom) = foundingInvite
}
private val material = keyMaterial("5eed0000000000000000000000000000000000000000000000000000000000e5")
@@ -204,6 +206,28 @@ class CeremonyFollowThroughJvmTest {
assertTrue(created.isEmpty())
}
+ /** docs/robust-group-admins.md, Phase 4: a room that exists is asked whether its founding invite went out. */
+ @Test
+ fun `a room whose founding invite never went out has it finished`(): Unit = runBlocking {
+ val session = finishedCeremony()
+ signKeyState(session)
+ GroupFixtures.seedRoom(db, roomOf(material))
+ foundingInvite = MarmotGroupCreation.FoundingInvite.Sent(roomOf(material), invited = listOf(alice, bob), notAdded = listOf(bob))
+
+ assertEquals(CeremonyFollowThrough.Step.Invited(roomOf(material), listOf(bob)), next(session))
+ assertTrue(created.isEmpty(), "and no second room")
+ }
+
+ @Test
+ fun `a founding invite waiting on key packages says on whom`(): Unit = runBlocking {
+ val session = finishedCeremony()
+ signKeyState(session)
+ GroupFixtures.seedRoom(db, roomOf(material))
+ foundingInvite = MarmotGroupCreation.FoundingInvite.BlockedOn(listOf(alice))
+
+ assertEquals(CeremonyFollowThrough.Step.BlockedOn(listOf(alice)), next(session))
+ }
+
/**
* A subgroup's room needs its parent's certificate before its key state can
* even be proposed, so that is asked for first -- and then the parent's
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/FoundingAdminsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/FoundingAdminsJvmTest.kt
new file mode 100644
index 00000000..adb93818
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/FoundingAdminsJvmTest.kt
@@ -0,0 +1,221 @@
+package mobi.giza.compose.managers
+
+import androidx.room3.Room
+import com.vitorpamplona.marmot.groups.currentAdminIdentities
+import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.core.toHexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import kotlin.test.AfterTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertIs
+import kotlin.test.assertNotNull
+import kotlin.test.assertTrue
+import kotlin.time.Clock
+import kotlin.time.Instant
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.runBlocking
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.builder.getRoomDatabase
+import mobi.giza.compose.database.model.ChatMessage
+import mobi.giza.compose.database.model.ChatRoom
+import mobi.giza.compose.database.model.DkgSession
+import mobi.giza.compose.database.model.GroupKeyState
+import mobi.giza.compose.database.model.Participant
+import mobi.giza.compose.database.model.types.DkgRitualStage
+import mobi.giza.compose.database.repository.DatabaseChatRepository
+import mobi.giza.compose.database.repository.DatabaseNostrRepository
+import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.nostr.MarmotProfile
+import mobi.giza.compose.nostr.Relays
+
+/**
+ * A device checking the room it holds against the ceremony it took part in.
+ * docs/robust-group-admins.md, Phase 3.
+ *
+ * The rooms here are made with [MarmotGroupCreation.create] and a list of admins
+ * on purpose: that is the one way to stand in for a room some other device made
+ * with fewer admins than the ceremony had, which is what the check is for.
+ */
+class FoundingAdminsJvmTest {
+
+ private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder())
+ private val scope = CoroutineScope(Dispatchers.Default)
+ private val chatRepository = DatabaseChatRepository(db, scope)
+ private val nostrRepository = DatabaseNostrRepository(db, scope)
+
+ @AfterTest
+ fun closeDb() = db.close()
+
+ private val keyPair = KeyPair()
+ private val user = keyPair.pubKey.toHexKey()
+ private val alice = KeyPair().pubKey.toHexKey()
+ private val bob = KeyPair().pubKey.toHexKey()
+ private val founders = setOf(user, alice, bob)
+
+ private val thresholdPublicKey = "02" + KeyPair().pubKey.toHexKey()
+ private val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey)
+ private val ceremonyRoomId = "ce1e".repeat(16)
+ private val sessionId = "the-ceremony"
+
+ /**
+ * A room at [roomId] whose epoch-0 admins are [admins] -- whatever the ceremony
+ * said -- holding only its creator. Built from the steps `MarmotGroupCreation`
+ * takes, minus the invites: the check is about the policy, and listing an admin
+ * needs no key package of theirs.
+ */
+ private suspend fun roomWithAdmins(admins: Set, profile: MarmotProfile = MarmotProfile.LEGACY) {
+ (founders + admins).forEach { MarmotStandIn.seedProfile(db, it) }
+ val created = MarmotGroupFactory.create(
+ creator = keyPair,
+ roomId = roomId,
+ name = "#Ekklesia",
+ description = SharedKeyDerivation.describe("Admins of Ekklesia."),
+ adminPublicKeys = admins,
+ relays = Relays.DefaultDMRelayList.map { it.url },
+ profile = profile,
+ )
+ assertNotNull(
+ chatRepository.getOrCreateChatRoom(
+ chatRoomId = roomId,
+ activeUserPublicKey = user,
+ relayHint = null,
+ defaultSubject = "#Ekklesia",
+ description = null,
+ mlsGroupState = created.group.saveState().encodeTls().toHex(),
+ )
+ )
+ chatRepository.recordMarmotRouting(chatRoomId = roomId, routingId = created.routingId)
+ }
+
+ private suspend fun ceremony(participants: Set? = founders) {
+ db.chatRoomDao().upsert(ChatRoom(id = ceremonyRoomId, userPublicKey = user, subject = "Ekklesia", description = null, mlsGroupState = null))
+ db.dkgSessionDao().upsert(
+ DkgSession(
+ id = sessionId,
+ chatRoomId = ceremonyRoomId,
+ coordinatorPublicKey = user,
+ userPublicKey = user,
+ threshold = 2,
+ participantCount = 3,
+ participantPublicKeys = participants?.let { DkgSession.formatParticipants(it) },
+ subject = "Ekklesia",
+ stage = DkgRitualStage.COMPLETE,
+ hostPublicKey = user,
+ round1Random = "aa".repeat(32),
+ round2AuxRandom = "bb".repeat(32),
+ thresholdPublicKey = thresholdPublicKey,
+ secretShare = "cc".repeat(32),
+ )
+ )
+ }
+
+ private suspend fun keyState() {
+ db.groupKeyStateDao().replace(
+ GroupKeyState(
+ chatRoomId = roomId,
+ dkgSessionId = sessionId,
+ thresholdPublicKey = thresholdPublicKey,
+ derivationPath = SharedKeyDerivation.formatPath(SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH),
+ announcedBy = roomId,
+ announcedAt = Clock.System.now(),
+ )
+ )
+ }
+
+ @Test
+ fun `a room with no key behind it has no founders to check`(): Unit = runBlocking {
+ roomWithAdmins(setOf(user))
+ assertEquals(FoundingAdmins.Check.NotKeyBacked, FoundingAdmins.check(db, roomId))
+ }
+
+ @Test
+ fun `a device that holds no ceremony for the room cannot check it`(): Unit = runBlocking {
+ roomWithAdmins(setOf(user))
+ keyState()
+ assertEquals(FoundingAdmins.Check.CannotCheck, FoundingAdmins.check(db, roomId))
+ }
+
+ @Test
+ fun `a room made with every founder as an admin matches`(): Unit = runBlocking {
+ roomWithAdmins(founders)
+ ceremony()
+ keyState()
+ assertEquals(FoundingAdmins.Check.Matches, FoundingAdmins.check(db, roomId))
+ }
+
+ @Test
+ fun `a room made by a device that listed only itself is missing the others`(): Unit = runBlocking {
+ roomWithAdmins(setOf(user))
+ ceremony()
+ keyState()
+ assertEquals(FoundingAdmins.Check.Missing(setOf(alice, bob)), FoundingAdmins.check(db, roomId))
+ }
+
+ @Test
+ fun `a ceremony from before its participant list falls back to its room's members`(): Unit = runBlocking {
+ roomWithAdmins(setOf(user))
+ ceremony(participants = null)
+ db.participantDao().upsert(founders.map { Participant(participantPublicKey = it, chatRoomId = ceremonyRoomId, relayHint = null) })
+ keyState()
+ assertEquals(FoundingAdmins.Check.Missing(setOf(alice, bob)), FoundingAdmins.check(db, roomId))
+ }
+
+ /** What the Welcome path writes: one line naming who is missing, and none when nobody is. */
+ @Test
+ fun `the room says who it is missing, once, and only when someone is`(): Unit = runBlocking {
+ roomWithAdmins(setOf(user))
+ ceremony()
+ keyState()
+
+ FoundingAdmins.announceIfMissing(db, roomId, user)
+ val lines = db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage }
+ .filter { it.messageType == ChatMessage.TYPE_FOUNDING_ADMINS_MISSING }
+ val line = lines.single()
+ assertTrue(alice.take(8) in line.content && bob.take(8) in line.content, line.content)
+ assertTrue(ChatMessage.TYPE_FOUNDING_ADMINS_MISSING in ChatMessage.MEMBERSHIP_TYPES, "it would render as a chat bubble")
+ }
+
+ @Test
+ fun `a room that names every founder says nothing`(): Unit = runBlocking {
+ roomWithAdmins(founders)
+ ceremony()
+ keyState()
+
+ assertEquals(FoundingAdmins.Check.Matches, FoundingAdmins.announceIfMissing(db, roomId, user))
+ assertTrue(db.chatMessageDao().getChatMessagesByChatRoomId(roomId).none {
+ it.chatMessage.messageType == ChatMessage.TYPE_FOUNDING_ADMINS_MISSING
+ })
+ }
+
+ /**
+ * The repair: one commit that adds the missing founders to the policy and
+ * leaves every admin already there in place. On the current profile, where
+ * the app governs a room; the relay's OK is played by hand.
+ */
+ @Test
+ fun `an admin puts the missing founders back into the policy`(): Unit = runBlocking {
+ roomWithAdmins(setOf(user), MarmotProfile.CURRENT)
+ ceremony()
+ keyState()
+ val missing = assertIs(FoundingAdmins.check(db, roomId)).publicKeys
+
+ chatRepository.addAdmins(db.chatRoomDao().findChatRoomById(roomId)!!, missing)
+ okTheLatestCommit()
+
+ val room = db.chatRoomDao().findChatRoomById(roomId)!!
+ val group = assertNotNull(db.marmotEngine.groupFor(room.routingId))
+ assertEquals(founders, group.currentAdminIdentities())
+ assertEquals(FoundingAdmins.Check.Matches, FoundingAdmins.check(db, roomId))
+ }
+
+ private suspend fun okTheLatestCommit() {
+ val event = db.nostrEventDao().getMLSGroupEvents(since = Instant.fromEpochSeconds(0), limit = 20)
+ .filter { it.kind == GroupEvent.KIND }
+ .last { db.marmotCommitResultDao().getMarmotCommitRequestById(it.id) != null }
+ val request = assertNotNull(db.broadcastNostrEventRequestDao().getFirstBroadcastNostrEventRequestByNostrEventId(event.id))
+ nostrRepository.broadcastProcessed(request, "published")
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/KeyStateSignsItselfJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/KeyStateSignsItselfJvmTest.kt
index ce886ee3..c5c15336 100644
--- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/KeyStateSignsItselfJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/KeyStateSignsItselfJvmTest.kt
@@ -9,8 +9,10 @@ import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlinx.coroutines.runBlocking
+import mobi.giza.compose.database.model.DkgSession
import mobi.giza.compose.database.model.FrostSigningItem
import mobi.giza.compose.database.model.FrostSigningSession
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.database.model.types.DkgApprovalStep
import mobi.giza.compose.database.model.types.DkgRitualStage
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
@@ -32,15 +34,13 @@ class KeyStateSignsItselfJvmTest {
private val chatRepository = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY {
override suspend fun createMarmotGroup(
- groupId: String,
- name: String,
- purpose: String,
- adminPublicKeys: Set,
- userPublicKey: HexKey,
+ ceremony: DkgSession,
+ ceremonyRoom: LocalChatRoom,
keyPair: KeyPair,
- path: List,
parentChatRoomId: HexKey?,
): MarmotGroupCreation.Outcome {
+ val groupId = SharedKeyDerivation.marmotGroupId(ceremony.thresholdPublicKey!!)
+ val adminPublicKeys = ChillDkgRitualManager.participantsOf(ceremony, ceremonyRoom)
created += groupId to adminPublicKeys
return MarmotGroupCreation.Outcome.Failed("the room is MarmotGroupCreation's to test")
}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt
index 3b7f1528..1285b919 100644
--- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt
@@ -22,7 +22,15 @@ import kotlinx.coroutines.IO
import kotlinx.coroutines.runBlocking
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.builder.getRoomDatabase
+import com.vitorpamplona.marmot.appComponents.CurrentProfileGroupFactory
+import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal
+import mobi.giza.compose.database.model.ChatRoom
+import mobi.giza.compose.database.model.DkgSession
+import mobi.giza.compose.database.model.MarmotKeyPackage
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+import mobi.giza.compose.database.model.types.DkgRitualStage
import mobi.giza.compose.database.model.NostrEvent
+import mobi.giza.compose.database.model.Participant
import mobi.giza.compose.database.model.Profile
import mobi.giza.compose.database.repository.DatabaseChatRepository
import mobi.giza.compose.extensions.toHex
@@ -153,9 +161,145 @@ class MarmotGroupCreationJvmTest {
assertEquals("#Ekklesia", data.name)
}
- private suspend fun seedProfile(publicKey: String) {
+ /**
+ * One writer for the flags, from the group's policy, both ways: a row the
+ * policy names is flagged, and a row it does not name loses a flag it had.
+ * docs/robust-group-admins.md, Phase 2.
+ */
+ @Test
+ fun `admin flags follow the group's policy, both ways`(): Unit = runBlocking {
+ seedProfile(user)
+ MarmotGroupCreation.create(
+ database = db,
+ chatRepository = repository,
+ groupId = groupId,
+ name = "#Ekklesia",
+ purpose = "Admins of Ekklesia.",
+ adminPublicKeys = setOf(user),
+ userPublicKey = user,
+ keyPair = keyPair,
+ )
+
+ val stranger = KeyPair().pubKey.toHexKey()
+ seedProfile(stranger)
+ val creatorRow = db.chatRoomDao().findChatRoomById(groupId)!!.localParticipants
+ .single { it.participant.participantPublicKey == user }.participant
+ db.participantDao().upsert(
+ listOf(
+ creatorRow.copy(adminAt = null),
+ Participant(participantPublicKey = stranger, chatRoomId = groupId, relayHint = null, adminAt = Clock.System.now()),
+ )
+ )
+
+ val group = assertNotNull(db.chatRoomDao().findChatRoomById(groupId)!!.chatRoom.toMlsGroup())
+ assertEquals(2, AdminFlags.reconcile(db, groupId, group))
+
+ val rows = db.chatRoomDao().findChatRoomById(groupId)!!.localParticipants.associate {
+ it.participant.participantPublicKey to it.participant.adminAt
+ }
+ assertNotNull(rows[user], "the policy names the creator")
+ assertNull(rows[stranger], "the policy does not name the stranger")
+ assertEquals(0, AdminFlags.reconcile(db, groupId, group), "and a second pass changes nothing")
+ }
+
+ // ---- From a ceremony: docs/robust-group-admins.md, Phase 1 ----------------
+
+ private val alice = KeyPair()
+ private val bob = KeyPair()
+ private val ceremonyRoomId = "ce1e".repeat(16)
+
+ /** A finished ceremony over [user], alice and bob, as [owner]'s device holds it. */
+ private suspend fun ceremonyOn(database: GizaDatabase, owner: KeyPair): Pair {
+ val everyone = listOf(keyPair, alice, bob)
+ everyone.forEach { seedProfile(it.pubKey.toHexKey(), database) }
+
+ // Everybody but the device's own owner, as that device would have synced them.
+ everyone.filter { it !== owner }.forEach { peer ->
+ val bundle = CurrentProfileGroupFactory.createKeyPackage(NostrSignerInternal(peer))
+ database.marmotKeyPackageDao().upsert(
+ MarmotKeyPackage(
+ id = peer.pubKey.toHexKey().take(60) + "0000",
+ publicKey = peer.pubKey.toHexKey(),
+ tlsEncodedMarmotKeyPackage = bundle.keyPackage.toTlsBytes(),
+ profile = MarmotProfile.CURRENT.wireName,
+ )
+ )
+ }
+
+ database.chatRoomDao().upsert(
+ ChatRoom(id = ceremonyRoomId, userPublicKey = owner.pubKey.toHexKey(), subject = "Ekklesia", description = null, mlsGroupState = null)
+ )
+ val session = DkgSession(
+ id = "the-ceremony",
+ chatRoomId = ceremonyRoomId,
+ coordinatorPublicKey = user,
+ userPublicKey = owner.pubKey.toHexKey(),
+ threshold = 2,
+ participantCount = 3,
+ participantPublicKeys = DkgSession.formatParticipants(everyone.map { it.pubKey.toHexKey() }.toSet()),
+ subject = "Ekklesia",
+ stage = DkgRitualStage.COMPLETE,
+ hostPublicKey = owner.pubKey.toHexKey(),
+ round1Random = "aa".repeat(32),
+ round2AuxRandom = "bb".repeat(32),
+ thresholdPublicKey = "02" + "ab".repeat(32),
+ secretShare = "cc".repeat(32),
+ )
+ database.dkgSessionDao().upsert(session)
+ return session to assertNotNull(database.chatRoomDao().findChatRoomById(ceremonyRoomId))
+ }
+
+ @Test
+ fun `the room's admins are the ceremony's participants, whoever creates it`(): Unit = runBlocking {
+ val founders = setOf(user, alice.pubKey.toHexKey(), bob.pubKey.toHexKey())
+ val alicesDb = getRoomDatabase(Room.inMemoryDatabaseBuilder())
+
+ try {
+ // The coordinator's device, and a member's -- the two ways the room gets made.
+ listOf(db to keyPair, alicesDb to alice).forEach { (database, owner) ->
+ val (session, ceremonyRoom) = ceremonyOn(database, owner)
+
+ val outcome = MarmotGroupCreation.createFor(
+ database = database,
+ chatRepository = DatabaseChatRepository(database, CoroutineScope(Dispatchers.IO)),
+ ceremony = session,
+ ceremonyRoom = ceremonyRoom,
+ keyPair = owner,
+ keyPackageLookupTimeout = 2_000L,
+ )
+ val created = assertIs(outcome)
+ assertEquals(groupId, created.room.chatRoom.id, "the room is not the one the key derives")
+ assertEquals("#Ekklesia", created.room.chatRoom.subject)
+
+ val group = assertNotNull(created.room.chatRoom.toMlsGroup())
+ assertEquals(founders, group.currentAdminIdentities(), "${owner.pubKey.toHexKey().take(8)}'s room")
+ }
+ } finally {
+ alicesDb.close()
+ }
+ }
+
+ @Test
+ fun `a device that was not in the ceremony cannot create its room`(): Unit = runBlocking {
+ val (session, ceremonyRoom) = ceremonyOn(db, keyPair)
+ val outsider = session.copy(userPublicKey = KeyPair().pubKey.toHexKey())
+
+ val outcome = MarmotGroupCreation.createFor(
+ database = db,
+ chatRepository = repository,
+ ceremony = outsider,
+ ceremonyRoom = ceremonyRoom,
+ keyPair = KeyPair(),
+ )
+
+ assertIs(outcome)
+ assertNull(db.chatRoomDao().findChatRoomById(groupId), "a room was made anyway")
+ }
+
+ private suspend fun seedProfile(publicKey: String, database: GizaDatabase = db) {
+ if (database.profileDao().getProfileByPublicKey(publicKey) != null) return
val nostrEventId = publicKey.take(63) + "f"
- db.nostrEventDao().upsert(
+ database.nostrEventDao().upsert(
NostrEvent(
id = nostrEventId,
pubKey = publicKey,
@@ -165,7 +309,7 @@ class MarmotGroupCreationJvmTest {
sig = "0".repeat(128),
)
)
- db.profileDao().upsert(
+ database.profileDao().upsert(
Profile(publicKey = publicKey, userName = "member", nostrEventId = nostrEventId)
)
}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt
new file mode 100644
index 00000000..99d6a32b
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt
@@ -0,0 +1,397 @@
+package mobi.giza.compose.managers
+
+import androidx.room3.Room
+import com.vitorpamplona.marmot.groups.currentAdminIdentities
+import com.vitorpamplona.marmot.groups.isLocalAdmin
+import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent
+import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent
+import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.core.toHexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
+import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler
+import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent
+import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
+import kotlin.test.Test
+import kotlin.test.assertFalse
+import kotlin.test.assertEquals
+import kotlin.test.assertIs
+import kotlin.test.assertNotNull
+import kotlin.test.assertTrue
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlin.time.Instant
+import kotlinx.coroutines.runBlocking
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.builder.getRoomDatabase
+import mobi.giza.compose.database.model.MarmotKeyPackage
+import mobi.giza.compose.nostr.Relays
+import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.database.model.types.DkgRitualStage
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+import mobi.giza.compose.database.model.DkgSession
+import mobi.giza.compose.database.model.ChatRoom
+import mobi.giza.compose.database.model.types.DkgApprovalStep
+import mobi.giza.compose.database.repository.DatabaseChatRepository
+import mobi.giza.compose.database.repository.DatabaseMarmotRepository
+import mobi.giza.compose.database.repository.DatabaseNostrRepository
+import mobi.giza.compose.nostr.MarmotProfile
+
+/**
+ * The promise a robust group makes -- "everyone administers the group together" --
+ * held on every device of every founding member. docs/robust-group-admins.md.
+ *
+ * Two halves. The ceremony half runs real ChillDKG on [CeremonyNetwork] and checks
+ * that every device agrees who the founding members are. The room half has one app
+ * device create the admin room and the others join it by a real Welcome, gift
+ * wrapped and stored through the same funnel a relay's copy goes through, because
+ * the Welcome is where a joiner first learns -- or fails to learn -- who its
+ * admins are.
+ */
+class RobustGroupAdminsJvmTest {
+
+ /** One phone: its own database, as in the app, and nothing shared with the others. */
+ private class Phone(profile: MarmotProfile) : AutoCloseable {
+ val keyPair = KeyPair()
+ val publicKey: HexKey = keyPair.pubKey.toHexKey()
+ val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder())
+ val chatRepository = DatabaseChatRepository(db, CoroutineScope(Dispatchers.Default))
+ private val nostrRepository = DatabaseNostrRepository(db, CoroutineScope(Dispatchers.Default))
+ private val marmotRepository = DatabaseMarmotRepository(db, CoroutineScope(Dispatchers.Default))
+
+ /** This phone's key package, as another phone would have synced it. */
+ lateinit var keyPackage: MarmotKeyPackage
+
+ val ready: suspend () -> Unit = {
+ marmotRepository.publishMarmotKeyPackageBundle(keyPair, setOf(profile))
+ val bundle = db.marmotKeyPackageBundleDao().getAllMarmotKeyPackageBundles(publicKey).single()
+ keyPackage = MarmotKeyPackage(
+ id = bundle.id,
+ publicKey = publicKey,
+ tlsEncodedMarmotKeyPackage = bundle.tlsEncodedMarmotKeyPackage,
+ profile = profile.wireName,
+ )
+ }
+
+ /**
+ * A relay's OK on the newest commit this phone put on the wire. An invite
+ * into a room that already has members holds its Welcome back until then.
+ */
+ suspend fun okTheLatestCommit() {
+ val event = db.nostrEventDao().getMLSGroupEvents(since = Instant.fromEpochSeconds(0), limit = 20)
+ .filter { it.kind == GroupEvent.KIND }
+ .last { db.marmotCommitResultDao().getMarmotCommitRequestById(it.id) != null }
+ val request = assertNotNull(db.broadcastNostrEventRequestDao().getFirstBroadcastNostrEventRequestByNostrEventId(event.id))
+ nostrRepository.broadcastProcessed(request, "published")
+ }
+
+ override fun close() = db.close()
+ override fun toString() = publicKey.take(8)
+ }
+
+ private val foundingThresholdPublicKey = "02" + KeyPair().pubKey.toHexKey()
+ private val roomId = SharedKeyDerivation.marmotGroupId(foundingThresholdPublicKey)
+
+ /**
+ * Three phones; the first creates the admin room with all three as its admins,
+ * as `CeremonyFollowThrough` does after a ceremony, and the other two join it.
+ */
+ private suspend fun foundedRoom(profile: MarmotProfile, size: Int = 3): List {
+ val phones = List(size) { Phone(profile) }
+ phones.forEach { it.ready() }
+ phones.forEach { phone -> phones.forEach { MarmotStandIn.seedProfile(phone.db, it.publicKey) } }
+
+ val creator = phones.first()
+ phones.drop(1).forEach { creator.db.marmotKeyPackageDao().upsert(it.keyPackage) }
+
+ val outcome = MarmotGroupCreation.create(
+ database = creator.db,
+ chatRepository = creator.chatRepository,
+ groupId = roomId,
+ name = "Ekklesia",
+ purpose = "Admins of Ekklesia.",
+ adminPublicKeys = phones.map { it.publicKey }.toSet(),
+ userPublicKey = creator.publicKey,
+ keyPair = creator.keyPair,
+ keyPackageLookupTimeout = 2_000L,
+ profile = profile,
+ )
+ val created = assertIs(outcome)
+ assertTrue(created.notAdded.isEmpty(), "the creator could not invite ${created.notAdded}")
+
+ phones.drop(1).forEach { welcome(from = creator, to = it) }
+ return phones
+ }
+
+ /** Hands [to] the Welcome [from] queued for it, wrapped as a relay would carry it. */
+ private suspend fun welcome(from: Phone, to: Phone, roomId: String = this.roomId) {
+ val payload = from.db.giftWrapPayloadDao().getAllGiftWrapUnsigned()
+ .filter { it.kind == WelcomeEvent.KIND }
+ .single { payload -> payload.tags.any { it.size > 1 && it[1] == to.keyPackage.id } }
+
+ val rumor = RumorAssembler.assembleRumor(
+ pubKey = from.publicKey,
+ ev = EventTemplate(payload.createdAt.epochSeconds, payload.kind, payload.tags, payload.content),
+ )
+ val signer = NostrSignerSync(from.keyPair)
+ val seal = signer.signNormal(
+ createdAt = rumor.createdAt, kind = SealEvent.KIND, tags = emptyArray(),
+ content = signer.nip44Encrypt(rumor.toJson(), to.publicKey),
+ )
+ val wrap = GiftWrapEvent.create(event = seal, recipientPubKey = to.publicKey, createdAt = rumor.createdAt)
+
+ MarmotStandIn.storeInApp(to.db, to.keyPair, wrap)
+ assertNotNull(to.db.chatRoomDao().findChatRoomById(roomId), "$to did not join from the Welcome")
+ }
+
+ // ---- The room ----------------------------------------------------------------
+
+ /** [block] on a freshly founded room, once on each profile a room can be made on. */
+ private fun onEveryProfile(
+ profiles: List = listOf(MarmotProfile.LEGACY, MarmotProfile.CURRENT),
+ block: suspend (MarmotProfile, List) -> Unit,
+ ) = runBlocking {
+ profiles.forEach { profile ->
+ val phones = foundedRoom(profile)
+ try {
+ block(profile, phones)
+ } finally {
+ phones.forEach { it.close() }
+ }
+ }
+ }
+
+ private suspend fun Phone.room() = assertNotNull(db.chatRoomDao().findChatRoomById(roomId), "$this has no room")
+
+ /** Whom this phone's own rows call an admin. */
+ private suspend fun Phone.flaggedAdmins(): Set = room().localParticipants
+ .map { it.participant }
+ .filter { it.deletedAt == null && it.adminAt != null }
+ .map { it.participantPublicKey }
+ .toSet()
+
+ @Test
+ fun `every founding member is in the room's admin policy, on every device`() = onEveryProfile { profile, phones ->
+ val founders = phones.map { it.publicKey }.toSet()
+
+ phones.forEach { phone ->
+ val group = assertNotNull(phone.room().chatRoom.toMlsGroup(), "$phone holds no group ($profile)")
+ assertEquals(founders, group.currentAdminIdentities(), "$phone's admin policy ($profile)")
+ assertTrue(group.isLocalAdmin(), "$phone is not an admin of its own room ($profile)")
+ }
+ }
+
+ /**
+ * The rows, which are what the screens label members with. The creator's are
+ * caught up by `MarmotGroupCreation`; a joiner's come from the Welcome, which
+ * wrote none of them until Phase 2 put `AdminFlags.reconcile` on that path.
+ */
+ @Test
+ fun `every device flags every founding member as an admin`() = onEveryProfile { profile, phones ->
+ val founders = phones.map { it.publicKey }.toSet()
+
+ phones.forEach { phone ->
+ assertEquals(founders, phone.flaggedAdmins(), "$phone's rows say a different set are admins ($profile)")
+ }
+ }
+
+ /**
+ * The boundary docs/robust-group-admins.md, D1 draws: founding, not present.
+ *
+ * On both profiles since Phase 4. Before it, `MarmotGroupCreation` invited the
+ * founders on the current profile through a room read before its routing id was
+ * recorded, so the engine's group at the real address still held only the
+ * creator, and this later invite took the founding path -- no commit, and
+ * nobody else told.
+ */
+ @Test
+ fun `a member added after the founding is not an admin`() = onEveryProfile { profile, phones ->
+ val founders = phones.map { it.publicKey }.toSet()
+ val creator = phones.first()
+
+ Phone(profile).use { later ->
+ later.ready()
+ (phones + later).forEach { phone -> (phones + later).forEach { MarmotStandIn.seedProfile(phone.db, it.publicKey) } }
+
+ creator.chatRepository.inviteMember(creator.room(), later.publicKey, later.keyPackage)
+ creator.okTheLatestCommit()
+ welcome(from = creator, to = later)
+
+ listOf(creator, later).forEach { phone ->
+ val group = assertNotNull(phone.room().chatRoom.toMlsGroup(), "$phone holds no group ($profile)")
+ assertEquals(founders, group.currentAdminIdentities(), "$phone's admin policy ($profile)")
+ assertTrue(later.publicKey !in phone.flaggedAdmins(), "$phone flags the later member ($profile)")
+ }
+ assertFalse(assertNotNull(later.room().chatRoom.toMlsGroup()).isLocalAdmin(), "the later member governs ($profile)")
+ }
+ }
+
+ /**
+ * A room joined before Phase 2, whose joiner's rows flag nobody, is caught up
+ * at the next start, once. docs/robust-group-admins.md, Phase 6.
+ */
+ @Test
+ fun `a room joined before the Welcome wrote flags is caught up at start`() = onEveryProfile { profile, phones ->
+ val founders = phones.map { it.publicKey }.toSet()
+ val joiner = phones.last()
+ joiner.db.participantDao().upsert(joiner.room().localParticipants.map { it.participant.copy(adminAt = null) })
+ assertTrue(joiner.flaggedAdmins().isEmpty(), "the fixture did not clear the flags ($profile)")
+
+ assertEquals(founders.size, AdminFlags.reconcileAll(joiner.db), "($profile)")
+ assertEquals(founders, joiner.flaggedAdmins(), "($profile)")
+ assertEquals(0, AdminFlags.reconcileAll(joiner.db), "and a second start changes nothing ($profile)")
+ }
+
+ // ---- The founding invite: docs/robust-group-admins.md, Phase 4 -------------
+
+ private val ceremonyRoomId = "ce1e".repeat(16)
+
+ /** The ceremony [phones] ran, as [owner]'s device holds it: everyone in it, and its key [roomId]'s. */
+ private suspend fun ceremonyOn(owner: Phone, phones: List, thresholdPublicKey: HexKey): Pair {
+ owner.db.chatRoomDao().upsert(
+ ChatRoom(id = ceremonyRoomId, userPublicKey = owner.publicKey, subject = "Ekklesia", description = null, mlsGroupState = null)
+ )
+ val session = DkgSession(
+ id = "the-ceremony",
+ chatRoomId = ceremonyRoomId,
+ coordinatorPublicKey = owner.publicKey,
+ userPublicKey = owner.publicKey,
+ threshold = 2,
+ participantCount = phones.size,
+ participantPublicKeys = DkgSession.formatParticipants(phones.map { it.publicKey }.toSet()),
+ subject = "Ekklesia",
+ stage = DkgRitualStage.COMPLETE,
+ hostPublicKey = owner.publicKey,
+ round1Random = "aa".repeat(32),
+ round2AuxRandom = "bb".repeat(32),
+ thresholdPublicKey = thresholdPublicKey,
+ secretShare = "cc".repeat(32),
+ )
+ owner.db.dkgSessionDao().upsert(session)
+ return session to assertNotNull(owner.db.chatRoomDao().findChatRoomById(ceremonyRoomId))
+ }
+
+ /**
+ * A room whose founding invite never went out: made, with every founder in
+ * its policy, and nobody but its creator in its tree -- what `create` leaves
+ * when `addMembers` throws.
+ */
+ private suspend fun roomWithoutItsInvite(profile: MarmotProfile, phones: List, roomId: String) {
+ val creator = phones.first()
+ val created = MarmotGroupFactory.create(
+ creator = creator.keyPair,
+ roomId = roomId,
+ name = "#Ekklesia",
+ description = SharedKeyDerivation.describe("Admins of Ekklesia."),
+ adminPublicKeys = phones.map { it.publicKey },
+ relays = Relays.DefaultDMRelayList.map { it.url },
+ profile = profile,
+ )
+ assertNotNull(
+ creator.chatRepository.getOrCreateChatRoom(
+ chatRoomId = roomId,
+ activeUserPublicKey = creator.publicKey,
+ relayHint = null,
+ defaultSubject = "#Ekklesia",
+ description = null,
+ mlsGroupState = created.group.saveState().encodeTls().toHex(),
+ )
+ )
+ creator.chatRepository.recordMarmotRouting(chatRoomId = roomId, routingId = created.routingId)
+ }
+
+ @Test
+ fun `a founding invite that never went out is finished, and every founder is an admin`(): Unit = runBlocking {
+ listOf(MarmotProfile.LEGACY, MarmotProfile.CURRENT).forEach { profile ->
+ val phones = List(3) { Phone(profile) }
+ try {
+ phones.forEach { it.ready() }
+ phones.forEach { phone -> phones.forEach { MarmotStandIn.seedProfile(phone.db, it.publicKey) } }
+ val creator = phones.first()
+ phones.drop(1).forEach { creator.db.marmotKeyPackageDao().upsert(it.keyPackage) }
+
+ val thresholdPublicKey = "02" + KeyPair().pubKey.toHexKey()
+ val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey)
+ roomWithoutItsInvite(profile, phones, roomId)
+ val (session, ceremonyRoom) = ceremonyOn(creator, phones, thresholdPublicKey)
+
+ val invite = MarmotGroupCreation.finishFoundingInvite(
+ creator.db, creator.chatRepository, session, ceremonyRoom, keyPackageLookupTimeout = 2_000L,
+ )
+ val sent = assertIs(invite, "($profile)")
+ assertEquals(phones.drop(1).map { it.publicKey }.toSet(), sent.invited.toSet(), "($profile)")
+ assertTrue(sent.notAdded.isEmpty(), "($profile)")
+
+ assertEquals(
+ MarmotGroupCreation.FoundingInvite.NothingToDo,
+ MarmotGroupCreation.finishFoundingInvite(creator.db, creator.chatRepository, session, ceremonyRoom, 2_000L),
+ "and a second run invites nobody ($profile)",
+ )
+
+ phones.drop(1).forEach { welcome(from = creator, to = it, roomId = roomId) }
+ val founders = phones.map { it.publicKey }.toSet()
+ phones.forEach { phone ->
+ val room = assertNotNull(phone.db.chatRoomDao().findChatRoomById(roomId), "$phone has no room ($profile)")
+ val group = assertNotNull(room.chatRoom.toMlsGroup(), "$phone holds no group ($profile)")
+ assertEquals(founders, group.currentAdminIdentities(), "$phone's admin policy ($profile)")
+ assertTrue(group.isLocalAdmin(), "$phone is not an admin ($profile)")
+ }
+ } finally {
+ phones.forEach { it.close() }
+ }
+ }
+ }
+
+ /** Past epoch 0 a founder without a leaf may be one who left; that is not this step's to undo. */
+ @Test
+ fun `a room past its founding invites nobody`() = onEveryProfile { profile, phones ->
+ val creator = phones.first()
+ val (session, ceremonyRoom) = ceremonyOn(creator, phones, foundingThresholdPublicKey)
+
+ assertEquals(
+ MarmotGroupCreation.FoundingInvite.NothingToDo,
+ MarmotGroupCreation.finishFoundingInvite(creator.db, creator.chatRepository, session, ceremonyRoom, 2_000L),
+ "($profile)",
+ )
+ }
+
+ // ---- The ceremony ------------------------------------------------------------
+
+ @Test
+ fun `the founding set is the same set on every device that took part`(): Unit = runBlocking {
+ CeremonyNetwork.nip17(size = 3).use { network ->
+ val everyone = network.devices.map { it.publicKey }.toSet()
+ val session = network.propose(threshold = 2)
+ network.deliverUntilQuiet()
+ network.devices.drop(1).forEach { network.approve(it, session.id, DkgApprovalStep.HOST_KEY) }
+ network.deliverUntilQuiet()
+
+ network.devices.forEach { device ->
+ val theirs = assertNotNull(network.session(device, session.id), "$device has no ceremony")
+ assertEquals(everyone, ChillDkgRitualManager.memberPublicKeys(network.room(device)), "$device's room")
+ assertEquals(everyone, theirs.participantPublicKeySet(), "$device's ceremony")
+ assertEquals(
+ everyone,
+ ChillDkgRitualManager.participantsOf(theirs, network.room(device)),
+ "$device's founding set",
+ )
+ }
+ }
+ }
+
+ @Test
+ fun `a subgroup's founding set is its ceremony's participants on every device in it`(): Unit = runBlocking {
+ val parentId = SharedKeyDerivation.marmotGroupId("02" + KeyPair().pubKey.toHexKey())
+ CeremonyNetwork.marmot(size = 4, roomId = parentId).use { network ->
+ val picked = network.devices.take(3).map { it.publicKey }.toSet()
+ val session = network.propose(threshold = 2, participants = picked, parentChatRoomId = parentId, subject = "Translation")
+ network.deliverUntilQuiet()
+
+ network.devices.take(3).forEach { device ->
+ val theirs = assertNotNull(network.session(device, session.id), "$device has no ceremony")
+ assertEquals(picked, ChillDkgRitualManager.participantsOf(theirs, network.room(device)), "$device")
+ }
+ }
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt
index 9f504526..6ae97ea3 100644
--- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt
@@ -19,6 +19,8 @@ import kotlin.test.assertNotEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
import kotlinx.coroutines.runBlocking
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.builder.getRoomDatabase
@@ -32,15 +34,18 @@ import mobi.giza.compose.database.model.NostrEvent
import mobi.giza.compose.database.model.Profile
import mobi.giza.compose.database.model.ShareRefreshConfirmation
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+import mobi.giza.compose.database.repository.DatabaseChatRepository
import mobi.giza.compose.database.model.types.DkgRitualStage
import mobi.giza.compose.database.model.types.FrostSigningStage
import mobi.giza.compose.database.model.types.ShareGenerationState
+import mobi.giza.compose.database.model.types.ShareRefreshApprovalStep
import mobi.giza.compose.database.model.types.ShareRefreshStage
import mobi.giza.compose.database.model.types.ShareStanding
import mobi.giza.compose.extensions.toHex
import mobi.giza.compose.nostr.dkg.DkgRitualEvents
import mobi.giza.compose.nostr.frost.FrostSigningEvents
import mobi.giza.compose.nostr.frost.ShareRefreshEvents
+import mobi.giza.compose.ui.view.state.SharesSummary
/**
* A share refresh between devices (docs/frost-share-refresh.md, Phase 7).
@@ -260,7 +265,7 @@ class ShareRefreshRitualJvmTest {
}
@Test
- fun `nothing of a member's own goes out before they approve`() = runBlocking {
+ fun `nothing of a member's own goes out before they approve, but the proposer is not asked`() = runBlocking {
val group = Group(3, 2)
val all = devicesFor(group)
val refresh = propose(all[0])
@@ -404,26 +409,6 @@ class ShareRefreshRitualJvmTest {
assertTrue(all.drop(1).any { it.refresh(refresh.id)!!.failureReason!!.contains("Share refresh") }, "an honest recipient has to say what it found")
}
- /**
- * Two members open a rotation from the same generation at once. With every
- * owner saying yes to everything, the group never splits: at most one
- * completes, and every device that moved holds the same table.
- */
- @Test
- fun `two rotations opened at once never split the group`() = runBlocking {
- val group = Group(4, 2)
- val all = devicesFor(group)
- val first = propose(all[0])
- val second = propose(all[1])
- pump(all)
- answerEverything(all, first.id)
- answerEverything(all, second.id)
-
- val completed = listOf(first.id, second.id).filter { id -> all.any { it.refresh(id)?.stage == ShareRefreshStage.COMPLETE } }
- assertTrue(completed.size <= 1, "two rotations from one generation both completed")
- val tables = all.map { it.active().generation to it.active().publicShares }.toSet()
- assertEquals(1, tables.size, "devices disagree about the group's table: $tables")
- }
/**
* The upgrade: an older build stored the coordinator's sum and stopped, asking
@@ -718,7 +703,7 @@ class ShareRefreshRitualJvmTest {
assertEquals(listOf(nameOf(carol)), dealing.waitingOn)
assertTrue(dealing.canAbandon, "a member who took part can still end it")
assertTrue(summaryOn(bob).pending.isEmpty())
- assertTrue(!summaryOn(bob).canRotate)
+ assertTrue(summaryOn(bob).rotation is mobi.giza.compose.ui.view.state.SharesSummary.Rotation.Held)
// Carol takes part; her confirmation is slow to arrive.
ShareRefreshManager.approve(carol.db, carol.room, refresh.id, carol.privateKey)
@@ -770,10 +755,34 @@ class ShareRefreshRitualJvmTest {
val summary = summaryOn(device)
assertNull(summary.running)
assertTrue(summary.lastFailure!!.contains("Abandoned"), summary.lastFailure)
- assertTrue(summary.canRotate)
+ assertEquals(mobi.giza.compose.ui.view.state.SharesSummary.Rotation.Available, summary.rotation)
}
}
+ /**
+ * Two members propose from one base before either hears of the other. Each is
+ * approved for its own and refuses the other on arrival, as a recipient,
+ * out loud -- so neither stalls and nothing forks.
+ */
+ @Test
+ fun `two proposals crossing on the wire end with neither stuck and at most one generation`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val first = propose(all[0])
+ val second = propose(all[1])
+ pump(all)
+ approveAll(all, first.id)
+ approveAll(all, second.id)
+
+ all.forEach { device ->
+ val stages = listOf(first.id, second.id).map { device.refresh(it)?.stage }
+ assertTrue(stages.none { it != null && it != ShareRefreshStage.COMPLETE && it != ShareRefreshStage.FAILED }, "device ${device.index} left one running: $stages")
+ assertTrue(stages.count { it == ShareRefreshStage.COMPLETE } <= 1, "device ${device.index}: $stages")
+ assertTrue(ShareRefreshManager.rotationHold(device.db, device.room, device.key()) !is RotationHold.Running, "device ${device.index}")
+ }
+ assertEquals(1, all.map { it.active().publicShares }.toSet().size, "every device on one table")
+ }
+
@Test
fun `a withheld member ends with the new table and no share, and declines to sign`() = runBlocking {
val group = Group(3, 2)
@@ -1025,6 +1034,179 @@ class ShareRefreshRitualJvmTest {
assertTrue(error.message!!.contains("fewer than the 2 it takes to sign"), error.message)
}
+ // ---- a rotation waits for the last one to be signed (docs/rotation-waits-for-key-state.md) -------------------
+
+ /**
+ * Signing proposals arrive, and nothing after them: a key state stays open,
+ * approved or not. Since docs/rotate-shares-single-approval.md the new
+ * generation's key state signs itself, so a test that looks at a rotation
+ * whose key state is not yet signed has to hold it there.
+ */
+ private val signingHeldOpen: (MarmotInnerEvent) -> Boolean = { it.kind in FrostSigningEvents.ALL && !FrostSigningEvents.isProposal(it.kind) }
+
+ /** Every recipient takes part and the rotation completes; its key state is proposed and left open. */
+ private suspend fun takePart(all: List, refreshId: String) {
+ all.forEach { ShareRefreshManager.approve(it.db, it.room, refreshId, it.privateKey) }
+ pump(all, hold = signingHeldOpen)
+ }
+
+ @Test
+ fun `the next rotation waits until the group has signed the last one`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val (alice, bob) = all
+ assertNull(ShareRefreshManager.rotationHold(alice.db, alice.room, alice.key()), "generation 0 waits on nothing")
+
+ val first = propose(alice)
+ pump(all)
+ assertEquals(RotationHold.Running(first.id), ShareRefreshManager.rotationHold(bob.db, bob.room, bob.key()))
+ takePart(all, first.id)
+
+ // The refresh is complete and its key state is out for signatures: everyone waits.
+ all.forEach { device ->
+ val hold = ShareRefreshManager.rotationHold(device.db, device.room, device.key())
+ assertTrue(hold is RotationHold.AwaitingKeyState && hold.generation == 1 && hold.signingSessionId != null, "device ${device.index}: $hold")
+ }
+ val refused = assertFailsWith { propose(bob) }
+ assertTrue(refused.message!!.contains("generation 1"), refused.message)
+ assertEquals(listOf(first.id), bob.db.shareRefreshDao().getSessionsForKey(ceremonyId).map { it.id }, "nothing new was opened")
+
+ approveSigning(all)
+ all.forEach { assertNull(ShareRefreshManager.rotationHold(it.db, it.room, it.key()), "device ${it.index}") }
+ assertNotEquals(first.id, propose(bob).id)
+ }
+
+ @Test
+ fun `rotating without a member waits as well`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val (alice, _, carol) = all
+ val first = propose(alice)
+ pump(all)
+ takePart(all, first.id)
+
+ val refused = assertFailsWith {
+ ShareRefreshManager.proposeWithout(alice.db, alice.room, alice.publicKey, alice.privateKey, carol.publicKey)
+ }
+ assertTrue(refused.message!!.contains("not yet signed"), refused.message)
+ }
+
+ @Test
+ fun `a key state with nobody asking for it still holds the next rotation`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val first = propose(all[0])
+ pump(all)
+ takePart(all, first.id)
+ // The coordinator's key-state proposal failed, or its device went away.
+ all.forEach { device ->
+ device.db.frostSigningSessionDao().getSessionsForChatRoom(group.roomId).forEach {
+ device.db.frostSigningSessionDao().upsert(it.copy(stage = FrostSigningStage.FAILED))
+ }
+ }
+ val hold = ShareRefreshManager.rotationHold(all[1].db, all[1].room, all[1].key())
+ assertEquals(RotationHold.AwaitingKeyState(1, signingSessionId = null), hold)
+ }
+
+ @Test
+ fun `a rebind waiting on signatures holds a rotation, until this device declines it`() = runBlocking {
+ // Four members, one left stale: three live signers of a 2-of-n key, so a
+ // single refusal leaves a session open rather than ending it.
+ val group = Group(4, 2)
+ val all = devicesFor(group)
+ val (alice, bob, carol) = all
+ val staleId = group.idOf[3]
+ val refresh = propose(alice, mapOf(staleId to ShareStanding.STALE))
+ pump(all)
+ approveAll(all, refresh.id)
+ approveSigning(all)
+ assertNull(ShareRefreshManager.rotationHold(alice.db, alice.room, alice.key()))
+
+ val daveKeys = KeyPair()
+ val daveHost = ChillDkgRitualManager.deriveHostPublicKey(daveKeys.privKey!!).value.toHex()
+ val rebind = GroupKeyStateManager.proposeRebind(alice.db, alice.room, alice.publicKey, alice.key(), staleId, daveKeys.pubKey.toHexKey(), daveHost)
+ pump(all)
+
+ listOf(alice, bob, carol).forEach { device ->
+ assertEquals(RotationHold.AwaitingKeyState(1, rebind.id), ShareRefreshManager.rotationHold(device.db, device.room, device.key()), "device ${device.index}")
+ }
+
+ // One refusal does not end it, so it sits open; it no longer holds Bob, who refused it.
+ FrostSigningManager.decline(bob.db, bob.room, rebind.id)
+ pump(all)
+ assertNotEquals(FrostSigningStage.FAILED, bob.db.frostSigningSessionDao().getSessionById(rebind.id)!!.stage)
+ assertNull(ShareRefreshManager.rotationHold(bob.db, bob.room, bob.key()))
+ assertEquals(RotationHold.AwaitingKeyState(1, rebind.id), ShareRefreshManager.rotationHold(carol.db, carol.room, carol.key()))
+ }
+
+ @Test
+ fun `a device that missed the certificate cannot propose from the old generation`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val first = propose(all[0])
+ pump(all)
+ approveAll(all, first.id)
+ approveSigning(all)
+
+ // Alice on a second device that heard the group's signature but none of the refresh.
+ val late = device(group, 0)
+ val signed = assertNotNull(GroupKeyStateManager.signedEventFor(all[1].db, group.roomId)).toEvent()
+ assertNotNull(GroupKeyStateManager.record(late.db, group.roomId, signed))
+ assertEquals(0, late.active().generation)
+
+ assertEquals(RotationHold.Behind(groupGeneration = 1, localGeneration = 0), ShareRefreshManager.rotationHold(late.db, late.room, late.key()))
+ assertFailsWith { propose(late) }
+ }
+
+ /** The rotate action as the room's Shares section reads it. */
+ private suspend fun rotation(device: Device): SharesSummary.Rotation? =
+ DatabaseChatRepository(device.db, CoroutineScope(Job())).sharesSummary(device.room)?.rotation
+
+ @Test
+ fun `the Shares section holds the button while a rotation is unfinished, and says why`() = runBlocking {
+ mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = true
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val (alice, bob) = all
+ assertEquals(SharesSummary.Rotation.Available, rotation(bob))
+
+ val refresh = propose(alice)
+ pump(all)
+ assertEquals(SharesSummary.Rotation.Held(SharesSummary.Rotation.Reason.ROTATION_RUNNING), rotation(bob))
+
+ takePart(all, refresh.id)
+ val awaiting = SharesSummary.Rotation.Held(SharesSummary.Rotation.Reason.AWAITING_SIGNATURES, canAskForSignature = false)
+ assertEquals(awaiting, rotation(bob), "the coordinator is already asking")
+
+ // The coordinator's proposal fails: nobody is asking, so Bob may.
+ all.forEach { device ->
+ device.db.frostSigningSessionDao().getSessionsForChatRoom(group.roomId).forEach {
+ device.db.frostSigningSessionDao().upsert(it.copy(stage = FrostSigningStage.FAILED))
+ }
+ }
+ assertEquals(awaiting.copy(canAskForSignature = true), rotation(bob))
+ val asked = ShareRefreshManager.proposeOwedKeyState(bob.db, bob.room, bob.publicKey, bob.key())
+ pump(all, hold = signingHeldOpen)
+ assertEquals(awaiting, rotation(bob))
+ assertFailsWith("one ask at a time") {
+ ShareRefreshManager.proposeOwedKeyState(alice.db, alice.room, alice.publicKey, alice.key())
+ }
+
+ approveSigning(all)
+ assertEquals(FrostSigningStage.COMPLETE, bob.db.frostSigningSessionDao().getSessionById(asked.id)?.stage)
+ all.forEach { assertEquals(SharesSummary.Rotation.Available, rotation(it), "device ${it.index}") }
+ val stated = Event.fromJson(bob.db.frostSigningSessionDao().getItems(asked.id).single().unsignedEventJson)
+ assertTrue(stated.tags.any { it.contains(refresh.id) }, "the refresh is named as the coordinator would have named it")
+ }
+
+ @Test
+ fun `a member left out of a rotation is offered no rotate button`() = runBlocking {
+ mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = true
+ val (_, all) = rotatedWithout(2)
+ assertEquals(SharesSummary.Rotation.Unavailable, rotation(all[2]))
+ assertEquals(SharesSummary.Rotation.Available, rotation(all[0]))
+ }
+
// ---- Phase 10: re-enrollment -----------------------------------------------------------------------------------
/** Every helper approves every repair waiting on them. */
@@ -1192,6 +1374,8 @@ class ShareRefreshRitualJvmTest {
val refresh = propose(all[round % 3])
pump(all)
approveAll(all, refresh.id)
+ // The next rotation waits for this one's key state, and the old shares go.
+ approveSigning(all)
}
all.forEach { device ->
assertEquals(3, device.active().generation)
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailSharesJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailSharesJvmTest.kt
new file mode 100644
index 00000000..cd61fa31
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailSharesJvmTest.kt
@@ -0,0 +1,137 @@
+package mobi.giza.compose.ui.view.model
+
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.test.UnconfinedTestDispatcher
+import kotlinx.coroutines.test.resetMain
+import kotlinx.coroutines.test.setMain
+import kotlinx.coroutines.withTimeout
+import mobi.giza.compose.database.model.ChatRoom
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+import mobi.giza.compose.database.model.types.ShareStanding
+import mobi.giza.compose.repository.ChatRepository
+import mobi.giza.compose.repository.NostrRepository
+import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState
+import mobi.giza.compose.ui.view.state.SharesSummary
+import mobi.giza.compose.ui.view.state.RotationPreview
+import kotlin.test.AfterTest
+import kotlin.test.BeforeTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+
+/**
+ * The room detail screen's Shares section follows the group while it is open
+ * (docs/rotation-waits-for-key-state.md, Phase 3): the rotate button the last
+ * rotation held comes back when the group signs, without the screen being left
+ * and opened again.
+ */
+@OptIn(ExperimentalCoroutinesApi::class)
+class ChatRoomDetailSharesJvmTest {
+ @BeforeTest
+ fun setUp() {
+ Dispatchers.setMain(UnconfinedTestDispatcher())
+ }
+
+ @AfterTest
+ fun tearDown() {
+ Dispatchers.resetMain()
+ }
+
+ private val chatRoomId = "c0ffee00".repeat(8)
+ private val me = "a".repeat(64)
+ private val localChatRoom = LocalChatRoom(
+ chatRoom = ChatRoom(id = chatRoomId, userPublicKey = me, subject = "Admins", description = null, mlsGroupState = null)
+ )
+
+ private fun summary(rotation: SharesSummary.Rotation) =
+ SharesSummary(generation = 1, members = emptyList(), pending = emptyList(), rotation = rotation, canAskToBeRepaired = false)
+
+ private class Repository(val room: LocalChatRoom, var shares: SharesSummary) :
+ ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY {
+ val inputs = MutableSharedFlow(replay = 1)
+ var reads = 0
+ var rotations = 0
+ override suspend fun rotateShares(localChatRoom: LocalChatRoom): String? { rotations++; return null }
+ var preview: RotationPreview? = null
+ override suspend fun rotationPreview(localChatRoom: LocalChatRoom, without: HexKey?): RotationPreview? = preview
+ override suspend fun getChatRoomByIdentifier(id: HexKey): LocalChatRoom? = room.takeIf { id == room.chatRoom.id }
+ override suspend fun sharesSummary(localChatRoom: LocalChatRoom): SharesSummary { reads++; return shares }
+ override fun observeSharesInputs(chatRoomId: String): Flow = inputs
+ }
+
+ private fun viewModel(repository: Repository) = ChatRoomDetailViewModel(
+ chatRoomId = chatRoomId,
+ activeUserPublicKey = me,
+ relayHint = null,
+ initialChatRoomDetailUIState = ChatRoomDetailUIState.Loading,
+ nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY,
+ chatRepository = repository,
+ )
+
+ private suspend fun ChatRoomDetailViewModel.awaitRotation(expected: SharesSummary.Rotation) = withTimeout(5_000) {
+ while ((chatRoomDetailUIState as? ChatRoomDetailUIState.Loaded)?.shares?.rotation != expected) delay(10)
+ }
+
+ @Test
+ fun `the rotate button comes back when the group signs, with the screen open`() = runBlocking {
+ val held = SharesSummary.Rotation.Held(SharesSummary.Rotation.Reason.AWAITING_SIGNATURES)
+ val repository = Repository(localChatRoom, summary(held))
+ val viewModel = viewModel(repository)
+ viewModel.initiateChatRoomDetail()
+ viewModel.awaitRotation(held)
+
+ // The group's signature lands in the database while the screen is open.
+ repository.shares = summary(SharesSummary.Rotation.Available)
+ repository.inputs.emit(Unit)
+ viewModel.awaitRotation(SharesSummary.Rotation.Available)
+ }
+
+ @Test
+ fun `a burst of signing messages is read once it settles`() = runBlocking {
+ val repository = Repository(localChatRoom, summary(SharesSummary.Rotation.Available))
+ val viewModel = viewModel(repository)
+ viewModel.initiateChatRoomDetail()
+ viewModel.awaitRotation(SharesSummary.Rotation.Available)
+ delay(ChatRoomDetailViewModel.SHARES_SETTLE_MILLIS * 2)
+ val before = repository.reads
+
+ repeat(20) { repository.inputs.emit(Unit) }
+ delay(ChatRoomDetailViewModel.SHARES_SETTLE_MILLIS * 3)
+
+ val reads = repository.reads - before
+ assertTrue(reads in 1..2, "20 changes in a burst read the section $reads times")
+ assertEquals(SharesSummary.Rotation.Available, (viewModel.chatRoomDetailUIState as ChatRoomDetailUIState.Loaded).shares?.rotation)
+ }
+
+ @Test
+ fun `rotating asks first, naming who it leaves out`() = runBlocking {
+ val shares = summary(SharesSummary.Rotation.Available)
+ val repository = Repository(localChatRoom, shares)
+ // As ShareRefreshManager.preview reads it: the stale withheld again, the retired gone already.
+ repository.preview = RotationPreview(takingPart = listOf("Ama", "Bongani"), untilBroughtBack = listOf("Carol"), forGood = emptyList(), refusal = null)
+ val viewModel = viewModel(repository)
+
+ val unavailable = kotlinx.coroutines.CompletableDeferred()
+ viewModel.previewRotation(localChatRoom) { unavailable.complete(Unit) }
+ val proposal = withTimeout(5_000) {
+ while (viewModel.rotationProposal == null) delay(10)
+ viewModel.rotationProposal!!
+ }
+ assertEquals(listOf("Carol"), proposal.preview.untilBroughtBack)
+ assertEquals(0, repository.rotations, "nothing is proposed before the owner confirms")
+
+ val done = kotlinx.coroutines.CompletableDeferred()
+ viewModel.rotateShares(proposal) { done.complete(it) }
+ assertNull(withTimeout(5_000) { done.await() })
+ assertEquals(1, repository.rotations)
+ assertNull(viewModel.rotationProposal)
+ assertTrue(!unavailable.isCompleted)
+ }
+}
diff --git a/docs/README.md b/docs/README.md
index b80c1f3c..d78df979 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -37,6 +37,7 @@ the [retired](./retired/) notes now.
| [marmot-kmp.md](./marmot-kmp.md) | moving the group layer off quartz's engine and onto marmot-kmp, mls-kmp and crypto-kmp — why staying on quartz 1.15.2 is staying on an engine that left, the 228 import lines and the one rule that places all but two of them, the group state on a device that must still open afterwards, nine phases that put the swap in one commit and the evidence around it, how often this app persists a group once a sent message no longer rewrites it, and the schema change that followed, opened from the version the app ships |
| [giza-wallet-removal.md](./giza-wallet-removal.md) | taking every wallet out of Giza, phased and built but for moving off the wallet library (7b). Covers why a Giza member declines a Bennu peer's wallet proposal instead of ignoring or signing it, why the wallet's kinds are retired rather than freed, why a recovery phrase stays as a key backup that has to derive the same npub and id byte for byte, and why the threshold crypto keeps the build tied to the wallet library until the last phase |
| [giza-rebrand.md](./giza-rebrand.md) | forking Bennu as Giza under `mobi.giza` — what carries the name, what must not be renamed and why, why the desktop data directory changes first, and how the fork keeps merging from Bennu |
+| [robust-group-admins.md](./robust-group-admins.md) | making every founding member of a robust group an admin of its room, on every device -- phased and built. Covers why the ceremony's participants are the founding set, the Welcome that flags no admins, the joiner's check against the ceremony it took part in, and finishing an invite that partly failed |
Start with the ceremony if you are new to this area; the Marmot notes all assume it.
Read the skipped-keys note before debugging any "the other device never got it"
diff --git a/docs/automatic-key-ceremony.md b/docs/automatic-key-ceremony.md
index 337c884a..23cb240d 100644
--- a/docs/automatic-key-ceremony.md
+++ b/docs/automatic-key-ceremony.md
@@ -388,6 +388,11 @@ on a COMPLETE ceremony this device coordinated:
room does not exist -> create it
```
+> **Since [robust-group-admins.md](./robust-group-admins.md), Phase 4:** a fifth line, after
+> the room exists -- a room still at epoch 0 without its founders, whose founding invite never
+> went out, has it finished. And the room's admins are no longer the caller's to pass: the
+> repository takes the ceremony and reads them off it.
+
- **What it calls:** the code behind `DkgRitualViewModel.proposeBirthCertificate`,
`proposeKeyState` and `createAdminGroup`. That code moves from the view model
into the manager (and `DkgRepository`), along with each one's "already asked"
diff --git a/docs/frost-share-refresh.md b/docs/frost-share-refresh.md
index b86389fb..3b158571 100644
--- a/docs/frost-share-refresh.md
+++ b/docs/frost-share-refresh.md
@@ -26,7 +26,8 @@ ceremony they describe and the rule that a room's id *is* the key it signs with.
| 11 | `99229090` | `compileDebugKotlinAndroid`; the M3 audit at its budgets. **Not seen on a device or a desktop window** |
| 12 | `4949f0fe` | `ShareRefreshRitualJvmTest`: three refreshes in a row, then the recovery walk from the generation-0 share lands on every device's live share, each generation checked against its table. `jvmTest` 1200/1200 |
| 13 | `99229090` | `ShareRefreshRitualJvmTest`: with the flag off, the recipients decline a rotation out loud and it fails; proposing one throws. Android, desktop and iOS device checks not done |
-| after | rotate-shares-single-approval.md | taking part is a rotation's only approval: `CONFIRM` is gone, the proposer's dialog is its approval, the new generation's key state signs itself, and a running rotation can be abandoned from the Shares section. See that note |
+| after 13 | `159ae402`, `d358a0db`, `98567629`, `95131248` | [rotation-waits-for-key-state.md](./rotation-waits-for-key-state.md): a rotation waits for the group to sign the last one's key state, the Shares section says why, follows the group while open, and the proposer is not asked about their own rotation. `ShareRefreshRitualJvmTest` 25/25, `ChatRoomDetailSharesJvmTest` 3/3; `./gradlew check` (`jvmTest` 1240/1240, `testDebugUnitTest` 496/496, lint, audits). **Not seen on a device or a desktop window** |
+| after that | rotate-shares-single-approval.md | taking part is a rotation's only approval: `CONFIRM` is gone, the proposer's dialog is its approval, the new generation's key state signs itself, and a running rotation can be abandoned from the Shares section. See that note |
| 5 | `4040ae74` | `SecureDeleteJvmTest` (5, two of them controls that fail without the fix); `jvmTest` 1176/1176; `compileDebugKotlinAndroid`, `processDebugResources` |
| 6 | `fce51e20` | `ShareGenerationsJvmTest` (7: a real 2-of-3 signature with hand-refreshed shares verifying as the unchanged room, a decline from a device without the generation, a withheld member who is not a signer); every existing signing test unedited; `jvmTest` 1183/1183; `compileDebugKotlinAndroid`; the M3, brand and wallet audits |
@@ -49,7 +50,7 @@ Where the build chose differently from the plan:
| Phase 7: the refusals | one more: every participant not retired has to be a recipient or withheld, so a proposal cannot leave someone in neither list. A participant stale at the base generation is withheld again, as stale, automatically: a refresh brings nobody back, a repair does. A recipient that refuses a proposal on arrival broadcasts a failure, since the certificate needs it; anyone else refuses silently. D5's capability check waits for Phase 13 |
| Phase 7: a kill between storing the pending generation and sending the confirmation | handled the way the plan said -- `confirmAndStore` is idempotent for the refresh that holds the claim, so the next pass stores it again and sends -- but not tested on its own |
| Phase 7: the transcript | system lines through `RitualNotice`, settled. The request line opens nothing until the refresh screen exists (Phase 11) |
-| Phase 8: any recipient proposes the new key state | the coordinator does, automatically, the moment its refresh completes; anyone can again. That races the certificate to the other devices, and lost in the first test run: a device still holding the generation as pending declined. A proposal at a generation this device has confirmed and is waiting on the certificate for now waits instead, and the refresh resumes it on activation (`FrostSigningManager.resumeAt`) |
+| Phase 8: any recipient proposes the new key state | the coordinator does, automatically, the moment its refresh completes; anyone can again. That races the certificate to the other devices, and lost in the first test run: a device still holding the generation as pending declined. A proposal at a generation this device has confirmed and is waiting on the certificate for now waits instead, and the refresh resumes it on activation (`FrostSigningManager.resumeAt`). "Anyone can again" had no button until [rotation-waits-for-key-state.md](./rotation-waits-for-key-state.md): the Shares section offers it when the key state is owed and nobody is asking |
| Phase 8: `ShareRefreshCutoverJvmTest` | the cutover tests live in `ShareRefreshRitualJvmTest`, which has the multi-device harness. The bytes-on-disk check is `SecureDeleteJvmTest`'s, against a file; these devices are in memory. A device that disagrees with the group's table keeps its share and logs it, untested |
| Phase 8: gen-0's randomness nulled | emptied: `round1Random` and `round2AuxRandom` are not nullable, and a complete ceremony never reads them again |
| Phase 9: an action on the members screen | a dialog the room detail screen raises after a removal succeeds, when the member held a live share (asked before the removal, while they are still in the roster). "Not now" leaves it; nothing offers it again yet -- Phase 11's Shares section is where a rotation can be started at any time. `MemberRemovalRefreshJvmTest` is two tests in the ritual harness |
@@ -478,7 +479,12 @@ host keys, so a room-wide message is fine here, which it is **not** for repair (
enforced with a write-once column on `KeyShareGeneration`, set in the same transaction that
stores the `PENDING` row. **It is as important as the nonce rules, and for the same reason: it
is the one way the group splits.**
-- an open ChillDKG or refresh for the same key.
+- an open ChillDKG or refresh for the same key;
+- **on the proposer's device only**, a rotation whose key state the group has not signed yet, a
+ key-state proposal still open there, or a device behind the group
+ ([rotation-waits-for-key-state.md](./rotation-waits-for-key-state.md),
+ `ShareRefreshManager.rotationHold`). Not on arrival: a recipient a few seconds behind on the
+ signature would end a rotation that was fine.
**Approval gates.** One, with `pendingApproval` mirroring `advance` exactly:
@@ -486,15 +492,18 @@ host keys, so a room-wide message is fine here, which it is **not** for repair (
|---|---|---|
| `DEAL` | round 1 | joins the refresh and agrees to the withheld list. Withholding someone is a decision about them, so every recipient makes it, not only the proposer |
-The proposer makes it by proposing, from a dialog that names everyone the proposal leaves out.
+The proposer makes it by proposing, from a dialog that names everyone the proposal leaves out
+([rotation-waits-for-key-state.md](./rotation-waits-for-key-state.md), Phase 4).
-*As first built there were two gates.* `CONFIRM` stood before CertEq, on the reasoning that it
-"stops a coordinator substituting a table the recipients never dealt". It never did: that is
-`participantStep2`'s check, which runs before any prompt could appear and fails the refresh out
-loud, and the one confirmation per generation is the write-once `ShareRefreshConfirmation`. Both
-hold whoever is looking. [rotate-shares-single-approval.md](./rotate-shares-single-approval.md)
-removed the gate; `ShareRefreshApprovalStep.CONFIRM` and `confirmApprovedAt` remain, unread, so
-rows written before still decode. The proposer, also asked at first, is not asked either.
+*As first built there were two gates, and the proposer was asked at both.* `CONFIRM` stood
+before CertEq, on the reasoning that it "stops a coordinator substituting a table the recipients
+never dealt". It never did: that is `participantStep2`'s check, which runs before any prompt
+could appear and fails the refresh out loud, and the one confirmation per generation is the
+write-once `ShareRefreshConfirmation`. Both hold whoever is looking.
+rotation-waits-for-key-state.md first stopped asking the proposer;
+[rotate-shares-single-approval.md](./rotate-shares-single-approval.md) then removed the gate for
+everyone. `ShareRefreshApprovalStep.CONFIRM` and `confirmApprovedAt` remain, unread, so rows
+written before still decode.
**Transcript.** System lines in the room, as the ceremony writes them, idempotent by reading the
row before writing:
diff --git a/docs/robust-group-admins.md b/docs/robust-group-admins.md
new file mode 100644
index 00000000..0ba663cd
--- /dev/null
+++ b/docs/robust-group-admins.md
@@ -0,0 +1,285 @@
+# Every founding member of a robust group is its admin
+
+A robust group promises, on the screen that makes it, that "everyone administers the
+group together". This note is the plan that made the promise true on every device from
+the moment the group exists: what "founding member" means, the four places the promise
+broke before, and the eight phases that closed them.
+
+**Built**, phases 0-7, one commit each. The phases below are kept as written,
+because they are the reasoning; where the build chose differently the table says
+so, and it did nine times worth reading:
+
+| what the plan said | what it turned out to be |
+|---|---|
+| a new `ChillDkgRitualManager.foundingMembersOf` | never built. `participantsOf` already was that function, fallback and all; Phase 1 made `MarmotGroupCreation.createFor` its one caller on the way to a room, and took the list off `ChatRepository.createMarmotGroup` altogether |
+| Phase 2's `stampAdmins` replaced by `AdminFlags.reconcile` with the creation's list | with the group's policy instead. Reading the list back would have kept two sources for one flag, which is the drift D2 is about |
+| Phase 2's Welcome test in `WelcomeBundleMatchJvmTest` | in `RobustGroupAdminsJvmTest`, where Phase 0 already delivers real gift-wrapped Welcomes between three app devices. The bundle test is about which key package a Welcome names, not what it leaves behind |
+| Phase 3 reports `Differs(missing, unexpected)` and offers removing unexpected admins | `Missing` only. Removing an admin is out of scope, so an admin the ceremony did not have is not this plan's to act on |
+| Phase 3's repair on every room | on the current profile only. The app makes no governance commit on a legacy room -- no removal, no disband -- so a legacy room gets the warning and the transcript line and not the button |
+| Phase 4 invites founders "who have never had a row in the room, not even a soft-deleted one" | founders without a leaf in a room still at **epoch 0**. Rows are hard-deleted when a member leaves, so "never had a row" cannot be told from "left"; epoch 0 can, because leaving is a commit and the founding invite is the commit that ends epoch 0 |
+| Phase 4 is about `notAdded` | it also fixed what Phase 0 found: on the current profile `MarmotGroupCreation` invited the founders through a room read before its routing id was recorded, so the engine adopted a second copy of the group under the room id, and every later invite into that room took the founding path -- no commit, and nobody already in the room told |
+| Phase 4's "Invite again" for any other active admin | only on the device holding the room at epoch 0, which is its creator's: nobody else holds the room until the invite reaches them. The coordinator's device does it on its own as step 4 |
+| Phase 6 reconciles behind a stored "reconciled" preference | on every start, with no flag. `AdminFlags.reconcile` writes nothing when the rows already agree, so running it again costs one decode per room and a preference would only be a second thing to keep right |
+
+Written against `fc437d05`.
+
+Read [shared-key-ceremony.md](./shared-key-ceremony.md) and
+[ceremony-creation.md](./ceremony-creation.md) first.
+
+## What a robust group is, in the code
+
+A robust group is two rooms and a key.
+
+```
+SelectChatRoomTypeViewModel.createNip17ChatRoom
+ │
+ ├─ the NIP-17 room members = picked + creator; no admins, no MLS
+ │ └─ proposeRitual ceremony participants = room members + creator
+ │
+ ├─ the ChillDKG key t-of-n over those participants
+ │
+ └─ the admin room (Marmot) id = marmotGroupId(threshold key)
+ created by CeremonyFollowThrough (step 3) or DkgRitualViewModel,
+ both through MarmotGroupCreation.create(adminPublicKeys = participantsOf(session))
+```
+
+The NIP-17 room has no admin concept, and that is correct: membership is the p-tag set
+and nothing in it can be governed. **Admin means admin of the Marmot room**, whose
+epoch-0 admin policy (`AdminPolicyV1` on the current profile, `MarmotGroupData.admin_pubkeys`
+on the legacy one) is what the library enforces and what `isLocalAdmin()` reads.
+`Participant.adminAt` is a local cache of it.
+
+A subgroup is the same shape with a different participant set, and everything below
+applies to it unchanged.
+
+`ChatRoomType` is not persisted. Nothing on a device records that a room was made robust;
+what marks one is a `GroupKeyState` -- a room whose id is derived from a threshold key.
+
+## What "founding member" means
+
+**D1. The founding members of a key-backed room are the participants of the ceremony that
+made its key** -- `DkgSession.participantPublicKeySet()` on the row
+`GroupKeyState.dkgSessionId` names. For a top-level robust group that is the picked members
+plus the creator; for a subgroup, the picked admins plus the coordinator.
+
+Not the NIP-17 room's rows, which `ChillDkgRitualManager.memberPublicKeys` already warns
+can drift. Not the admin list a Welcome arrives with, which is one device's claim. The
+session row is the one record every founding member's device built independently from the
+proposal it agreed to, and the ceremony would not have completed if they disagreed about `n`.
+
+A member added to the admin room later is not a founding member and is not made an admin by
+anything here.
+
+## Where the promise breaks today
+
+| | gap | effect | phase |
+|---|---|---|---|
+| G1 | The founding set is computed at three call sites -- `SelectChatRoomTypeViewModel.adminCount`, `CeremonyFollowThrough.takeNextStep` step 3, `DkgRitualViewModel` -- and passed into `MarmotGroupCreation.create` as a free parameter. `participantsOf` falls back to the room's rows when the session carries no set | nothing stops a caller passing a different set; a room's admin list is fixed at a derived address forever, so one wrong call is permanent | 1 |
+| G2 | The Welcome path in `NostrDao` writes `Participant.fromMlsGroup(...)` rows with no `adminAt`. Only the creator (`stampAdmins`) and a later commit (`processGroupMembershipChanges`) ever set it | on every device but the creator's, the admin room shows no admins until some other commit arrives -- which may be never | 2 |
+| G3 | A joiner never checks the admin list it was welcomed into against the ceremony it took part in | a device that created the room with a different list (a bug, an older build, a Bennu peer) goes unnoticed | 3 |
+| G4 | `MarmotGroupCreation.create` returns `notAdded` when `addMembers` partly fails. Those founding members are listed as admins but hold no leaf, so the policy treats them as inactive, and nothing invites them again | a founding admin who is not in the room | 4 |
+
+G2 has a smaller blast radius than it sounds: `canGovern` reads `isLocalAdmin()`, and
+`SubgroupManager` reads `currentAdminIdentities()`, so permissions are right. What is wrong
+is every reader of `adminAt` -- today the subgroup picker's "Admin of this group" line --
+and the fact that two devices disagree about the same room.
+
+## Decisions
+
+**D2. The admin policy is the truth; `adminAt` is derived from it on every path.** One
+function writes the flags, from `mlsGroup.currentAdminIdentities()`, and the creation,
+Welcome and commit paths all call it. `stampAdmins` stops taking a list of its own.
+
+**D3. No wire change.** Putting the founding set on the signed `GroupKeyStateEvent` (so a
+quorum signs it) was considered and left out: every founding member already holds the set
+on its own session row, a later joiner is by definition not one of them, and the 30326 event
+is shared with Bennu. Revisit if a device ever needs to check the founding set without
+having taken part.
+
+**D4. No schema change.** Every check below is derived on demand from rows that already
+exist -- the session, the key state, the stored MLS group, the participant rows -- so no
+Room migration and no new column.
+
+## Phases
+
+One commit per phase. Each phase ends with:
+
+```bash
+./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest
+```
+
+and phases that touch UI also with:
+
+```bash
+./gradlew :composeApp:m3Audit
+```
+
+### Phase 0: pin the invariant in a failing test
+
+Before changing anything, a test that states the promise and shows where it fails.
+
+**Add** `composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt`,
+on the `CeremonyNetwork` harness `RobustRoomKeyCeremonyTest` uses, with three devices:
+
+- `every founding member is an admin of the room the key makes, on every device` -- run the
+ ceremony and follow-through, deliver the Welcomes, then on each device assert
+ `currentAdminIdentities() == participants`, `isLocalAdmin()` and `adminAt != null` on
+ exactly the founding rows. **Expected to fail on `adminAt` for the two joiners (G2).**
+- `the founding set is the same set at every step` -- picked + creator, the NIP-17 room's
+ members, the session's participants and the admin policy are one set.
+- `a member added after the founding is not an admin` -- the boundary D1 draws.
+- The same three for a subgroup, on the `SubgroupCeremonyInParentRoomTest` fixtures.
+
+Mark the failing assertions `@Ignore("Phase 2")` and the like, so the build stays green and
+each phase un-ignores what it fixes.
+
+**Done when** the test exists, the passing parts pass, and each ignored part names its phase.
+
+### Phase 1: one derivation of the founding set (G1)
+
+**Change** `ChatRepository.createMarmotGroup` / `MarmotGroupCreation.create` to take the
+`DkgSession` instead of `adminPublicKeys`, and derive the set inside, through a new
+`ChillDkgRitualManager.foundingMembersOf(session, room)`:
+
+- returns `session.participantPublicKeySet()` when present;
+- falls back to the room's members only for a row that predates the column (logged), as
+ `participantsOf` does today;
+- requires the creating device to be in the set -- a device outside the ceremony holds no
+ key state for the room and should never get here, so reaching it is a bug, not an outcome.
+
+The two call sites (`CeremonyFollowThrough.takeNextStep` step 3 and
+`DkgRitualViewModel`'s admin-room action) stop computing a set. `SelectChatRoomTypeViewModel`
+keeps `adminCount` -- the session does not exist yet on that screen -- but computes it with
+the same `(members + creator).distinct()` rule `proposeRitual` uses, and a comment points at
+the other.
+
+**Tests.** `MarmotGroupCreationJvmTest`: `the room's admins are the ceremony's participants,
+whoever creates it` -- the coordinator's path and a non-coordinator's manual path produce
+the same admin policy. `CeremonyFollowThroughJvmTest` keeps passing unchanged.
+
+**Done when** no caller can name a room's admins.
+
+### Phase 2: the Welcome writes admin flags (G2)
+
+**Add** `AdminFlags.reconcile(database, localChatRoom, mlsGroup)` in `managers/` -- flags
+only, never membership: sets `adminAt` on rows the policy names and clears it on rows it
+does not. It is `processGroupMembershipChanges`'s `graduatedAdmins` / `removedAdmins` /
+new-participant logic, lifted out.
+
+**Call it** from:
+
+- the Welcome path in `NostrDao` (after the participant upsert, before
+ `GroupKeyStateManager.adopt`);
+- `MarmotGroupCreation`, replacing `stampAdmins`. Its reasoning -- flags are safe, a
+ membership reconciliation on a best-effort step is not -- moves to the new function's KDoc;
+- `processGroupMembershipChanges`, replacing its three inline admin computations.
+
+Having `Participant.fromMlsGroup` set `adminAt` itself would fix the Welcome alone, but it
+only ever builds new rows: it cannot clear a flag on a stored one, so half the logic would
+still live somewhere else. One function that does both is the point of D2.
+
+**Tests.** Un-ignore Phase 0's joiner assertions. Add to `WelcomeBundleMatchJvmTest`:
+`a member welcomed into a room sees its admins at once`.
+
+**Done when** every device shows the same admins the moment it holds the room.
+
+### Phase 3: a joiner checks what it was welcomed into (G3)
+
+**Add** `FoundingAdmins.check(database, localChatRoom): Check` in `managers/`, returning one
+of:
+
+- `NotKeyBacked` -- no key state; a convenient room, nothing to check;
+- `CannotCheck` -- key state, but this device holds no session for it (a later joiner);
+- `Matches` -- every founding member is in the admin policy;
+- `Missing(publicKeys: Set)` -- founding members the policy does not name, against
+ `foundingMembersOf`. For a subgroup, also against the birth certificate's
+ `SubgroupBirthCertificateEvent.parseAdminPublicKeys`, which the parent's quorum signed.
+
+**Call it** once at the Welcome, after `adopt`, and write a transcript line on `Missing`
+(a new `ChatMessage.TYPE_FOUNDING_ADMINS_MISSING`, derived like the membership captions).
+And on every load of `ChatRoomDetailViewModel`, into a new
+`ChatRoomDetailUIState.Loaded.foundingAdmins` field.
+
+The room is not left or refused. Its address is the key, and there is no second room to go
+to; a warning that names who is missing is what can be acted on.
+
+**Repair**, where this device is an active admin: an "Make founding members admins" action
+adds the missing ones to the policy in one admin-policy update commit. Additions only -- the
+commit is built from the current policy plus `Missing`, never as a replacement list.
+
+**Tests.** `FoundingAdminsJvmTest`: one case per `Check`, including a Welcome built by a
+device that listed only itself, and the repair commit leaving every existing admin in place.
+
+**Done when** a founding member left out of the admin policy is said, on the device that
+can see it, and can be put back by any admin.
+
+### Phase 4: every founding admin is invited (G4)
+
+**Add step 4 to `CeremonyFollowThrough.takeNextStep`**, after the room exists: founding
+members who have never had a row in the room -- not even a soft-deleted one -- are invited
+with `addMembers`, one commit for all of them. "Never had a row" keeps this step to
+finishing the founding invite: it never re-invites anybody who was in the room and left it.
+Read-then-act like the other steps, so a repeat does nothing.
+
+Who acts: the coordinator, as for step 3, so two devices do not race the same epoch. Any
+other active admin gets an "Invite again" action on the detail screen for the same set, for
+the case the coordinator's phone is in a drawer.
+
+A founding member with no key package is reported as `BlockedOn`, exactly as creation does,
+and the step is retried the next time the follow-through runs.
+
+**Tests.** `CeremonyFollowThroughJvmTest`: `a founding member the first invite missed is
+invited again`, `a founding member who was in the room is not`, and `a second run invites
+nobody`.
+
+**Done when** `Outcome.Created.notAdded` is something the follow-through finishes, not
+something a screen reports and forgets.
+
+### Phase 5: show it
+
+- The admin room's member list shows "Admin" as supporting text on rows with `adminAt`.
+- Phase 3's warning card and repair action, and Phase 4's "Invite again", on the detail
+ screen.
+- The NIP-17 room's detail says its members administer the group through the admin room,
+ with a link to it, rather than showing no admins.
+
+Strings in `strings.xml`, sentence case; every new button a 48dp target; the card's states
+through `ScreenStateTransition`. The m3 audit is the check.
+
+**Done when** a person can tell who administers the group, and whether that is everybody who
+made it, without reading a transcript.
+
+### Phase 6: rooms that already exist
+
+No migration is needed (D4), but the rooms made before Phase 2 still carry unflagged
+joiner rows and possibly uninvited founding admins.
+
+- `AdminFlags.reconcile` runs once per Marmot room at startup, behind a stored
+ "reconciled" preference, so G2 is repaired without waiting for a commit.
+- Phase 4's step already runs over every completed session; it covers G4 for old rooms.
+- Phase 3's check runs on every detail load; it covers G3 for old rooms.
+
+**Tests.** A fixture room with joiner rows missing `adminAt` is reconciled on start, once.
+
+### Phase 7: docs
+
+- This note: mark it built, with a table of where the build chose differently.
+- [ceremony-creation.md](./ceremony-creation.md) and [subgroups.md](./subgroups.md): link
+ here from the admin-room creation sections.
+- [README.md](./README.md): the table row is added with this note.
+
+## Out of scope
+
+- **Removing or demoting an admin**, founding or not. This plan makes the founding members
+ admins; what happens to them afterwards is left as it is.
+- **Making a later member an admin.** A separate feature, being planned separately.
+- **Convenient groups.** Their only admin is the creator, by design.
+- **The NIP-17 room.** It has no state to govern; see *What a robust group is*.
+
+## Risks
+
+- **Bennu peers.** One can create the admin room with a different list; Phase 3 can say so
+ and repair it, but not prevent it.
+- **Racing invites.** Phase 4 is coordinator-first to avoid two commits on one epoch; the
+ manual "Invite again" can still race, and convergence already resolves that fork
+ (`ConvergenceForkJvmTest`).
diff --git a/docs/rotate-shares-single-approval.md b/docs/rotate-shares-single-approval.md
index 19244aa2..c4f154e4 100644
--- a/docs/rotate-shares-single-approval.md
+++ b/docs/rotate-shares-single-approval.md
@@ -34,6 +34,24 @@ the reasoning. Where the build chose differently:
| Phase 6: fix `record` the way the ceremony's was | `record` and `publishOwn` both. The first version of the test passed without the fix: timestamps are kept to the second, and a redelivery in the same second looks identical. The test now backdates the messages a day first, and fails with the old behaviour put back |
| (not in the plan) | one full `jvmTest` run died on a SIGSEGV in SQLite's native code (`sqlite3DbMallocRawNN`), inside a background `MarmotKeyPackageDao.upsert`. That looks like an existing test leaving a write running against an in-memory database it has closed. The rerun was clean. Not investigated |
+**Merged into `giza`** alongside [rotation-waits-for-key-state.md](./rotation-waits-for-key-state.md),
+built in parallel from the same base. The two agreed on not asking the proposer; where
+they met:
+
+- **The proposer's dialog** is this note's (`previewRotation`, read from `plan`, with
+ the refusal), under that note's title and caveat. Its own dialog, which listed stale
+ members from the summary, went; `ChatRoomDetailSharesJvmTest` asks the same question
+ of this one. The preview's refusal now carries `rotationHold`'s reason.
+- **The proposer** is approved to take part only. That note also set
+ `confirmApprovedAt`, which nothing reads any more.
+- **The Shares section** has both: that note's held button, its reason and "Ask the group
+ to sign", and this note's running card and abandon.
+- **That note's hold tests** waited on a key state nobody had signed by simply not
+ signing it. That state signs itself now, so they hold the signing messages after the
+ proposal (`signingHeldOpen`) to look at it.
+- This note's test of two rotations opened at once gave way to that note's, which
+ asserts the same and more.
+
**Not done:** the emulator session in Phase 7. Nothing here has run on a device:
not the dialog, not the card, not the upgrade in place.
diff --git a/docs/rotation-waits-for-key-state.md b/docs/rotation-waits-for-key-state.md
new file mode 100644
index 00000000..4010f5ff
--- /dev/null
+++ b/docs/rotation-waits-for-key-state.md
@@ -0,0 +1,369 @@
+# A rotation waits for the last one to be signed
+
+A plan to hold the **Rotate shares** button until the group has signed the key state
+the previous rotation produced, and to stop asking the person who proposed a rotation
+to approve it.
+
+Read [frost-share-refresh.md](./frost-share-refresh.md) first, especially Phase 7's
+approval gates, Phase 8 (the cutover) and D6 (when the old share is wiped). Read
+[automatic-key-ceremony.md](./automatic-key-ceremony.md) as well. Its rule, "the device
+asks its owner only for decisions the device cannot make on its own", is the precedent
+for Phase 4 here.
+
+**Built**, one commit per phase on `claude/rotate-shares-pending-proposal-9d72d7`
+(`159ae402`, `d358a0db`, `98567629`, `95131248`), against the code as it stood at
+`fc437d05`. The phases are kept as written because they are the reasoning. Where the
+build chose differently:
+
+| what the plan said | what it turned out to be |
+|---|---|
+| R1(c)'s open question: does a key-state session nobody finishes ever fail here? | Only once `participantCount - threshold + 1` members have declined (`FrostSigningSession.declinesThatAbandon`), so one refusal does not end it. An open session counts **unless this device declined it**. The coordinator who proposed it cannot decline its own, and stays held until others do or it completes |
+| Phase 2's `ChatRepository.proposeKeyState` does the work | the work is `ShareRefreshManager.proposeOwedKeyState`, which the repository wraps, so it is tested in the ritual harness without building an `Identity` |
+| Phase 2's held line links to the proposals | a **See the proposal** button under the line, to `ProposalListRoute` |
+| Phase 2's summary tests are their own file | two tests in `ShareRefreshRitualJvmTest`, reading `DatabaseChatRepository.sharesSummary` on the harness's devices through every `Rotation` value, the re-ask included |
+| Phase 3 recomputes on repairs too, or leaves them out | left out: `ShareRepairDao` has no observable query |
+| Phase 4's dialog says "%1$s will be left out again…" | a line, then one name per line. Joining names into one string needs a separator the catalogue cannot hold |
+| Phase 4's crossing proposals end in one completed refresh or one a recipient can abandon | each proposer is a recipient of the other's proposal and refuses it on arrival ("another refresh of this key is still running here"), out loud, so neither is left running. The test asserts the property, not which one survives: nothing running, at most one complete, every device on one table |
+
+**Not done:** none of it has been seen on a device or a desktop window: the disabled
+button and its line, the re-ask, the confirmation dialog, or the section updating while
+open.
+
+---
+
+## The bug
+
+A rotation does not end when its refresh session reaches `COMPLETE`. It ends when the
+group has signed the new generation's key state (kind 30326). That signature is the
+first one the new shares make, and every device waits for it before it wipes the old
+shares (D6). Here is the sequence:
+
+```
+ Rotate shares
+ └─ ShareRefreshSession PROPOSED … COMPLETE ← canRotate checks only this
+ └─ coordinator: GroupKeyStateManager.proposeGeneration
+ └─ FrostSigningSession over a 30326 at g+1 ← open, waiting on a quorum
+ └─ signed → record() → retireOlderShares → wipe g
+```
+
+`DatabaseChatRepository.sharesSummary` (`DatabaseChatRepository.kt:681-688`) works
+out `canRotate` as:
+
+```kotlin
+val running = refreshes.any { it.stage != COMPLETE && it.stage != FAILED }
+canRotate = ExperimentalFeatures.shareRefresh && shares.secretShare != null && !running
+```
+
+So the button comes back once the refresh is `COMPLETE`, while the key-state
+proposal for `g+1` is still collecting signatures. `ShareRefreshManager.proposeRefresh`
+has no further check either. Its `running(...)` guard (`ShareRefreshManager.kt:207`)
+looks only at refresh sessions. A second tap then does the following:
+
+1. It starts a refresh from base `g+1` before anyone has shown that `g+1` can sign.
+ That is the thing D6 exists to prevent. Two unproven generations are now stacked.
+2. It turns the open `g+1` key-state proposal into a dead end. Once `g+2` is active
+ and its key state is signed, `retireOlderShares` calls `failRotated(g+2)`, and every
+ open session below `g+2` fails. That includes the `g+1` key-state session that
+ members may still be approving. They approve a proposal that can only fail.
+3. A device that has not received the `g+1` certificate yet refuses the new proposal
+ on arrival ("it refreshes generation g+1, and this device is at generation g"), and
+ if it is a recipient it broadcasts a failure.
+
+The same gap reaches the room detail screen's "Rotate shares without them?" dialog
+(`ChatRoomDetailScreen.kt:192-207`). `rotateSharesWithout` never reads `canRotate`.
+
+Two smaller problems sit next to the main one:
+
+- **The screen is not reactive.** `ChatRoomDetailViewModel.initiateChatRoomDetail`
+ reads `sharesSummary` once and reads it again only after one of the screen's own
+ actions. A key state signed in the background does not re-enable anything until the
+ screen is opened again.
+- **Nothing guards a double tap.** `sharesAction` (`ChatRoomDetailViewModel.kt:146`)
+ does not disable the button while it runs. A second tap is caught by `running(...)`,
+ which hands back the first session, and the screen still says "Share rotation
+ proposed" a second time. `isActionPending` exists on the view model but nothing uses
+ it.
+
+## The question: should the proposer approve their own rotation?
+
+At the moment the proposer is asked like everyone else:
+
+> The proposer is auto-approved for nothing. Proposing a refresh is not agreeing to
+> withhold whomever the form defaulted to. (frost-share-refresh.md, Phase 7)
+
+`nothing of a member's own goes out before they approve` in `ShareRefreshRitualJvmTest`
+asserts it. So tapping **Rotate shares** puts a "Take part in rotating the shares" row
+in front of the person who just tapped it, and later a "Store your new share" row.
+
+The reason given is real, but it describes the screen, not the protocol. The plain
+button runs no confirmation step at all. It withholds every stale member automatically
+and never says so. The way to fix that is to have the tap state what it agrees to, not
+to ask a second time. The ceremony has already settled this:
+`ChillDkgRitualManager` approves the coordinator's host key at proposal
+(`ChillDkgRitualManager.kt:308`), and since automatic-key-ceremony.md both rounds are
+automatic for everyone.
+
+**Recommendation: yes.** Once the tap goes through a confirmation that names who is
+withheld and as what, approve the proposer's `DEAL` and `CONFIRM` at proposal.
+
+- `DEAL` is the decision about the withheld list. A proposer who has been shown the
+ list and confirmed it has made that decision.
+- `CONFIRM` guards against "a coordinator substituting a table the recipients never
+ dealt". The proposer *is* the coordinator, so it cannot defend against itself. The
+ CertEq check its device runs is what does the work, and a tap adds nothing to that.
+
+Approval stays exactly as it is for every *other* recipient. Whether `CONFIRM` should
+become automatic for everyone, as round 2 did in the ceremony, is a separate decision.
+It is listed under [Not in this plan](#not-in-this-plan).
+
+The key-state proposal at the end of a rotation already approves its proposer:
+`FrostSigningManager.proposeSigning` sets `signApprovedAt` (`FrostSigningManager.kt:364`).
+Nothing changes there.
+
+---
+
+## Phase 0: decisions
+
+| # | Question | Recommendation | Why |
+|---|---|---|---|
+| R1 | What counts as "a proposal for a group-signed key is pending"? | Any of: (a) a refresh for the key not yet `COMPLETE`/`FAILED`, which is today's check; (b) the key state the group has signed for the room names a generation **below** this device's active one; (c) an open `FrostSigningSession` for the key whose single item is a 30326, at any generation, rebinds included; (d) the signed state names a generation **above** this device's active one, so this device is behind | (b) covers the window before the coordinator's proposal arrives and the case where it failed. (c) covers a Phase 10b rebind and the ceremony's first state. (d) catches a device that missed a certificate, whose proposal every other device would refuse |
+| R2 | Is the check made on the proposer's device only, or by recipients on arrival as well? | **On the proposer's device only.** Recipients keep today's refusals | A recipient that refuses on arrival broadcasts a failure. A device a few seconds behind on the key-state signature would then kill a valid rotation. The rule is "don't stack unproven generations from here", and the proposer is the device that can follow it |
+| R3 | Does a running **repair** block rotation? | **No**, unless its rebind key state is open, which R1(c) already covers | `ShareRepairManager` has no abandon. A repair whose target never comes back would disable the button for good |
+| R4 | What if the key state is never signed? | The Shares section offers **Ask the group to sign the new shares**, which calls `proposeGeneration` again ("anyone can propose it again", Phase 8), but only when R1(b) holds and no R1(c) session is open | Without this, a coordinator who disappears after `COMPLETE` disables the button for everyone, with nothing offered to fix it |
+| R5 | Is the button hidden or disabled? | **Disabled, with a line saying why** | The user asked for it disabled. A missing button looks like a lost feature, and a disabled one with a reason tells people what they are waiting for |
+| R6 | Does the proposer's confirmation name the withheld? | Yes. The plain button gets a dialog in the style of "Rotate shares without them?", listing every stale member who will be withheld again (or saying nobody is) | That is the condition the Phase 7 sentence was protecting, and Phase 4 depends on it |
+
+The question R1(c) has to answer before it is relied on: **does a 30326 signing session
+that never reaches a quorum ever reach `FAILED` on this device?** If declining it
+(`FrostSigningManager.decline`, `:2090`) only stops this device's own participation,
+an open session would disable the button indefinitely. Phase 1 checks this first. If the
+answer is no, R1(c) counts a session only while it is younger than the signing stall
+window, or only while this device has not declined it.
+
+---
+
+## Phase 1: the rule, in the manager
+
+One function that the summary and the propose paths both read, so the screen and the
+protocol cannot drift apart. That is the same discipline `pendingApproval` follows with
+`advance`.
+
+**`ShareRefreshManager`**
+
+```kotlin
+/** Why this device must not propose a rotation of [key] now, or null when it may. */
+sealed interface RotationHold {
+ data class Running(val refreshId: String) : RotationHold
+ data class AwaitingKeyState(val generation: Int, val signingSessionId: String?) : RotationHold
+ data class Behind(val groupGeneration: Int, val localGeneration: Int) : RotationHold
+}
+
+suspend fun rotationHold(database: GizaDatabase, localChatRoom: LocalChatRoom, key: DkgSession): RotationHold?
+```
+
+- `Running`: the current `running(database, key)`.
+- `AwaitingKeyState(g, id)`: covers R1(b) and R1(c). `g` is the active generation,
+ read through `ShareGenerations.active`. `id` is the open 30326 session, if there is
+ one, found from `frostSigningSessionDao().getOpenSessionsForKey(key.id)` with the
+ item read by `getItems`. The signed generation is
+ `GroupKeyStateManager.keyStateFor(database, roomId)?.generation ?: 0`.
+- `Behind`: R1(d).
+- Generation 0 with no open 30326 session is never held. It needs no new key state
+ (`proposeGeneration` refuses it).
+
+**`proposeRefresh`** keeps handing back a running refresh. That is what
+`a second proposal while one runs hands back the first` asserts. For `AwaitingKeyState`
+and `Behind` it throws an `IllegalStateException` carrying the reason, which
+`DatabaseChatRepository.failureOf` already turns into the snackbar text.
+`proposeWithout` goes through `proposeRefresh`, so the removal dialog is covered too.
+
+**Tests**, in `ShareRefreshRitualJvmTest`:
+
+- `the next rotation waits until the group has signed the last one`: refresh to
+ generation 1, then check that `proposeRefresh` throws naming generation 1. Approve
+ the key-state signing on a quorum (`approveSigning`), and the next refresh proposes.
+- `a rebind waiting on signatures holds a rotation`: uses the Phase 10b fixture.
+- `a device that missed the certificate cannot propose from the old generation`.
+- `rotating without a member waits as well`: `proposeWithout` while generation 1 is
+ unsigned.
+- the R1(c) question above, answered by a test whichever way it goes.
+
+**Existing tests that will break, as intended:**
+`the recovery walk rebuilds the live share three refreshes on` runs three refreshes
+back to back with no key state signed in between, which is exactly what this phase
+forbids. Add `approveSigning(all)` after each round. Before relying on it, check that
+`ShareGenerations.wipeBefore` leaves the recovery data the walk reads, which should hold
+because it nulls only `secretShare`. If it does not, that is a real bug for restoring
+after a wipe, and it has to be fixed rather than worked around in the test.
+
+**Done when** the new tests pass and `jvmTest` is green.
+
+---
+
+## Phase 2: the Shares section says why
+
+**`SharesSummary`.** `canRotate: Boolean` becomes something the screen can explain:
+
+```kotlin
+/** Whether this device may propose a rotation, and if not, what it waits on. */
+val rotation: Rotation
+
+sealed interface Rotation {
+ data object Unavailable : Rotation // no live share, or the flag is off: no button
+ data object Available : Rotation
+ data class Held(val reason: Reason, val canAskForSignature: Boolean) : Rotation
+ enum class Reason { ROTATION_RUNNING, AWAITING_SIGNATURES, BEHIND }
+}
+```
+
+`sharesSummary` maps `rotationHold` onto it. `canAskForSignature` is
+`AwaitingKeyState` with `signingSessionId == null` (R4).
+
+**`ChatRoomDetailScreen`** (`:438-469`):
+
+- The caveat text and the button are shown for `Available` and `Held`. For `Held` the
+ button has `enabled = false`, and the line below it comes from the reason:
+ - `rotation_held_running`: "A rotation is in progress"
+ - `rotation_held_awaiting_signatures`: "Waiting for the group to sign the new shares
+ before another rotation"
+ - `rotation_held_behind`: "This device is catching up with the group's latest
+ rotation"
+
+ These go in sentence case, through the catalogue, coloured `onSurfaceVariant` like
+ the caveat.
+- When `canAskForSignature` is true, a `TextButton` **Ask the group to sign the new
+ shares** calls a new `ChatRepository.proposeKeyState(localChatRoom)`. That
+ calls `GroupKeyStateManager.proposeGeneration(..., refreshId = )` and reports through `notify`.
+- With `AWAITING_SIGNATURES` and an open session, the line links to the room's
+ proposals, using the same `ProposalListRoute` the overflow already opens (`:622`).
+ The proposal waiting on the reader is one tap away.
+- **The removal dialog.** `ChatRoomDetailViewModel.removeMember` raises
+ `rotationOffer` only when `holdsShare` is true *and* rotation is `Available`. When
+ it is `Held`, the snackbar says the member still holds a share and a rotation can be
+ started once the group has signed the current one. The offer is not shown and then
+ refused.
+
+**The double tap.** `sharesAction` sets `isActionPending` for its duration, and every
+Shares section button reads it as `enabled = !isActionPending.value && …`.
+
+**Tests.** A `sharesSummary` test in `jvmTest` for each `Rotation` value, built on the
+ritual harness. Plus the M3 audit: no literals, no `.dp`, sentence case.
+
+**Done when** `./gradlew :composeApp:m3Audit` and `:composeApp:jvmTest` pass, and the
+section has been looked at on the desktop target in each of the three held states.
+
+---
+
+## Phase 3: the button comes back on its own
+
+Re-read the shares summary whenever something it depends on changes, instead of only
+after this screen's own actions.
+
+- In `ChatRoomDetailViewModel`, collect `combine(groupKeyStateDao().observeByChatRoomId(id),
+ frostSigningSessionDao().observeSessionsForChatRoom(id),
+ shareRefreshDao().observeSessionsForRoom(id))` through a new
+ `ChatRepository.observeSharesInputs(chatRoomId): Flow`. Debounce it, and
+ recompute **only** `shares` on the `Loaded` state with `copy(shares = …)`. A full
+ `initiateChatRoomDetail` would reload the subgroups and the profile as well.
+- Repairs are left out on purpose (R3). Their pending approvals still refresh on the
+ existing paths.
+
+**Done when** a test drives the view model with a fake repository whose flow emits
+after a key state is filed and sees `rotation` move from `Held` to `Available`. Also
+check by hand on desktop that approving the key state from a second device re-enables
+the button without leaving the screen.
+
+---
+
+## Phase 4: the proposer is not asked about their own rotation
+
+Only after Phases 1–3, and only together with R6's dialog.
+
+**The confirmation.** The plain **Rotate shares** button opens an `AlertDialog`:
+
+- title: `rotate_shares_confirm_title`, "Rotate the group's shares?"
+- body: the existing caveat, plus a line built from `SharesSummary.members` with
+ `standing == STALE`: "%1$s will be left out again until they are brought back", or
+ "Every member with a share takes part" when there are none.
+- confirm: **Rotate shares**. Dismiss: **Not now**.
+
+The "Rotate shares without them?" dialog already names the person being retired, so it
+counts as R6's confirmation as it stands.
+
+**The manager.** In `proposeRefresh`, the new `ShareRefreshSession` is created with
+`dealApprovedAt = now` and `confirmApprovedAt = now`, and the KDoc at
+`ShareRefreshManager.kt:111-116` is rewritten to state the rule and its reason: the
+proposer confirmed the withheld list, and is the coordinator whose substitution
+`CONFIRM` guards against. As a result:
+
+- `advance` publishes the proposer's round 1 straight after the proposal, so other
+ devices see "dealt" from the proposer at once.
+- `pendingApproval` is null for the proposer throughout, so no "Take part" or
+ "Store your new share" row appears for them, and `announceApprovalNeeded` writes no
+ "approval needed" line for them.
+- Other recipients are asked exactly as before.
+
+**Watch:** two members who propose from the same base before either hears of the
+other. With both proposers auto-confirmed, each has confirmed its own refresh, and D3a
+stops it confirming the other. Each refresh needs every recipient, so at most one can
+certify, and possibly neither. That is the same outcome as two people who each tapped
+**Approve** on their own, so no new failure mode appears. It just arrives faster. Add a
+test that shows it ends in one completed refresh or in a state a recipient can
+**Abandon**, and never in two certificates.
+
+**Tests.**
+
+- `nothing of a member's own goes out before they approve` is rewritten: the proposer's
+ outbox holds `PROPOSAL` and `ROUND_1`, every other device's holds nothing, and only
+ the others are asked. Its last assertion, that the proposer *is* asked, is inverted.
+ This test is the one that records the decision, so its name and comment change along
+ with it.
+- `approveAll` still works unchanged, since it skips devices that have nothing pending.
+- the concurrent-proposal test above.
+
+**Strings.** `share_rotation_requested` becomes "Share rotation proposed; every other
+member is asked to take part". `StringCatalogueJvmTest` needs no change.
+
+---
+
+## Phase 5: the record
+
+- In `frost-share-refresh.md`, add rows to "Where it stands" for this work. Rewrite the
+ Phase 7 sentence "The proposer is auto-approved for nothing" as the new rule and its
+ reason. Add "a rotation whose key state the group has not signed" to Phase 7's list of
+ refusals, marked as the proposer's own check only (R2).
+- Mark this file **Built**, with the commits, in the manner of
+ automatic-key-ceremony.md's table of "what the plan said / what it turned out to be".
+- `./gradlew check` runs the m3, brand and wallet audits.
+
+---
+
+## Not in this plan
+
+- **`CONFIRM` automatic for every recipient**, the ceremony's round-2 decision applied
+ to refresh. It is defensible on the same argument, but it changes what every member
+ is asked, so it needs its own decision. *Since decided and built:*
+ [rotate-shares-single-approval.md](./rotate-shares-single-approval.md), which also
+ lets the new generation's key state sign itself and replaced this note's confirmation
+ dialog with one read from the proposal's own plan.
+- **Recipients refusing a proposal whose base key state they have not seen signed**
+ (R2). Without D5's capability check there is no way to tell "behind" from "never
+ will".
+- **An abandon for repairs**, which R3 would need before a repair could hold rotation.
+- **The refresh screen** that Phase 11 of frost-share-refresh.md described and the
+ Shares section replaced. The held state's line is the only progress shown.
+
+## Files
+
+| file | phase |
+|---|---|
+| `managers/ShareRefreshManager.kt`: `rotationHold`, `proposeRefresh` | 1, 4 |
+| `database/repository/DatabaseChatRepository.kt`: `sharesSummary`, `proposeKeyState`, `observeSharesInputs` | 2, 3 |
+| `repository/ChatRepository.kt` | 2, 3 |
+| `ui/view/state/SharesSummary.kt`: `Rotation` | 2 |
+| `ui/view/model/ChatRoomDetailViewModel.kt`: `isActionPending`, the observer, the removal offer | 2, 3 |
+| `ui/composable/ChatRoomDetailScreen.kt`: disabled button and reason, ask-to-sign, the confirmation dialog | 2, 4 |
+| `composeResources/values/strings.xml` | 2, 4 |
+| `jvmTest/.../ShareRefreshRitualJvmTest.kt` | 1, 4 |
+| `docs/frost-share-refresh.md` | 5 |
diff --git a/docs/subgroups.md b/docs/subgroups.md
index 88f129d8..6055b00c 100644
--- a/docs/subgroups.md
+++ b/docs/subgroups.md
@@ -671,6 +671,12 @@ re-deriving:
- **`adopt` before the members are added**, because filing the key state is local
and certain and adding members is neither.
+> **Since [robust-group-admins.md](./robust-group-admins.md):** the repository's
+> `createMarmotGroup` takes the ceremony and the room it ran in instead of
+> `adminPublicKeys`, and `MarmotGroupCreation.createFor` reads the admins, the id and the name
+> off the ceremony. A subgroup's founding admins are its ceremony's participants, as a
+> group's are, so the same rule makes both.
+
`parentChatRoomId` is the one genuinely new parameter, written onto the
`ChatRoom` row. The subgroup's description carries the path through
`SharedKeyDerivation.describe`, exactly as the admin room's does — MIP-01 has no