diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index da0a70a0..671f8eb9 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -108,7 +108,6 @@
Leave group
Couldn't leave the group
Member actions
- Admin
Holds a share
Make admin
Make %1$s an admin?
@@ -142,6 +141,12 @@
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
+ Taking part: %1$s
+ Left out until they are brought back: %1$s
+ Left out for good: %1$s
+ Each member taking part is asked once. Rotating counts as your own agreement, so you are not asked again.
+ This group has no key this device can rotate
+ This rotation cannot start: %1$s
Shares
Generation %1$d
Holds a share
@@ -152,10 +157,31 @@
Ask to be brought back
Approve
Take part in rotating the shares
- Store your new share
+ Every member takes part.
+ Without %1$s.
+ %1$s until they are brought back
+ %1$s for good
+ Your device then sends its part, stores your new share and signs the group\'s new key state without asking again.
+ Rotating the shares
+ Members are sending their parts of the new shares.
+ Members are storing their new shares.
+ The group is signing its new key state. The old shares are deleted once it has.
+ If someone has stopped answering, any member taking part can abandon the rotation. Every share stays as it was, and the group can start again.
+ Abandon rotation
+ Abandon this rotation?
+ It ends for every member. Nobody gets a new share, and the group keeps signing with the shares it has.
+ 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
@@ -507,4 +533,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/FrostSigningSessionDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/FrostSigningSessionDao.kt
index b1f23073..0f30919c 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/FrostSigningSessionDao.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/FrostSigningSessionDao.kt
@@ -83,6 +83,13 @@ interface FrostSigningSessionDao {
suspend fun getSessionsForChatRoom(chatRoomId: String): List
/** Sessions of one key still running: what a share rotation has to end. */
+ /** Sessions still running that [userPublicKey]'s owner has neither approved nor declined. */
+ @Query(
+ "SELECT * FROM FrostSigningSession WHERE userPublicKey = :userPublicKey AND stage NOT IN ('COMPLETE', 'FAILED') " +
+ "AND signApprovedAt IS NULL AND signDeclinedAt IS NULL ORDER BY createdAt ASC"
+ )
+ suspend fun getOpenUnansweredSessionsFor(userPublicKey: HexKey): List
+
@Query("SELECT * FROM FrostSigningSession WHERE dkgSessionId = :dkgSessionId AND stage NOT IN ('COMPLETE', 'FAILED')")
suspend fun getOpenSessionsForKey(dkgSessionId: String): List
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 7853d805..52fc2b4c 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
@@ -61,6 +61,7 @@ import mobi.giza.compose.exceptions.MarmotMissingChatGroupException
import mobi.giza.compose.extensions.exporterSecret
import mobi.giza.compose.extensions.shortened
import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.managers.AdminFlags
import mobi.giza.compose.managers.AdminGovernance
import mobi.giza.compose.managers.GovernanceGate
import mobi.giza.compose.managers.GovernanceManager
@@ -149,7 +150,7 @@ abstract class MarmotOutboundDao(
)
// The creator administers the room from epoch 0, and this device learns that
// nowhere else. docs/member-admin-promotion.md, Phase 1.
- MarmotInboundManager.reconcileAdmins(database, chatRoom.id, mlsGroup)
+ AdminFlags.reconcile(database, chatRoom.id, mlsGroup)
// Invite peer. On the current profile the manager owns the group from the row
// just written, and the invite moves that instance rather than the one the
@@ -1082,6 +1083,42 @@ abstract class MarmotOutboundDao(
}
}
+ /**
+ * 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
+
+ // A governed room's admins change only with the group's signature, so the
+ // repair is proposed rather than committed. The founders it adds took part
+ // in the ceremony and hold shares of the key, as R1 asks of every admin.
+ // docs/member-admin-promotion.md, Phase 5.
+ if (GovernanceGate.isGoverned(group)) {
+ GovernanceManager.propose(database, localChatRoom, localChatRoom.chatRoom.userPublicKey) { copy ->
+ copy.proposeAppDataUpdate(AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(current + added).encode())
+ }
+ 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 1ccd8dba..54941a19 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
@@ -68,6 +68,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
@@ -908,6 +910,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
@@ -969,6 +982,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/dao/ShareRefreshDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt
index eefbf601..bb4d1fee 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt
@@ -28,6 +28,13 @@ abstract class ShareRefreshDao {
@Query("SELECT * FROM ShareRefreshSession WHERE dkgSessionId = :dkgSessionId ORDER BY createdAt DESC")
abstract suspend fun getSessionsForKey(dkgSessionId: String): List
+ /**
+ * Every refresh [userPublicKey] is in that has not finished, oldest first:
+ * what `ShareRefreshManager.resumeRunning` moves on.
+ */
+ @Query("SELECT * FROM ShareRefreshSession WHERE userPublicKey = :userPublicKey AND stage NOT IN ('COMPLETE', 'FAILED') ORDER BY createdAt ASC")
+ abstract suspend fun getRunningSessionsFor(userPublicKey: HexKey): List
+
@Query("SELECT * FROM ShareRefreshSession WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC")
abstract fun observeSessionsForRoom(chatRoomId: String): Flow>
@@ -37,6 +44,9 @@ abstract class ShareRefreshDao {
@Upsert
abstract suspend fun upsert(message: ShareRefreshMessage)
+ @Query("SELECT * FROM ShareRefreshMessage WHERE sessionId = :sessionId")
+ abstract suspend fun getMessagesForSession(sessionId: String): List
+
@Query("SELECT * FROM ShareRefreshMessage WHERE sessionId = :sessionId AND kind = :kind")
abstract suspend fun getMessagesByKind(sessionId: String, kind: Kind): List
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 f40a60b2..9a2a46a3 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
@@ -593,6 +593,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.
*
@@ -610,6 +618,7 @@ data class ChatMessage(
TYPE_ADMIN_REMOVED,
TYPE_CHANGE_NOT_APPLIED,
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/model/ShareRefreshSession.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshSession.kt
index a7478251..846724ce 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshSession.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshSession.kt
@@ -74,7 +74,14 @@ data class ShareRefreshSession(
/** Secret-adjacent. Round 2's auxiliary randomness for the confirmation's signature. */
val auxRandom: HexKey,
+ /** When this device's owner agreed to take part: the refresh's one approval. */
val dealApprovedAt: Instant? = null,
+
+ /**
+ * Written by builds before docs/rotate-shares-single-approval.md, when storing
+ * the new share was its own approval. Read by nothing; kept rather than
+ * migrated away.
+ */
val confirmApprovedAt: Instant? = null,
/** The furthest step this device has asked its owner about, so the request line is written once. */
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ChatRoomType.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ChatRoomType.kt
index 79ae3884..b97177ae 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ChatRoomType.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ChatRoomType.kt
@@ -7,9 +7,8 @@ import kotlinx.serialization.Serializable
*
* The choice decides the room's founding admins, written into its epoch-0 admin
* list. That list is the group's state from then on, and a promotion or demotion
- * changes it; `MarmotInboundManager.reconcileAdmins` and
- * `processGroupMembershipChanges` keep each participant's `adminAt` in line with
- * whatever it says now. See docs/member-admin-promotion.md.
+ * changes it; `AdminFlags.reconcile` keeps each participant's `adminAt` in line
+ * with whatever it says now. See docs/member-admin-promotion.md.
*/
@Serializable
enum class ChatRoomType {
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRefreshApprovalStep.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRefreshApprovalStep.kt
index e871ce94..347551fe 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRefreshApprovalStep.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRefreshApprovalStep.kt
@@ -1,21 +1,30 @@
package mobi.giza.compose.database.model.types
/**
- * The two decisions a recipient makes in a share refresh. Each publishes
- * something different and commits the member to something different.
+ * Everything a share refresh has ever asked a recipient. One step is still
+ * asked; the other is kept so rows that stored it by name still decode
+ * (`ShareRefreshSession.approvalRequestedThrough`).
*/
enum class ShareRefreshApprovalStep {
/**
- * Deal round 1: join the refresh, and agree to the withheld list. Withholding
+ * Take part: deal round 1, and agree to the withheld list. Withholding
* someone takes their signing away, so every recipient decides it, not only
- * the proposer.
+ * the proposer. **The only approval a refresh asks for**: the device does
+ * everything after it on its own (docs/rotate-shares-single-approval.md).
*/
DEAL,
/**
- * Confirm round 2: store the new generation and say so. This is what stops a
- * coordinator substituting a table the recipients never dealt, and the one
- * confirmation per base generation this device will ever give.
+ * Was: confirm round 2, storing the new generation and saying so. **No
+ * longer asked**, and nothing produces it.
+ *
+ * Its two reasons never needed a person. Stopping a coordinator substituting
+ * a table nobody dealt is `FrostRefresh.participantStep2`'s check, which runs
+ * before any prompt could appear and fails the refresh out loud. The one
+ * confirmation per base generation is `ShareRefreshConfirmation`, claimed in
+ * the same transaction as the pending share. Neither depended on the tap.
+ * Don't put the gate back: a person shown "store your new share" has nothing
+ * to check that the device has not already checked.
*/
CONFIRM,
}
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 d59d9826..380ddac4 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
@@ -1,5 +1,8 @@
package mobi.giza.compose.database.repository
+import mobi.giza.compose.database.model.ShareRefreshSession
+import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
+import com.vitorpamplona.quartz.nip01Core.core.Event
import co.touchlab.kermit.Logger
import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent
import com.vitorpamplona.quartz.nip01Core.core.HexKey
@@ -11,6 +14,9 @@ import mobi.giza.compose.managers.AdminGovernance
import mobi.giza.compose.managers.GovernanceGate
import mobi.giza.compose.managers.GovernanceSupport
import mobi.giza.compose.managers.MarmotInboundManager
+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
@@ -29,10 +35,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
@@ -47,13 +55,14 @@ import mobi.giza.compose.identity.Identity
import mobi.giza.compose.identity.toKeyPair
import mobi.giza.compose.managers.ShareRefreshManager
import mobi.giza.compose.ui.view.state.GovernanceStatus
+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
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
@@ -78,27 +87,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)
@@ -652,7 +695,7 @@ class DatabaseChatRepository(
val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return false
// A row whose state this build cannot read has no admin set to agree with.
val group = runCatching { room.chatRoom.toMlsGroup() }.getOrNull() ?: return false
- return MarmotInboundManager.reconcileAdmins(database, chatRoomId, group)
+ return AdminFlags.reconcile(database, chatRoomId, group) > 0
}
override suspend fun adminFloor(chatRoomId: String): Int {
@@ -693,6 +736,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)
@@ -712,30 +768,107 @@ class DatabaseChatRepository(
val shares = ShareGenerations.active(database, key)
if (shares.roster.isEmpty()) return null
val names = localChatRoom.localParticipants.associate { it.participant.participantPublicKey to it.profile?.humanReadableNameOrPubkey() }
+ fun nameOf(member: HexKey) = names[member] ?: member.take(8)
val refreshes = database.shareRefreshDao().getSessionsForKey(key.id)
val repairs = database.shareRepairDao().getSessionsForKey(key.id)
val pending = refreshes.mapNotNull { session ->
when (ShareRefreshManager.pendingApproval(database, session)) {
- ShareRefreshApprovalStep.DEAL -> SharesSummary.PendingApproval(session.id, SharesSummary.PendingApproval.Kind.REFRESH_DEAL)
- ShareRefreshApprovalStep.CONFIRM -> SharesSummary.PendingApproval(session.id, SharesSummary.PendingApproval.Kind.REFRESH_CONFIRM)
- null -> null
+ ShareRefreshApprovalStep.DEAL -> {
+ val roster = ShareGenerations.at(database, key, session.baseGeneration)?.roster.orEmpty()
+ .associate { it.participantId to it.memberPublicKey }
+ SharesSummary.PendingApproval(
+ sessionId = session.id,
+ kind = SharesSummary.PendingApproval.Kind.REFRESH_DEAL,
+ withheld = session.withheldStandings().map { (id, standing) ->
+ SharesSummary.Withheld(roster[id]?.let(::nameOf) ?: id.toString(), standing)
+ },
+ )
+ }
+ // Never pending since docs/rotate-shares-single-approval.md.
+ ShareRefreshApprovalStep.CONFIRM, null -> null
}
} + repairs.filter { ShareRepairManager.isAwaitingApproval(database, it) }
.map { SharesSummary.PendingApproval(it.id, SharesSummary.PendingApproval.Kind.REPAIR_HELP) }
- val running = refreshes.any { it.stage != ShareRefreshStage.COMPLETE && it.stage != ShareRefreshStage.FAILED }
+ val runningRefresh = refreshes.firstOrNull { it.stage != ShareRefreshStage.COMPLETE && it.stage != ShareRefreshStage.FAILED }
+ val running = runningRefresh?.let { session ->
+ // The approval row covers a member not yet asked; this is everything after it.
+ if (ShareRefreshManager.pendingApproval(database, session) != null) return@let null
+ ShareRefreshManager.progress(database, session)?.let { progress ->
+ SharesSummary.Running(
+ sessionId = session.id,
+ step = when (progress.step) {
+ ShareRefreshManager.Progress.Step.DEALING -> SharesSummary.Running.Step.DEALING
+ ShareRefreshManager.Progress.Step.STORING -> SharesSummary.Running.Step.STORING
+ },
+ waitingOn = progress.waitingOn.map(::nameOf),
+ since = progress.since,
+ canAbandon = progress.canAbandon,
+ )
+ }
+ } ?: signingNewGeneration(localChatRoom, key, shares.generation, refreshes)
val mine = shares.roster.firstOrNull { it.memberPublicKey == me }
val repairing = repairs.any { it.targetPublicKey == me && it.stage != ShareRepairStage.FAILED && it.stage != ShareRepairStage.COMPLETE }
SharesSummary(
generation = shares.generation,
members = shares.roster.map { entry ->
- SharesSummary.Member(entry.memberPublicKey, names[entry.memberPublicKey] ?: entry.memberPublicKey.take(8), entry.standing, entry.memberPublicKey == me)
+ 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 && !running,
+ 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
+ ?.takeIf { ExperimentalFeatures.shareRefresh },
)
}.getOrNull()
+ /**
+ * The last step of a rotation: complete, and the group signing the new
+ * generation's key state, which the old shares wait on before they are
+ * deleted. Shown only while that signature is actually open, so a key state
+ * nobody is asking for does not read as one under way.
+ */
+ private suspend fun signingNewGeneration(
+ localChatRoom: LocalChatRoom,
+ key: DkgSession,
+ generation: Int,
+ refreshes: List,
+ ): SharesSummary.Running? {
+ val refresh = refreshes.firstOrNull { it.stage == ShareRefreshStage.COMPLETE && it.baseGeneration + 1 == generation } ?: return null
+ val signed = GroupKeyStateManager.signedStateFor(database, localChatRoom.chatRoom.id)
+ if ((signed?.generation ?: 0) >= generation) return null
+ val signing = database.frostSigningSessionDao()
+ val open = signing.getOpenSessionsForKey(key.id).firstOrNull { session ->
+ (session.generation ?: 0) == generation && signing.getItems(session.id).singleOrNull()
+ ?.let { Event.fromJsonOrNull(it.unsignedEventJson)?.kind } == GroupKeyStateEvent.KIND
+ } ?: return null
+ return SharesSummary.Running(
+ sessionId = refresh.id,
+ step = SharesSummary.Running.Step.SIGNING,
+ waitingOn = emptyList(),
+ since = open.createdAt,
+ canAbandon = false,
+ )
+ }
+
+ 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? {
@@ -750,11 +883,25 @@ class DatabaseChatRepository(
return failureOf(runCatching { ShareRefreshManager.proposeRefresh(database, localChatRoom, me, privateKey, key) }.exceptionOrNull())
}
+ override suspend fun rotationPreview(localChatRoom: LocalChatRoom, without: HexKey?): RotationPreview? = runCatching {
+ if (!ExperimentalFeatures.shareRefresh) return null
+ val me = localChatRoom.chatRoom.userPublicKey
+ val preview = ShareRefreshManager.preview(database, localChatRoom, me, without) ?: return null
+ val names = localChatRoom.localParticipants.associate { it.participant.participantPublicKey to it.profile?.humanReadableNameOrPubkey() }
+ fun nameOf(member: HexKey) = names[member] ?: member.take(8)
+ RotationPreview(
+ takingPart = preview.takingPart.map(::nameOf),
+ untilBroughtBack = preview.withheld.filterValues { it == ShareStanding.STALE }.keys.map(::nameOf),
+ forGood = preview.withheld.filterValues { it == ShareStanding.RETIRED }.keys.map(::nameOf),
+ refusal = preview.refusal,
+ )
+ }.getOrNull()
+
override suspend fun approveShares(localChatRoom: LocalChatRoom, approval: SharesSummary.PendingApproval): String? {
val (_, privateKey) = privateKeyOrNull() ?: return "This identity cannot sign"
return failureOf(runCatching {
when (approval.kind) {
- SharesSummary.PendingApproval.Kind.REFRESH_DEAL, SharesSummary.PendingApproval.Kind.REFRESH_CONFIRM ->
+ SharesSummary.PendingApproval.Kind.REFRESH_DEAL ->
ShareRefreshManager.approve(database, localChatRoom, approval.sessionId, privateKey)
SharesSummary.PendingApproval.Kind.REPAIR_HELP ->
ShareRepairManager.approve(database, localChatRoom, approval.sessionId, privateKey)
@@ -762,6 +909,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())
@@ -824,4 +977,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/database/repository/DatabaseNostrRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt
index 611cb87d..7d105ec7 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt
@@ -59,6 +59,8 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import mobi.giza.compose.managers.ChillDkgRitualManager
+import mobi.giza.compose.managers.FrostSigningManager
+import mobi.giza.compose.managers.ShareRefreshManager
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import mobi.giza.compose.identity.Identity
@@ -144,10 +146,18 @@ class DatabaseNostrRepository(
// Under the same lock as the inbound path that otherwise drives a ritual, so
// a message arriving mid-sweep is not acted on twice at once.
return storeNostrEventMutex.withLock {
+ val userPublicKey = activeKeyPair.pubKey.toHexKey()
ChillDkgRitualManager.resumeRunning(
database = database,
- userPublicKey = activeKeyPair.pubKey.toHexKey(),
+ userPublicKey = userPublicKey,
nostrPrivateKey = privateKey
+ ) + ShareRefreshManager.resumeRunning(
+ database = database,
+ userPublicKey = userPublicKey,
+ nostrPrivateKey = privateKey
+ ) + FrostSigningManager.resumeVouched(
+ database = database,
+ userPublicKey = userPublicKey,
)
}
}
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/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt
index 509ead3f..5b948f82 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt
@@ -442,14 +442,14 @@ object FrostSigningManager {
}
// The other answer a device can give on its owner's behalf, and only to one
- // question: what the room a ceremony it finished signs with. For that there
- // is exactly one true statement, and `vouchesFor` signs nothing else --
- // any other proposal, a key state included, is asked about as before.
- // docs/automatic-key-ceremony.md, Phase 7.
- if (FrostSigningEvents.isProposal(innerEvent.kind) && signsAsItsOwnKeyState(database, session)) {
- logger.i("Session ${session.id} is the key state of a ceremony this device finished; signing")
- update(database, session) { it.copy(signApprovedAt = Clock.System.now()) }
- }
+ // question: what the room a ceremony it finished signs with, or a rotation
+ // it completed. For that there is exactly one true statement, and
+ // `vouchesFor` signs nothing else -- any other proposal, a key state
+ // included, is asked about as before. docs/automatic-key-ceremony.md,
+ // Phase 7, and docs/rotate-shares-single-approval.md, Phase 5.
+ // A rotation's key state can arrive before the rotation completes here, and
+ // is asked again then ([resumeAt]).
+ if (FrostSigningEvents.isProposal(innerEvent.kind)) approveIfVouched(database, session)
if (session.stage == FrostSigningStage.FAILED) {
logger.i("Session $sessionId already failed; ignoring kind ${innerEvent.kind}")
@@ -1966,11 +1966,45 @@ object FrostSigningManager {
* [generation], which has just become signable here. A session proposed while
* this device still waited on that generation's certificate stops at the share
* it did not yet have; nothing else would wake it until the next message.
+ *
+ * That includes the generation's own key state, which the coordinator proposes
+ * the moment its certificate verifies -- often before this device's. On arrival
+ * this device could not vouch for it, since the rotation it names was not yet
+ * complete here; now it can, so it asks again rather than leaving the owner a
+ * question the device can answer (docs/rotate-shares-single-approval.md, Phase 5).
*/
suspend fun resumeAt(database: GizaDatabase, localChatRoom: LocalChatRoom, dkgSessionId: String, generation: Int) {
database.frostSigningSessionDao().getOpenSessionsForKey(dkgSessionId)
.filter { (it.generation ?: 0) == generation && it.chatRoomId == localChatRoom.chatRoom.id }
- .forEach { advance(database, localChatRoom, it.id) }
+ .forEach { session ->
+ approveIfVouched(database, session)
+ advance(database, localChatRoom, session.id)
+ }
+ }
+
+ /**
+ * Signs every open key state this user's device can now vouch for and has not
+ * been answered about -- what a build that asked about them left waiting. Run
+ * by the sweep beside the rituals' (docs/rotate-shares-single-approval.md,
+ * Phase 5). Returns how many it approved.
+ */
+ suspend fun resumeVouched(database: GizaDatabase, userPublicKey: HexKey): Int {
+ var approved = 0
+ database.frostSigningSessionDao().getOpenUnansweredSessionsFor(userPublicKey).forEach { session ->
+ if (!approveIfVouched(database, session)) return@forEach
+ val localChatRoom = database.chatRoomDao().findChatRoomById(session.chatRoomId) ?: return@forEach
+ advance(database, localChatRoom, session.id)
+ approved += 1
+ }
+ return approved
+ }
+
+ /** Approves [session] on its owner's behalf when [signsAsItsOwnKeyState] says this device can. */
+ private suspend fun approveIfVouched(database: GizaDatabase, session: FrostSigningSession): Boolean {
+ if (!signsAsItsOwnKeyState(database, session)) return false
+ logger.i("Session ${session.id} is a key state this device can vouch for; signing")
+ update(database, session) { it.copy(signApprovedAt = Clock.System.now()) }
+ return true
}
/**
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt
index 0b1dcab3..60c82131 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt
@@ -13,6 +13,7 @@ import mobi.giza.compose.database.model.types.DkgRitualStage
import mobi.giza.compose.database.model.GroupKeyState
import mobi.giza.compose.database.model.GroupSignedEvent
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+import mobi.giza.compose.database.model.types.ShareRefreshStage
import mobi.giza.compose.database.model.types.ShareStanding
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent
@@ -616,11 +617,13 @@ object GroupKeyStateManager {
* [claimFrom] checks the derivation, the same check [stateFrom] makes;
* 6. claiming the parent the ceremony was run for, or none for a group's own,
* with a certificate that parent's quorum signed -- [claimFrom] again;
- * 7. with no state for that room already signed on this device;
- * 8. and naming no share generation and no member binding. A rotation's key
- * state, or one binding an id to a new identity, says more than the
- * ceremony did -- which shares the group now signs with, who holds an id --
- * and that is its owner's to agree to (docs/frost-share-refresh.md).
+ * 7. with no state for that room already signed on this device -- or, for a
+ * state naming share generation `h`, none signed at `h` or later;
+ * 8. and naming no share generation and no member binding -- **unless** it
+ * is the one key state a rotation this device completed implies
+ * ([vouchesForGeneration], docs/rotate-shares-single-approval.md, Phase 5).
+ * A state binding an id to a new identity is never vouched for: who holds
+ * an id is governance, not arithmetic, and its owner decides it.
*/
suspend fun vouchesFor(
database: GizaDatabase,
@@ -652,13 +655,72 @@ object GroupKeyStateManager {
// 6's parent
if (claim.parentChatRoomId != key.parentChatRoomId) return false
- // 7
val signed = stateAmong(database.groupSignedEventDao().getByKind(GroupKeyStateEvent.KIND), claim.chatRoomId)
- if (signed != null) return false
+ val generation = claim.generation
+ if (generation == null) {
+ // 7, for a ceremony's state
+ if (signed != null) return false
+ // 8: a binding is never vouched for
+ return claim.memberBindings == null
+ }
+ // 7, for a rotation's
+ if (signed != null && (signed.generation ?: 0) >= generation) return false
// 8
- if (claim.generation != null || claim.memberBindings != null) return false
+ return vouchesForGeneration(database, session, key, unsigned, claim, signed)
+ }
+ /**
+ * Whether a key state naming share generation `h` is exactly the one a
+ * rotation this device completed implies (docs/rotate-shares-single-approval.md,
+ * Phase 5). For such a rotation every fact the state names is one this device
+ * holds and has checked against the certificate: the table, the rotation, who
+ * it retired. So there is one true statement, and a person shown it has
+ * nothing to add. Every one of these has to hold:
+ *
+ * - generation `h` is the one this device signs with, and it holds a share
+ * of it -- a device withheld from `h` neither signs at `h` nor vouches for
+ * a table it did not help make;
+ * - the rotation that made `h` is the one the state names, and it is
+ * complete here;
+ * - the state's public-share hash is this device's table at `h`;
+ * - the ids it retires are the ids this device's roster at `h` retires;
+ * - it binds no id to a new identity;
+ * - the signing session is at `h`;
+ * - its path and parent are the ones the room's signed state already names,
+ * when there is one -- [proposeGeneration] copies them from it.
+ */
+ private suspend fun vouchesForGeneration(
+ database: GizaDatabase,
+ session: FrostSigningSession,
+ key: DkgSession,
+ unsigned: Event,
+ claim: GroupKeyState,
+ signed: GroupKeyState?,
+ ): Boolean {
+ val generation = claim.generation ?: return false
+ val tags = GroupKeyStateEvent.parseShareGeneration(unsigned.tags).getOrNull() ?: return false
+ if (tags.bindings.isNotEmpty() || claim.memberBindings != null) return false
+ if ((session.generation ?: 0) != generation) return false
+
+ val active = ShareGenerations.active(database, key)
+ if (active.generation != generation || active.secretShare == null) return false
+ val publicShares = active.publicShares ?: return false
+ if (ShareGenerations.publicSharesHash(publicShares) != claim.publicSharesHash) return false
+ if (tags.retiredIds.sorted() != active.roster.filter { it.standing == ShareStanding.RETIRED }.map { it.participantId }.sorted()) return false
+
+ val refreshId = tags.refreshId ?: return false
+ val row = database.keyShareDao().getGeneration(key.id, generation) ?: return false
+ if (row.refreshSessionId != refreshId) return false
+ val refresh = database.shareRefreshDao().getSessionById(refreshId) ?: return false
+ if (refresh.stage != ShareRefreshStage.COMPLETE || refresh.dkgSessionId != key.id || refresh.baseGeneration + 1 != generation) return false
+
+ if (signed != null) {
+ if (claim.derivationPath != signed.derivationPath) return false
+ if (claim.parentChatRoomId != signed.parentChatRoomId) return false
+ val certificate = { json: String? -> json?.let { Event.fromJsonOrNull(it)?.id } }
+ if (certificate(claim.birthCertificateJson) != certificate(signed.birthCertificateJson)) return false
+ }
return true
}
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 ff9283e8..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,13 +197,7 @@ object MarmotGroupCreation {
logger.w("$groupId created without ${notAdded.size} member(s): $notAdded")
}
- // The creating device learns who administers the room from nowhere else:
- // `adminAt` is otherwise written only when a commit arrives. Read off the
- // group, which names the creator whether or not [adminPublicKeys] did.
- // Swallowed on failure, like `adopt` above: what a missing flag costs is a
- // label, and the room is made and usable.
- runCatching { MarmotInboundManager.reconcileAdmins(database, groupId, group) }
- .onFailure { logger.e("Created $groupId but could not flag its admins", it) }
+ flagAdmins(database, groupId)
return Outcome.Created(
room = chatRepository.getChatRoomByIdentifier(groupId) ?: localChatRoom,
@@ -201,6 +205,186 @@ 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: 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.
+ *
+ * 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.
+ *
+ * Swallowed on failure, like `adopt` above it: the room is made and usable,
+ * and what a missing flag costs is a label rather than anything being wrong.
+ */
+ private suspend fun flagAdmins(database: GizaDatabase, groupId: String) {
+ runCatching {
+ 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)
+ }
+ }
+
/**
* Every peer's published key package, or null where there is none.
*
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 acdeb629..6360103e 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt
@@ -142,7 +142,6 @@ object MarmotInboundManager {
priorAdmins: Set? = null,
) {
logger.d("processGroupMembershipChanges")
- val adminPublicKeys = mlsGroup.currentAdminIdentities()
val commitedGroupMembers = Participant.fromMlsGroup(
mlsGroup = mlsGroup,
@@ -159,20 +158,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 adminFlags = adminFlagChanges(localChatRoom.localParticipants.map { it.participant }, adminPublicKeys)
- logger.d("adminFlags: $adminFlags")
// Placeholder profiles for new participants...
newParticipants.forEach { newParticipant ->
@@ -237,9 +229,9 @@ object MarmotInboundManager {
)
}
// Handle membership changes...
- database.participantDao().upsert(adminFlags)
database.participantDao().delete(excludedParticipants)
database.participantDao().upsert(newParticipants)
+ AdminFlags.reconcile(database, localChatRoom.chatRoom.id, mlsGroup)
val userPublicKey = localChatRoom.chatRoom.userPublicKey
val disbanded = mlsGroup.currentGroupState().isDisbanded
@@ -265,6 +257,7 @@ object MarmotInboundManager {
// Phase 1 could have wrong. Only for accounts still in the tree: one that
// left took its admin rights with it, and "left the group" says so already.
if (priorAdmins != null && !disbanded && !removedUs) {
+ val adminPublicKeys = mlsGroup.currentAdminIdentities()
val members = committedGroupMembersPublicKeys.toSet()
(priorAdmins - adminPublicKeys).filter { it in members }.sorted().forEach { demoted ->
announceLine(database, localChatRoom, ChatMessage.TYPE_ADMIN_REMOVED,
@@ -287,45 +280,6 @@ object MarmotInboundManager {
}
}
- /**
- * The participant rows whose `adminAt` disagrees with [adminPublicKeys], each
- * corrected: flagged now if the group names them, cleared if it does not. Rows
- * that already agree are left out, so a flag keeps the moment it was first set.
- */
- internal fun adminFlagChanges(participants: List, adminPublicKeys: Set): List {
- val now = Clock.System.now()
- return participants.mapNotNull { participant ->
- val named = participant.participantPublicKey in adminPublicKeys
- when {
- named && participant.adminAt == null -> participant.copy(adminAt = now)
- !named && participant.adminAt != null -> participant.copy(adminAt = null)
- else -> null
- }
- }
- }
-
- /**
- * Brings the room's `adminAt` flags into line with [mlsGroup]'s admin set, and
- * says nothing about it.
- *
- * The flag is a cache of the group's state, and until this existed it was written
- * only when a commit arrived -- so on the device that created a convenient room or
- * a direct message, nobody was an admin until somebody else committed. Run where
- * rooms are made and when a room is opened, it makes the cache true before
- * anything reads it as news. Only flags move: membership is
- * [processGroupMembershipChanges]'s, which also captions what it changes. Returns
- * whether any row changed. See docs/member-admin-promotion.md, Phase 1.
- */
- suspend fun reconcileAdmins(database: GizaDatabase, chatRoomId: String, mlsGroup: MlsGroup): Boolean {
- val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return false
- val changes = adminFlagChanges(
- participants = room.localParticipants.map { it.participant },
- adminPublicKeys = mlsGroup.currentAdminIdentities(),
- )
- if (changes.isNotEmpty()) database.participantDao().upsert(changes)
- return changes.isNotEmpty()
- }
-
private suspend fun memberName(database: GizaDatabase, publicKey: HexKey): String =
database.profileDao().getProfileByPublicKey(publicKey)?.humanReadableNameOrPubkey()
?: publicKey.take(8)
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 2cc97bd7..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
/**
@@ -60,8 +62,12 @@ import mobi.giza.compose.nostr.frost.ShareRefreshEvents
* - **Every recipient takes part** (D2). A certificate needs them all; anyone
* who cannot is withheld, and repaired later.
*
- * Nothing of this device's own goes out without its owner's approval, at two
- * gates ([ShareRefreshApprovalStep]). [pendingApproval] mirrors them.
+ * Nothing of this device's own goes out until its owner agrees to take part,
+ * with the withheld list the proposal names ([ShareRefreshApprovalStep.DEAL]).
+ * That is the only gate, and [pendingApproval] mirrors it. Everything after it
+ * -- dealing, checking the combined result, storing the new share, confirming --
+ * the device does itself: the check is the device's, and a person tapping
+ * "store" added nothing to it (docs/rotate-shares-single-approval.md).
*/
object ShareRefreshManager {
private val logger = Logger.withTag("ShareRefreshManager")
@@ -107,13 +113,81 @@ object ShareRefreshManager {
// ---- proposing ------------------------------------------------------------------------------------------------
+ /**
+ * Who a refresh of [key] from [shares] would deal to and who it would leave
+ * out, with [withheld] asked for: every live participant not in it is a
+ * recipient, and every stale participant is withheld again, as what they
+ * were -- a refresh does not bring anybody back, a repair does. [refusal] is
+ * why it cannot run, or null. One function for [proposeRefresh] and
+ * [preview], so the dialog shows exactly what the proposal will say.
+ */
+ private fun plan(key: DkgSession, shares: ShareGenerations.Shares, userPublicKey: HexKey, withheld: Map): Plan {
+ val recipients = shares.roster
+ .filter { it.standing == ShareStanding.LIVE && it.participantId !in withheld }
+ .map { it.participantId }
+ val allWithheld = withheld + shares.roster
+ .filter { it.standing == ShareStanding.STALE && it.participantId !in withheld }
+ .associate { it.participantId to ShareStanding.STALE }
+ val myId = shares.signerIds[userPublicKey]
+ val refusal = when {
+ shares.secretShare == null -> "this device holds no share of generation ${shares.generation}"
+ myId == null -> "this device is not a signer of generation ${shares.generation}"
+ else -> refusal(key, shares, recipients, allWithheld)
+ ?: "the proposer has to be a recipient".takeIf { myId !in recipients }
+ }
+ return Plan(recipients, allWithheld, refusal)
+ }
+
+ private data class Plan(val recipients: List, val withheld: Map, val refusal: String?)
+
+ /** A refresh as it would be proposed, by member rather than by id. */
+ data class Preview(
+ val takingPart: List,
+ val withheld: Map,
+ /** Why it cannot be proposed, or null. */
+ val refusal: String?,
+ )
+
+ /**
+ * What [proposeRefresh] would open from this device, without opening it: who
+ * takes part and who is left out, stale members included, and whether it
+ * would be refused. The proposer's dialog shows this, and pressing it is the
+ * proposer's agreement to take part (docs/rotate-shares-single-approval.md,
+ * Phase 4). [without] is a member to withhold for good, as after a removal.
+ */
+ suspend fun preview(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, without: HexKey? = null): Preview? {
+ val key = FrostSigningManager.completedKey(database, localChatRoom.chatRoom.id) ?: return null
+ if (!isKeysRoom(database, localChatRoom, key)) return null
+ val shares = ShareGenerations.active(database, key)
+ val withheld = without?.let { member ->
+ val id = shares.signerIds[member] ?: return Preview(emptyList(), emptyMap(), "they hold no share of the group's key")
+ mapOf(id to ShareStanding.RETIRED)
+ } ?: emptyMap()
+ val plan = plan(key, shares, userPublicKey, withheld)
+ val memberOf = shares.roster.associate { it.participantId to it.memberPublicKey }
+ return Preview(
+ takingPart = plan.recipients.mapNotNull { memberOf[it] },
+ withheld = plan.withheld.mapNotNull { (id, standing) -> memberOf[id]?.let { it to standing } }.toMap(),
+ refusal = plan.refusal ?: rotationHold(database, localChatRoom, key)?.reason,
+ )
+ }
+
/**
* Opens a refresh of [key], making this device the coordinator. Every live
- * participant not in [withheld] is a recipient.
+ * participant not in [withheld] is a recipient, and every stale one is
+ * withheld again ([plan]).
*
- * The proposer is auto-approved for nothing: proposing a refresh is not
- * agreeing to withhold whomever the form defaulted to, so it is asked at both
- * gates like everyone else.
+ * **Proposing is the proposer's agreement to take part**: the proposer's
+ * 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. 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,
@@ -128,21 +202,11 @@ 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)
- requireNotNull(shares.secretShare) { "This device holds no share of generation ${shares.generation}" }
- val myId = requireNotNull(shares.signerIds[userPublicKey]) { "This device is not a signer of generation ${shares.generation}" }
-
- val recipients = shares.roster
- .filter { it.standing == ShareStanding.LIVE && it.participantId !in withheld }
- .map { it.participantId }
- // Stale participants are withheld again, as what they were: a refresh does
- // not bring anybody back. That is a repair.
- val allWithheld = withheld + shares.roster
- .filter { it.standing == ShareStanding.STALE && it.participantId !in withheld }
- .associate { it.participantId to ShareStanding.STALE }
- refusal(key, shares, recipients, allWithheld)?.let { throw IllegalStateException("Cannot refresh: $it") }
- require(myId in recipients) { "The proposer has to be a recipient" }
+ val (recipients, allWithheld, refused) = plan(key, shares, userPublicKey, withheld)
+ refused?.let { throw IllegalStateException("Cannot refresh: $it") }
val session = ShareRefreshSession(
id = RandomInstance.bytes(32).toHex(),
@@ -155,6 +219,7 @@ object ShareRefreshManager {
withheld = ShareRefreshSession.formatWithheld(allWithheld),
round1Random = RandomInstance.bytes(32).toHex(),
auxRandom = RandomInstance.bytes(32).toHex(),
+ dealApprovedAt = Clock.System.now(),
)
database.shareRefreshDao().upsert(session)
announce(database, session, ChatMessage.TYPE_SHARE_REFRESH_STARTED, startedLine(session, shares), userPublicKey)
@@ -203,12 +268,109 @@ 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 {
it.stage != ShareRefreshStage.COMPLETE && it.stage != ShareRefreshStage.FAILED
}
+ // ---- resuming ------------------------------------------------------------------------------------------------
+
+ /**
+ * Moves every running refresh of this user's as far as its stored messages
+ * allow. What a tap on "Store your new share" used to do, for refreshes that
+ * already have everything they need and will receive nothing more -- one an
+ * older build left waiting on that tap, or one the app died in between
+ * storing a message and acting on it (docs/rotate-shares-single-approval.md,
+ * Phase 3).
+ *
+ * Not only the approved ones: a coordinator waiting on everyone's round 1 and
+ * a withheld device waiting on the certificate may also hold what they need,
+ * and [advance] stops at the one gate for anyone who has not taken part.
+ * Safe to run as often as the caller likes: [advance] repeats no work.
+ */
+ suspend fun resumeRunning(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray): Int {
+ if (!ExperimentalFeatures.shareRefresh) return 0
+ val running = database.shareRefreshDao().getRunningSessionsFor(userPublicKey)
+ running.forEach { session ->
+ val localChatRoom = database.chatRoomDao().findChatRoomById(session.chatRoomId)
+ if (localChatRoom == null) {
+ logger.w("Refresh ${session.id} is in ${session.chatRoomId}, which is gone; not resuming it")
+ return@forEach
+ }
+ advance(database, localChatRoom, session.id, nostrPrivateKey)
+ }
+ if (running.isNotEmpty()) logger.i("Resumed ${running.size} running refresh(es)")
+ return running.size
+ }
+
// ---- inbound ---------------------------------------------------------------------------------------------------
/**
@@ -340,10 +502,14 @@ object ShareRefreshManager {
logger.w("Refresh ${session.id}: kind ${innerEvent.kind} from ${innerEvent.pubKey.take(8)}, who is not a recipient; ignoring")
return true
}
+ // Stored once, on first arrival: its time is when the rotation last
+ // moved, and a relay repeating itself is not progress ([progress]).
val known = database.shareRefreshDao().getMessage(session.id, innerEvent.kind, innerEvent.pubKey) != null
- database.shareRefreshDao().upsert(ShareRefreshMessage(session.id, innerEvent.pubKey, innerEvent.kind, innerEvent.content))
- if (!known && innerEvent.pubKey != session.userPublicKey) {
- announce(database, session, stepType(innerEvent.kind), stepLine(innerEvent.kind), innerEvent.pubKey)
+ if (!known) {
+ database.shareRefreshDao().upsert(ShareRefreshMessage(session.id, innerEvent.pubKey, innerEvent.kind, innerEvent.content))
+ if (innerEvent.pubKey != session.userPublicKey) {
+ announce(database, session, stepType(innerEvent.kind), stepLine(innerEvent.kind), innerEvent.pubKey)
+ }
}
}
@@ -388,6 +554,8 @@ object ShareRefreshManager {
val hostSecretKey = ChillDkgRitualManager.deriveHostSecretKey(nostrPrivateKey)
if (isRecipient) {
+ // The one gate: taking part, with these members withheld. Every
+ // step after it follows from that decision and asks nothing more.
if (session.dealApprovedAt == null) {
announceApprovalNeeded(database, session, ShareRefreshApprovalStep.DEAL)
return
@@ -412,10 +580,10 @@ object ShareRefreshManager {
session = moveTo(database, session, ShareRefreshStage.COLLECTING_ROUND_2)
if (isRecipient && ownMessage(database, session, ShareRefreshEvents.ROUND_2) == null) {
- if (session.confirmApprovedAt == null) {
- announceApprovalNeeded(database, session, ShareRefreshApprovalStep.CONFIRM)
- return
- }
+ // No gate here. participantStep2 is the check that stops a
+ // coordinator substituting a table nobody dealt, and it runs
+ // whoever is looking; confirmAndStore is the one-confirmation
+ // rule, and it holds whoever is looking.
val secretShare = base.secretShare ?: throw IllegalStateException("this device holds no share of generation ${base.generation}")
val step2 = FrostRefresh.participantStep2(hostSecretKey, secretShare, params, myId.toUInt(), ByteVector(cmsg1.hexToByteArray()), ByteVector32(session.auxRandom))
step2.fault.raiseIfFaulty("round 2", base)
@@ -583,8 +751,11 @@ object ShareRefreshManager {
/**
* What this device's owner is being asked for, or null. **Must mirror the
- * gates in [advance] exactly**: drift makes the screen offer an approval that
+ * gate in [advance] exactly**: drift makes the screen offer an approval that
* does nothing, or none while the refresh sits still.
+ *
+ * Only ever [ShareRefreshApprovalStep.DEAL]. [ShareRefreshApprovalStep.CONFIRM]
+ * was a second gate until docs/rotate-shares-single-approval.md.
*/
suspend fun pendingApproval(database: GizaDatabase, session: ShareRefreshSession): ShareRefreshApprovalStep? {
if (session.stage == ShareRefreshStage.COMPLETE || session.stage == ShareRefreshStage.FAILED) return null
@@ -592,11 +763,44 @@ object ShareRefreshManager {
val base = ShareGenerations.at(database, key, session.baseGeneration) ?: return null
val myId = base.roster.firstOrNull { it.memberPublicKey == session.userPublicKey }?.participantId ?: return null
if (myId !in session.recipientIdList()) return null
- if (session.dealApprovedAt == null) return ShareRefreshApprovalStep.DEAL
- if (session.coordinatorRound1 != null && session.confirmApprovedAt == null &&
- ownMessage(database, session, ShareRefreshEvents.ROUND_2) == null
- ) return ShareRefreshApprovalStep.CONFIRM
- return null
+ return if (session.dealApprovedAt == null) ShareRefreshApprovalStep.DEAL else null
+ }
+
+ /**
+ * Where a running refresh stands, as the Shares section shows it once its one
+ * approval is given: which step, who it waits on, since when, and whether
+ * this device may abandon it (docs/rotate-shares-single-approval.md, Phase 6).
+ * Null once it has finished.
+ *
+ * With nothing left to approve, this is the only place a member who took part
+ * can see a rotation stall, and the only way they can end it.
+ */
+ suspend fun progress(database: GizaDatabase, session: ShareRefreshSession): Progress? {
+ if (session.stage == ShareRefreshStage.COMPLETE || session.stage == ShareRefreshStage.FAILED) return null
+ val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return null
+ val base = ShareGenerations.at(database, key, session.baseGeneration) ?: return null
+ val memberOf = base.roster.associate { it.participantId to it.memberPublicKey }
+ val recipients = session.recipientIdList()
+ val messages = database.shareRefreshDao().getMessagesForSession(session.id)
+ fun missing(kind: Kind) = recipients
+ .filter { id -> messages.none { it.kind == kind && it.participantPublicKey == memberOf[id] } }
+ .mapNotNull { memberOf[it] }
+ val (step, waitingOn) = when {
+ session.coordinatorRound1 == null -> Progress.Step.DEALING to missing(ShareRefreshEvents.ROUND_1).ifEmpty { listOf(session.coordinatorPublicKey) }
+ else -> Progress.Step.STORING to missing(ShareRefreshEvents.ROUND_2).ifEmpty { listOf(session.coordinatorPublicKey) }
+ }
+ val myId = memberOf.entries.firstOrNull { it.value == session.userPublicKey }?.key
+ return Progress(
+ step = step,
+ waitingOn = waitingOn,
+ since = messages.maxOfOrNull { it.createdAt } ?: session.createdAt,
+ canAbandon = myId != null && myId in recipients,
+ )
+ }
+
+ /** See [progress]. */
+ data class Progress(val step: Step, val waitingOn: List, val since: Instant, val canAbandon: Boolean) {
+ enum class Step { DEALING, STORING }
}
/** Approves the step this device's owner is being asked for, and moves on. */
@@ -605,8 +809,8 @@ object ShareRefreshManager {
val now = Clock.System.now()
when (pendingApproval(database, session)) {
ShareRefreshApprovalStep.DEAL -> update(database, session) { it.copy(dealApprovedAt = now) }
- ShareRefreshApprovalStep.CONFIRM -> update(database, session) { it.copy(confirmApprovedAt = now) }
- null -> return
+ // Never pending any more; kept so the `when` stays over the whole enum.
+ ShareRefreshApprovalStep.CONFIRM, null -> return
}
advance(database, localChatRoom, sessionId, nostrPrivateKey)
}
@@ -649,9 +853,9 @@ object ShareRefreshManager {
/** Queues this device's own message and records it, so the coordinator's own is in its sums. */
private suspend fun publishOwn(database: GizaDatabase, localChatRoom: LocalChatRoom, session: ShareRefreshSession, kind: Kind, content: String) {
broadcast(database, localChatRoom, session, kind, content, ShareRefreshEvents.assembleTags(session.id))
- val known = ownMessage(database, session, kind) != null
+ if (ownMessage(database, session, kind) != null) return
database.shareRefreshDao().upsert(ShareRefreshMessage(session.id, session.userPublicKey, kind, content))
- if (!known) announce(database, session, stepType(kind), stepLine(kind), session.userPublicKey)
+ announce(database, session, stepType(kind), stepLine(kind), session.userPublicKey)
}
/** One of this device's messages, as an inner event of the key's Marmot room. */
@@ -707,6 +911,7 @@ object ShareRefreshManager {
update(database, session) { it.copy(approvalRequestedThrough = step) }
val line = when (step) {
ShareRefreshApprovalStep.DEAL -> "Your approval is needed to take part in rotating the group's shares."
+ // Unreachable: CONFIRM is no longer asked. Kept because the enum keeps the value.
ShareRefreshApprovalStep.CONFIRM -> "Your approval is needed to store your new share."
}
announce(database, session, ChatMessage.TYPE_SHARE_REFRESH_APPROVAL_NEEDED, line, session.userPublicKey)
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 577505da..2fff1ef1 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,12 +19,13 @@ 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.GovernanceStatus
import mobi.giza.compose.ui.view.state.SharesSummary
+import mobi.giza.compose.ui.view.state.RotationPreview
interface ChatRepository {
suspend fun observeChatRoomListByPublicKey(publicKey: String): Flow>
@@ -197,29 +200,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
@@ -314,6 +349,21 @@ interface ChatRepository {
*/
suspend fun stepDownAndLeave(localChatRoom: LocalChatRoom, heir: 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
@@ -330,12 +380,34 @@ 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?
+ /**
+ * Who a rotation proposed from this device would take part and who it would
+ * leave out -- [without] for good, as after a removal -- or null when the room
+ * has no key this device can rotate. Nothing is sent.
+ */
+ suspend fun rotationPreview(localChatRoom: LocalChatRoom, without: HexKey? = null): RotationPreview?
+
/** 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?
@@ -485,19 +557,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,
@@ -546,16 +626,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/repository/NostrRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/NostrRepository.kt
index c46b7309..2b235e02 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/NostrRepository.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/NostrRepository.kt
@@ -58,10 +58,12 @@ interface NostrRepository {
suspend fun reopenInbox(activeKeyPair: KeyPair): Int
/**
- * Moves every key ceremony [activeKeyPair] has joined as far as the messages
- * already stored allow. Run once per activation, after [reopenInbox], since what
- * that opens may be what a ceremony was waiting for. Returns how many it looked
- * at. See docs/automatic-key-ceremony.md, Phase 3.
+ * Moves every key ceremony [activeKeyPair] has joined, and every share rotation
+ * it is in, as far as the messages already stored allow. Run once per
+ * activation, after [reopenInbox], since what that opens may be what one was
+ * waiting for. Returns how many it looked at. See
+ * docs/automatic-key-ceremony.md and docs/rotate-shares-single-approval.md,
+ * Phase 3 of each.
*/
suspend fun resumeRunningCeremonies(activeKeyPair: KeyPair): Int
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 4241f545..50e12847 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
@@ -88,10 +91,21 @@ import mobi.giza.compose.resources.stepping_down_to_leave
import mobi.giza.compose.resources.require_signatures_sent
import mobi.giza.compose.resources.change_proposed
import mobi.giza.compose.ui.view.state.GovernanceStatus
-import mobi.giza.compose.resources.admin_badge
import mobi.giza.compose.resources.holds_a_share
import mobi.giza.compose.ui.view.state.AdminLeave
import mobi.giza.compose.ui.view.state.MemberAction
+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
@@ -115,7 +129,6 @@ import mobi.giza.compose.resources.leave_group
import mobi.giza.compose.resources.remove_from_group
import mobi.giza.compose.resources.shares_action_sent
import mobi.giza.compose.resources.pending_repair_help
-import mobi.giza.compose.resources.pending_rotation_confirm
import mobi.giza.compose.resources.pending_rotation_deal
import mobi.giza.compose.resources.abandon
import mobi.giza.compose.resources.approve
@@ -133,8 +146,39 @@ 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.rotation_cannot_start
+import mobi.giza.compose.resources.rotation_left_out_for_good
+import mobi.giza.compose.resources.rotation_left_out_until_brought_back
+import mobi.giza.compose.resources.rotation_proposing_is_taking_part
+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 mobi.giza.compose.resources.waiting_on_s_since_s
+import mobi.giza.compose.resources.rotation_ended
+import mobi.giza.compose.resources.abandon_rotation_body
+import mobi.giza.compose.resources.abandon_rotation_question
+import mobi.giza.compose.resources.abandon_rotation
+import mobi.giza.compose.resources.rotation_abandon_explainer
+import mobi.giza.compose.resources.rotation_step_signing
+import mobi.giza.compose.resources.rotation_step_storing
+import mobi.giza.compose.resources.rotation_step_dealing
+import mobi.giza.compose.resources.rotation_running
+import mobi.giza.compose.resources.pending_rotation_commits
+import mobi.giza.compose.resources.rotation_withheld_for_good
+import mobi.giza.compose.resources.rotation_withheld_until_back
+import mobi.giza.compose.resources.pending_rotation_without
+import mobi.giza.compose.resources.pending_rotation_everyone
import androidx.compose.material3.AlertDialog
import mobi.giza.compose.resources.disband_group
import mobi.giza.compose.resources.disband_group_explainer
@@ -199,10 +243,16 @@ fun ChatRoomDetailScreen(
val steppingDownToLeave = stringResource(Res.string.stepping_down_to_leave)
val requireSignaturesSent = stringResource(Res.string.require_signatures_sent)
val changeProposed = stringResource(Res.string.change_proposed)
- val adminLabel = stringResource(Res.string.admin_badge)
+ val adminLabel = stringResource(Res.string.admin)
val shareLabel = stringResource(Res.string.holds_a_share)
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
@@ -211,9 +261,19 @@ fun ChatRoomDetailScreen(
AlertDialog(
onDismissRequest = { chatRoomDetailViewModel.dismissRotationOffer() },
title = { Text(stringResource(Res.string.rotate_shares_without_title)) },
- text = { Text(stringResource(Res.string.rotate_shares_without_body)) },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) {
+ Text(stringResource(Res.string.rotate_shares_without_body))
+ // The removed member is named by the title; the others it would leave out are not.
+ offer.preview?.let { RotationLeftOut(it.copy(forGood = emptyList())) }
+ offer.preview?.refusal?.let { Text(stringResource(Res.string.rotation_cannot_start, it), color = MaterialTheme.colorScheme.error) }
+ }
+ },
confirmButton = {
- TextButton(onClick = { chatRoomDetailViewModel.rotateSharesWithout(offer) { failure -> notify(failure ?: rotationRequested) } }) {
+ TextButton(
+ enabled = offer.preview?.refusal == null,
+ onClick = { chatRoomDetailViewModel.rotateSharesWithout(offer) { failure -> notify(failure ?: rotationRequested) } }
+ ) {
Text(stringResource(Res.string.rotate_shares))
}
},
@@ -225,6 +285,68 @@ fun ChatRoomDetailScreen(
)
}
+ var abandoningRotation by remember { mutableStateOf(null) }
+ abandoningRotation?.let { sessionId ->
+ AlertDialog(
+ onDismissRequest = { abandoningRotation = null },
+ title = { Text(stringResource(Res.string.abandon_rotation_question)) },
+ text = { Text(stringResource(Res.string.abandon_rotation_body)) },
+ confirmButton = {
+ TextButton(
+ onClick = {
+ abandoningRotation = null
+ (chatRoomDetailViewModel.chatRoomDetailUIState as? ChatRoomDetailUIState.Loaded)?.let { loaded ->
+ chatRoomDetailViewModel.abandonRotation(loaded.localChatRoom, sessionId) { failure -> notify(failure ?: sharesActionSent) }
+ }
+ },
+ colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error)
+ ) {
+ Text(stringResource(Res.string.abandon_rotation))
+ }
+ },
+ dismissButton = {
+ TextButton(onClick = { abandoningRotation = null }) {
+ Text(stringResource(Res.string.not_now))
+ }
+ },
+ )
+ }
+
+ // The proposer's one approval: the rotation as it will be proposed, with
+ // everyone it leaves out named (docs/rotate-shares-single-approval.md, Phase 4).
+ chatRoomDetailViewModel.rotationProposal?.let { proposal ->
+ AlertDialog(
+ onDismissRequest = { chatRoomDetailViewModel.dismissRotationProposal() },
+ 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
+ if (refusal != null) {
+ Text(stringResource(Res.string.rotation_cannot_start, refusal), color = MaterialTheme.colorScheme.error)
+ } else {
+ Text(stringResource(Res.string.rotation_proposing_is_taking_part))
+ }
+ }
+ },
+ confirmButton = {
+ TextButton(
+ enabled = proposal.preview.refusal == null,
+ onClick = { chatRoomDetailViewModel.rotateShares(proposal) { failure -> notify(failure ?: rotationRequested) } }
+ ) {
+ Text(stringResource(Res.string.rotate_shares))
+ }
+ },
+ dismissButton = {
+ TextButton(onClick = { chatRoomDetailViewModel.dismissRotationProposal() }) {
+ Text(stringResource(Res.string.not_now))
+ }
+ },
+ )
+ }
+
ScreenStateTransition(chatRoomDetailViewModel.chatRoomDetailUIState) { uiState ->
when (val chatRoomDetailUIState = uiState) {
is ChatRoomDetailUIState.Error -> {
@@ -425,6 +547,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(
@@ -456,6 +666,28 @@ fun ChatRoomDetailScreen(
style = MaterialTheme.typography.bodyMedium
)
}
+ // Above the members: with nothing left to approve, this is
+ // where a member who took part sees a rotation stall, and the
+ // only way out of one (docs/rotate-shares-single-approval.md).
+ shares.running?.let { running ->
+ item(key = "rotation-running") {
+ RotationRunningCard(
+ running = running,
+ onAbandon = { abandoningRotation = running.sessionId },
+ )
+ }
+ }
+ if (shares.running == null) {
+ shares.lastFailure?.let { reason ->
+ item(key = "rotation-ended") {
+ Text(
+ text = stringResource(Res.string.rotation_ended, reason),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ }
+ }
items(items = shares.members, key = { member -> "share-${member.publicKey}" }) { member ->
ListItem(
headlineContent = {
@@ -481,16 +713,23 @@ fun ChatRoomDetailScreen(
stringResource(
when (approval.kind) {
SharesSummary.PendingApproval.Kind.REFRESH_DEAL -> Res.string.pending_rotation_deal
- SharesSummary.PendingApproval.Kind.REFRESH_CONFIRM -> Res.string.pending_rotation_confirm
SharesSummary.PendingApproval.Kind.REPAIR_HELP -> Res.string.pending_repair_help
}
)
)
},
+ // Taking part is agreeing to who is left out, and it is the
+ // only thing this rotation will ask: so the row says both.
+ supportingContent = if (approval.kind == SharesSummary.PendingApproval.Kind.REFRESH_DEAL) {
+ { RotationTakingPart(approval.withheld) }
+ } else {
+ null
+ },
trailingContent = {
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)
@@ -501,6 +740,7 @@ fun ChatRoomDetailScreen(
}
}
FilledTonalButton(
+ enabled = !chatRoomDetailViewModel.isActionPending.value,
onClick = {
chatRoomDetailViewModel.approveShares(chatRoomDetailUIState.localChatRoom, approval) { failure ->
notify(failure ?: sharesActionSent)
@@ -513,7 +753,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(
@@ -521,19 +763,65 @@ 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.rotateShares(chatRoomDetailUIState.localChatRoom) { failure ->
- notify(failure ?: rotationRequested)
+ chatRoomDetailViewModel.previewRotation(chatRoomDetailUIState.localChatRoom) {
+ notify(noKeyToRotate)
}
}
) {
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)
@@ -787,11 +1075,17 @@ fun ChatRoomDetailScreen(
chatRoomDetailViewModel.removeMember(
localChatRoom = chatRoomDetailUIState.localChatRoom,
memberPublicKey = memberPublicKey,
- ) { failure ->
+ ) { failure, rotationHeld ->
// In a governed room the removal is a proposal
// the group still has to sign.
val governed = chatRoomDetailUIState.governance is GovernanceStatus.Governed
- notify(failure ?: if (governed) changeProposed else removalRequested)
+ notify(
+ failure ?: when {
+ governed -> changeProposed
+ rotationHeld -> rotationHeldAfterRemoval
+ else -> removalRequested
+ }
+ )
}
} else {
confirmingAdminChange = action to memberPublicKey
@@ -811,11 +1105,13 @@ fun ChatRoomDetailScreen(
},
supportingContent = {
// Two facts, shown apart: when they disagree, a share is
- // still owed or still to be rotated away.
- // docs/member-admin-promotion.md, D2.
+ // still owed or still to be rotated away
+ // (docs/member-admin-promotion.md, D2). Admin from the
+ // group's policy, through `AdminFlags` --
+ // docs/robust-group-admins.md.
val memberPublicKey = localParticipant.participant.participantPublicKey
val roles = listOfNotNull(
- adminLabel.takeIf { memberPublicKey in chatRoomDetailUIState.adminPublicKeys },
+ adminLabel.takeIf { localParticipant.participant.adminAt != null },
shareLabel.takeIf { memberPublicKey in chatRoomDetailUIState.shareHolders },
)
Column {
@@ -1451,4 +1747,139 @@ private fun ChatRoomMessagingScreenPreview() {
)
}
}
-}
\ No newline at end of file
+}
+
+/** Who a rotation leaves out, a line per standing, nothing when it leaves out nobody. */
+@Composable
+private fun RotationLeftOut(preview: RotationPreview) {
+ if (preview.untilBroughtBack.isNotEmpty()) {
+ Text(stringResource(Res.string.rotation_left_out_until_brought_back, preview.untilBroughtBack.joinToString(", ")))
+ }
+ if (preview.forGood.isNotEmpty()) {
+ Text(stringResource(Res.string.rotation_left_out_for_good, preview.forGood.joinToString(", ")))
+ }
+}
+
+/** What taking part in a rotation agrees to: who it leaves out, and that nothing more will be asked. */
+@Composable
+private fun RotationTakingPart(withheld: List) {
+ val leftOut = withheld.map { entry ->
+ stringResource(
+ if (entry.standing == ShareStanding.RETIRED) Res.string.rotation_withheld_for_good else Res.string.rotation_withheld_until_back,
+ entry.name
+ )
+ }
+ Column {
+ Text(
+ if (leftOut.isEmpty()) stringResource(Res.string.pending_rotation_everyone)
+ else stringResource(Res.string.pending_rotation_without, leftOut.joinToString(", "))
+ )
+ Text(stringResource(Res.string.pending_rotation_commits))
+ }
+}
+
+/**
+ * A rotation past its one approval: the step it is on, who it waits on and since
+ * when, and abandon for a member taking part. Shown whether or not it has
+ * stalled -- unlike a ceremony, a rotation has no screen of its own to show it.
+ */
+@Composable
+private fun RotationRunningCard(running: SharesSummary.Running, onAbandon: () -> Unit) {
+ Card(
+ modifier = Modifier.fillMaxWidth(),
+ colors = CardDefaults.cardColors(
+ containerColor = MaterialTheme.colorScheme.secondaryContainer,
+ contentColor = MaterialTheme.colorScheme.onSecondaryContainer
+ )
+ ) {
+ Column(
+ modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.containerPadding),
+ verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)
+ ) {
+ Text(stringResource(Res.string.rotation_running), style = MaterialTheme.typography.titleSmall)
+ Text(
+ stringResource(
+ when (running.step) {
+ SharesSummary.Running.Step.DEALING -> Res.string.rotation_step_dealing
+ SharesSummary.Running.Step.STORING -> Res.string.rotation_step_storing
+ SharesSummary.Running.Step.SIGNING -> Res.string.rotation_step_signing
+ }
+ ),
+ style = MaterialTheme.typography.bodyMedium
+ )
+ if (running.waitingOn.isNotEmpty()) {
+ Text(
+ stringResource(Res.string.waiting_on_s_since_s, running.waitingOn.joinToString(", "), running.since.toFormattedTimeAndDateString()),
+ style = MaterialTheme.typography.bodyMedium
+ )
+ }
+ if (running.canAbandon) {
+ Text(stringResource(Res.string.rotation_abandon_explainer), style = MaterialTheme.typography.bodyMedium)
+ TextButton(
+ onClick = onAbandon,
+ modifier = Modifier.align(Alignment.End),
+ colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error)
+ ) {
+ Text(stringResource(Res.string.abandon_rotation))
+ }
+ }
+ }
+ }
+}
+
+/**
+ * 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 35d4ed09..1ac8795e 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
@@ -17,8 +17,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.ExperimentalFeatures
@@ -33,6 +38,7 @@ import mobi.giza.compose.ui.composable.navigation.routes.Route
import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState
import mobi.giza.compose.ui.view.state.GovernanceStatus
import mobi.giza.compose.ui.view.state.SharesSummary
+import mobi.giza.compose.ui.view.state.RotationPreview
class ChatRoomDetailViewModel(
val chatRoomId: String,
@@ -113,6 +119,13 @@ class ChatRoomDetailViewModel(
// docs/member-admin-promotion.md, Phase 11.
val me = localChatRoom.chatRoom.userPublicKey
val roomIsOpen = !isDisbanded && localChatRoom.chatRoom.leftGroupAt == null
+ // 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,
@@ -136,8 +149,39 @@ class ChatRoomDetailViewModel(
governance = runCatching { chatRepository.governanceStatus(chatRoomId) }
.onFailure { if (it is CancellationException) throw it }
.getOrNull(),
+ 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) }
+ }
}
}
@@ -146,15 +190,21 @@ 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()
+ // 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
@@ -162,7 +212,7 @@ class ChatRoomDetailViewModel(
// Not for a removal the group has yet to sign: they are still in the
// room, and the offer would come before the fact it is about.
val proposed = (chatRoomDetailUIState as? ChatRoomDetailUIState.Loaded)?.governance is GovernanceStatus.Governed
- if (failure == null && heldShare && !proposed) rotationOffer = RotationOffer(localChatRoom, memberPublicKey)
+ if (rotation == SharesSummary.Rotation.Available && !proposed) rotationOffer = RotationOffer(localChatRoom, memberPublicKey, preview)
}
}
}
@@ -214,33 +264,113 @@ class ChatRoomDetailViewModel(
}
}
+ /**
+ * 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)
+ }
+ }
+ }
+
/**
* Runs one Shares section action, reloads the screen, and reports: null for
* done, or why not. Every one of them is a proposal or an answer the group
* 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) }
}
}
- fun rotateShares(localChatRoom: LocalChatRoom, onDone: (String?) -> Unit) =
- sharesAction(onDone) { chatRepository.rotateShares(localChatRoom) }
+ /** A rotation this device could propose, shown before it is: pressing it is the proposer's agreement to take part. */
+ data class RotationProposal(val localChatRoom: LocalChatRoom, val preview: RotationPreview)
+
+ var rotationProposal: RotationProposal? by mutableStateOf(null)
+ private set
+
+ /**
+ * Asks who a rotation would take part and leave out, and shows it. Nothing is
+ * sent until [rotateShares]. [onUnavailable] is told when there is nothing to
+ * show -- the room has no key this device can rotate.
+ */
+ fun previewRotation(localChatRoom: LocalChatRoom, onUnavailable: () -> Unit) {
+ viewModelScope.launch(Dispatchers.IO) {
+ val preview = chatRepository.rotationPreview(localChatRoom)
+ viewModelScope.launch(Dispatchers.Main) {
+ if (preview == null) onUnavailable() else rotationProposal = RotationProposal(localChatRoom, preview)
+ }
+ }
+ }
+
+ fun dismissRotationProposal() {
+ rotationProposal = null
+ }
+
+ /** Proposes the rotation [rotationProposal] showed. */
+ fun rotateShares(proposal: RotationProposal, onDone: (String?) -> Unit) {
+ rotationProposal = null
+ sharesAction(onDone) { chatRepository.rotateShares(proposal.localChatRoom) }
+ }
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) }
fun askToBeRepaired(localChatRoom: LocalChatRoom, onDone: (String?) -> Unit) =
sharesAction(onDone) { chatRepository.askToBeRepaired(localChatRoom) }
- /** A removed member who still holds a share of the room's key, for the offer to rotate without them. */
- data class RotationOffer(val localChatRoom: LocalChatRoom, val memberPublicKey: HexKey)
+ /**
+ * A removed member who still holds a share of the room's key, for the offer to
+ * rotate without them, with who else it would leave out.
+ */
+ data class RotationOffer(val localChatRoom: LocalChatRoom, val memberPublicKey: HexKey, val preview: RotationPreview? = null)
var rotationOffer: RotationOffer? by mutableStateOf(null)
private set
@@ -363,6 +493,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 ab7db125..b34dfc2a 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 c292ec61..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
@@ -244,8 +244,17 @@ class SynchronizationViewModel(
// a message and acting on it -- would sit still for good.
// After the reopen, since what that opened may be what it
// was waiting for. docs/automatic-key-ceremony.md, Phase 3.
+ // A share rotation is the same, past its one approval
+ // (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 1b340f37..fe5c11dd 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
@@ -103,6 +103,33 @@ sealed interface ChatRoomDetailUIState {
val adminLeave: AdminLeave? = null,
/** Where a keyed room stands on needing the group's signature; null for any other room. */
val governance: GovernanceStatus? = 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/RotationPreview.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/RotationPreview.kt
new file mode 100644
index 00000000..0d7d997d
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/RotationPreview.kt
@@ -0,0 +1,17 @@
+package mobi.giza.compose.ui.view.state
+
+/**
+ * A share rotation as the proposer's dialog shows it before anything is sent
+ * (docs/rotate-shares-single-approval.md, Phase 4): who takes part and who is
+ * left out, by name. Pressing the dialog's button is the proposer's agreement
+ * to take part, so it shows everything that agreement covers.
+ */
+data class RotationPreview(
+ val takingPart: List,
+ /** Withheld as stale: left out until a repair brings them back. */
+ val untilBroughtBack: List,
+ /** Withheld as retired: left out for good. */
+ val forGood: List,
+ /** Why the rotation cannot be proposed, or null when it can. */
+ val refusal: String?,
+)
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 720377f0..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
@@ -1,26 +1,75 @@
package mobi.giza.compose.ui.view.state
import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import kotlin.time.Instant
import mobi.giza.compose.database.model.types.ShareStanding
/**
* A room's key, as the Shares section shows it (docs/frost-share-refresh.md,
* Phase 11): the generation the group signs with, who holds what, what this
- * device is being asked, and what it may start.
+ * device is being asked, what is running, and what it may start.
*/
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. */
+ val running: Running? = null,
+ /** Why the newest rotation ended, when it ended without completing and nothing has run since. */
+ val lastFailure: String? = null,
) {
data class Member(val publicKey: HexKey, val name: String, val standing: ShareStanding, val isSelf: Boolean)
- /** Something this device's owner is being asked, and the session it is for. */
- data class PendingApproval(val sessionId: String, val kind: Kind) {
- enum class Kind { REFRESH_DEAL, REFRESH_CONFIRM, REPAIR_HELP }
+ /**
+ * 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
+ * taking part is (docs/rotate-shares-single-approval.md, Phase 6).
+ */
+ data class PendingApproval(val sessionId: String, val kind: Kind, val withheld: List = emptyList()) {
+ /** A rotation asks one thing, to take part; storing the new share stopped being a question. */
+ enum class Kind { REFRESH_DEAL, REPAIR_HELP }
+ }
+
+ data class Withheld(val name: String, val standing: ShareStanding)
+
+ /**
+ * A rotation running past its one approval. With nothing left to approve,
+ * this is the only place a member who took part sees it stall, and the only
+ * way out of one.
+ */
+ data class Running(
+ val sessionId: String,
+ val step: Step,
+ val waitingOn: List,
+ val since: Instant,
+ /** This device is a recipient of a rotation not yet certified, so it may end it for everyone. */
+ val canAbandon: Boolean,
+ ) {
+ enum class Step { DEALING, STORING, SIGNING }
}
}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminFlagsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminFlagsJvmTest.kt
index 2cbd7e4a..cca6eb41 100644
--- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminFlagsJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminFlagsJvmTest.kt
@@ -18,7 +18,6 @@ import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.builder.getRoomDatabase
import mobi.giza.compose.database.model.MarmotKeyPackage
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.nostr.MarmotProfile
@@ -95,21 +94,4 @@ class AdminFlagsJvmTest {
assertEquals(linesBefore, db.chatMessageDao().getChatMessagesByChatRoomId(roomId).size, "a reconcile wrote a line")
assertFalse(chatRepository.reconcileAdmins(roomId), "a second reconcile found something to change")
}
-
- @Test
- fun `a flag the group no longer backs is cleared, and one that agrees keeps its moment`() {
- val since = Instant.fromEpochSeconds(1_700_000_000)
- val rows = listOf(
- Participant(participantPublicKey = "a", chatRoomId = "r", relayHint = null, adminAt = since),
- Participant(participantPublicKey = "b", chatRoomId = "r", relayHint = null, adminAt = since),
- Participant(participantPublicKey = "c", chatRoomId = "r", relayHint = null),
- )
-
- val changes = MarmotInboundManager.adminFlagChanges(rows, adminPublicKeys = setOf("a", "c"))
- .associateBy { it.participantPublicKey }
-
- assertEquals(setOf("b", "c"), changes.keys, "a row that already agreed was rewritten")
- assertNull(changes.getValue("b").adminAt)
- assertNotNull(changes.getValue("c").adminAt)
- }
}
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 a135d260..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).
@@ -134,17 +139,23 @@ class ShareRefreshRitualJvmTest {
.filter { it.publicKey == device.publicKey }
.sortedWith(compareBy({ it.createdAt }, { it.kind }))
- private suspend fun pump(between: List) {
+ private suspend fun pump(
+ between: List,
+ hold: (MarmotInnerEvent) -> Boolean = { false },
+ tamper: (MarmotInnerEvent) -> MarmotInnerEvent = { it },
+ ) {
var moved = true
while (moved) {
moved = false
for (from in between) for (to in between) {
if (from === to) continue
outbox(from).forEach { queued ->
- if (!to.received.add(queued.id)) return@forEach
+ if (queued.id in to.received || hold(queued)) return@forEach
+ to.received += queued.id
moved = true
- to.db.marmotInnerEventDao().upsert(queued.copy(chatRoomId = to.group.roomId))
- val event = Event(queued.id, queued.publicKey, queued.createdAt.epochSeconds, queued.kind, queued.tags, queued.content, "")
+ val delivered = tamper(queued)
+ to.db.marmotInnerEventDao().upsert(delivered.copy(chatRoomId = to.group.roomId))
+ val event = Event(queued.id, queued.publicKey, queued.createdAt.epochSeconds, queued.kind, queued.tags, delivered.content, "")
if (ShareRefreshEvents.isShareRefreshKind(event.kind)) {
ShareRefreshManager.processRefreshPayload(to.db, to.room, event, to.publicKey, to.privateKey)
} else if (mobi.giza.compose.nostr.frost.ShareRepairEvents.isShareRepairKind(event.kind)) {
@@ -176,6 +187,47 @@ class ShareRefreshRitualJvmTest {
private suspend fun propose(by: Device, withheld: Map = emptyMap()) =
ShareRefreshManager.proposeRefresh(by.db, by.room, by.publicKey, by.privateKey, by.key(), withheld)
+ /** One thing a device's owner was asked during a rotation. */
+ private sealed interface Ask {
+ data class Rotation(val step: mobi.giza.compose.database.model.types.ShareRefreshApprovalStep) : Ask
+ data object KeyState : Ask
+ data class Signature(val kind: Int) : Ask
+ }
+
+ /**
+ * Every owner says yes to whatever they are asked, about the rotation or any
+ * signature, until nobody is asked anything -- and the list of what each was
+ * asked, in order. The count is what docs/rotate-shares-single-approval.md
+ * takes from three to one.
+ */
+ private suspend fun answerEverything(between: List, refreshId: String): Map> {
+ val asks = between.associate { it.index to mutableListOf() }
+ var asked = true
+ while (asked) {
+ asked = false
+ for (device in between) {
+ device.refresh(refreshId)?.let { session ->
+ ShareRefreshManager.pendingApproval(device.db, session)?.let { step ->
+ asks.getValue(device.index) += Ask.Rotation(step)
+ ShareRefreshManager.approve(device.db, device.room, refreshId, device.privateKey)
+ asked = true
+ }
+ }
+ val signing = device.db.frostSigningSessionDao()
+ signing.getSessionsForChatRoom(device.group.roomId)
+ .filter { FrostSigningManager.isAwaitingApproval(it, signing.getItems(it.id)) }
+ .forEach { session ->
+ val kind = Event.fromJsonOrNull(signing.getItems(session.id).single().unsignedEventJson)!!.kind
+ asks.getValue(device.index) += if (kind == mobi.giza.compose.nostr.frost.GroupKeyStateEvent.KIND) Ask.KeyState else Ask.Signature(kind)
+ FrostSigningManager.approve(device.db, device.room, session.id)
+ asked = true
+ }
+ }
+ pump(between)
+ }
+ return asks
+ }
+
// ---- the tests ---------------------------------------------------------------------------------------------
@Test
@@ -213,18 +265,522 @@ 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])
pump(all)
- all.forEach { device ->
- assertEquals(listOf(ShareRefreshEvents.PROPOSAL).takeIf { device.index == 0 } ?: emptyList(), outbox(device).map { it.kind }, "device ${device.index}")
+ all.drop(1).forEach { device ->
+ assertEquals(emptyList(), outbox(device).map { it.kind }, "device ${device.index}")
assertNotNull(ShareRefreshManager.pendingApproval(device.db, device.refresh(refresh.id)!!), "device ${device.index} must be asked")
}
- // The proposer is asked like anyone: proposing is not agreeing to withhold whoever the form defaulted to.
- assertTrue(all[0].db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId).any { it.chatMessage.messageType == ChatMessage.TYPE_SHARE_REFRESH_APPROVAL_NEEDED })
+ // Proposing is the proposer's agreement, made from a dialog that named
+ // everyone left out: its device deals at once, and its owner is not asked.
+ val proposer = all[0]
+ assertEquals(listOf(ShareRefreshEvents.PROPOSAL, ShareRefreshEvents.ROUND_1), outbox(proposer).map { it.kind })
+ assertNull(ShareRefreshManager.pendingApproval(proposer.db, proposer.refresh(refresh.id)!!))
+ assertTrue(proposer.db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId).none { it.chatMessage.messageType == ChatMessage.TYPE_SHARE_REFRESH_APPROVAL_NEEDED })
+ }
+
+ // ---- Phase 4 of rotate-shares-single-approval: what the proposer is shown ----------------------------------------
+
+ /** The dialog shows what the proposal will say: the same recipients, the same members left out, as the same standing. */
+ @Test
+ fun `the preview is the proposal`() = runBlocking {
+ suspend fun agrees(by: Device, without: HexKey? = null) {
+ val preview = assertNotNull(ShareRefreshManager.preview(by.db, by.room, by.publicKey, without))
+ assertNull(preview.refusal, preview.refusal)
+ val refresh = if (without == null) propose(by) else ShareRefreshManager.proposeWithout(by.db, by.room, by.publicKey, by.privateKey, without)
+ val roster = by.active().roster.associate { it.participantId to it.memberPublicKey }
+ assertEquals(preview.takingPart, refresh.recipientIdList().map { roster.getValue(it) })
+ assertEquals(preview.withheld, refresh.withheldStandings().mapKeys { roster.getValue(it.key) })
+ }
+
+ // Nobody stale, nobody removed.
+ val fresh = devicesFor(Group(3, 2))
+ agrees(fresh[0])
+
+ // One stale, withheld again without being asked for.
+ val (_, rotated) = rotatedWithout(2)
+ val stale = ShareRefreshManager.preview(rotated[0].db, rotated[0].room, rotated[0].publicKey)!!
+ assertEquals(mapOf(rotated[2].publicKey to ShareStanding.STALE), stale.withheld)
+ agrees(rotated[0])
+ }
+
+ @Test
+ fun `the preview of a removal names the removed for good and the stale until they are back`() = runBlocking {
+ val group = Group(5, 2)
+ val all = devicesFor(group)
+ val first = propose(all[0], mapOf(group.idOf[4] to ShareStanding.STALE))
+ pump(all)
+ approveAll(all, first.id)
+ approveSigning(all)
+
+ val preview = assertNotNull(ShareRefreshManager.preview(all[0].db, all[0].room, all[0].publicKey, without = all[3].publicKey))
+ assertNull(preview.refusal, preview.refusal)
+ assertEquals(mapOf(all[3].publicKey to ShareStanding.RETIRED, all[4].publicKey to ShareStanding.STALE), preview.withheld)
+ assertEquals(setOf(all[0], all[1], all[2]).map { it.publicKey }.toSet(), preview.takingPart.toSet())
+ }
+
+ @Test
+ fun `the preview of a rotation that would be refused says why and sends nothing`() = runBlocking {
+ val group = Group(2, 2)
+ val (alice, bob) = devicesFor(group)
+ val preview = assertNotNull(ShareRefreshManager.preview(alice.db, alice.room, alice.publicKey, without = bob.publicKey))
+ assertTrue(preview.refusal!!.contains("fewer than the 2 it takes to sign"), preview.refusal)
+ assertTrue(outbox(alice).isEmpty())
+ assertNull(alice.db.shareRefreshDao().getSessionsForKey(ceremonyId).firstOrNull())
+ }
+
+ // ---- the approvals, counted (docs/rotate-shares-single-approval.md) ---------------------------------------------
+
+ /**
+ * Taking part is the only approval. With every recipient's owner agreeing to
+ * take part and nothing more, every device stores its new share, confirms it,
+ * and arrives at the new generation; and nothing ever asks to store it.
+ */
+ @Test
+ fun `after taking part, every device stores its new share without being asked again`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val refresh = propose(all[0])
+ pump(all)
+ all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) }
+ pump(all)
+
+ all.forEach { device ->
+ val session = device.refresh(refresh.id)!!
+ assertEquals(ShareRefreshStage.COMPLETE, session.stage, "device ${device.index}")
+ assertNull(ShareRefreshManager.pendingApproval(device.db, session), "device ${device.index}")
+ assertNull(session.confirmApprovedAt, "nothing writes the old second approval")
+ assertEquals(ShareGenerationState.ACTIVE, device.db.keyShareDao().getGeneration(ceremonyId, 1)?.state, "device ${device.index}")
+ assertTrue(outbox(device).any { it.kind == ShareRefreshEvents.ROUND_2 }, "device ${device.index} did not confirm")
+ val lines = device.db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId)
+ .filter { it.chatMessage.messageType == ChatMessage.TYPE_SHARE_REFRESH_APPROVAL_NEEDED }
+ assertEquals(if (device.index == 0) 0 else 1, lines.size, "device ${device.index} must be asked once, the proposer never")
+ }
+ }
+
+ /**
+ * The last recipient to take part deals at once, and confirms on the next
+ * pass that brings the coordinator's sum, with no call in between.
+ */
+ @Test
+ fun `the last to take part deals and then confirms with nothing more asked`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val refresh = propose(all[0])
+ pump(all)
+ all.dropLast(1).forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) }
+ pump(all)
+ val last = all.last()
+ assertTrue(outbox(last).none { it.kind == ShareRefreshEvents.ROUND_1 })
+
+ ShareRefreshManager.approve(last.db, last.room, refresh.id, last.privateKey)
+ assertTrue(outbox(last).any { it.kind == ShareRefreshEvents.ROUND_1 }, "it deals in the approve call")
+ pump(all)
+ assertTrue(outbox(last).any { it.kind == ShareRefreshEvents.ROUND_2 }, "and confirms when the sum arrives")
+ all.forEach { assertEquals(ShareRefreshStage.COMPLETE, it.refresh(refresh.id)?.stage) }
+ }
+
+ /**
+ * What the second approval was said to protect, protected without it: a
+ * coordinator's sum altered on its way fails the rotation on every device,
+ * and nobody arrives at a new generation.
+ */
+ @Test
+ fun `a tampered sum fails the rotation with nobody asked`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val refresh = propose(all[0])
+ pump(all)
+ all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) }
+ pump(all, tamper = { event ->
+ if (event.kind != ShareRefreshEvents.COORDINATOR_ROUND_1) event
+ else event.copy(content = event.content.dropLast(2) + if (event.content.endsWith("00")) "01" else "00")
+ })
+
+ all.forEach { device ->
+ val session = device.refresh(refresh.id)!!
+ assertEquals(ShareRefreshStage.FAILED, session.stage, "device ${device.index}")
+ assertEquals(0, device.active().generation, "device ${device.index} moved to a generation")
+ }
+ assertTrue(all.drop(1).any { it.refresh(refresh.id)!!.failureReason!!.contains("Share refresh") }, "an honest recipient has to say what it found")
+ }
+
+
+ /**
+ * The upgrade: an older build stored the coordinator's sum and stopped, asking
+ * its owner to store the new share. Nothing more will arrive, so only the
+ * sweep can move it -- and it does, once, and the rotation completes.
+ */
+ @Test
+ fun `a rotation left waiting on the old second approval resumes from the sweep`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val (coordinator, others) = all.first() to all.drop(1)
+ val refresh = propose(coordinator)
+ pump(all)
+ all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) }
+ // The sum goes out, but the others' build files it and stops.
+ pump(all, hold = { it.kind == ShareRefreshEvents.COORDINATOR_ROUND_1 })
+ val sum = outbox(coordinator).single { it.kind == ShareRefreshEvents.COORDINATOR_ROUND_1 }
+ others.forEach { device ->
+ device.received += sum.id
+ device.db.marmotInnerEventDao().upsert(sum.copy(chatRoomId = group.roomId))
+ device.db.shareRefreshDao().upsert(
+ device.refresh(refresh.id)!!.copy(
+ coordinatorRound1 = sum.content,
+ stage = ShareRefreshStage.COLLECTING_ROUND_2,
+ approvalRequestedThrough = mobi.giza.compose.database.model.types.ShareRefreshApprovalStep.CONFIRM,
+ )
+ )
+ assertTrue(outbox(device).none { it.kind == ShareRefreshEvents.ROUND_2 }, "device ${device.index}")
+ }
+ pump(all)
+ others.forEach { assertTrue(outbox(it).none { e -> e.kind == ShareRefreshEvents.ROUND_2 }, "nothing arrives to move device ${it.index}") }
+
+ others.forEach { assertEquals(1, ShareRefreshManager.resumeRunning(it.db, it.publicKey, it.privateKey)) }
+ others.forEach { assertEquals(1, outbox(it).count { e -> e.kind == ShareRefreshEvents.ROUND_2 }, "device ${it.index} confirmed from the sweep") }
+ pump(all)
+ all.forEach { assertEquals(ShareRefreshStage.COMPLETE, it.refresh(refresh.id)?.stage, "device ${it.index}") }
+
+ // Twice more: nothing runs, nothing goes out.
+ val sent = all.map { outbox(it).size }
+ repeat(2) { all.forEach { device -> assertEquals(0, ShareRefreshManager.resumeRunning(device.db, device.publicKey, device.privateKey)) } }
+ assertEquals(sent, all.map { outbox(it).size })
+ }
+
+ /** A rotation nobody has taken part in yet is looked at by the sweep and sends nothing. */
+ @Test
+ fun `the sweep sends nothing for a member who has not taken part`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val refresh = propose(all[0])
+ pump(all)
+ val member = all[1]
+ assertEquals(1, ShareRefreshManager.resumeRunning(member.db, member.publicKey, member.privateKey))
+ assertTrue(outbox(member).isEmpty())
+ assertEquals(mobi.giza.compose.database.model.types.ShareRefreshApprovalStep.DEAL, ShareRefreshManager.pendingApproval(member.db, member.refresh(refresh.id)!!))
+ val asked = member.db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId).count { it.chatMessage.messageType == ChatMessage.TYPE_SHARE_REFRESH_APPROVAL_NEEDED }
+ assertEquals(1, asked, "asked once, however often the sweep looks")
+ }
+
+ @Test
+ fun `a build without rotation resumes nothing`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ propose(all[0])
+ pump(all)
+ mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = false
+ assertEquals(0, ShareRefreshManager.resumeRunning(all[1].db, all[1].publicKey, all[1].privateKey))
+ }
+
+ /**
+ * The whole of the change: a recipient is asked one thing before the old
+ * shares are deleted -- to take part. Storing the new share and signing the
+ * new generation's key state follow from it. The proposer is asked nothing:
+ * proposing was taking part.
+ */
+ @Test
+ fun `a recipient is asked only to take part`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val refresh = propose(all[0])
+ pump(all)
+ val asks = answerEverything(all, refresh.id)
+
+ val rotation = listOf(Ask.Rotation(mobi.giza.compose.database.model.types.ShareRefreshApprovalStep.DEAL))
+ assertEquals(emptyList(), asks[0], "the proposer, whose proposal was its answer")
+ all.drop(1).forEach { device -> assertEquals(rotation, asks[device.index], "device ${device.index}") }
+ all.forEach { device ->
+ assertEquals(1, device.db.groupKeyStateDao().getByChatRoomId(group.roomId)?.generation, "device ${device.index}")
+ assertNull(device.key().secretShare, "device ${device.index} kept the old share")
+ }
+ }
+
+ /**
+ * A completed rotation's key state is the one statement its recipients'
+ * devices can vouch for, so they sign it with nobody asked, and every device
+ * deletes the share it was meant to delete.
+ */
+ @Test
+ fun `a completed rotation signs its new key state and the old shares go, with nobody asked`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val refresh = propose(all[0])
+ pump(all)
+ all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) }
+ pump(all)
+
+ all.forEach { device ->
+ assertEquals(ShareRefreshStage.COMPLETE, device.refresh(refresh.id)?.stage)
+ assertEquals(1, device.db.groupKeyStateDao().getByChatRoomId(group.roomId)?.generation, "device ${device.index}")
+ assertNull(device.key().secretShare, "device ${device.index} kept the old share")
+ val signing = device.db.frostSigningSessionDao()
+ assertTrue(signing.getSessionsForChatRoom(group.roomId).none { FrostSigningManager.isAwaitingApproval(it, signing.getItems(it.id)) }, "device ${device.index} was asked")
+ }
+ }
+
+ /**
+ * The coordinator proposes the key state the moment its own certificate
+ * verifies, so a recipient can hear the proposal first. It cannot vouch for a
+ * rotation not yet complete here; once the certificate arrives, it can, and
+ * does, without its owner.
+ */
+ @Test
+ fun `a key state heard before the certificate is vouched for once the certificate arrives`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val refresh = propose(all[0])
+ pump(all)
+ all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) }
+ pump(all, hold = { it.kind == ShareRefreshEvents.CERTIFICATE })
+
+ val member = all[1]
+ val signing = member.db.frostSigningSessionDao()
+ val keyState = signing.getSessionsForChatRoom(group.roomId).single()
+ assertEquals(1, keyState.generation)
+ assertNull(keyState.signApprovedAt, "not vouched for before the rotation completes here")
+ assertTrue(member.refresh(refresh.id)!!.stage != ShareRefreshStage.COMPLETE)
+
+ pump(all)
+ assertNotNull(signing.getSessionById(keyState.id)?.signApprovedAt, "vouched for once it completes")
+ all.forEach { device ->
+ assertEquals(1, device.db.groupKeyStateDao().getByChatRoomId(group.roomId)?.generation, "device ${device.index}")
+ assertNull(device.key().secretShare, "device ${device.index}")
+ }
+ }
+
+ /** Each rule, broken on its own, leaves a rotation's key state with the member. */
+ @Test
+ fun `a device vouches for its rotation's key state and nothing else`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val refresh = propose(all[0])
+ pump(all)
+ // Every device completes the rotation; the key state is proposed, and held.
+ all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) }
+ pump(all, hold = { FrostSigningEvents.isProposal(it.kind) })
+ val (coordinator, member) = all
+ assertEquals(ShareRefreshStage.COMPLETE, member.refresh(refresh.id)?.stage)
+
+ val proposed = coordinator.db.frostSigningSessionDao().getSessionsForChatRoom(group.roomId).single()
+ val session = proposed.copy(userPublicKey = member.publicKey, signApprovedAt = null)
+ val item = coordinator.db.frostSigningSessionDao().getItems(proposed.id).single()
+ val event = Event.fromJson(item.unsignedEventJson)
+ fun with(tags: Array>) = listOf(item.copy(unsignedEventJson = Event(event.id, event.pubKey, event.createdAt, event.kind, tags, event.content, event.sig).toJson()))
+ fun replacing(name: String, value: String) = with(event.tags.map { if (it.firstOrNull() == name) arrayOf(name, value) else it }.toTypedArray())
+ suspend fun vouches(on: Device = member, s: mobi.giza.compose.database.model.FrostSigningSession = session, items: List = listOf(item)) =
+ GroupKeyStateManager.vouchesFor(on.db, s.copy(userPublicKey = on.publicKey), items)
+
+ assertTrue(vouches(), "the one true statement")
+ assertTrue(!vouches(items = replacing("frost_pubshares", "ab".repeat(32))), "another table")
+ assertTrue(!vouches(items = replacing("frost_refresh", "cd".repeat(32))), "another rotation")
+ assertTrue(!vouches(items = with(event.tags + arrayOf("frost_retired", group.idOf[2].toString()))), "retiring someone this rotation did not")
+ val binding = mobi.giza.compose.nostr.frost.GroupKeyStateEvent.MemberBinding(group.idOf[2], KeyPair().pubKey.toHexKey(), group.hostKeys[0])
+ assertTrue(!vouches(items = with(event.tags + arrayOf("frost_member", binding.encode()))), "binding an id to a new identity")
+ assertTrue(!vouches(s = session.copy(generation = 0)), "a session at another generation")
+ assertTrue(!vouches(items = replacing("frost_generation", "2")), "a generation this device does not sign with")
+ assertTrue(!vouches(s = session.copy(derivationPath = SharedKeyDerivation.formatPath(listOf(9420L, 0L, 1L)))), "at another path")
+
+ // A rotation not complete here: the same statement, from a device that has not finished.
+ member.db.shareRefreshDao().upsert(member.refresh(refresh.id)!!.copy(stage = ShareRefreshStage.COLLECTING_ROUND_2))
+ assertTrue(!vouches(), "a rotation that is not complete here")
+ member.db.shareRefreshDao().upsert(member.refresh(refresh.id)!!.copy(stage = ShareRefreshStage.COMPLETE))
+
+ // Once the group has signed it, the next statement at the same generation is not the one true one.
+ all.forEach { it.received.clear() }
+ pump(all)
+ assertEquals(1, member.db.groupKeyStateDao().getByChatRoomId(group.roomId)?.generation)
+ assertTrue(!vouches(), "a room already holding a state at this generation")
+ }
+
+ /** A member withheld from the rotation holds no share of it, and vouches for nothing it did not help make. */
+ @Test
+ fun `a withheld member does not vouch for the new key state`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val withheld = all[2]
+ val refresh = propose(all[0], mapOf(group.idOf[2] to ShareStanding.STALE))
+ pump(all)
+ all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) }
+ pump(all, hold = { FrostSigningEvents.isProposal(it.kind) })
+ assertEquals(ShareRefreshStage.COMPLETE, withheld.refresh(refresh.id)?.stage)
+
+ val proposed = all[0].db.frostSigningSessionDao().getSessionsForChatRoom(group.roomId).single()
+ val items = all[0].db.frostSigningSessionDao().getItems(proposed.id)
+ assertTrue(GroupKeyStateManager.vouchesFor(all[1].db, proposed.copy(userPublicKey = all[1].publicKey), items), "a recipient does")
+ assertTrue(!GroupKeyStateManager.vouchesFor(withheld.db, proposed.copy(userPublicKey = withheld.publicKey), items), "the withheld member does not")
+ }
+
+ /** A key state an older build left asking is answered by the sweep, once. */
+ @Test
+ fun `a key state left asking by an older build is signed from the sweep`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val refresh = propose(all[0])
+ pump(all)
+ all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) }
+ pump(all, hold = { FrostSigningEvents.isProposal(it.kind) })
+
+ // The proposal arrives at a member as an older build filed it: stored, asked, not vouched for.
+ val member = all[1]
+ val proposal = outbox(all[0]).first { FrostSigningEvents.isProposal(it.kind) }
+ member.received += proposal.id
+ member.db.marmotInnerEventDao().upsert(proposal.copy(chatRoomId = group.roomId))
+ val shareRefresh = member.refresh(refresh.id)!!
+ member.db.shareRefreshDao().upsert(shareRefresh.copy(stage = ShareRefreshStage.COLLECTING_ROUND_2))
+ FrostSigningManager.processSigningPayload(member.db, member.room, Event(proposal.id, proposal.publicKey, proposal.createdAt.epochSeconds, proposal.kind, proposal.tags, proposal.content, ""), member.publicKey)
+ member.db.shareRefreshDao().upsert(shareRefresh)
+ val filed = member.db.frostSigningSessionDao().getSessionsForChatRoom(group.roomId).single()
+ assertNull(filed.signApprovedAt, "filed and asked, as the older build left it")
+
+ assertEquals(1, FrostSigningManager.resumeVouched(member.db, member.publicKey))
+ assertNotNull(member.db.frostSigningSessionDao().getSessionById(filed.id)?.signApprovedAt)
+ assertEquals(0, FrostSigningManager.resumeVouched(member.db, member.publicKey), "once")
+ }
+
+ // ---- Phase 6 of rotate-shares-single-approval: the Shares section ------------------------------------------------
+
+ private suspend fun summaryOn(device: Device): mobi.giza.compose.ui.view.state.SharesSummary {
+ val scope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined + kotlinx.coroutines.Job())
+ return try {
+ assertNotNull(mobi.giza.compose.database.repository.DatabaseChatRepository(device.db, scope).sharesSummary(device.room), "device ${device.index}")
+ } finally {
+ scope.coroutineContext[kotlinx.coroutines.Job]?.cancel()
+ }
+ }
+
+ private fun nameOf(device: Device) = device.publicKey.take(8)
+
+ @Test
+ fun `a rotation asks one thing, to take part`() {
+ assertEquals(
+ listOf(mobi.giza.compose.ui.view.state.SharesSummary.PendingApproval.Kind.REFRESH_DEAL, mobi.giza.compose.ui.view.state.SharesSummary.PendingApproval.Kind.REPAIR_HELP),
+ mobi.giza.compose.ui.view.state.SharesSummary.PendingApproval.Kind.entries.toList(),
+ )
+ }
+
+ /** Taking part is agreeing to who is left out, so the row that asks it names them. */
+ @Test
+ fun `the taking-part row names who is left out, and the withheld member sees the rotation run`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ propose(all[0], mapOf(group.idOf[2] to ShareStanding.STALE))
+ pump(all)
+
+ val asked = summaryOn(all[1])
+ val row = asked.pending.single()
+ assertEquals(mobi.giza.compose.ui.view.state.SharesSummary.PendingApproval.Kind.REFRESH_DEAL, row.kind)
+ assertEquals(listOf(mobi.giza.compose.ui.view.state.SharesSummary.Withheld(nameOf(all[2]), ShareStanding.STALE)), row.withheld)
+ assertNull(asked.running, "the row covers a member not yet asked")
+
+ val withheld = summaryOn(all[2])
+ assertTrue(withheld.pending.isEmpty())
+ val running = assertNotNull(withheld.running)
+ assertEquals(listOf(nameOf(all[1])), running.waitingOn)
+ assertTrue(!running.canAbandon, "only a member taking part may end it")
+ }
+
+ /**
+ * Once a member has taken part there is nothing left to approve, so the
+ * running rotation is what they see: the step, who it waits on, and abandon.
+ */
+ @Test
+ fun `a running rotation names who it waits on at each step`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val (alice, bob, carol) = all
+ val refresh = propose(alice)
+ pump(all)
+ ShareRefreshManager.approve(bob.db, bob.room, refresh.id, bob.privateKey)
+ pump(all)
+
+ val dealing = assertNotNull(summaryOn(bob).running)
+ assertEquals(mobi.giza.compose.ui.view.state.SharesSummary.Running.Step.DEALING, dealing.step)
+ 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).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)
+ pump(all, hold = { it.kind == ShareRefreshEvents.ROUND_2 && it.publicKey == carol.publicKey })
+ val storing = assertNotNull(summaryOn(bob).running)
+ assertEquals(mobi.giza.compose.ui.view.state.SharesSummary.Running.Step.STORING, storing.step)
+ assertEquals(listOf(nameOf(carol)), storing.waitingOn)
+
+ // A relay repeating itself is not progress. Dated a day back first, so a
+ // redelivery that rewrote a row would show, whatever the clock's precision.
+ val dao = bob.db.shareRefreshDao()
+ val dayAgo = kotlin.time.Clock.System.now() - kotlin.time.Duration.parse("1d")
+ dao.getMessagesForSession(refresh.id).forEach { dao.upsert(it.copy(createdAt = dayAgo, updatedAt = dayAgo, savedAt = dayAgo)) }
+ val since = assertNotNull(summaryOn(bob).running).since
+ assertTrue(kotlin.time.Clock.System.now() - since > kotlin.time.Duration.parse("23h"))
+ bob.received.clear()
+ pump(all, hold = { it.kind == ShareRefreshEvents.ROUND_2 && it.publicKey == carol.publicKey })
+ assertEquals(since, summaryOn(bob).running?.since, "a redelivered message moved the stall clock")
+ }
+
+ @Test
+ fun `the last step is the group signing the new key state, which nobody abandons`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val refresh = propose(all[0])
+ pump(all)
+ all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) }
+ pump(all, hold = { FrostSigningEvents.isProposal(it.kind) })
+
+ val signing = assertNotNull(summaryOn(all[0]).running, "the coordinator's own key state is open")
+ assertEquals(mobi.giza.compose.ui.view.state.SharesSummary.Running.Step.SIGNING, signing.step)
+ assertTrue(!signing.canAbandon)
+
+ pump(all)
+ all.forEach { assertNull(summaryOn(it).running, "device ${it.index}: nothing is running once it is signed") }
+ }
+
+ @Test
+ fun `an abandoned rotation says why until the next one`() = runBlocking {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val refresh = propose(all[0])
+ pump(all)
+ ShareRefreshManager.approve(all[1].db, all[1].room, refresh.id, all[1].privateKey)
+ ShareRefreshManager.abandon(all[1].db, all[1].room, refresh.id)
+ pump(all)
+
+ all.forEach { device ->
+ val summary = summaryOn(device)
+ assertNull(summary.running)
+ assertTrue(summary.lastFailure!!.contains("Abandoned"), summary.lastFailure)
+ 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
@@ -336,11 +892,15 @@ class ShareRefreshRitualJvmTest {
val all = devicesFor(group)
val refresh = propose(all[0])
pump(all)
- approveAll(all, refresh.id)
+ // The key state is held on its way, so the rotation completes with nothing signed yet.
+ all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) }
+ pump(all, hold = { FrostSigningEvents.isProposal(it.kind) })
+ all.forEach { assertEquals(ShareRefreshStage.COMPLETE, it.refresh(refresh.id)?.stage) }
// Not yet: the old share stays until the new ones have signed something.
all.forEach { assertNotNull(it.key().secretShare, "device ${it.index} deleted before the group signed") }
+ pump(all)
approveSigning(all)
all.forEach { device ->
@@ -474,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. */
@@ -641,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/composable/ChatRoomMemberRowJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomMemberRowJvmTest.kt
index b0fe514a..cc1c4eae 100644
--- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomMemberRowJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomMemberRowJvmTest.kt
@@ -97,7 +97,16 @@ class ChatRoomMemberRowJvmTest {
fun `an admin's row says so, and a share holder's says that apart`() {
render(
onNavigateToRoute = {},
- state = state().copy(adminPublicKeys = setOf(named), shareHolders = setOf(stillLoading)),
+ state = state().let { loaded ->
+ loaded.copy(
+ localChatRoom = loaded.localChatRoom.copy(
+ localParticipants = loaded.localChatRoom.localParticipants.map {
+ if (it.participant.participantPublicKey == named) it.copy(participant = it.participant.copy(adminAt = kotlin.time.Instant.fromEpochSeconds(1_700_000_000))) else it
+ },
+ ),
+ shareHolders = setOf(stillLoading),
+ )
+ },
) {
onNodeWithText("Admin").assertExists()
onNodeWithText("Holds a share").assertExists()
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 02b9cf96..c2d13410 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -19,7 +19,8 @@ the [retired](./retired/) notes now.
| [ceremony-creation.md](./ceremony-creation.md) | one place to start a key ceremony — how joining a subgroup's ceremony opened a second one for the parent room, the screen that showed a ceremony and offered to start one in the same button, and the removal of the nip30303 documents, whose kinds collided with the ceremony's, leaving the member chronicle with nothing to carry and nothing to say |
| [frost-batch-signing.md](./frost-batch-signing.md) | signing several events in one ceremony — why one nonce can never cover two messages, and the phased schema, wire and UI work that follows from it |
| [frost-session-resend.md](./frost-session-resend.md) | asking the members who never got a signing proposal to look again — why a proposer can repeat only what it wrote, why a member's availability signal needs no repeating, and the one half that has to come from the silent member's own device |
-| [frost-share-refresh.md](./frost-share-refresh.md) | giving every member a new share of the same group key, phased and not built — why enrollment cannot rotate a share, the zero-sum refresh that can, what a rotation protects against and the two things it never can, and re-enrollment as the repair that brings back the members a refresh left out |
+| [frost-share-refresh.md](./frost-share-refresh.md) | giving every member a new share of the same group key, phased and built behind a flag that is off in release — why enrollment cannot rotate a share, the zero-sum refresh that can, what a rotation protects against and the two things it never can, and re-enrollment as the repair that brings back the members a refresh left out |
+| [rotate-shares-single-approval.md](./rotate-shares-single-approval.md) | taking part is the only approval: a phased plan, built but for its device session, that makes a share rotation run by itself after a member agrees to take part. Covers the three asks a recipient gets today, why storing the new share was never a decision, the one key state for a new generation a device can sign without asking, and the abandon a member loses once nothing is left to approve |
| [marmot-membership.md](./marmot-membership.md) | how members join an MLS group, and the epoch race that makes a missing member look like a successful invite |
| [member-chronicle.md](./member-chronicle.md) | handing a member added after the work was done the group's signed record — why the events are not on the wire at all, and why the room's id is enough to verify them |
| [marmot-direct-messages.md](./marmot-direct-messages.md) | a one-to-one message inside a group as a stock NIP-59 gift wrap — what its MIP-03 carve-out costs, why the sender cannot read their own, and the one query that would broadcast it |
@@ -37,6 +38,7 @@ the [retired](./retired/) notes now.
| [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 |
| [member-admin-promotion.md](./member-admin-promotion.md) | making a member an admin and back, phased and built but for promotion with a share and demotion with a refresh, under three rules: every admin holds a share, every commit in a keyed room is a proposal until the group's threshold signature is on it, and a robust group keeps at least three admins. Covers why the commit rides inside the group's signature and the rule inside the group's state, which lets every device refuse an unsigned commit with the libraries as they are, why a member's own leave stays exempt, and why a removed admin comes back as an admin when re-invited today |
| [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 de05aa02..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"
@@ -514,7 +519,9 @@ decline. It means the device cannot vouch for the statement, so a person has to.
waits for that member's taps.
- **It does not automate signatures other than the key state.** A post, a
profile, a certificate for some other group, or anything in a batch is still
- asked about, exactly as today.
+ asked about, exactly as today. A share rotation's key state for its new
+ generation was automated later, by the same rule, in
+ [rotate-shares-single-approval.md](./rotate-shares-single-approval.md).
## Order and size
diff --git a/docs/frost-share-refresh.md b/docs/frost-share-refresh.md
index 2ba0b94a..3b158571 100644
--- a/docs/frost-share-refresh.md
+++ b/docs/frost-share-refresh.md
@@ -26,6 +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 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 |
@@ -48,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 |
@@ -477,18 +479,31 @@ 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.** Two, mirroring the ceremony's, with `pendingApproval` mirroring `advance`
-exactly:
+**Approval gates.** One, with `pendingApproval` mirroring `advance` exactly:
| step | publishes | why it is its own decision |
|---|---|---|
| `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 |
-| `CONFIRM` | CertEq | commits to the new generation. This is what stops a coordinator substituting a table the recipients never dealt |
-The proposer is auto-approved for nothing. Proposing a refresh is not agreeing to withhold
-whomever the form defaulted to.
+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, 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:
@@ -524,7 +539,9 @@ What a device does with a certificate, and when the old share goes.
- `frost_retired` per retired id.
It is signed under `g+1`, which makes it the first signature the new shares make: the proof
- D6 waits for.
+ D6 waits for. A recipient's device signs it without asking when it is exactly the state the
+ rotation it completed implies (`GroupKeyStateManager.vouchesForGeneration`,
+ [rotate-shares-single-approval.md](./rotate-shares-single-approval.md), Phase 5).
3. **`GroupKeyStateManager` changes, and the comment in `GroupKeyStateEvent.kt` (L84–87) gets
answered.**
- The comment expects that rotation would break `verifies()`. It does not: the *key* is
@@ -649,7 +666,7 @@ Under CLAUDE.md's rules:
Standing gets a text label, not only an icon, so the icon gets `Decorative`.
- **The refresh screen.** A progress ladder that names who it waits on, like the ceremony's,
- with the two approvals.
+ with its one approval (two as first built; see [rotate-shares-single-approval.md](./rotate-shares-single-approval.md)).
- The `DEAL` prompt lists who is withheld, and as what.
- The `CONFIRM` prompt is the ceremony's CertEq prompt in different words.
- **The copy has to tell the truth from [what it protects against](#what-a-refresh-protects-against-and-what-it-cannot).**
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
new file mode 100644
index 00000000..c4f154e4
--- /dev/null
+++ b/docs/rotate-shares-single-approval.md
@@ -0,0 +1,591 @@
+# Taking part is the only approval
+
+A plan to make a share rotation run by itself once a member has agreed to take
+part. The member decides one thing: whether to take part in this rotation, with
+these members withheld. Their device does everything after that. It deals its
+part, checks the combined result, stores the new share, confirms it, signs the
+group's new key state, and deletes the old share. **Abandon** stays, because the
+one stall automation cannot fix is a member who agreed and then went quiet.
+
+This is the same change [automatic-key-ceremony.md](./automatic-key-ceremony.md)
+made to the ceremony, applied to [frost-share-refresh.md](./frost-share-refresh.md).
+Read both first. This plan follows the first one's shape, because the reasoning
+is the same and so are most of the traps.
+
+**Built**, one commit per phase on `claude/rotate-shares-single-approval-338a7d`
+(`18f426ca` to the commit that adds this header), against `fc437d05`, on
+2026-11-20. Each recipient is now asked once and the proposer not at all:
+`ShareRefreshRitualJvmTest`'s `answerEverything` counts the asks, and they went
+from three per recipient to one. jvmTest 1250/1250, `compileDebugKotlinAndroid`, `m3Audit` at its budgets,
+the brand and wallet audits. 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 |
+|---|---|
+| Phase 1: three asks per recipient, the proposer included | two for the proposer. Its device proposes the key state, and a proposer's signature is its proposal. The pinned test said so, and Phase 4 took the proposer to none |
+| Phase 2: the fork test, two proposals with an overlapping recipient who confirms one | two proposals opened at once never reach the write-once rule. Each device refuses the second on arrival ("another refresh of this key is still running here"), and the refusals end both. The test asserts what matters, that the group never splits. The write-once rule keeps its own test, against the DAO, which never involved the gate |
+| Phase 2: a tampered sum fails on every honest recipient | it fails on every device, the coordinator included, through the FAILURE an honest recipient broadcasts. The coordinator used its own untampered sum and had confirmed |
+| Phase 3: rename `resumeRunningCeremonies` or widen its KDoc | widened. It now also runs `ShareRefreshManager.resumeRunning` and, from Phase 5, `FrostSigningManager.resumeVouched` |
+| Phase 4: `rotationPreview` runs the same selection as `proposeRefresh` | both call one private `ShareRefreshManager.plan`, which also carries the refusals that were `require`s. Those now throw `IllegalStateException` rather than `IllegalArgumentException`. The removal dialog names only the stale members, since its title already names the removed one |
+| Phase 5: re-check vouching in `resumeAt` and the sweep | one `approveIfVouched` behind all three: arrival, `resumeAt`, and `resumeVouched`. The sweep answers any key state the device can vouch for, a ceremony's included, through a new `getOpenUnansweredSessionsFor` |
+| Phase 5: path and parent match the room's signed state | the birth certificate is compared by event id, not JSON. No test has a signed generation-0 state to differ from, since the ritual harness's devices hold none, so the test breaks the path against rule 4 instead |
+| Phase 6: the running card shows who it waits on and since when, with an inline abandon past a day | always shown, with no threshold. Unlike a ceremony, a rotation has no screen of its own, so the card is the only place it can be seen at all. Abandon got a confirmation dialog, since the Shares section had none |
+| Phase 6: running until the key state is signed | while that signature is *open*. A key state nobody is asking for would otherwise read as one under way, forever |
+| 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.
+
+The headline: **a device asks its owner only for decisions it cannot make on
+its own.** Taking part is one of those decisions, because it agrees to the
+withheld list, and withholding someone takes their signing away. Storing the new
+share is not a decision. The device has already checked the combined result
+against the commitments and the table before it asks, and a person tapping
+**Approve** under "Store your new share" adds nothing to that check.
+
+---
+
+## What a member is asked today
+
+A rotation in a room whose key is `t`-of-`n`. Today every recipient is asked
+**three** times, not two. The third ask is easy to miss because it looks like an
+ordinary signing request rather than part of the rotation.
+
+| # | step | whose | today | after this plan |
+|---|---|---|---|---|
+| 1 | propose the rotation | proposer | **Rotate shares** button, no dialog, or the dialog after a removal | a dialog naming who takes part and who is withheld. Pressing it is the proposer's approval (R2) |
+| 2 | deal round 1 (`DEAL`) | every recipient, proposer included | Shares section row, *Take part in rotating the shares* | **unchanged: the one approval**. The row now names who is withheld |
+| 3 | sum round 1 (`cmsg1`) | coordinator | automatic | automatic |
+| 4 | check, store the pending generation, send CertEq (`CONFIRM`) | every recipient | Shares section row, *Store your new share* | automatic. If the check fails, the rotation fails and says so, as it does today |
+| 5 | certificate, activate `g+1` | coordinator, then every device | automatic | automatic |
+| 6 | propose the `g+1` key state | coordinator | automatic (`proposeGeneration`) | automatic |
+| 7 | sign the `g+1` key state | every recipient, `t` needed | signing approval, because `vouchesFor` rule 8 refuses any state with a generation (`fc437d05`) | automatic when the state is exactly the one this device's own completed rotation implies (Phase 5). Asked as today otherwise |
+| 8 | wipe generation `g` | every device | automatic once 7 is signed | automatic |
+| — | abandon | any recipient | only on a pending approval row | **kept**, and reachable for the whole run (Phase 6) |
+
+Today a recipient taps at rows 2, 4 and 7, and the proposer taps the button and
+then rows 2, 4 and 7 as well. After this plan a recipient taps once, and the
+proposer taps once.
+
+### Where the gates are
+
+| finding | where |
+|---|---|
+| G1. `advance` stops before round 1 until `dealApprovedAt` is set | `ShareRefreshManager.kt:391` |
+| G2. `advance` stops before round 2 until `confirmApprovedAt` is set | `ShareRefreshManager.kt:415` |
+| G3. `pendingApproval` mirrors G1 and G2, and must keep doing so | `ShareRefreshManager.kt:589-600` |
+| G4. The proposer is approved for nothing on proposal, by design | `ShareRefreshManager.kt:111-116`, asserted by `ShareRefreshRitualJvmTest` "nothing of a member's own goes out before they approve" |
+| G5. A rotation's key state is never vouched for: `vouchesFor` rule 8 | `GroupKeyStateManager.kt:659-660` |
+| G6. Vouching is decided once, on the proposal's arrival. A device that receives the `g+1` key state before its own rotation has activated `g+1` cannot vouch for it then, and nothing asks again | `FrostSigningManager.kt:447`, `resumeAt` at `:1945` |
+| G7. Nothing resumes a rotation except an arriving message. The sweep covers ceremonies only | `DatabaseNostrRepository.resumeRunningCeremonies` calls `ChillDkgRitualManager.resumeRunning` and nothing else |
+| G8. The Shares section shows `REFRESH_CONFIRM` as its own row, with its own string | `SharesSummary.kt:24`, `DatabaseChatRepository.kt:674`, `ChatRoomDetailScreen.kt:406`, `pending_rotation_confirm` |
+| G9. The only abandon button is on a pending approval row. Once a member has approved the last thing asked of them, they can no longer abandon a rotation stuck on somebody else | `ChatRoomDetailScreen.kt:413` |
+| G10. The `DEAL` row does not say who is withheld, which is the whole of what that approval decides | `ChatRoomDetailScreen.kt:399-410` |
+
+G9 is a bug today only in a narrow case: a member who has confirmed and is
+waiting on the certificate. Removing `CONFIRM` makes it the normal case. Every
+member who has taken part would have no way out of a stalled rotation, and
+`canRotate` stays false while one runs, so the group could not start another.
+Phase 6 is not optional.
+
+G10 is the same kind of gap. Once `DEAL` is the only approval, it carries all
+the weight of the decision, and today the row shows none of what is being
+decided.
+
+---
+
+## Why `CONFIRM` was never a decision
+
+`ShareRefreshApprovalStep.CONFIRM`'s KDoc gives two reasons for the gate. Neither
+needs a person.
+
+- **"This is what stops a coordinator substituting a table the recipients never
+ dealt."** The check that stops it is `FrostRefresh.participantStep2`. It
+ decrypts and sums the dealt values, runs the Feldman check against the
+ commitments, recomputes every public share, and checks the new share against
+ its public share and the table against the threshold key. It runs before the
+ prompt appears, whatever the person does. A substituted table fails there and
+ the rotation fails out loud (`raiseIfFaulty`, `fail`, FAILURE). It never
+ reaches the prompt. The prompt shows nothing the person could check
+ themselves.
+- **"The one confirmation per base generation this device will ever give."** The
+ write-once claim is `ShareRefreshConfirmation`, taken in the same transaction
+ as the `PENDING` row (`confirmAndStore`). It holds whether or not a person
+ tapped. A second refresh from the same base is refused by the database, not by
+ the owner.
+
+The only thing a person could do at `CONFIRM` that the device cannot is change
+their mind. Abandon still covers that, from the whole run once Phase 6 lands.
+
+The same argument covers the key state at row 7. For a rotation this device
+completed, the new generation's public-share table, the refresh id and the
+retired ids are all facts the device holds and has checked against the
+certificate. Exactly one key state can be true. If the proposal matches it, a
+person has nothing to add. That is the rule automatic-key-ceremony.md Phase 0.5
+set for the ceremony's own key state. `fc437d05` kept rotation states out of it
+because they say more than a ceremony does. Phase 5 adds the rule for what they
+say.
+
+---
+
+## Phase 0: decisions
+
+**An hour. Each has a recommendation.**
+
+**Decided 2026-11-20: all six as recommended.** Execution began the same day.
+
+| # | question | recommendation | if decided otherwise |
+|---|---|---|---|
+| R1 | What does taking part consent to? | **The whole rotation.** `dealApprovedAt` keeps its column and name and now means "agreed to take part, with these members withheld". The member is not asked about this rotation again, and neither is the signature on its key state when that state is exactly what the rotation implies | Keep row 7 asked. A rotation still needs `t` taps after the certificate before the old shares are wiped, and in the meantime the old shares stay on every device |
+| R2 | Is proposing the proposer's approval? | **Yes, once the proposal is a dialog that names who takes part and who is withheld, stale members included.** The reason the proposer is asked today is that "proposing is not agreeing to withhold whomever the form defaulted to". The fix for that is a form that shows its defaults. Asking again afterwards does not fix it | The proposer taps twice: the button, then the row. Harmless, but it is the same decision twice |
+| R3 | Anything new on the wire? | **No.** Kinds 30340-30345, the tags and the ordering stay. A Giza build from before this change keeps its gates, and a rotation that includes it finishes when that member taps, as today. Rotation is behind `ExperimentalFeatures.shareRefresh`, off in release, so no shipped build is affected | — |
+| R4 | The schema | **No migration.** `confirmApprovedAt` stays, unread, with KDoc saying earlier builds wrote it. `ShareRefreshApprovalStep.CONFIRM` stays in the enum because `approvalRequestedThrough` stores it by name on rows already written. This matches automatic-key-ceremony.md Phase 0.3 | Drop both in a schema bump: a migration and a migration test for two nullable values nothing reads |
+| R5 | Bindings (10b) | **Still asked.** A key state that adds a `frost_member` binding re-binds an id to a new identity. That is governance, not arithmetic, and `fc437d05` was right to keep it asked. Phase 5 vouches only for a state whose bindings are exactly the ones already signed for that generation, which right after a rotation means none | — |
+| R6 | A timer that abandons by itself? | **No**, as in the ceremony. The Shares section says who the rotation is waiting on and since when. Whether that is too long is for the group to judge | — |
+
+---
+
+## Phase 1: pin today's gates
+
+**Two hours. Do this before changing anything.**
+
+`ShareRefreshRitualJvmTest` already has the multi-device harness (`devicesFor`,
+`pump`, `approveAll`, `approveSigning`). What it lacks is a test that says where
+the gates are. `approveAll` approves "whatever they are asked, until nobody is
+asked anything", which passes whatever the gates are.
+
+Add, against today's behaviour:
+
+- **today's gates, pinned:** propose in a 2-of-3. Every recipient approves
+ exactly once (`DEAL`), then `pump` until quiet. Every recipient is at
+ `pendingApproval == CONFIRM`, nobody has a `PENDING` generation, and the
+ outbox holds round 1 and `cmsg1` and nothing more. Phase 2 flips this
+ assertion, and that flip is the change.
+- **the key state, pinned:** run a rotation to COMPLETE with `approveAll`, then
+ `pump`. The `g+1` key-state session is open and awaiting approval on every
+ recipient, and generation `g` is still `RETIRING`, not `WIPED`. Phase 5 flips
+ this one.
+- **counted asks:** a helper `asksOf(device)` that counts the
+ `TYPE_SHARE_REFRESH_APPROVAL_NEEDED` lines plus signing approval lines a device
+ wrote for one rotation. Today it is 3 per recipient. Phases 2, 4 and 5 take it
+ to 1.
+
+---
+
+## Phase 2: the manager stops at taking part and nowhere else
+
+**Half a day. Closes G1 to G3.**
+
+In `ShareRefreshManager`:
+
+- **`advance`** loses the `confirmApprovedAt` block (`:415-418`). The `DEAL`
+ gate at `:391` stays and gets a comment: it is now the only gate. The steps
+ after it are already idempotent. `ownMessage(ROUND_2)` guards the send, and
+ `confirmAndStore` is idempotent for the session that holds the claim. Removing
+ the gate adds no path. It only stops cutting the existing one short.
+- **`pendingApproval`** becomes:
+
+ ```kotlin
+ if (session.stage == COMPLETE || session.stage == FAILED) return null
+ // ...key, base, myId as now...
+ if (myId !in session.recipientIdList()) return null
+ return if (session.dealApprovedAt == null) ShareRefreshApprovalStep.DEAL else null
+ ```
+
+ It is still "a step is pending exactly when `advance` would stop at it", which
+ is now easy to see.
+- **`approve`** acts on `DEAL` only. A `CONFIRM` approval from a screen left open
+ across the upgrade cannot arrive any more (`pendingApproval` never returns
+ it), but the `when` keeps the arm as a logged no-op so the enum stays
+ exhaustive.
+- **`announceApprovalNeeded`** only ever receives `DEAL`. The `CONFIRM` arm of
+ its `when` stays with a one-line comment saying nothing reaches it, so nobody
+ takes it for live wording.
+- **KDoc.** The object's KDoc (`:63-64`, "at two gates") and
+ `ShareRefreshApprovalStep`'s become the record of what a rotation has *ever*
+ asked: one step still asked, one kept so old rows decode. Move the reasoning in
+ [Why `CONFIRM` was never a decision](#why-confirm-was-never-a-decision) into
+ the `CONFIRM` KDoc, so the next reader does not put the gate back.
+ `ShareRefreshSession.confirmApprovedAt` gets "written by builds before
+ docs/rotate-shares-single-approval.md; read by nothing".
+
+A round-2 fault keeps the failure path it has today: `raiseIfFaulty`, `fail`,
+broadcast FAILURE. The difference is that it can now happen with nobody looking.
+The transcript's *ended* line already covers that, and Phase 6 puts it in the
+Shares section too.
+
+**Tests**, in `ShareRefreshRitualJvmTest`:
+
+- Phase 1's pinned assertion, flipped: each recipient approves once and every
+ device reaches COMPLETE at generation `g+1`, with no other call;
+- `pendingApproval` never returns `CONFIRM`, sampled after every `pump` pass;
+- the last recipient to approve sends round 1, and on the next pass round 2
+ goes out with no further call;
+- a coordinator that substitutes `cmsg1` in transit (the harness tampers with it)
+ fails the rotation on every honest recipient, with no approval in between, and
+ nobody holds a `PENDING` generation. This was always the protection, and the
+ test shows it no longer depends on a person;
+- **the fork rule still holds without a person:** two proposals from one base,
+ both approved at `DEAL` by an overlapping recipient. That recipient confirms
+ one and fails the other, and at most one certificate exists. This is the
+ existing "a device confirms one refresh per generation" test, run with the
+ confirm gate gone. If it needed the gate to pass, the gate was carrying D3a,
+ and that has to be found now;
+- "nothing of a member's own goes out before they approve" passes unchanged
+ (until Phase 4 changes the proposer's half of it).
+
+---
+
+## Phase 3: running rotations resume without a message
+
+**Half a day. Closes G7. Ships with Phase 2.**
+
+With the `CONFIRM` tap gone, a rotation paused at `CONFIRM` by the old build has
+`cmsg1` stored, is waiting on its own round 2, and will receive no more messages.
+Without a sweep it never moves.
+
+```kotlin
+/**
+ * Moves every running rotation of this user's as far as its stored messages
+ * allow. What a tap on "Store your new share" used to do, for rotations that
+ * already have everything they need and will receive nothing more.
+ */
+suspend fun resumeRunning(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray): Int
+```
+
+- **What it selects:** a new `ShareRefreshDao.getRunningSessionsFor(userPublicKey)`,
+ sessions not COMPLETE or FAILED, oldest first. It does **not** filter on
+ `dealApprovedAt`. A coordinator waiting on others' round 1 and a withheld
+ device waiting on the certificate also have work a sweep can finish, and
+ `advance` stops at the `DEAL` gate for anyone not yet approved.
+- **What it calls:** for each, look up the room (skip a gone room with a warning)
+ and `advance`. `advance` already returns at its first missing input.
+- **Where it is wired:** `DatabaseNostrRepository.resumeRunningCeremonies`, after
+ `ChillDkgRitualManager.resumeRunning`, under the same `storeNostrEventMutex`.
+ Rename it to `resumeRunningRituals` while there, or leave the name and widen
+ its KDoc. It runs from `SynchronizationViewModel` once the live subscription is
+ open, so anything it publishes goes into a pipeline that is already running.
+- **Behind the flag.** With `ExperimentalFeatures.shareRefresh` off it resumes
+ nothing. A release build has no rotations to resume. If one somehow exists, it
+ was refused on arrival.
+
+The same sweep covers the second half of G6 for upgrades. A `g+1` key-state
+session that an old build left awaiting approval is re-checked against
+`vouchesFor` (Phase 5). That part lands with Phase 5, which owns the rule.
+
+**Tests:**
+
+- **the upgrade case:** a session with `cmsg1` stored, `dealApprovedAt` set,
+ `confirmApprovedAt` null, `approvalRequestedThrough = CONFIRM`, which is
+ exactly what the old build leaves. Run the sweep with no message arriving. It
+ publishes round 2, and on the harness the rotation completes;
+- a session never approved at `DEAL` is advanced but sends nothing;
+- a FAILED or COMPLETE session is not touched;
+- two sweeps in a row publish nothing twice;
+- with the flag off, the sweep does nothing.
+
+---
+
+## Phase 4: proposing is the proposer's approval
+
+**Half a day. Closes G4. Only if R2 is decided as recommended.**
+
+The proposer is asked today because the button commits them to a withheld list
+they were never shown. The fix is to show it.
+
+- **A dialog behind *Rotate shares*.** `AlertDialog` in `ChatRoomDetailScreen`,
+ in the style of the existing `rotate_shares_without_*` dialog. It shows:
+ - *Taking part*: every live member's name;
+ - *Left out until they are brought back*: every stale member, who
+ `proposeRefresh` withholds again automatically (`:139-143`). Today the
+ proposer never sees this list;
+ - the existing `shares_rotation_caveat` copy;
+ - confirm **Rotate shares**, dismiss **Not now**.
+
+ It reads from a new `ChatRepository.rotationPreview(localChatRoom)` that runs
+ the same selection `proposeRefresh` does, and `refusal`, so a rotation that
+ would be refused says why before the tap rather than as a snackbar after it.
+ `proposeRefresh` and the preview share one private function for the
+ recipient/withheld split, so they cannot drift.
+- **The removal dialog** (`rotate_shares_without_body`) gains the same stale list
+ when there is one. The removed member is already named.
+- **`proposeRefresh`** sets `dealApprovedAt = now` on the session it creates. The
+ KDoc at `:111-116` becomes: proposing, from a dialog that named everyone
+ withheld, is agreeing to the rotation, and the proposer is not asked again.
+ `proposeWithout` inherits it.
+- **The repository API** keeps `rotateShares(localChatRoom)`. The dialog is where
+ the decision is shown, and the manager does not need to know a dialog exists.
+
+Strings go in `strings.xml`, sentence case: `rotation_taking_part`,
+`rotation_left_out_until_brought_back`, `not_now` if not already there.
+
+**Tests:**
+
+- the proposer's half of "nothing of a member's own goes out before they
+ approve" flips. The proposer publishes the proposal and its round 1 in the one
+ `proposeRefresh` call, and writes no approval-needed line. The other
+ recipients' half is unchanged;
+- `rotationPreview` and `proposeRefresh` agree on recipients and withheld for
+ every fixture: 0, 1 and 2 stale, and a retired member;
+- a preview of a rotation that `refusal` rejects carries the reason and no
+ recipients.
+
+---
+
+## Phase 5: a rotation's key state signs itself
+
+**A day. Closes G5 and G6.**
+
+`GroupKeyStateManager.vouchesFor` signs exactly one statement per room: the key
+state of a ceremony this device finished. Rule 8 (`fc437d05`) keeps every
+generation state out. This phase replaces rule 8 with the rule for the one
+generation state that can be true.
+
+**The rule.** For a claim with `generation = h ≥ 1`, rules 1 to 6 stand as they
+are. Rules 7 and 8 become:
+
+7. **No state for this room is signed here at generation `h` or later.** This
+ replaces "no state at all", which would refuse every rotation, since a room
+ that rotates already has a generation-0 state.
+8. **This device completed the rotation that made `h`:**
+ - `KeyShareGeneration(key, h)` exists here, is `ACTIVE`, and holds a secret
+ share. A device withheld from `h` cannot sign at `h` anyway, and should not
+ vouch for a table it did not help make;
+ - its `refreshSessionId` equals the claim's `frost_refresh`, and that
+ `ShareRefreshSession` is COMPLETE here;
+ - the claim's `frost_pubshares` equals
+ `ShareGenerations.publicSharesHash(` that row's `publicShares` `)`;
+ - the claim's `frost_retired` ids equal the ids `RETIRED` in this device's
+ roster at `h`;
+ - the claim's bindings equal the bindings already in a group-signed state at
+ `h` on this device. Right after a rotation that is none. A state that adds
+ a binding is a 10b re-bind and stays asked (R5);
+ - the signing session's `generation` is `h`.
+9. **Path and parent match the room's signed state**, not only the admin path.
+ `proposeGeneration` copies them from `keyStateFor`, so a claim whose path or
+ birth certificate differs from what the room already signed is not the one
+ true statement.
+
+Each condition calls what already exists (`claimFrom`, `stateAmong`,
+`ShareGenerations.publicSharesHash`, the key-share DAO). None of it is copied,
+for the reason automatic-key-ceremony.md Phase 7 gives: the rule for signing and
+the rule for keeping must be one function.
+
+**Asking again when the answer can change (G6).** Vouching is decided once, when
+the proposal arrives (`FrostSigningManager.kt:447`). For a rotation that is
+often too early. The coordinator proposes the `g+1` state the moment its own
+certificate verifies, and a recipient can receive the proposal before the
+certificate, while `h` is still `PENDING` here. Two changes:
+
+- `FrostSigningManager.resumeAt(database, room, dkgSessionId, generation)`,
+ which `ShareRefreshManager.advance` already calls after `activate`, runs
+ `signsAsItsOwnKeyState` on each open session at that generation before
+ advancing it, and approves the ones it vouches for;
+- Phase 3's sweep does the same for open key-state sessions, for the upgrade
+ case: a session an old build left asking.
+
+`signsAsItsOwnKeyState` already refuses a session that has been approved or
+declined, so a person who answered first keeps their answer.
+
+**What stays asked.** Anything that fails a check takes the normal path: the
+approval line, the proposal, the member's decision. Failing a check is not a
+reason to decline. It means the device cannot vouch for the statement, so a
+person has to. That includes a key state proposed by a member whose rotation
+this device never saw. That should not happen, and if it does, a person should
+look.
+
+**Tests**, in `ShareRefreshRitualJvmTest` and `KeyStateSignsItselfJvmTest`:
+
+- Phase 1's key-state assertion, flipped: each recipient approves `DEAL` once.
+ With no other call, the group signs the `g+1` key state, every device wipes
+ generation `g`, and the group signs at `g+1` as the same room. `asksOf` is 1
+ per recipient (0 for the proposer after Phase 4);
+- **the race:** the proposal for the `g+1` state is delivered before the
+ certificate. It is not vouched for on arrival, and is vouched for when the
+ certificate activates `h`;
+- each check broken on its own leaves the session at `isAwaitingApproval`:
+ - a different `frost_pubshares`;
+ - a `frost_refresh` naming a rotation this device did not complete;
+ - a retired id added or missing;
+ - a new binding (the 10b test's re-bind state stays asked, so its
+ `approveSigning(listOf(alice, bob))` call is still needed);
+ - a session at generation `h−1`;
+ - a device withheld from `h`;
+ - a room already holding a signed state at `h`;
+ - a path or parent that differs from the room's signed state;
+- `fc437d05`'s regression stays covered: a generation-1 state on devices that
+ hold no first state still needs every rule to pass, and is asked when one
+ fails;
+- every existing `KeyStateSignsItselfJvmTest` case passes unedited for
+ generation-0 states.
+
+---
+
+## Phase 6: the Shares section, with one approval
+
+**A day. Closes G8 to G10.**
+
+Under CLAUDE.md's rules: strings in the catalogue in sentence case, spacing and
+colour from the theme, outcomes through `rememberNotifier`, `Decorative` on any
+icon whose label sits beside it.
+
+**The approval row says what it decides (G10).**
+
+- `SharesSummary.PendingApproval` gains `withheld: List`, each with a
+ display name and `STALE` or `RETIRED`, filled in by
+ `DatabaseChatRepository.sharesSummary` from the session's `withheldStandings()`.
+- The `REFRESH_DEAL` row's headline becomes *Take part in rotating the shares*,
+ as now. Its `supportingContent` becomes one of:
+ - *Every member takes part.*
+ - *Without Alice until they are brought back, and without Bob for good.* Built
+ from format arguments, not concatenation, with a plural-safe form for one
+ name or several.
+ - A line on what taking part now commits to: *Your device sends its part,
+ stores your new share and signs the group's new key state without asking
+ again.*
+- The row keeps **Abandon** and **Approve**.
+
+**`REFRESH_CONFIRM` goes (G8).** The enum value in `SharesSummary.PendingApproval.Kind`
+is UI state only, so it is removed outright, along with its arm in
+`sharesSummary` and `approveShares` and the `pending_rotation_confirm` string.
+Run `m3-extract-strings.py --list` afterwards to catch any other orphans.
+
+**A running rotation is visible, and can be abandoned, for its whole run (G9).**
+
+- `SharesSummary` gains `running: Running?`, with the session id, the stage in
+ words (*dealing*, *storing the new shares*, *signing the new key state*), the
+ members it is waiting on, the time of the newest `ShareRefreshMessage` for the
+ session, and `canAbandon` (this device is a recipient). The rotation counts as
+ running until the `g+1` key state is signed, not only until the certificate,
+ because that signature is what the old shares wait on.
+- "Waiting on" comes from stored rows: recipients with no round 1, then no round
+ 2, then the coordinator's sum or certificate, then the key-state session's
+ missing signers. The stall clock is dated from the newest message, not the
+ newest transcript line, for the reason automatic-key-ceremony.md's build table
+ gives: `ShareRefreshManager.record` must store a message once, on first
+ arrival. Check that it does (`:343-344` upserts on every redelivery, which
+ rewrites the row) and fix it the way `ChillDkgRitualManager.record` was fixed.
+- The Shares section shows it as a card above the members: *Rotating the
+ shares*, the stage, *Waiting on Carol since yesterday*, and **Abandon** when
+ `canAbandon`, behind the existing confirmation. It sits above the member list
+ because a stall is the most important thing in the section when there is one.
+- A rotation that ended shows its reason from `failureReason` until the next one
+ starts, so a fault found with nobody looking is not lost in the transcript.
+
+**The transcript** needs no code change. Check it rather than assume it.
+`CONFIRM` approval-needed lines already written by the old build still render,
+and the automatic round 2 writes the same `TYPE_SHARE_REFRESH_CONFIRMED` line a
+tapped one did. Each device now writes one approval-needed line per rotation
+instead of two.
+
+**Tests:**
+
+- a `SharesSummary` test that the `DEAL` row carries the withheld list, and that
+ no `REFRESH_CONFIRM` kind exists;
+- `running` names the right members at each stage, including the key-state
+ stage after the certificate;
+- `canAbandon` is true for a recipient who has already approved, and false for a
+ withheld member;
+- a redelivered round 1 does not move the stall clock;
+- `./gradlew :composeApp:m3Audit` at its budgets, floors not moved.
+
+---
+
+## Phase 7: the record, and three emulators
+
+**Half a day of docs, then a device session.**
+
+- **frost-share-refresh.md**: Phase 7's *Approval gates* table shrinks to one
+ row, with a short history of `CONFIRM` (why it existed, why it went, why the
+ enum value and column remain). Phase 8's step 2 says the key state signs itself
+ under the rule in this plan's Phase 5. Phase 11's bullet *the two approvals*
+ becomes one. The build table gains a row pointing here.
+- **automatic-key-ceremony.md**, *What this does not do*: "It does not automate
+ signatures other than the key state" gains "a rotation's key state is
+ automated too, by rotate-shares-single-approval.md".
+- **README.md**: this note's row, and frost-share-refresh.md's row, which still
+ says "not built" although it is.
+- **This note**: a *Built* header and a table of where the build chose
+ differently.
+
+**On three emulators** (Bob, Charlie, Medium), a debug build so the flag is on:
+
+1. A 2-of-3 room. Bob presses **Rotate shares** and confirms the dialog. Charlie
+ and Medium each tap **Approve** once. Nobody touches anything else. All three
+ show generation 1, and the transcript shows the key state signed and no
+ second approval line.
+2. Remove Medium. Bob rotates without them from the dialog. Charlie taps once.
+ Medium's standing is *retired*.
+3. **The upgrade:** on the current build, stop a rotation at *Store your new
+ share* on all three, install this build over it, and open the app. It should
+ finish from the sweep alone.
+4. Charlie approves and then force-stops the app. Bob's and Medium's Shares
+ section name Charlie and how long they have been waiting, and **Abandon**
+ ends the rotation on all three.
+
+`./gradlew check` must pass: `m3-audit`, `brand-audit`, `wallet-audit`.
+
+---
+
+## What this does not do
+
+- **It does not run while the app is closed.** The live subscription is
+ foreground-only ([long-running-sync.md](./long-running-sync.md)). After
+ approving, each member's device still has to be opened once the others have
+ dealt, again once the coordinator has summed, and again for the key state.
+ What changes is that opening the app is enough.
+- **It does not change the protocol.** Every recipient still has to take part
+ (D2), the majority and write-once rules (D3) still hold, and the old share is
+ still wiped only after the group signs the new generation (D6). This plan only
+ changes who presses what.
+- **It does not change older peers.** A build from before this change still asks
+ at both gates, and a rotation that includes one waits for that member's taps.
+ D5's capability check is still unbuilt, so nothing tells the proposer in
+ advance.
+- **It does not automate repair.** A helper's approval in a repair (10a) spends
+ its share's secrecy on the target's behalf. That is a decision about someone
+ else, and stays asked.
+- **It does not automate re-binding an id to a new identity** (10b, R5).
+- **It does not add a way to decline.** A member who does not want to take part
+ abandons, which ends the rotation for everyone. A rotation cannot finish
+ without every recipient, so a quiet "no" and a loud one end the same way. The
+ loud one is just faster.
+
+## Order and size
+
+| phase | size | depends on |
+|---|---|---|
+| 0 decisions | an hour | — |
+| 1 pin today's gates | two hours | — |
+| 2 manager: one gate | half a day | 1 |
+| 3 resume sweep | half a day | 2 |
+| 4 proposing is approving | half a day | 2, R2 |
+| 5 the key state signs itself | a day | 2 |
+| 6 Shares section | a day | 2, 5 (for the key-state stage) |
+| 7 docs, emulators | half a day plus a session | all |
+
+**Phases 2 and 3 ship together.** With 2 and without 3, a rotation paused by the
+old build at *Store your new share* sits still until a message happens to
+arrive. **Phase 6's abandon card ships with Phase 2 or before it.** Without it, a
+member who has approved has no way to end a stalled rotation (G9). Phases 4 and 5
+are independent of each other and can land in either order. Everything is behind
+`ExperimentalFeatures.shareRefresh`, so no phase changes a release build.
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