feat: a keyed room switches on the group's signature by itself

Requiring the group's signature for changes was a button an admin had
to find on the room's screen. Nothing about it was a decision: the two
conditions it waits on -- every member's device can follow, enough of
them are admins -- were already checked in code. The button is gone.

One device switches it on: the admin in the room's lowest leaf, which
in a room as made is its creator (GovernanceSupport.switcherOf). Not
every admin's, because two commits at one epoch are not settled for
their authors (docs/marmot-v2.md, Phase 8); every device reads the same
leaf, so they agree on one without talking. GovernanceFollowThrough
runs the switch whenever a member says it follows signed commits, and
on start.

Not at creation: a Bennu or older-Giza founder would be cut off without
anyone knowing, and a founding invite finished later is a bare commit a
governed room refuses. The room switches seconds after its founders
join instead. The screen names whose device it is waiting on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-20 09:16:22 +02:00
1 parent 469c5632c7
commit 950ed24756
12 files changed
+236 -34

No files matched your search

@@ -125,7 +125,8 @@
<string name="make_admin_and_leave">Make admin and leave</string>
<string name="disband_group_instead">Disband group instead</string>
<string name="governance_on">Changes to who is in this group need the group's signature. It always keeps at least %1$d admins.</string>
<string name="require_signatures">Require the group's signature for changes</string>
<string name="governance_switching">Turning on the group's signature for changes.</string>
<string name="governance_switch_waits_for">Changes will need the group's signature as soon as %1$s's Giza is next online.</string>
<string name="require_signatures_explainer">From then on, adding or removing a member, or changing who the admins are, is proposed and has to be signed by the group before it happens.</string>
<string name="governance_waiting">Waiting for %1$s to open an up-to-date Giza. Until then, this group can't require its signature on changes, and nobody else can be made an admin.</string>
<string name="make_admin_body_keyed">They'll be asked to accept, then the group signs it, and they'll hold a share of the group's key and be asked to approve its changes.</string>
@@ -135,7 +136,6 @@
<string name="accept">Accept</string>
<string name="promotion_accepted">Accepted; the group signs it next</string>
<string name="change_proposed">Proposed; it happens once the group signs it</string>
<string name="require_signatures_sent">Sent; changes will need the group's signature once a relay accepts it</string>
<string name="stepping_down_to_leave">Stepping down; you'll leave once a relay accepts it</string>
<string name="remove_from_group">Remove from group</string>
<string name="disband_group">Disband group</string>
@@ -1079,7 +1079,7 @@ abstract class MarmotOutboundDao(
if (GovernanceGate.isGoverned(group)) return
val missing = GovernanceSupport.missing(database, roomId, group)
if (missing.isNotEmpty()) {
throw IllegalStateException("Waiting for ${missing.map { memberName(it) }.sorted().joinToString()} to update Giza")
throw IllegalStateException("Waiting for ${missing.map { memberName(it) }.sorted().joinToString()} to open an up-to-date Giza")
}
val floor = AdminGovernance.adminFloor(database, roomId, group)
val admins = group.currentAdminIdentities() intersect AdminGovernance.members(group)
@@ -723,7 +723,7 @@ class DatabaseChatRepository(
GovernanceGate.minimumAdmins(group)?.let { return GovernanceStatus.Governed(it) }
if (room.chatRoom.leftGroupAt == null) GovernanceSupport.announce(database, chatRoomId, group, room.chatRoom.userPublicKey)
val missing = GovernanceSupport.missing(database, chatRoomId, group)
return if (missing.isEmpty()) GovernanceStatus.Ready(AdminGovernance.adminFloor(database, chatRoomId, group))
return if (missing.isEmpty()) GovernanceStatus.Ready(AdminGovernance.adminFloor(database, chatRoomId, group), GovernanceSupport.switcherOf(group))
else GovernanceStatus.Waiting(missing)
}
@@ -11,6 +11,7 @@ import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.conflate
import mobi.giza.compose.ExperimentalFeatures
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
import mobi.giza.compose.nostr.frost.GovernanceSupportEvent
import mobi.giza.compose.nostr.frost.PromotionEvents
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
@@ -37,7 +38,11 @@ object GovernanceFollowThrough {
suspend fun observe(database: GizaDatabase, keyPair: KeyPair) {
combine(
database.governanceProposalDao().observeAll(),
database.marmotInnerEventDao().observeCountByKinds(listOf(PromotionEvents.OFFER, PromotionEvents.ACCEPT, PromotionEvents.HANDOVER)),
// A member saying their device follows signed commits may be the last one
// a room was waiting on before its rule can be switched on.
database.marmotInnerEventDao().observeCountByKinds(
listOf(PromotionEvents.OFFER, PromotionEvents.ACCEPT, PromotionEvents.HANDOVER, GovernanceSupportEvent.KIND)
),
database.groupSignedEventDao().observeByKind(GroupKeyStateEvent.KIND),
) { _, _, _ -> Unit }
.conflate()
@@ -55,8 +60,11 @@ object GovernanceFollowThrough {
/** One pass over everything owed. */
suspend fun pass(database: GizaDatabase, keyPair: KeyPair) = mutex.withLock {
rotationsOwed(database).forEach { proposal -> rotateAway(database, keyPair, proposal) }
if (!ExperimentalFeatures.shareRefresh) return@withLock
val me = keyPair.pubKey.toHexKey()
// A keyed room's rule, switched on once every member can follow it, by the one
// device whose it is to switch. docs/remove-convenient-groups.md, "After the build".
GovernanceSupport.switchWhereOwed(database, me)
if (!ExperimentalFeatures.shareRefresh) return@withLock
val privateKey = keyPair.privKey ?: return@withLock
// Phase 8, the device that offered: an accepted offer is proposed for the
@@ -1,14 +1,20 @@
package mobi.giza.compose.managers
import co.touchlab.kermit.Logger
import com.vitorpamplona.marmot.groups.currentAdminIdentities
import com.vitorpamplona.marmot.groups.currentGroupState
import com.vitorpamplona.mls.group.MlsGroup
import com.vitorpamplona.mls.tree.Credential
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import kotlinx.coroutines.CancellationException
import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
import kotlin.time.Clock
import kotlin.time.Instant
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.nostr.MarmotProfile
import mobi.giza.compose.database.model.MarmotInnerEvent
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.nostr.frost.GovernanceSupportEvent
/**
@@ -18,6 +24,9 @@ import mobi.giza.compose.nostr.frost.GovernanceSupportEvent
* The rule cannot be switched on while anybody in the room would be left behind
* by it: a device that does not know it applies the bare commits Giza drops and
* reads none of the envelopes, and is in a different group from the first change.
* Once everybody has, one device switches the rule on by itself ([switchWhereOwed]);
* nobody opens a screen or presses anything.
*
* So each device says, once per room, that it can follow: when it is welcomed in,
* when it starts, when the room's screen is opened, and back when it hears another
* say it.
@@ -89,5 +98,74 @@ object GovernanceSupport {
}
}
/**
* The one device that switches [group]'s rule on: the admin in its lowest leaf --
* in a room as it was made, its creator. Null when no admin holds a leaf.
*
* One, because the library settles two commits made at the same epoch for every
* device that only watched them, but not for the two that made them: those swap
* branches and stay apart (docs/marmot-v2.md, Phase 8). Every admin switching the
* moment the last member said it would be exactly that race. The lowest leaf is
* read off the group's state, so every device names the same one without a word
* between them.
*/
fun switcherOf(group: MlsGroup): HexKey? {
val admins = group.currentAdminIdentities()
return group.members()
.sortedBy { (leafIndex, _) -> leafIndex }
.firstNotNullOfOrNull { (_, leaf) ->
(leaf.credential as? Credential.Basic)?.identity?.toHexKey()?.takeIf { it in admins }
}
}
/**
* Whether this device owes [room] the switch now: a keyed room on the current
* profile, open, not yet requiring the group's signature, whose [switcherOf] is
* this device's account, where every member has said they follow signed commits
* and enough of them are admins. The checks `requireSignatures` makes, read first
* so a room that is not ready is passed over rather than refused.
*/
suspend fun switchOwed(database: GizaDatabase, room: LocalChatRoom, group: MlsGroup): Boolean {
val me = room.chatRoom.userPublicKey
if (room.chatRoom.leftGroupAt != null || room.chatRoom.marmotProfile() != MarmotProfile.CURRENT) return false
if (!AdminGovernance.isKeyedRoom(group) || GovernanceGate.isGoverned(group)) return false
if (group.currentGroupState().isDisbanded) return false
if (switcherOf(group) != me) return false
if (missing(database, room.chatRoom.id, group).isNotEmpty()) return false
val admins = group.currentAdminIdentities() intersect AdminGovernance.members(group)
return admins.size >= AdminGovernance.adminFloor(database, room.chatRoom.id, group)
}
/**
* Switches the rule on in every room of [me]'s that is owed it -- [switchOwed] --
* saying first, where it has not, that this device follows signed commits, since
* it is a member too. Run by `GovernanceFollowThrough` whenever a member says it,
* and when it starts, so the switch needs nobody to open a screen or press
* anything. A switch still waiting for a relay is not sent twice; one that fails
* is logged and tried again on the next pass.
*
* @return how many rooms a switch was sent in.
*/
suspend fun switchWhereOwed(database: GizaDatabase, me: HexKey): Int =
database.chatRoomDao().getChatRoomIdsWithMlsState().count { chatRoomId ->
runCatching {
val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return@runCatching false
if (room.chatRoom.userPublicKey != me) return@runCatching false
val engine = database.marmotEngine
val group = engine.groupFor(room.routingId) ?: return@runCatching false
if (switcherOf(group) != me) return@runCatching false
announce(database, chatRoomId, group, me)
if (!switchOwed(database, room, group)) return@runCatching false
if (!engine.gate.canPrepareLocalCommit(room.routingId)) return@runCatching false
database.marmotOutboundDao().requireSignatures(room)
logger.i("Switched on the group's signature for changes in $chatRoomId")
true
}.getOrElse {
if (it is CancellationException) throw it
logger.w("Couldn't switch on the group's signature in $chatRoomId: ${it.message}")
false
}
}
private val logger = Logger.withTag("GovernanceSupport")
}
@@ -88,7 +88,6 @@ import mobi.giza.compose.ui.theme.spacing
import mobi.giza.compose.resources.couldn_t_leave_the_group
import mobi.giza.compose.resources.admin_change_requested
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.resources.admin_offer_sent
import mobi.giza.compose.resources.promotion_accepted
@@ -244,7 +243,6 @@ fun ChatRoomDetailScreen(
val couldNotLeave = stringResource(Res.string.couldn_t_leave_the_group)
val adminChangeRequested = stringResource(Res.string.admin_change_requested)
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 adminOfferSent = stringResource(Res.string.admin_offer_sent)
val promotionAccepted = stringResource(Res.string.promotion_accepted)
@@ -1188,11 +1186,7 @@ fun ChatRoomDetailScreen(
governance = governance,
canGovern = chatRoomDetailUIState.canGovern,
nameOf = nameOf,
onRequireSignatures = {
chatRoomDetailViewModel.requireSignatures(chatRoomDetailUIState.localChatRoom) { failure ->
notify(failure ?: requireSignaturesSent)
}
},
me = chatRoomDetailUIState.localChatRoom.chatRoom.userPublicKey,
)
}
}
@@ -34,7 +34,8 @@ import mobi.giza.compose.resources.cancel
import mobi.giza.compose.resources.disband_group_instead
import mobi.giza.compose.resources.governance_on
import mobi.giza.compose.resources.governance_waiting
import mobi.giza.compose.resources.require_signatures
import mobi.giza.compose.resources.governance_switch_waits_for
import mobi.giza.compose.resources.governance_switching
import mobi.giza.compose.resources.require_signatures_explainer
import mobi.giza.compose.resources.make_admin
import mobi.giza.compose.resources.make_admin_and_leave
@@ -203,16 +204,20 @@ internal fun LeaveAsAdminDialog(
/**
* Whether a keyed room's changes need the group's signature. Once they do, a line
* saying so; before, for an admin, the switch -- or who it is still waiting on,
* since switching it on with a member whose device cannot follow would leave them
* in a different group from the first change. docs/member-admin-promotion.md, Phase 4b.
* saying so; before, for an admin, whose device is switching it on -- or who it is
* still waiting on, since switching it on with a member whose device cannot follow
* would leave them in a different group from the first change.
* docs/member-admin-promotion.md, Phase 4b.
*
* Nothing to press: one device switches it on by itself once everybody can follow.
* docs/remove-convenient-groups.md, "After the build".
*/
@Composable
internal fun GovernanceSection(
governance: GovernanceStatus,
canGovern: Boolean,
nameOf: (HexKey) -> String,
onRequireSignatures: () -> Unit,
me: HexKey,
) {
val explainer = Modifier.padding(
horizontal = MaterialTheme.spacing.containerPadding,
@@ -226,11 +231,17 @@ internal fun GovernanceSection(
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = explainer,
)
is GovernanceStatus.Ready -> if (canGovern) {
TextButton(onClick = onRequireSignatures) {
Icon(Icons.Default.Verified, contentDescription = Decorative)
Text(stringResource(Res.string.require_signatures), modifier = Modifier.padding(start = MaterialTheme.spacing.relatedGap))
}
is GovernanceStatus.Ready -> if (canGovern && governance.switcher != null) {
Text(
text = if (governance.switcher == me) {
stringResource(Res.string.governance_switching)
} else {
stringResource(Res.string.governance_switch_waits_for, nameOf(governance.switcher))
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = explainer,
)
Text(
text = stringResource(Res.string.require_signatures_explainer),
style = MaterialTheme.typography.bodySmall,
@@ -266,10 +266,6 @@ class ChatRoomDetailViewModel(
}
}
/** Makes the room's changes need the group's signature. docs/member-admin-promotion.md, Phase 4b. */
fun requireSignatures(localChatRoom: LocalChatRoom, onDone: (String?) -> Unit) =
adminAction(onDone) { chatRepository.requireSignatures(localChatRoom) }
/** Accepts becoming an admin of a keyed room. docs/member-admin-promotion.md, Phase 8. */
fun acceptPromotion(localChatRoom: LocalChatRoom, offerId: HexKey, onDone: (String?) -> Unit) =
adminAction(onDone) { chatRepository.acceptPromotion(localChatRoom, offerId)?.let { throw IllegalStateException(it) } }
@@ -10,8 +10,12 @@ sealed interface GovernanceStatus {
/** It does: every change is proposed, signed by the group, and only then applied. */
data class Governed(val minimumAdmins: Int) : GovernanceStatus
/** It does not yet, and every member's device could follow if it were switched on. */
data class Ready(val minimumAdmins: Int) : GovernanceStatus
/**
* It does not yet, and every member's device could follow: [switcher]'s device
* switches it on by itself, the next time it is online. Null [switcher] when no
* admin holds a leaf. docs/remove-convenient-groups.md, "After the build".
*/
data class Ready(val minimumAdmins: Int, val switcher: HexKey?) : GovernanceStatus
/** It does not yet, and these members have not said their device could follow. */
data class Waiting(val missing: Set<HexKey>) : GovernanceStatus
@@ -292,6 +292,73 @@ class GovernanceGateJvmTest {
assertEquals(0, chatRepository.announceGovernanceSupport(), "said twice")
}
private val frank = MarmotStandIn()
/** Frank joins Dana's room after Erin, by Dana's bare commit; Erin and the app apply it. */
private suspend fun frankJoins() {
MarmotStandIn.seedProfile(db, frank.hex, "Frank")
frank.makeBundle()
val add = dana.commitLocally(routingId) { dana.manager.addMember(routingId, frank.bundle.keyPackage.toTlsBytes()) }
frank.manager.processWelcome(assertNotNull(add.welcomeBytes), frank.bundle)
frank.inbound.trackGroup(routingId)
val event = commitEvent(add)
erin.inbound.processGroupEvent(event)
MarmotStandIn.storeInApp(db, user, event)
}
@Test
fun `the first admin's device switches the rule on by itself once everyone has said it`() = runBlocking {
// Dana made the room and holds its first leaf; once she is no admin, the app's
// leaf is the lowest an admin holds, and the switch is the app's to make.
governedRoom(governed = false)
erinJoins()
frankJoins()
val admins = listOf(userHex, erin.hex, frank.hex)
val commit = dana.commitLocally(routingId) {
val staged = dana.manager.stageAppDataUpdate(routingId, AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(admins).encode())
dana.manager.installState(routingId, staged.pendingState)
staged.result
}
val event = commitEvent(commit)
erin.inbound.processGroupEvent(event)
frank.inbound.processGroupEvent(event)
MarmotStandIn.storeInApp(db, user, event)
assertEquals(userHex, GovernanceSupport.switcherOf(appGroup()))
says(dana)
says(erin)
GovernanceFollowThrough.pass(db, user)
assertFalse(GovernanceGate.isGoverned(appGroup()), "switched on before Frank said it")
says(frank)
GovernanceFollowThrough.pass(db, user)
okTheLatestCommit()
assertTrue(GovernanceGate.isGoverned(appGroup()), "nobody pressed anything, and nothing happened")
assertEquals(0, GovernanceSupport.switchWhereOwed(db, userHex), "switched twice")
}
@Test
fun `a device that is not the first admin leaves the switch to it`() = runBlocking {
// Every admin's device switching the moment the last member said it would be two
// commits at one epoch, which the library cannot settle for their authors.
governedRoom(governed = false)
erinJoins()
danaSetsAdminsBare(listOf(dana.hex, userHex, erin.hex))
says(dana)
says(erin)
assertEquals(GovernanceStatus.Ready(minimumAdmins = 3, switcher = dana.hex), chatRepository.governanceStatus(roomId))
GovernanceFollowThrough.pass(db, user)
assertEquals(0, GovernanceSupport.switchWhereOwed(db, userHex))
assertFalse(GovernanceGate.isGoverned(appGroup()))
assertTrue(db.marmotCommitResultDao().let { dao ->
db.nostrEventDao().getMLSGroupEvents(since = kotlin.time.Instant.fromEpochSeconds(0), limit = 50)
.none { it.kind == GroupEvent.KIND && dao.getMarmotCommitRequestById(it.id) != null }
}, "the app sent a commit of its own")
}
@Test
fun `hearing another member say it, this device says it back`() = runBlocking {
governedRoom(governed = false)
@@ -316,7 +383,7 @@ class GovernanceGateJvmTest {
assertTrue("Erin" in refusal.message.orEmpty(), refusal.message)
says(erin)
assertEquals(GovernanceStatus.Ready(minimumAdmins = 3), chatRepository.governanceStatus(roomId))
assertEquals(GovernanceStatus.Ready(minimumAdmins = 3, switcher = dana.hex), chatRepository.governanceStatus(roomId))
chatRepository.requireSignatures(room())
val switch = okTheLatestCommit()
+4 -1
View File
@@ -460,7 +460,10 @@ does not; nothing changes in a room without the marker.
records who has said it.
- **Require signatures for changes**, on a keyed room's detail screen, for an admin, once
every current member has said it. It is one bare commit adding the marker line to the
profile description. Until every member has, the screen names who has not.
profile description. Until every member has, the screen names who has not. (Since
made automatic -- one device, the admin in the lowest leaf, sends it once everybody has
said it, and the button is gone; [remove-convenient-groups.md](./remove-convenient-groups.md),
"After the build".)
- An invite into a governed room is refused for an account that has not said it, with
words that say why, once it is in the room (it says so from its own device on joining).
+44 -3
View File
@@ -420,9 +420,50 @@ screen the member had no reason to open.
Pinned in `GovernanceGateJvmTest`: a welcomed member has said it before anybody else
speaks, and a device whose saying is taken back says it again at start, once.
Once nobody is outstanding an admin still taps **Require the group's signature for
changes**, and the room's share rotation has to be on (a development build). Then the
member's row offers **Make admin**, and the member accepts on their own device.
#### The switch is nobody's to press
Even then an admin had to find **Require the group's signature for changes** on the
room's screen and tap it. Nothing about the switch is a decision: the two conditions it
waits on -- every member can follow, enough of them are admins -- are already checked in
code, and a group whose point is a key its members hold together is a group that means
to sign its changes. So the button is gone, and one device switches the rule on by
itself.
- **Which device.** The admin in the room's lowest leaf (`GovernanceSupport.switcherOf`)
-- in a room as it was made, its creator. Not every admin's: two commits at one epoch
are settled for every device that watched them but not for the two that made them,
which swap branches and stay apart ([marmot-v2.md](./marmot-v2.md), Phase 8). Every
device reads the same leaf off the same state, so they agree on one without a word
between them.
- **When.** `GovernanceFollowThrough`, which already runs while the app is open and
reads everything again on each pass, now passes whenever a member says it follows
signed commits, and on start. A room that is owed the switch (`switchOwed`) gets the
commit `requireSignatures` always sent; one still waiting for a relay is not sent
twice.
- **The screen** says which device it is waiting on: "Turning on the group's signature
for changes." on that device, "Changes will need the group's signature as soon as
Bob's Giza is next online." on the others.
*Not at creation*, though that was the first preference. A room born governed --
the marker in its epoch-0 description -- would need no switch, but:
- a Bennu founder, or one on an older Giza build, takes part in the ceremony like
anyone else, and would apply the bare commits Giza drops: in a different group from
the first change, with nobody told. The support check is the only thing that knows,
and it can only be asked once the room exists;
- a founder whose founding invite has to be finished later (robust-group-admins,
Phase 4) is added by a bare commit, which the founders already in a governed room
would refuse.
Switching once everybody has joined and said it costs the seconds it takes the
founders' devices to process their Welcomes, and costs nothing when one of them cannot
follow -- the room simply stays as it is.
Pinned in `GovernanceGateJvmTest`: the first admin's device switches by itself once the
last member says it, and not before; any other admin's device sends nothing.
Then the member's row offers **Make admin** -- with the room's share rotation on, which
is a development build for now -- and the member accepts on their own device.
## Out of scope