From 638d1d291ae11ea9a3c53c16946995ad59a2be48 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 02:52:20 +0200 Subject: [PATCH] feat: a member is made an admin of a keyed room, and enrolled into its key (member-admin-promotion, Phase 8) Under the experimental FROST enrollment. In a governed keyed room past its ceremony's generation, Make admin is an offer (30374); the member accepts (30375), naming the ChillDKG host key their shares will be sealed to, which is the one decision only they can make. The offering device then proposes one batch for the group to sign: the change making them an admin, and the key state binding the next participant id to them, with that id's public share -- interpolated from the table every device already holds -- added to the table it hashes. Every device adds the id when it files that key state, and only if the extended table hashes to what the group signed. Once the change lands the offering device hands over (30376) the table, roster and signed key state; the new member's device checks them against the room's own signature, files its record of the key, and asks to be enrolled. t holders run reduced FROST enrollment at newId = n through the repair protocol, with no approval of their own -- the signed binding was it -- and the new share is checked against the signed table. A signing session's n is now the generation's table size, which an enrollment grows; the repair session carries the n an enrollment runs with (schema v42, still unshipped). GovernanceFollowThrough drives the offerer's and the new member's steps. Co-Authored-By: Claude Opus 5.5 --- .../42.json | 11 +- .../composeResources/values/strings.xml | 6 + .../database/dao/MarmotInnerEventDao.kt | 6 + .../compose/database/dao/MarmotOutboundDao.kt | 10 +- .../compose/database/model/ChatMessage.kt | 8 + .../database/model/GovernanceProposal.kt | 6 + .../repository/DatabaseChatRepository.kt | 14 + .../giza/compose/managers/AdminGovernance.kt | 2 +- .../compose/managers/FrostSigningManager.kt | 20 +- .../managers/GovernanceFollowThrough.kt | 47 ++- .../compose/managers/GovernanceManager.kt | 25 +- .../compose/managers/GroupKeyStateManager.kt | 98 +++-- .../giza/compose/managers/PromotionManager.kt | 386 ++++++++++++++++++ .../compose/managers/ShareRepairManager.kt | 40 +- .../compose/nostr/frost/GovernanceEvents.kt | 42 +- .../compose/nostr/frost/ShareRepairEvents.kt | 7 + .../giza/compose/repository/ChatRepository.kt | 14 + .../ui/composable/ChatRoomDetailScreen.kt | 28 +- .../ui/composable/MemberAdminControls.kt | 28 +- .../composable/widgets/chat/ChatTranscript.kt | 1 + .../ui/view/model/ChatRoomDetailViewModel.kt | 8 + .../ui/view/state/ChatRoomDetailUIState.kt | 6 + .../managers/PromotionOffersJvmTest.kt | 87 ++++ .../managers/ShareRefreshRitualJvmTest.kt | 134 ++++++ 24 files changed, 968 insertions(+), 66 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/PromotionManager.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/PromotionOffersJvmTest.kt diff --git a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/42.json b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/42.json index 541025de..18939899 100644 --- a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/42.json +++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/42.json @@ -2,7 +2,7 @@ "formatVersion": 1, "database": { "version": 42, - "identityHash": "39b2db6475abf484600535c71c7df8f8", + "identityHash": "ca900fd23a959e4ec66c5ccc50b3c0fd", "entities": [ { "tableName": "BroadcastNostrEventReceipt", @@ -2574,7 +2574,7 @@ }, { "tableName": "GovernanceProposal", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `routingId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `frostSigningSessionId` TEXT NOT NULL, `commitEventId` TEXT NOT NULL, `commitEventJson` TEXT NOT NULL, `peerKeyPackageEventId` TEXT, `priorStateHex` TEXT NOT NULL, `pendingStateHex` TEXT NOT NULL, `stage` TEXT NOT NULL, `thenRotateWithout` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `routingId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `frostSigningSessionId` TEXT NOT NULL, `commitEventId` TEXT NOT NULL, `commitEventJson` TEXT NOT NULL, `peerKeyPackageEventId` TEXT, `priorStateHex` TEXT NOT NULL, `pendingStateHex` TEXT NOT NULL, `stage` TEXT NOT NULL, `thenRotateWithout` TEXT, `promotionOfferId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", "fields": [ { "fieldPath": "id", @@ -2646,6 +2646,11 @@ "columnName": "thenRotateWithout", "affinity": "TEXT" }, + { + "fieldPath": "promotionOfferId", + "columnName": "promotionOfferId", + "affinity": "TEXT" + }, { "fieldPath": "createdAt", "columnName": "createdAt", @@ -5341,7 +5346,7 @@ ], "setupQueries": [ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", - "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '39b2db6475abf484600535c71c7df8f8')" + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'ca900fd23a959e4ec66c5ccc50b3c0fd')" ] } } \ No newline at end of file diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 671f8eb9..edf42ae3 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -130,6 +130,12 @@ Require the group's signature for changes 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. Before changes can need the group's signature, %1$s need to update Giza. + 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. + Once the group signs it, they stay in the group as a member and their share of the group's key is rotated away. + Asked; they become an admin once they accept and the group signs it + %1$s asked you to become an admin. You'll hold a share of the group's key, and be asked to approve its changes. + Accept + Accepted; the group signs it next Proposed; it happens once the group signs it Sent; changes will need the group's signature once a relay accepts it Stepping down; you'll leave once a relay accepts it diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotInnerEventDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotInnerEventDao.kt index 2a2dade6..5bf826e0 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotInnerEventDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotInnerEventDao.kt @@ -69,6 +69,12 @@ interface MarmotInnerEventDao { @Query("SELECT COUNT(*) FROM MarmotInnerEvent WHERE chatRoomId = :chatRoomId AND kind IN (:kinds)") fun observeCountByChatRoomAndKinds(chatRoomId: String, kinds: List): Flow + @Query("SELECT * FROM MarmotInnerEvent WHERE kind IN (:kinds) ORDER BY createdAt ASC") + suspend fun getByKinds(kinds: List): List + + @Query("SELECT COUNT(*) FROM MarmotInnerEvent WHERE kind IN (:kinds)") + fun observeCountByKinds(kinds: List): Flow + @Query("DELETE FROM MarmotInnerEvent WHERE id = :id") suspend fun deleteById(id: String) 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 275fd016..7f2378a7 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 @@ -64,6 +64,7 @@ import mobi.giza.compose.extensions.toHex import mobi.giza.compose.managers.AdminFlags import mobi.giza.compose.managers.AdminGovernance import mobi.giza.compose.managers.ShareRefreshManager +import mobi.giza.compose.managers.PromotionManager import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.managers.GovernanceGate import mobi.giza.compose.managers.GovernanceManager @@ -950,7 +951,14 @@ abstract class MarmotOutboundDao( open suspend fun promote(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) { val group = governedGroup(localChatRoom) if (memberPublicKey in group.currentAdminIdentities()) return - check(!AdminGovernance.isKeyedRoom(group)) { KEYED_ROOM_REFUSAL } + // A keyed room: an offer the member accepts, then the group signs the change + // and the key state that gives them a share (docs/member-admin-promotion.md, + // Phase 8). + if (AdminGovernance.isKeyedRoom(group)) { + check(AdminGovernance.keyedChangesAllowed(group)) { KEYED_ROOM_REFUSAL } + PromotionManager.offer(database, localChatRoom, localChatRoom.chatRoom.userPublicKey, memberPublicKey) + return + } if (memberPublicKey !in AdminGovernance.members(group)) { throw IllegalArgumentException("${memberName(memberPublicKey)} is not in the group any more") } 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 9a2a46a3..9eba3761 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 @@ -579,6 +579,13 @@ data class ChatMessage( const val TYPE_ADMIN_ADDED = "adminAdded" const val TYPE_ADMIN_REMOVED = "adminRemoved" + /** + * An offer to make a member an admin of a keyed room, or their answer to one: + * this device's own account of what it asked or said, before the group signs + * anything. docs/member-admin-promotion.md, Phase 8. + */ + const val TYPE_ADMIN_OFFERED = "adminOffered" + /** * A change to a governed room that this device refused: a commit sent bare, * or an envelope whose check failed. Every device refuses the same ones, @@ -616,6 +623,7 @@ data class ChatMessage( TYPE_GROUP_DISBANDED, TYPE_ADMIN_ADDED, TYPE_ADMIN_REMOVED, + TYPE_ADMIN_OFFERED, TYPE_CHANGE_NOT_APPLIED, TYPE_CHANGE_REJECTED, TYPE_FOUNDING_ADMINS_MISSING, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GovernanceProposal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GovernanceProposal.kt index ab26534d..02735680 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GovernanceProposal.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GovernanceProposal.kt @@ -56,6 +56,12 @@ data class GovernanceProposal( * because the change can land long after it was proposed, across a restart. */ val thenRotateWithout: HexKey? = null, + /** + * The promotion offer this change answers, for a promotion in a keyed room: once + * it lands, the new admin is handed what they need to be enrolled into the key + * (docs/member-admin-promotion.md, Phase 8). + */ + val promotionOfferId: HexKey? = null, override val createdAt: Instant = Clock.System.now(), override val updatedAt: Instant = createdAt, override val savedAt: Instant = createdAt, 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 2f2f6d94..d1bd0264 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 @@ -12,6 +12,7 @@ import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair import mobi.giza.compose.managers.AdminGovernance import mobi.giza.compose.managers.GovernanceGate +import mobi.giza.compose.managers.PromotionManager import mobi.giza.compose.managers.GovernanceFollowThrough import mobi.giza.compose.managers.GovernanceSupport import mobi.giza.compose.managers.MarmotInboundManager @@ -736,6 +737,19 @@ class DatabaseChatRepository( database.marmotOutboundDao().demote(localChatRoom, adminPublicKey) } + override suspend fun pendingPromotion(chatRoomId: String): PromotionManager.Offer? { + val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return null + return PromotionManager.pendingOffer(database, chatRoomId, room.chatRoom.userPublicKey) + } + + override suspend fun acceptPromotion(localChatRoom: LocalChatRoom, offerId: HexKey): String? { + val identity = activeIdentity.value ?: return "No identity is signed in" + val nostrPrivateKey = identity.toKeyPair().privKey ?: return "This identity cannot sign" + return runCatching { + PromotionManager.accept(database, localChatRoom, identity.nostrPublicKey, nostrPrivateKey, offerId) + }.exceptionOrNull()?.let { it.message ?: it::class.simpleName ?: "Unknown error" } + } + override suspend fun stepDownAndLeave(localChatRoom: LocalChatRoom, heir: HexKey?) { database.marmotOutboundDao().stepDownAndLeave(localChatRoom, heir) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt index 345913eb..da6195ca 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt @@ -72,7 +72,7 @@ object AdminGovernance { * `AdminPolicyV1` says is never valid. */ fun canPromote(group: MlsGroup, actor: HexKey, target: HexKey): Boolean = - !isKeyedRoom(group) && + (!isKeyedRoom(group) || keyedChangesAllowed(group)) && target in members(group) && MarmotGroupPermissions.canPromote(group.currentAdminIdentities(), actor, target) 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 5b948f82..f4d4e7cc 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt @@ -357,7 +357,9 @@ object FrostSigningManager { userPublicKey = userPublicKey, dkgSessionId = ceremony.id, threshold = ceremony.threshold, - participantCount = ceremony.participantCount, + // The table's size, not the ceremony's: an enrollment adds an id + // (docs/member-admin-promotion.md, Phase 8). + participantCount = shares.publicShares?.size ?: ceremony.participantCount, signerId = signerId, derivationPath = path?.let(SharedKeyDerivation::formatPath), generation = shares.generation, @@ -516,7 +518,8 @@ object FrostSigningManager { key: DkgSession, signerId: Int, path: List?, - generation: Int = 0 + generation: Int = 0, + participantCount: Int = key.participantCount, ) = FrostSigningSession( id = sessionId, chatRoomId = localChatRoom.chatRoom.id, @@ -527,7 +530,7 @@ object FrostSigningManager { userPublicKey = userPublicKey, dkgSessionId = key.id, threshold = key.threshold, - participantCount = key.participantCount, + participantCount = participantCount, signerId = signerId, derivationPath = path?.let(SharedKeyDerivation::formatPath), generation = generation @@ -611,6 +614,9 @@ object FrostSigningManager { // could choose the key the group signs as, and every signer would put // their share behind an author none of them checked. val path = signingPath(database, localChatRoom, key) + // `n` is the generation's table, which an enrollment grows + // (docs/member-admin-promotion.md, Phase 8); the ceremony's count otherwise. + val n = generation?.let { ShareGenerations.at(database, key, it) }?.publicShares?.size ?: key.participantCount val unsignedEvents = proposed.map { event -> unsignedEventOf( key = key, @@ -644,7 +650,7 @@ object FrostSigningManager { // docs/giza-wallet-removal.md, Phase 1. WalletRefusal.of(unsignedEvents)?.let { why -> logger.w("Signing proposal $sessionId $why; declining") - val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0) + val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0, participantCount = n) .copy(signDeclinedAt = Clock.System.now()) database.frostSigningSessionDao().upsert(declined) database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents)) @@ -659,7 +665,7 @@ object FrostSigningManager { unsignedEvents.firstOrNull { it.kind == GovernanceStatementEvent.KIND }?.let { statement -> GovernanceManager.refusalOf(database, localChatRoom, statement)?.let { why -> logger.w("Signing proposal $sessionId carries a change that is refused: $why; declining") - val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0) + val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0, participantCount = n) .copy(signDeclinedAt = Clock.System.now()) database.frostSigningSessionDao().upsert(declined) database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents)) @@ -691,7 +697,7 @@ object FrostSigningManager { ) // An unreadable tag is filed as -1: no generation, so nothing reads it as a // share this device holds, and the decline says why. - val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: -1) + val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: -1, participantCount = n) .copy(signDeclinedAt = Clock.System.now()) database.frostSigningSessionDao().upsert(declined) database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents)) @@ -707,7 +713,7 @@ object FrostSigningManager { } } - val session = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0) + val session = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0, participantCount = n) database.frostSigningSessionDao().upsert(session) database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents)) announceStarted(database, session) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt index a3fcda23..9bdf87a7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt @@ -7,7 +7,11 @@ import com.vitorpamplona.quartz.nip01Core.core.toHexKey import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair import kotlin.time.Clock import kotlinx.coroutines.CancellationException +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.PromotionEvents import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import mobi.giza.compose.database.GizaDatabase @@ -31,7 +35,11 @@ object GovernanceFollowThrough { /** Follows this device's proposals until cancelled. */ suspend fun observe(database: GizaDatabase, keyPair: KeyPair) { - database.governanceProposalDao().observeAll() + combine( + database.governanceProposalDao().observeAll(), + database.marmotInnerEventDao().observeCountByKinds(listOf(PromotionEvents.OFFER, PromotionEvents.ACCEPT, PromotionEvents.HANDOVER)), + database.groupSignedEventDao().observeByKind(GroupKeyStateEvent.KIND), + ) { _, _, _ -> Unit } .conflate() .collect { try { @@ -47,8 +55,45 @@ 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() + val privateKey = keyPair.privKey ?: return@withLock + + // Phase 8, the device that offered: an accepted offer is proposed for the + // group's signature, once; a promotion that landed is handed over. + PromotionManager.acceptedOffers(database, me).forEach { (offer, acceptance) -> + if (offer.id in failedOffers) return@forEach + val room = database.chatRoomDao().findChatRoomById(offer.chatRoomId) ?: return@forEach + runCatching { PromotionManager.propose(database, room, me, offer, acceptance) }.onFailure { + if (it is CancellationException) throw it + failedOffers += offer.id + logger.w("Couldn't propose the promotion ${offer.id.take(8)}…: ${it.message}") + announce(database, offer.chatRoomId, me, "Couldn't ask the group to make them an admin: ${it.message}") + } + } + PromotionManager.handoversOwed(database).forEach { proposal -> + runCatching { PromotionManager.handover(database, proposal, me) }.onFailure { + if (it is CancellationException) throw it + logger.w("Couldn't hand over ${proposal.id.take(8)}…: ${it.message}") + } + } + + // Phase 8, the new admin's device: a handover is checked and taken. + PromotionManager.handoversToMe(database, me).forEach { handover -> + if (handover.id in failedHandovers) return@forEach + val room = database.chatRoomDao().findChatRoomById(handover.chatRoomId) ?: return@forEach + runCatching { PromotionManager.takeHandover(database, room, me, privateKey, handover) }.onFailure { + if (it is CancellationException) throw it + failedHandovers += handover.id + logger.w("Couldn't take the handover ${handover.id.take(8)}…: ${it.message}") + } + } } + /** Offers and handovers that failed once in this process: not retried on every pass. */ + private val failedOffers = mutableSetOf() + private val failedHandovers = mutableSetOf() + /** * This device's changes that have landed and owe a rotation without a member * they demoted or removed (Phase 9). Landed means a relay accepted it -- marked diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceManager.kt index 23f6c0a7..0fa0f5d8 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceManager.kt @@ -12,6 +12,7 @@ import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal import kotlin.time.Clock import kotlin.time.Instant @@ -102,6 +103,8 @@ object GovernanceManager { userPublicKey: HexKey, peerKeyPackageEventId: HexKey? = null, thenRotateWithout: HexKey? = null, + promotionOfferId: HexKey? = null, + alsoSign: List> = emptyList(), propose: (MlsGroup) -> Unit, ): String { val engine = database.marmotEngine @@ -123,16 +126,24 @@ object GovernanceManager { check(remaining.size >= floor) { "A group with a shared key needs at least $floor admins. Make someone else an admin first" } } - val session = FrostSigningManager.proposeSigning( + // The statement leads; anything signed with it -- a promotion's key state -- + // is one decision by one quorum, so it is one batch. + val statement = EventTemplate( + Clock.System.now().epochSeconds, + GovernanceStatementEvent.KIND, + GovernanceStatementEvent.assembleTags(roomId, prepared.epoch, prepared.change, userPublicKey), + prepared.commitEvent.toJson(), + ) + val session = FrostSigningManager.proposeSigningBatch( database = database, localChatRoom = localChatRoom, userPublicKey = userPublicKey, - kind = GovernanceStatementEvent.KIND, - tags = GovernanceStatementEvent.assembleTags(roomId, prepared.epoch, prepared.change, userPublicKey), - content = prepared.commitEvent.toJson(), + events = listOf(statement) + alsoSign, ) - val statementId = database.frostSigningSessionDao().getItems(session.id).single().eventId - record(database, localChatRoom, userPublicKey, prepared, statementId, session.id, peerKeyPackageEventId, thenRotateWithout) + val statementId = database.frostSigningSessionDao().getItems(session.id) + .first { Event.fromJsonOrNull(it.unsignedEventJson)?.kind == GovernanceStatementEvent.KIND } + .eventId + record(database, localChatRoom, userPublicKey, prepared, statementId, session.id, peerKeyPackageEventId, thenRotateWithout, promotionOfferId) return session.id } @@ -151,6 +162,7 @@ object GovernanceManager { sessionId: String, peerKeyPackageEventId: HexKey? = null, thenRotateWithout: HexKey? = null, + promotionOfferId: HexKey? = null, ): GovernanceProposal { val roomId = localChatRoom.chatRoom.id database.marmotCommitResultDao().upsert( @@ -176,6 +188,7 @@ object GovernanceManager { priorStateHex = prepared.staged.priorState.encodeTls().toHex(), pendingStateHex = prepared.staged.pendingState.encodeTls().toHex(), thenRotateWithout = thenRotateWithout, + promotionOfferId = promotionOfferId, ) database.governanceProposalDao().upsert(proposal) return proposal 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 60c82131..6403b019 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt @@ -4,6 +4,8 @@ import co.touchlab.kermit.Logger import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import kotlin.time.Clock +import fr.acinq.bitcoin.PublicKey +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate import kotlin.time.Instant import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.DkgSession @@ -219,8 +221,10 @@ object GroupKeyStateManager { val filed = database.groupKeyStateDao().replace(state) // `replace` re-stamps what it files, so the row is compared on what it says. if (filed.generation == state.generation && filed.announcedAt == state.announcedAt) { - retireOlderShares(database, state) + // Bindings first: one that enrolls a new id extends the table, and the + // table has to be the one the group signed before older shares go. applyBindings(database, state) + retireOlderShares(database, state) } return filed } @@ -261,6 +265,9 @@ object GroupKeyStateManager { val generation = state.generation ?: return val bindings = GroupKeyStateEvent.MemberBinding.decodeAll(state.memberBindings) if (bindings.isEmpty()) return + // A binding of the next id is an enrollment: the id joins the table first + // (docs/member-admin-promotion.md, Phase 8). + bindings.forEach { binding -> PromotionManager.enrollNewId(database, state, binding) } val members = database.keyShareDao().getMembers(state.dkgSessionId, generation) val changed = bindings.mapNotNull { binding -> val row = members.firstOrNull { it.participantId == binding.participantId } ?: return@mapNotNull null @@ -316,50 +323,71 @@ object GroupKeyStateManager { refreshId: String?, newBinding: GroupKeyStateEvent.MemberBinding? = null, ): FrostSigningSession { + val template = generationTemplate(database, localChatRoom, key, refreshId, newBinding) + return FrostSigningManager.proposeSigning( + database = database, + localChatRoom = localChatRoom, + userPublicKey = userPublicKey, + kind = template.kind, + tags = template.tags, + content = template.content, + key = key, + createdAt = template.createdAt, + ) + } + + /** + * The key state [proposeGeneration] asks the group to sign, unsigned, for a caller + * that signs it alongside something else -- a promotion signs it with the change + * it makes (docs/member-admin-promotion.md, Phase 8). [publicShares], when given, + * is the table the state names instead of this device's: the current one with a + * new member's public share appended. + */ + suspend fun generationTemplate( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + key: DkgSession, + refreshId: String?, + newBinding: GroupKeyStateEvent.MemberBinding? = null, + publicShares: List? = null, + ): EventTemplate { val shares = ShareGenerations.active(database, key) check(shares.generation >= 1) { "Generation 0 is the ceremony's, and needs no new key state" } - val publicShares = requireNotNull(shares.publicShares) { "Generation ${shares.generation} has no public shares" } + val table = publicShares ?: requireNotNull(shares.publicShares) { "Generation ${shares.generation} has no public shares" } val current = keyStateFor(database, localChatRoom.chatRoom.id) val path = current?.pathIndices() ?: SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH val parent = current?.parentChatRoomId?.let { parentId -> current.birthCertificateJson?.let { Event.fromJsonOrNull(it) }?.let { SubgroupParentage(parentId, it) } } val thresholdPublicKey = requireNotNull(key.thresholdPublicKey) - return FrostSigningManager.proposeSigning( - database = database, - localChatRoom = localChatRoom, - userPublicKey = userPublicKey, - kind = GroupKeyStateEvent.KIND, - tags = GroupKeyStateEvent.assembleTags( - chatRoomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey, path), - dkgSessionId = key.id, - path = path, - parent = parent, - generation = GroupKeyStateEvent.ShareGenerationTags( - generation = shares.generation, - publicSharesHash = ShareGenerations.publicSharesHash(publicShares), - refreshId = refreshId, - retiredIds = shares.roster.filter { it.standing == ShareStanding.RETIRED }.map { it.participantId }, - // Bindings already in force at this generation stay said, so a - // later state does not quietly undo them; a new one replaces any - // earlier binding of the same id. - bindings = ( - GroupKeyStateEvent.MemberBinding.decodeAll(current?.takeIf { it.generation == shares.generation }?.memberBindings) - .filter { it.participantId != newBinding?.participantId } + listOfNotNull(newBinding) - ), - ), - ), - content = thresholdPublicKey, - key = key, - // Later than the state it amends, by a second if it must be. Two states - // at one generation are told apart by their time alone, and a rebind - // stamped in the same second as the state it adds to would tie with it - // -- and the binding could be the one that loses. - createdAt = maxOf( - Clock.System.now().epochSeconds, - (current?.takeIf { (it.generation ?: 0) == shares.generation }?.announcedAt?.epochSeconds ?: 0L) + 1 + val tags = GroupKeyStateEvent.assembleTags( + chatRoomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey, path), + dkgSessionId = key.id, + path = path, + parent = parent, + generation = GroupKeyStateEvent.ShareGenerationTags( + generation = shares.generation, + publicSharesHash = ShareGenerations.publicSharesHash(table), + refreshId = refreshId, + retiredIds = shares.roster.filter { it.standing == ShareStanding.RETIRED }.map { it.participantId }, + // Bindings already in force at this generation stay said, so a + // later state does not quietly undo them; a new one replaces any + // earlier binding of the same id. + bindings = ( + GroupKeyStateEvent.MemberBinding.decodeAll(current?.takeIf { it.generation == shares.generation }?.memberBindings) + .filter { it.participantId != newBinding?.participantId } + listOfNotNull(newBinding) + ), ), ) + // Later than the state it amends, by a second if it must be. Two states + // at one generation are told apart by their time alone, and a rebind + // stamped in the same second as the state it adds to would tie with it + // -- and the binding could be the one that loses. + val createdAt = maxOf( + Clock.System.now().epochSeconds, + (current?.takeIf { (it.generation ?: 0) == shares.generation }?.announcedAt?.epochSeconds ?: 0L) + 1 + ) + return EventTemplate(createdAt, GroupKeyStateEvent.KIND, tags, thresholdPublicKey) } /** diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/PromotionManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/PromotionManager.kt new file mode 100644 index 00000000..5fb0c155 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/PromotionManager.kt @@ -0,0 +1,386 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.marmot.appComponents.AdminPolicyV1 +import com.vitorpamplona.marmot.groups.currentAdminIdentities +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.PublicKey +import fr.acinq.bitcoin.crypto.frost.FrostEnrollment +import kotlin.time.Clock +import kotlin.time.Instant +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonArray +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.int +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put +import mobi.giza.compose.ExperimentalFeatures +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.GovernanceProposal +import mobi.giza.compose.database.model.GovernanceProposalStage +import mobi.giza.compose.database.model.GroupKeyState +import mobi.giza.compose.database.model.KeyShareGeneration +import mobi.giza.compose.database.model.KeyShareMember +import mobi.giza.compose.database.model.MarmotInnerEvent +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.database.model.types.ShareGenerationState +import mobi.giza.compose.database.model.types.ShareStanding +import mobi.giza.compose.exceptions.MarmotMissingChatGroupException +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.frost.GroupKeyStateEvent +import mobi.giza.compose.nostr.frost.PromotionEvents + +/** + * Making a member an admin of a keyed room, which makes them a holder of its key + * too (R1). docs/member-admin-promotion.md, Phase 8; the steps are on + * [PromotionEvents]. + * + * The new member is enrolled at the next participant id, `n`, by reduced FROST + * enrollment -- the repair protocol run with `newId = n` and the `n` before it + * (`ShareRepairManager`). Every device puts the id in its table the same way: its + * public share is derived from the table it already has ([publicShareFor]) and + * accepted only when the extended table hashes to what the group signed + * ([enrollNewId]). So nothing about the new id is anybody's say-so. + * + * Only from a key past its ceremony's generation: generation 0 lives in the + * ceremony's own record, which has no room for an id the ceremony did not make. + */ +object PromotionManager { + private val logger = Logger.withTag("PromotionManager") + + // ---- the new id's public share, the same on every device ------------------------------------------------------- + + /** + * The public share of participant [newId] on the polynomial [table] lies on, by + * interpolation in the exponent from its first [threshold] entries. Any t entries + * give the same point, so every device that holds the same table gets the same one. + */ + fun publicShareFor(table: List, threshold: Int, newId: Int): PublicKey { + val helperIds = (0 until threshold).map { it.toUInt() } + val derived = FrostEnrollment.derivePublicShare(table.take(threshold), helperIds, newId.toUInt(), newId, threshold) + return derived.right ?: throw IllegalStateException("Couldn't derive id $newId's public share: ${derived.left?.message}") + } + + /** [table] with the next id's public share appended. */ + fun extended(table: List, threshold: Int): List = table + publicShareFor(table, threshold, table.size) + + /** + * Puts the next id in this device's table at [state]'s generation, when [binding] + * names it and the table extended by its derived public share is the one the + * group signed. Called with a signed key state's bindings, before they are + * applied; anything else -- an id already there, a table that would hash + * differently -- is left alone. + */ + suspend fun enrollNewId(database: GizaDatabase, state: GroupKeyState, binding: GroupKeyStateEvent.MemberBinding) { + val generation = state.generation ?: return + val key = database.dkgSessionDao().getSessionById(state.dkgSessionId) ?: return + val row = database.keyShareDao().getGeneration(key.id, generation) ?: return + val table = row.publicShareList() ?: return + if (binding.participantId != table.size) return + if (database.keyShareDao().getMembers(key.id, generation).any { it.participantId == binding.participantId }) return + + val withNewId = extended(table, key.threshold) + if (ShareGenerations.publicSharesHash(withNewId) != state.publicSharesHash) { + logger.w("A key state enrolls id ${binding.participantId} of ${key.id} with a table this device's does not extend to; leaving it") + return + } + val now = Clock.System.now() + database.keyShareDao().upsert(row.copy(publicShares = withNewId.joinToString(",") { it.value.toHex() }, updatedAt = now)) + database.keyShareDao().upsert( + listOf( + KeyShareMember( + dkgSessionId = key.id, + generation = generation, + participantId = binding.participantId, + memberPublicKey = binding.memberPublicKey, + hostPublicKey = binding.hostPublicKey, + standing = ShareStanding.STALE, + ) + ) + ) + logger.i("Id ${binding.participantId} of ${key.id} added for ${binding.memberPublicKey.take(8)}…, to be enrolled") + } + + // ---- 1. the offer -------------------------------------------------------------------------------------------- + + /** + * Offers [target] the role of admin in [localChatRoom], as [me]. Refused, in words + * a person can act on, where the room or its key cannot take a new admin. + */ + suspend fun offer(database: GizaDatabase, localChatRoom: LocalChatRoom, me: HexKey, target: HexKey): HexKey { + val group = database.marmotEngine.groupFor(localChatRoom.routingId) + ?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}") + check(AdminGovernance.keyedChangesAllowed(group)) { "This group's admins can't be changed from this device" } + check(me in group.currentAdminIdentities()) { "Only an admin can make someone else one" } + require(target in AdminGovernance.members(group)) { "They are not in the group any more" } + if (target in group.currentAdminIdentities()) return "" + val key = FrostSigningManager.completedKey(database, localChatRoom.chatRoom.id) + ?: throw IllegalStateException("This device holds no share of the group's key") + check(ShareGenerations.active(database, key).generation >= 1) { + "Rotate the group's shares once before adding an admin: the key's first generation is its ceremony's, and has no room for a new member" + } + val id = send(database, localChatRoom.chatRoom.id, me, PromotionEvents.OFFER, "", PromotionEvents.offerTags(localChatRoom.chatRoom.id, target)) + announce(database, localChatRoom.chatRoom.id, me, ChatMessage.TYPE_ADMIN_OFFERED, "Asked ${nameOf(database, target)} to become an admin") + return id + } + + /** An offer to [me] in [chatRoomId] that has not been answered, if there is one. */ + data class Offer(val id: HexKey, val from: HexKey) + + suspend fun pendingOffer(database: GizaDatabase, chatRoomId: String, me: HexKey): Offer? { + val events = database.marmotInnerEventDao().getByChatRoomAndKinds(chatRoomId, listOf(PromotionEvents.OFFER, PromotionEvents.ACCEPT)) + val answered = events.filter { it.kind == PromotionEvents.ACCEPT && it.publicKey == me } + .mapNotNull { PromotionEvents.value(it.tags, PromotionEvents.OFFER_TAG) } + .toSet() + val offer = events.lastOrNull { + it.kind == PromotionEvents.OFFER && PromotionEvents.value(it.tags, PromotionEvents.TARGET_TAG) == me && it.id !in answered + } ?: return null + return Offer(offer.id, offer.publicKey) + } + + // ---- 2. the acceptance --------------------------------------------------------------------------------------- + + /** + * Accepts [offerId], as [me], naming the ChillDKG host key that shares sent to + * this device will be sealed to: derived from the account key, as a ceremony's is. + */ + suspend fun accept(database: GizaDatabase, localChatRoom: LocalChatRoom, me: HexKey, nostrPrivateKey: ByteArray, offerId: HexKey) { + check(ExperimentalFeatures.shareRefresh) { "This build does not take part in enrollment" } + val host = ChillDkgRitualManager.deriveHostPublicKey(nostrPrivateKey).value.toHex() + send(database, localChatRoom.chatRoom.id, me, PromotionEvents.ACCEPT, "", PromotionEvents.acceptTags(localChatRoom.chatRoom.id, offerId, host)) + announce(database, localChatRoom.chatRoom.id, me, ChatMessage.TYPE_ADMIN_OFFERED, "You accepted becoming an admin. The group signs it next") + } + + // ---- 3. the proposal, by the device that offered --------------------------------------------------------------- + + /** This device's offers that have been accepted and not yet proposed, with their acceptance. */ + suspend fun acceptedOffers(database: GizaDatabase, me: HexKey): List> { + val events = database.marmotInnerEventDao().getByKinds(listOf(PromotionEvents.OFFER, PromotionEvents.ACCEPT)) + val proposed = database.governanceProposalDao().getAll() + .filter { it.stage != GovernanceProposalStage.STALE } + .mapNotNull { it.promotionOfferId } + .toSet() + return events.filter { it.kind == PromotionEvents.OFFER && it.publicKey == me && it.id !in proposed }.mapNotNull { offer -> + val target = PromotionEvents.value(offer.tags, PromotionEvents.TARGET_TAG) ?: return@mapNotNull null + val acceptance = events.lastOrNull { + it.kind == PromotionEvents.ACCEPT && it.publicKey == target && + PromotionEvents.value(it.tags, PromotionEvents.OFFER_TAG) == offer.id + } ?: return@mapNotNull null + offer to acceptance + } + } + + /** + * Proposes the promotion [offer] and [acceptance] agreed: one batch for the group + * to sign, the change that makes the member an admin and the key state that binds + * the next participant id to them, with that id's public share in the table. + */ + suspend fun propose( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + me: HexKey, + offer: MarmotInnerEvent, + acceptance: MarmotInnerEvent, + ): String { + val target = requireNotNull(PromotionEvents.value(offer.tags, PromotionEvents.TARGET_TAG)) + val host = requireNotNull(PromotionEvents.value(acceptance.tags, PromotionEvents.HOST_KEY_TAG)?.lowercase()?.takeIf { it.length == 66 }) { + "The acceptance names no host key" + } + val group = database.marmotEngine.groupFor(localChatRoom.routingId) + ?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}") + val key = FrostSigningManager.completedKey(database, localChatRoom.chatRoom.id) + ?: throw IllegalStateException("This device holds no share of the group's key") + val shares = ShareGenerations.active(database, key) + val table = requireNotNull(shares.publicShares) { "Generation ${shares.generation} has no public shares" } + val binding = GroupKeyStateEvent.MemberBinding(table.size, target, host) + val keyState = GroupKeyStateManager.generationTemplate( + database, localChatRoom, key, refreshId = null, newBinding = binding, publicShares = extended(table, key.threshold), + ) + val admins = group.currentAdminIdentities() + return GovernanceManager.propose( + database, localChatRoom, me, + promotionOfferId = offer.id, + alsoSign = listOf(keyState), + ) { copy -> + copy.proposeAppDataUpdate(AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(admins + target).encode()) + } + } + + // ---- 4. the handover, once the change lands -------------------------------------------------------------------- + + /** This device's promotions that have landed and not yet been handed over. */ + suspend fun handoversOwed(database: GizaDatabase): List = + database.governanceProposalDao().getAll().filter { proposal -> + proposal.promotionOfferId != null && ( + proposal.stage == GovernanceProposalStage.APPLIED || + (proposal.stage == GovernanceProposalStage.PUBLISHED && (database.marmotEngine.groupFor(proposal.routingId)?.epoch ?: 0) > proposal.epoch) + ) + } + + /** + * Hands the new admin what they need to be enrolled: the table and roster of the + * generation the group signs with, and the key state that binds their id, as the + * group signed it. Marks [proposal] done. + */ + suspend fun handover(database: GizaDatabase, proposal: GovernanceProposal, me: HexKey) { + val offer = database.marmotInnerEventDao().getById(proposal.promotionOfferId ?: return) ?: return + val target = PromotionEvents.value(offer.tags, PromotionEvents.TARGET_TAG) ?: return + val content = handoverContent(database, proposal.chatRoomId) ?: return + send(database, proposal.chatRoomId, me, PromotionEvents.HANDOVER, content, PromotionEvents.handoverTags(proposal.chatRoomId, target)) + database.governanceProposalDao().upsert(proposal.copy(stage = GovernanceProposalStage.DONE, updatedAt = Clock.System.now())) + } + + /** + * What a handover says about [chatRoomId]'s key, from this device: the table and + * roster of the generation the group signs with, and the key state as the group + * signed it. Null when this device holds no key for the room or no signed state. + */ + suspend fun handoverContent(database: GizaDatabase, chatRoomId: String): String? { + val key = FrostSigningManager.completedKey(database, chatRoomId) ?: return null + val shares = ShareGenerations.active(database, key) + val table = shares.publicShares ?: return null + val signedState = GroupKeyStateManager.signedEventFor(database, chatRoomId)?.toEvent() ?: return null + return buildJsonObject { + put("key", key.id) + put("generation", shares.generation) + put("threshold", key.threshold) + put("thresholdPublicKey", requireNotNull(key.thresholdPublicKey)) + put("publicShares", buildJsonArray { table.forEach { add(JsonPrimitive(it.value.toHex())) } }) + put("roster", buildJsonArray { + shares.roster.forEach { entry -> + add(buildJsonArray { + add(JsonPrimitive(entry.participantId)); add(JsonPrimitive(entry.memberPublicKey)) + add(JsonPrimitive(entry.hostPublicKey)); add(JsonPrimitive(entry.standing.name)) + }) + } + }) + put("keyState", signedState.toJson()) + }.toString() + } + + // ---- 5. the new admin's device ---------------------------------------------------------------------------------- + + /** Handovers to [me] this device has not acted on: no enrollment of its own for the key yet. */ + suspend fun handoversToMe(database: GizaDatabase, me: HexKey): List = + database.marmotInnerEventDao().getByKinds(listOf(PromotionEvents.HANDOVER)).filter { handover -> + PromotionEvents.value(handover.tags, PromotionEvents.TARGET_TAG) == me && handover.publicKey != me && + runCatching { Json.parseToJsonElement(handover.content).jsonObject["key"]!!.jsonPrimitive.content }.getOrNull() + ?.let { keyId -> database.shareRepairDao().getSessionsForKey(keyId).none { it.targetPublicKey == me } } == true + } + + /** + * Takes [handover] as the new admin: checks it against the room's own signature, + * files what it says -- this device's record of the key, its table and roster, + * and the signed key state -- and asks to be enrolled at its id. Nothing in it is + * taken on the sender's word: the key state has to be one the room signed and + * that derives the room, the table has to hash to what it names, and it has to + * bind the next id to this account under this device's host key. + */ + suspend fun takeHandover(database: GizaDatabase, localChatRoom: LocalChatRoom, me: HexKey, nostrPrivateKey: ByteArray, handover: MarmotInnerEvent) { + val json = Json.parseToJsonElement(handover.content).jsonObject + val keyId = json["key"]!!.jsonPrimitive.content + val generation = json["generation"]!!.jsonPrimitive.int + val threshold = json["threshold"]!!.jsonPrimitive.int + val thresholdPublicKey = json["thresholdPublicKey"]!!.jsonPrimitive.content + val table = json["publicShares"]!!.jsonArray.map { PublicKey(ByteVector(it.jsonPrimitive.content.hexToByteArray())) } + val roster = (json["roster"] as JsonArray).map { row -> + val cells = row.jsonArray + KeyShareMember( + dkgSessionId = keyId, + generation = generation, + participantId = cells[0].jsonPrimitive.int, + memberPublicKey = cells[1].jsonPrimitive.content, + hostPublicKey = cells[2].jsonPrimitive.content.lowercase(), + standing = ShareStanding.valueOf(cells[3].jsonPrimitive.content), + ) + } + val keyStateEvent = Event.fromJson(json["keyState"]!!.jsonPrimitive.content) + val myHost = ChillDkgRitualManager.deriveHostPublicKey(nostrPrivateKey).value.toHex() + val newId = table.size - 1 + + val state = GroupKeyStateManager.stateFrom(localChatRoom.chatRoom.id, keyStateEvent) + val binding = GroupKeyStateEvent.MemberBinding.decodeAll(state?.memberBindings).firstOrNull { it.participantId == newId } + val refusal = when { + state == null -> "its key state is not one this room signed" + state.dkgSessionId != keyId || state.generation != generation -> "its key state is for another key or generation" + !state.thresholdPublicKey.equals(thresholdPublicKey, ignoreCase = true) -> "its key is not the room's" + ShareGenerations.publicSharesHash(table) != state.publicSharesHash -> "its table is not the one the group signed" + binding == null || binding.memberPublicKey != me || !binding.hostPublicKey.equals(myHost, ignoreCase = true) -> "the group did not bind the new id to this device" + roster.map { it.participantId } != table.indices.toList() -> "its roster does not match its table" + else -> null + } + if (refusal != null) { + logger.w("Refusing a handover in ${localChatRoom.chatRoom.id}: $refusal") + announce(database, localChatRoom.chatRoom.id, me, ChatMessage.TYPE_CHANGE_NOT_APPLIED, "Couldn't take a share of the group's key: $refusal") + return + } + + val now = Clock.System.now() + val key = database.dkgSessionDao().getSessionById(keyId) ?: DkgSession( + id = keyId, + chatRoomId = localChatRoom.chatRoom.id, + coordinatorPublicKey = handover.publicKey, + userPublicKey = me, + threshold = threshold, + participantCount = newId, + stage = DkgRitualStage.COMPLETE, + hostPublicKey = myHost, + round1Random = "00".repeat(32), + round2AuxRandom = "00".repeat(32), + thresholdPublicKey = thresholdPublicKey, + ).also { database.dkgSessionDao().upsert(it) } + if (database.keyShareDao().getGeneration(keyId, generation) == null) { + database.keyShareDao().upsert( + KeyShareGeneration( + dkgSessionId = keyId, + generation = generation, + secretShare = null, + publicShares = table.joinToString(",") { it.value.toHex() }, + state = ShareGenerationState.ACTIVE, + activatedAt = now, + ) + ) + database.keyShareDao().upsert(roster) + } + GroupKeyStateManager.record(database, localChatRoom.chatRoom.id, keyStateEvent) + ShareRepairManager.requestRepair(database, localChatRoom, me, nostrPrivateKey, key, targetId = newId, nParticipants = newId) + } + + // ---- plumbing ---------------------------------------------------------------------------------------------------- + + /** Puts an inner event on the outbound queue, as every manager's messages go. Returns its id. */ + private suspend fun send(database: GizaDatabase, chatRoomId: String, me: HexKey, kind: Int, content: String, tags: Array>): HexKey { + val createdAt = Clock.System.now().epochSeconds + val id = EventHasher.hashId(pubKey = me, createdAt = createdAt, kind = kind, tags = tags, content = content) + database.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = id, publicKey = me, kind = kind, createdAt = Instant.fromEpochSeconds(createdAt), + tags = tags, content = content, chatRoomId = chatRoomId, + ) + ) + return id + } + + private suspend fun announce(database: GizaDatabase, chatRoomId: String, me: HexKey, type: String, content: String) { + database.chatMessageDao().upsert( + ChatMessage( + content = content, messageType = type, chatRoomId = chatRoomId, senderPublicKey = me, + isUserMessage = true, giftWrapPayloadId = null, marmotGroupEventId = null, marmotInnerEventId = null, + ) + ) + } + + private suspend fun nameOf(database: GizaDatabase, publicKey: HexKey): String = + database.profileDao().getProfileByPublicKey(publicKey)?.humanReadableNameOrPubkey() ?: publicKey.take(8) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRepairManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRepairManager.kt index 41dcaa31..fa76952a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRepairManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRepairManager.kt @@ -71,6 +71,7 @@ object ShareRepairManager { nostrPrivateKey: ByteArray, key: DkgSession, targetId: Int? = null, + nParticipants: Int? = null, ): ShareRepairSession { check(ExperimentalFeatures.shareRefresh) { "This build does not repair shares" } require(key.stage == DkgRitualStage.COMPLETE) { "Ceremony ${key.id} has not produced a key" } @@ -95,9 +96,14 @@ object ShareRepairManager { userPublicKey = userPublicKey, stage = if (isBound(entry, userPublicKey, hostPublicKey)) ShareRepairStage.COLLECTING else ShareRepairStage.AWAITING_BINDING, sessionRandom = RandomInstance.bytes(32).toHex(), + nParticipants = nParticipants, ) database.shareRepairDao().upsert(session) - announce(database, session, ChatMessage.TYPE_SHARE_REPAIR_REQUESTED, "asked to be brought back into the group's signing.", userPublicKey) + announce( + database, session, ChatMessage.TYPE_SHARE_REPAIR_REQUESTED, + if (nParticipants != null) "asked to be given a share of the group's key." else "asked to be brought back into the group's signing.", + userPublicKey, + ) broadcast( database, localChatRoom, userPublicKey, ShareRepairEvents.REQUEST, "", arrayOf( @@ -107,7 +113,7 @@ object ShareRepairManager { arrayOf(ShareRepairEvents.TARGET_TAG, id.toString()), arrayOf(ShareRepairEvents.HELPERS_TAG, session.helperIds), arrayOf(ShareRepairEvents.HOST_KEY_TAG, hostPublicKey), - ) + ) + listOfNotNull(nParticipants?.let { arrayOf(ShareRepairEvents.N_TAG, it.toString()) }) ) return session } @@ -146,8 +152,15 @@ object ShareRepairManager { val helpers = tag(ShareRepairEvents.HELPERS_TAG)?.split(",")?.map { it.trim().toIntOrNull() ?: return null } ?: return null val shares = ShareGenerations.active(database, key) val entry = shares.roster.firstOrNull { it.participantId == targetId } + // An enrollment at a new id names the n it runs with, which has to be that + // id: one past the table the group had before the new member's public share + // was added to it (docs/member-admin-promotion.md, Phase 8). + val nParticipants = tag(ShareRepairEvents.N_TAG)?.let { it.toIntOrNull() ?: return null } + val tableSize = shares.publicShares?.size ?: return null val reason = when { + nParticipants != null && (nParticipants != targetId || tableSize != targetId + 1) -> + "it enrolls id $targetId with n = $nParticipants, and this device's table has $tableSize entries" shares.generation != generation -> "it repairs into generation $generation, and this device is at ${shares.generation}" entry == null -> "id $targetId is not in the key" entry.standing != ShareStanding.STALE -> "id $targetId is ${entry.standing.name.lowercase()}" @@ -173,11 +186,14 @@ object ShareRepairManager { userPublicKey = userPublicKey, stage = if (isBound(entry!!, event.pubKey, hostKey)) ShareRepairStage.COLLECTING else ShareRepairStage.AWAITING_BINDING, sessionRandom = RandomInstance.bytes(32).toHex(), + nParticipants = nParticipants, ) database.shareRepairDao().upsert(session) announce( database, session, ChatMessage.TYPE_SHARE_REPAIR_REQUESTED, - if (session.stage == ShareRepairStage.AWAITING_BINDING) { + if (nParticipants != null) { + "asked to be given a share of the group's key, as the group agreed." + } else if (session.stage == ShareRepairStage.AWAITING_BINDING) { "asked to be brought back into the group's signing under a new identity. The group has to bind them to the id first." } else { "asked to be brought back into the group's signing." @@ -236,7 +252,9 @@ object ShareRepairManager { val thresholdPublicKey = PublicKey(ByteVector(requireNotNull(key.thresholdPublicKey).hexToByteArray())) val helpers = session.helperIdList() val helperIds = helpers.map { it.toUInt() } - val n = key.participantCount + // The table's size, not the ceremony's count: an enrollment grows it. An + // enrollment runs with the n before it, which its session names. + val n = session.nParticipants ?: table.size val t = key.threshold val sid = ByteVector32(session.id) val hostSecretKey = ChillDkgRitualManager.deriveHostSecretKey(nostrPrivateKey) @@ -251,13 +269,16 @@ object ShareRepairManager { throw IllegalStateException("the repaired member's proof does not match the group's public share") } markLive(database, key, session) - complete(database, session, "was brought back into the group's signing.", session.targetPublicKey) + complete(database, session, completedLine(session), session.targetPublicKey) return } // ---- a helper ---- if (myId != null && myId in helpers && session.userPublicKey != session.targetPublicKey) { - if (session.helpApprovedAt == null) { + // An enrollment needs no approval of its own: the group signed the + // binding that makes the new member the holder of this id, and that + // signature was every helper's chance to say no. + if (session.helpApprovedAt == null && session.nParticipants == null) { if (!session.approvalRequested) { update(database, session) { it.copy(approvalRequested = true) } announce(database, session, ChatMessage.TYPE_SHARE_REPAIR_APPROVAL_NEEDED, "Your approval is needed to help bring a member back into the group's signing.", session.userPublicKey) @@ -316,7 +337,7 @@ object ShareRepairManager { val proof = Crypto.signSchnorr(sid, share, null) broadcast(database, localChatRoom, session.userPublicKey, ShareRepairEvents.DONE, proof.toHex(), arrayOf(arrayOf(ShareRepairEvents.SESSION_TAG, session.id))) markLive(database, key, session) - complete(database, session, "was brought back into the group's signing.", session.targetPublicKey) + complete(database, session, completedLine(session), session.targetPublicKey) } } catch (e: CancellationException) { throw e @@ -327,6 +348,9 @@ object ShareRepairManager { } } + private fun completedLine(session: ShareRepairSession): String = + if (session.nParticipants != null) "now holds a share of the group's key." else "was brought back into the group's signing." + /** Approves helping with a repair, and moves on. */ suspend fun approve(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) { val session = database.shareRepairDao().getSessionById(sessionId) ?: return @@ -337,7 +361,7 @@ object ShareRepairManager { /** Whether this device's owner is being asked to help with [session]. */ suspend fun isAwaitingApproval(database: GizaDatabase, session: ShareRepairSession): Boolean { - if (session.stage != ShareRepairStage.COLLECTING || session.helpApprovedAt != null) return false + if (session.stage != ShareRepairStage.COLLECTING || session.helpApprovedAt != null || session.nParticipants != null) return false val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return false val shares = ShareGenerations.at(database, key, session.generation) ?: return false val myId = shares.roster.firstOrNull { it.memberPublicKey == session.userPublicKey && it.standing == ShareStanding.LIVE }?.participantId diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceEvents.kt index 0bd8e3e6..f3b6dae0 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceEvents.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceEvents.kt @@ -26,7 +26,10 @@ import com.vitorpamplona.quartz.nip01Core.tags.dTag.DTag * member who sends it. An own commit is already its sender's and needs no carrier. */ object GovernanceEvents { - val ALL: Set = setOf(GovernanceStatementEvent.KIND, OwnCommitEvent.KIND, GovernanceSupportEvent.KIND, GovernanceCarrierEvent.KIND) + val ALL: Set = setOf( + GovernanceStatementEvent.KIND, OwnCommitEvent.KIND, GovernanceSupportEvent.KIND, GovernanceCarrierEvent.KIND, + PromotionEvents.OFFER, PromotionEvents.ACCEPT, PromotionEvents.HANDOVER, + ) /** The epoch tag every envelope names: the epoch its commit is built at. */ const val EPOCH_TAG = "epoch" @@ -97,3 +100,40 @@ object GovernanceCarrierEvent { Event.fromJson(carrier.content).takeIf { it.kind == GovernanceStatementEvent.KIND } }.getOrNull() } + +/** + * Making a member an admin of a keyed room, which also makes them a holder of its + * key (R1). docs/member-admin-promotion.md, Phase 8. + * + * 1. An admin offers ([OFFER]) -- a request, carrying no authority. + * 2. The member accepts ([ACCEPT]), naming the ChillDKG host key the shares sent + * to them will be sealed to. This is the one decision only they can make. + * 3. The group signs the promotion and the key state that binds the next + * participant id to them, in one batch, and the commit lands. + * 4. The proposer hands over ([HANDOVER]) what the new member needs to take part: + * the share table, the roster and the signed key state. Nothing in it is + * trusted on the proposer's word -- the table has to hash to what the group + * signed, and the state has to be the room's own signature. + * 5. The member asks to be enrolled at the new id, and t holders run reduced + * FROST enrollment for them, as they would a repair. + */ +object PromotionEvents { + val OFFER: Kind = 30374 + val ACCEPT: Kind = 30375 + val HANDOVER: Kind = 30376 + + const val TARGET_TAG = "target" + const val OFFER_TAG = "offer" + const val HOST_KEY_TAG = "host" + + fun offerTags(chatRoomId: HexKey, target: HexKey): Array> = + arrayOf(DTag.assemble(chatRoomId), arrayOf(TARGET_TAG, target)) + + fun acceptTags(chatRoomId: HexKey, offerId: HexKey, hostPublicKey: HexKey): Array> = + arrayOf(DTag.assemble(chatRoomId), arrayOf(OFFER_TAG, offerId), arrayOf(HOST_KEY_TAG, hostPublicKey)) + + fun handoverTags(chatRoomId: HexKey, target: HexKey): Array> = + arrayOf(DTag.assemble(chatRoomId), arrayOf(TARGET_TAG, target)) + + fun value(tags: Array>, name: String): String? = tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/ShareRepairEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/ShareRepairEvents.kt index f09ee84a..ec26d60c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/ShareRepairEvents.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/ShareRepairEvents.kt @@ -37,6 +37,13 @@ object ShareRepairEvents { const val KEY_TAG = "frost_key" const val GENERATION_TAG = "frost_generation" + /** + * The `n` an enrollment at a new id runs with: that id, since the table held n + * entries before it (docs/member-admin-promotion.md, Phase 8). Absent on a + * repair, which uses the table it has. + */ + const val N_TAG = "repair_n" + fun value(tags: Array>, name: String): String? = tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1) fun parseSessionId(tags: Array>): String? = value(tags, SESSION_TAG)?.takeIf { it.length == 64 } 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 2fff1ef1..e2eb7a0e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -23,6 +23,7 @@ import mobi.giza.compose.managers.FoundingAdmins import mobi.giza.compose.managers.MarmotGroupCreation import mobi.giza.compose.managers.SubgroupManager import mobi.giza.compose.nostr.MarmotProfile +import mobi.giza.compose.managers.PromotionManager import mobi.giza.compose.ui.view.state.GovernanceStatus import mobi.giza.compose.ui.view.state.SharesSummary import mobi.giza.compose.ui.view.state.RotationPreview @@ -349,6 +350,15 @@ interface ChatRepository { */ suspend fun stepDownAndLeave(localChatRoom: LocalChatRoom, heir: HexKey?) + /** + * An offer to this device's account to become an admin of a keyed room that it + * has not answered, or null. docs/member-admin-promotion.md, Phase 8. + */ + suspend fun pendingPromotion(chatRoomId: String): PromotionManager.Offer? + + /** Accepts [offerId]. Returns null when the acceptance went out, or why it could not. */ + suspend fun acceptPromotion(localChatRoom: LocalChatRoom, offerId: HexKey): String? + /** * 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 @@ -624,6 +634,10 @@ interface ChatRepository { override suspend fun stepDownAndLeave(localChatRoom: LocalChatRoom, heir: HexKey?) = Unit + override suspend fun pendingPromotion(chatRoomId: String): PromotionManager.Offer? = null + + override suspend fun acceptPromotion(localChatRoom: LocalChatRoom, offerId: HexKey): String? = null + override suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) = Unit override suspend fun addAdmins(localChatRoom: LocalChatRoom, publicKeys: Set) = Unit 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 50e12847..0fab7df5 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 @@ -90,6 +90,8 @@ 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 import mobi.giza.compose.ui.view.state.GovernanceStatus import mobi.giza.compose.resources.holds_a_share import mobi.giza.compose.ui.view.state.AdminLeave @@ -243,6 +245,8 @@ 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 adminOfferSent = stringResource(Res.string.admin_offer_sent) + val promotionAccepted = stringResource(Res.string.promotion_accepted) val adminLabel = stringResource(Res.string.admin) val shareLabel = stringResource(Res.string.holds_a_share) val rotationRequested = stringResource(Res.string.share_rotation_requested) @@ -377,11 +381,21 @@ fun ChatRoomDetailScreen( ConfirmAdminChangeDialog( action = action, memberName = nameOf(memberPublicKey), + keyed = chatRoomDetailUIState.governance is GovernanceStatus.Governed, onDismiss = { confirmingAdminChange = null }, onConfirm = { confirmingAdminChange = null val room = chatRoomDetailUIState.localChatRoom - val onDone = { failure: String? -> notify(failure ?: adminChangeRequested) } + val governed = chatRoomDetailUIState.governance is GovernanceStatus.Governed + val onDone = { failure: String? -> + notify( + failure ?: when { + governed && action == MemberAction.MAKE_ADMIN -> adminOfferSent + governed -> changeProposed + else -> adminChangeRequested + } + ) + } when (action) { MemberAction.MAKE_ADMIN -> chatRoomDetailViewModel.makeAdmin(room, memberPublicKey, onDone) MemberAction.REMOVE_AS_ADMIN, MemberAction.STEP_DOWN -> @@ -1142,6 +1156,18 @@ fun ChatRoomDetailScreen( // Whether the room's changes need the group's signature, and the // switch that makes them. docs/member-admin-promotion.md, Phase 4b. + // An offer to this account to become an admin, with its one + // decision. docs/member-admin-promotion.md, Phase 8. + chatRoomDetailUIState.promotionOffer?.let { (offerId, from) -> + item { + PromotionOfferCard(fromName = nameOf(from)) { + chatRoomDetailViewModel.acceptPromotion(chatRoomDetailUIState.localChatRoom, offerId) { failure -> + notify(failure ?: promotionAccepted) + } + } + } + } + chatRoomDetailUIState.governance?.let { governance -> item { GovernanceSection( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt index 08b4ac14..0a15f180 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt @@ -39,6 +39,10 @@ import mobi.giza.compose.resources.require_signatures_explainer import mobi.giza.compose.resources.make_admin import mobi.giza.compose.resources.make_admin_and_leave import mobi.giza.compose.resources.make_admin_body +import mobi.giza.compose.resources.make_admin_body_keyed +import mobi.giza.compose.resources.remove_as_admin_body_keyed +import mobi.giza.compose.resources.promotion_offer_body +import mobi.giza.compose.resources.accept import mobi.giza.compose.resources.make_admin_title import mobi.giza.compose.resources.member_actions import mobi.giza.compose.resources.pick_heir_body @@ -107,18 +111,19 @@ private fun MemberAction.label() = when (this) { internal fun ConfirmAdminChangeDialog( action: MemberAction, memberName: String, + keyed: Boolean = false, onConfirm: () -> Unit, onDismiss: () -> Unit, ) { val (title, body, confirm) = when (action) { MemberAction.MAKE_ADMIN -> Triple( stringResource(Res.string.make_admin_title, memberName), - stringResource(Res.string.make_admin_body), + stringResource(if (keyed) Res.string.make_admin_body_keyed else Res.string.make_admin_body), stringResource(Res.string.make_admin), ) MemberAction.REMOVE_AS_ADMIN -> Triple( stringResource(Res.string.remove_as_admin_title, memberName), - stringResource(Res.string.remove_as_admin_body), + stringResource(if (keyed) Res.string.remove_as_admin_body_keyed else Res.string.remove_as_admin_body), stringResource(Res.string.remove_as_admin), ) MemberAction.STEP_DOWN -> Triple( @@ -244,3 +249,22 @@ internal fun GovernanceSection( } } } + +/** + * An offer to this account to become an admin of a keyed room, with the one + * decision only its owner can make: accepting puts them in the group's signing + * quorum. docs/member-admin-promotion.md, D3 and Phase 8. + */ +@Composable +internal fun PromotionOfferCard(fromName: String, onAccept: () -> Unit) { + Column(modifier = Modifier.fillMaxWidth().padding(horizontal = MaterialTheme.spacing.containerPadding, vertical = MaterialTheme.spacing.compactPadding)) { + Text( + text = stringResource(Res.string.promotion_offer_body, fromName), + style = MaterialTheme.typography.bodyMedium, + ) + TextButton(onClick = onAccept) { + Icon(Icons.Default.Verified, contentDescription = Decorative) + Text(stringResource(Res.string.accept), modifier = Modifier.padding(start = MaterialTheme.spacing.relatedGap)) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt index 6b1f4fc1..cc4cfb42 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt @@ -884,6 +884,7 @@ private fun RitualNotice( ChatMessage.TYPE_CHANGE_REJECTED -> Icons.Default.ErrorOutline ChatMessage.TYPE_ADMIN_ADDED -> Icons.Default.AdminPanelSettings ChatMessage.TYPE_ADMIN_REMOVED -> Icons.Default.RemoveModerator + ChatMessage.TYPE_ADMIN_OFFERED -> Icons.Default.AdminPanelSettings ChatMessage.TYPE_CHANGE_NOT_APPLIED -> Icons.Default.Block 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 1ac8795e..c8ca7a8d 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 @@ -149,6 +149,10 @@ class ChatRoomDetailViewModel( governance = runCatching { chatRepository.governanceStatus(chatRoomId) } .onFailure { if (it is CancellationException) throw it } .getOrNull(), + promotionOffer = runCatching { chatRepository.pendingPromotion(chatRoomId) } + .onFailure { if (it is CancellationException) throw it } + .getOrNull() + ?.let { it.id to it.from }, missingFoundingAdmins = missingFoundingAdmins, uninvitedFounders = uninvitedFounders, founderNames = (missingFoundingAdmins + uninvitedFounders).associateWith { publicKey -> @@ -236,6 +240,10 @@ class ChatRoomDetailViewModel( 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) } } + fun makeAdmin(localChatRoom: LocalChatRoom, memberPublicKey: HexKey, onDone: (String?) -> Unit) = adminAction(onDone) { chatRepository.promoteMember(localChatRoom, memberPublicKey) } 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 fe5c11dd..bd789af8 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,12 @@ 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, + /** + * An offer to this device's account to become an admin of this keyed room, + * by public key of the offer and of who made it; null when there is none. + * docs/member-admin-promotion.md, Phase 8. + */ + val promotionOffer: Pair? = 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 diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/PromotionOffersJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/PromotionOffersJvmTest.kt new file mode 100644 index 00000000..39ddb87e --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/PromotionOffersJvmTest.kt @@ -0,0 +1,87 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +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.assertNull +import kotlin.test.assertTrue +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.ChatRoom +import mobi.giza.compose.database.model.GovernanceProposal +import mobi.giza.compose.database.model.GovernanceProposalStage +import mobi.giza.compose.database.model.MarmotInnerEvent +import mobi.giza.compose.nostr.frost.PromotionEvents + +/** + * Which promotion offers are waiting on whom. docs/member-admin-promotion.md, + * Phase 8: an offer waits on the member until they accept it, and an accepted + * offer waits on the device that made it until it is proposed -- once. + */ +class PromotionOffersJvmTest { + + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val roomId = "1".repeat(64) + private val alice = KeyPair().pubKey.toHexKey() + private val erin = KeyPair().pubKey.toHexKey() + + private suspend fun room() { + MarmotStandIn.seedProfile(db, alice, "Alice") + MarmotStandIn.seedProfile(db, erin, "Erin") + db.chatRoomDao().upsert(ChatRoom(id = roomId, userPublicKey = erin, subject = "#keyed", description = null, mlsGroupState = null)) + } + + private suspend fun said(id: Char, by: String, kind: Int, tags: Array>, at: Long) = + db.marmotInnerEventDao().upsert( + MarmotInnerEvent(id = id.toString().repeat(64), publicKey = by, kind = kind, tags = tags, content = "", chatRoomId = roomId, createdAt = Instant.fromEpochSeconds(at)) + ) + + @Test + fun `an offer waits on the member until they accept it`() = runBlocking { + room() + said('a', alice, PromotionEvents.OFFER, PromotionEvents.offerTags(roomId, erin), 1) + + assertEquals(PromotionManager.Offer("a".repeat(64), alice), PromotionManager.pendingOffer(db, roomId, erin)) + assertNull(PromotionManager.pendingOffer(db, roomId, alice), "an offer to Erin was shown to Alice") + + said('b', erin, PromotionEvents.ACCEPT, PromotionEvents.acceptTags(roomId, "a".repeat(64), "02" + "c".repeat(64)), 2) + assertNull(PromotionManager.pendingOffer(db, roomId, erin), "an accepted offer still asked") + } + + @Test + fun `an accepted offer is the offerer's to propose, once`() = runBlocking { + room() + said('a', alice, PromotionEvents.OFFER, PromotionEvents.offerTags(roomId, erin), 1) + assertTrue(PromotionManager.acceptedOffers(db, alice).isEmpty(), "proposed before it was accepted") + + // Accepted by somebody else first: not an acceptance. + said('c', alice, PromotionEvents.ACCEPT, PromotionEvents.acceptTags(roomId, "a".repeat(64), "02" + "c".repeat(64)), 2) + assertTrue(PromotionManager.acceptedOffers(db, alice).isEmpty(), "the offerer accepted on the member's behalf") + + said('b', erin, PromotionEvents.ACCEPT, PromotionEvents.acceptTags(roomId, "a".repeat(64), "02" + "c".repeat(64)), 3) + assertEquals(listOf("a".repeat(64)), PromotionManager.acceptedOffers(db, alice).map { it.first.id }) + assertTrue(PromotionManager.acceptedOffers(db, erin).isEmpty(), "the member was asked to propose their own promotion") + + db.governanceProposalDao().upsert( + GovernanceProposal( + id = "d".repeat(64), chatRoomId = roomId, routingId = roomId, epoch = 1, frostSigningSessionId = "s", + commitEventId = "e".repeat(64), commitEventJson = "{}", priorStateHex = "", pendingStateHex = "", + promotionOfferId = "a".repeat(64), + ) + ) + assertTrue(PromotionManager.acceptedOffers(db, alice).isEmpty(), "proposed twice") + + // A proposal the group moved past frees the offer to be proposed again. + db.governanceProposalDao().upsert(db.governanceProposalDao().getById("d".repeat(64))!!.copy(stage = GovernanceProposalStage.STALE)) + assertEquals(1, PromotionManager.acceptedOffers(db, alice).size) + } +} 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 6ae97ea3..6b415c79 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -13,6 +13,8 @@ import fr.acinq.bitcoin.crypto.frost.Frost import fr.acinq.bitcoin.crypto.frost.KeyMaterial import kotlin.test.AfterTest import kotlin.test.Test +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonArray import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertNotEquals @@ -1358,6 +1360,138 @@ class ShareRefreshRitualJvmTest { return Device(group, -1, db, LocalChatRoom(chatRoom = chatRoom), keyPair).also { devices += it } } + // ---- member-admin-promotion, Phase 8: enrollment at a new id ----------------------------------------------- + + /** A 3-member 2-of-3 group that has rotated once, everyone included, with its key state signed. */ + private suspend fun rotatedOnce(): Pair> { + val group = Group(3, 2) + val all = devicesFor(group) + val refresh = propose(all[0]) + pump(all) + approveAll(all, refresh.id) + approveSigning(all) + return group to all + } + + /** A device for [keyPair] holding nothing of the key at all: the room, the members' profiles, no ceremony. */ + private suspend fun stranger(group: Group, keyPair: KeyPair): Device { + val db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + val publicKey = keyPair.pubKey.toHexKey() + (group.members + publicKey).forEach { member -> + val nostrEventId = "e$member".take(64) + db.nostrEventDao().upsert(NostrEvent(id = nostrEventId, pubKey = member, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = member, nostrEventId = nostrEventId)) + } + val chatRoom = ChatRoom(id = group.roomId, userPublicKey = publicKey, subject = "#Ekklesia", description = SharedKeyDerivation.describe("Admins."), mlsGroupState = "00") + db.chatRoomDao().upsert(chatRoom) + return Device(group, -1, db, LocalChatRoom(chatRoom = chatRoom), keyPair).also { devices += it } + } + + /** The group signs the key state binding the next id to [member] under [host], with that id's public share added. */ + private suspend fun bindNextId(all: List, member: HexKey, host: HexKey) { + val alice = all[0] + val table = alice.active().publicShares!! + val binding = mobi.giza.compose.nostr.frost.GroupKeyStateEvent.MemberBinding(table.size, member, host) + val template = GroupKeyStateManager.generationTemplate( + alice.db, alice.room, alice.key(), refreshId = null, newBinding = binding, + publicShares = PromotionManager.extended(table, alice.key().threshold), + ) + FrostSigningManager.proposeSigning(alice.db, alice.room, alice.publicKey, template.kind, template.tags, template.content, alice.key(), template.createdAt) + pump(all) + approveSigning(all) + pump(all) + } + + /** The handover the proposer's device would send, as Erin's device receives it. */ + private suspend fun handoverFrom(from: Device, to: HexKey): MarmotInnerEvent = + MarmotInnerEvent( + id = "f".repeat(64), publicKey = from.publicKey, kind = mobi.giza.compose.nostr.frost.PromotionEvents.HANDOVER, + tags = mobi.giza.compose.nostr.frost.PromotionEvents.handoverTags(from.group.roomId, to), + content = assertNotNull(PromotionManager.handoverContent(from.db, from.group.roomId)), + chatRoomId = from.group.roomId, + ) + + /** + * A member who never took part in the ceremony is enrolled at id 3 of a 2-of-3 + * key: every device adds the id from the key state the group signed, the new + * member checks what they are handed against it, two holders run reduced + * enrollment with nobody asked, and the new share signs. + */ + @Test + fun `a new member is enrolled at the next id, and signs with the group`() = runBlocking { + mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = true + val (_, all) = rotatedOnce() + val (alice, bob, carol) = all + val erinKeys = KeyPair() + val erinHost = ChillDkgRitualManager.deriveHostPublicKey(erinKeys.privKey!!).value.toHex() + val erin = stranger(all[0].group, erinKeys) + + bindNextId(all, erin.publicKey, erinHost) + all.forEach { device -> + assertEquals(4, device.active().publicShares!!.size, "the table on device ${device.index}") + val entry = device.active().roster.single { it.participantId == 3 } + assertEquals(erin.publicKey, entry.memberPublicKey) + assertEquals(ShareStanding.STALE, entry.standing, "id 3 waits for its share") + } + + PromotionManager.takeHandover(erin.db, erin.room, erin.publicKey, erin.privateKey, handoverFrom(alice, erin.publicKey)) + val everyone = all + erin + pump(everyone) + + val share = assertNotNull(erin.active().secretShare, "Erin must hold a share of id 3") + assertEquals(alice.active().publicShares!![3], share.publicKey(), "a share on the group's polynomial") + everyone.forEach { device -> + assertEquals(ShareStanding.LIVE, device.active().roster.single { it.participantId == 3 }.standing, "id 3 on device ${device.index}") + } + + // Erin signs, with Alice; Bob and Carol stay out. + val session = FrostSigningManager.proposeSigning(alice.db, alice.room, alice.publicKey, kind = 1, tags = arrayOf(), content = "Erin signs") + assertEquals(4, session.participantCount, "n is the table's, which grew") + pump(everyone) + FrostSigningManager.approve(erin.db, erin.room, session.id) + pump(everyone) + assertEquals(FrostSigningStage.COMPLETE, alice.db.frostSigningSessionDao().getSessionById(session.id)?.stage) + assertTrue(alice.db.frostSigningSessionDao().getSessionById(session.id)!!.signerIdList()!!.contains(3)) + listOf(bob, carol).forEach { assertNull(it.db.frostSigningSessionDao().getSessionById(session.id)?.signApprovedAt) } + } + + /** A handover that does not match what the group signed is refused, and nothing is asked for. */ + @Test + fun `a handover whose table the group did not sign is refused`() = runBlocking { + mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = true + val (_, all) = rotatedOnce() + val erinKeys = KeyPair() + val erin = stranger(all[0].group, erinKeys) + bindNextId(all, erin.publicKey, ChillDkgRitualManager.deriveHostPublicKey(erinKeys.privKey!!).value.toHex()) + + val honest = handoverFrom(all[0], erin.publicKey) + val json = kotlinx.serialization.json.Json.parseToJsonElement(honest.content).jsonObject + val shares = json["publicShares"]!!.jsonArray + val swapped = kotlinx.serialization.json.JsonArray(listOf(shares[1], shares[0]) + shares.drop(2)) + val forged = honest.copy(content = kotlinx.serialization.json.JsonObject(json + ("publicShares" to swapped)).toString()) + + PromotionManager.takeHandover(erin.db, erin.room, erin.publicKey, erin.privateKey, forged) + + assertNull(erin.db.dkgSessionDao().getSessionById(ceremonyId), "a key was filed from a forged handover") + assertTrue(erin.db.shareRepairDao().getSessionsForKey(ceremonyId).isEmpty()) + } + + /** A binding of the next id whose table this device cannot extend to is not applied. */ + @Test + fun `an id enrolled with a table that does not extend this one is not added`() = runBlocking { + mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = true + val (_, all) = rotatedOnce() + val alice = all[0] + val table = alice.active().publicShares!! + val state = assertNotNull(GroupKeyStateManager.keyStateFor(alice.db, alice.group.roomId)) + // The next id, but a hash over some other fourth share. + val wrong = state.copy(publicSharesHash = ShareGenerations.publicSharesHash(table + table[0])) + PromotionManager.enrollNewId(alice.db, wrong, mobi.giza.compose.nostr.frost.GroupKeyStateEvent.MemberBinding(3, "a".repeat(64), "02" + "b".repeat(64))) + + assertEquals(3, alice.active().publicShares!!.size) + assertTrue(alice.active().roster.none { it.participantId == 3 }) + } + // ---- Phase 12: restore --------------------------------------------------------------------------------------- /**