From 615afc30a1a5e97a76fc665b7b4a60427e66ccd0 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 00:38:20 +0200 Subject: [PATCH] feat: what a finished ceremony leaves: the confederation, certified (confederation, Phase 12) Every device that took part files the confederation under the room id its key derives, as upstream's canonical roster, key state and genesis, with its own shares kept as recovery packages. The genesis is verified against the key state before anything is written, and each of the device's own member groups gets a line saying it is part of it now. Co-Authored-By: Claude Opus 5.5 --- .../44.json | 141 +++++++++++++++++- .../composeResources/values/strings.xml | 1 + .../giza/compose/database/GizaDatabase.kt | 10 +- .../database/dao/ConfederationCeremonyDao.kt | 18 +++ .../compose/database/model/ChatMessage.kt | 4 + .../compose/database/model/Confederation.kt | 47 ++++++ .../DatabaseConfederationRepository.kt | 4 + .../managers/ConfederationFormation.kt | 97 ++++++++++++ .../managers/ConfederationRitualManager.kt | 7 + .../repository/ConfederationRepository.kt | 5 + .../ui/composable/ConfederationsScreen.kt | 5 +- .../composable/widgets/chat/ChatTranscript.kt | 1 + .../ui/view/model/ConfederationsViewModel.kt | 7 +- .../ui/view/state/ConfederationsUIState.kt | 2 +- .../managers/ConfederationCeremonyJvmTest.kt | 20 +++ docs/confederation.md | 1 + 16 files changed, 362 insertions(+), 8 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/Confederation.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationFormation.kt diff --git a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/44.json b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/44.json index 05131248..597bc999 100644 --- a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/44.json +++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/44.json @@ -2,7 +2,7 @@ "formatVersion": 1, "database": { "version": 44, - "identityHash": "e1b802a89798916abe7ff10117ed46d0", + "identityHash": "9913d6f59a2c30e53fa61ad44065d7c3", "entities": [ { "tableName": "BroadcastNostrEventReceipt", @@ -785,6 +785,107 @@ } ] }, + { + "tableName": "Confederation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `ceremonyId` TEXT NOT NULL, `name` TEXT NOT NULL, `roster` TEXT NOT NULL, `keyState` TEXT NOT NULL, `genesis` TEXT NOT NULL, `configSeq` INTEGER NOT NULL, `rosterHash` TEXT NOT NULL, `keyStateHash` TEXT NOT NULL, `recoveryPackages` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ceremonyId", + "columnName": "ceremonyId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roster", + "columnName": "roster", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyState", + "columnName": "keyState", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "genesis", + "columnName": "genesis", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "configSeq", + "columnName": "configSeq", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rosterHash", + "columnName": "rosterHash", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyStateHash", + "columnName": "keyStateHash", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "recoveryPackages", + "columnName": "recoveryPackages", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Confederation_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Confederation_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + } + ] + }, { "tableName": "ConfederationCeremony", "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `openingJson` TEXT NOT NULL, `stage` TEXT NOT NULL, `approvedAt` INTEGER, `dealerSeeds` TEXT, `recoveryNonces` TEXT, `keyState` TEXT, `transitionHash` TEXT, `genesis` TEXT, `recoveryPackages` TEXT, `confederationPublicKey` TEXT, `failureReason` TEXT, `culprit` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", @@ -934,6 +1035,42 @@ } ] }, + { + "tableName": "ConfederationMember", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`confederationId` TEXT NOT NULL, `groupPublicKey` TEXT NOT NULL, PRIMARY KEY(`confederationId`, `groupPublicKey`))", + "fields": [ + { + "fieldPath": "confederationId", + "columnName": "confederationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "groupPublicKey", + "columnName": "groupPublicKey", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "confederationId", + "groupPublicKey" + ] + }, + "indices": [ + { + "name": "index_ConfederationMember_groupPublicKey", + "unique": false, + "columnNames": [ + "groupPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationMember_groupPublicKey` ON `${TABLE_NAME}` (`groupPublicKey`)" + } + ] + }, { "tableName": "ConfederationCeremonyMessage", "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `senderPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `ConfederationCeremony`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", @@ -5733,7 +5870,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, 'e1b802a89798916abe7ff10117ed46d0')" + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '9913d6f59a2c30e53fa61ad44065d7c3')" ] } } \ 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 025e36fb..7a3f6211 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -738,4 +738,5 @@ The confederation's key is made The ceremony ended: %1$s %1$s: %2$d of %3$d admins to sign + Formed diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt index a06146a1..baf26602 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt @@ -66,7 +66,9 @@ import mobi.giza.compose.database.model.ChatMessageBroadcastNostrEventReceiptRel import mobi.giza.compose.database.model.ChatMessageBroadcastNostrEventRequestRelation import mobi.giza.compose.database.model.ChatMessageNostrEventRelation import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.Confederation import mobi.giza.compose.database.model.ConfederationCeremony +import mobi.giza.compose.database.model.ConfederationMember import mobi.giza.compose.database.model.ConfederationCeremonyMessage import mobi.giza.compose.database.model.ConfederationEvent import mobi.giza.compose.database.model.ConfederationInvitee @@ -133,7 +135,9 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) ChatMessageBroadcastNostrEventReceiptRelation::class, ChatMessageNostrEventRelation::class, ChatRoom::class, + Confederation::class, ConfederationCeremony::class, + ConfederationMember::class, ConfederationCeremonyMessage::class, ConfederationEvent::class, ConfederationInvitee::class, @@ -453,9 +457,9 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) // v43 adds the confederation (docs/confederation.md, Phase 4): ConfederationEvent, // ConfederationInvitee and ConfederationSigning. Three new tables, so Room generates it. AutoMigration(from = 42, to = 43), - // v44 adds the confederation's key ceremony (docs/confederation.md, Phase 11): - // ConfederationCeremony and ConfederationCeremonyMessage. Two new tables, so Room - // generates it. + // v44 adds the confederation's key ceremony and what it forms (docs/confederation.md, + // Phases 11 and 12): ConfederationCeremony, ConfederationCeremonyMessage, Confederation + // and ConfederationMember. New tables only, so Room generates it. AutoMigration(from = 43, to = 44), ] ) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationCeremonyDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationCeremonyDao.kt index 4d49b946..31ac7f8a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationCeremonyDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationCeremonyDao.kt @@ -44,4 +44,22 @@ interface ConfederationCeremonyDao { /** Once per sender and kind: a person's message for a step is the same bytes every time it is sent. */ @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertMessage(message: ConfederationCeremonyMessage): Long + + @Query("SELECT * FROM Confederation WHERE id = :id") + suspend fun getConfederation(id: HexKey): mobi.giza.compose.database.model.Confederation? + + @Query("SELECT * FROM Confederation WHERE proposalId = :proposalId") + suspend fun getConfederationForProposal(proposalId: HexKey): mobi.giza.compose.database.model.Confederation? + + @Query("SELECT * FROM Confederation ORDER BY createdAt DESC") + fun observeConfederations(): Flow> + + @Query("SELECT c.* FROM Confederation c JOIN ConfederationMember m ON m.confederationId = c.id WHERE m.groupPublicKey = :groupPublicKey ORDER BY c.createdAt DESC") + fun observeConfederationsOf(groupPublicKey: HexKey): Flow> + + @Upsert + suspend fun upsertConfederation(confederation: mobi.giza.compose.database.model.Confederation) + + @Insert(onConflict = OnConflictStrategy.IGNORE) + suspend fun insertMembers(members: List) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt index 3c88ff7b..16f51b26 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 @@ -541,6 +541,9 @@ data class ChatMessage( const val TYPE_CONFEDERATION_CEREMONY_COMPLETE = "confederationCeremonyComplete" const val TYPE_CONFEDERATION_CEREMONY_FAILED = "confederationCeremonyFailed" + /** A group's room, on its admins' devices: the group is now part of a formed confederation (Phase 12). */ + const val TYPE_CONFEDERATION_FORMED = "confederationFormed" + val CONFEDERATION_TYPES = setOf( TYPE_CONFEDERATION_PROPOSED, TYPE_CONFEDERATION_ACCEPTED, @@ -549,6 +552,7 @@ data class ChatMessage( TYPE_CONFEDERATION_CEREMONY_STARTED, TYPE_CONFEDERATION_CEREMONY_COMPLETE, TYPE_CONFEDERATION_CEREMONY_FAILED, + TYPE_CONFEDERATION_FORMED, ) val GROUP_IDENTITY_TYPES = setOf( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/Confederation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/Confederation.kt new file mode 100644 index 00000000..25bc8004 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/Confederation.kt @@ -0,0 +1,47 @@ +package mobi.giza.compose.database.model + +import androidx.room3.Entity +import androidx.room3.Index +import androidx.room3.PrimaryKey +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Clock +import kotlin.time.Instant + +/** + * A confederation this device holds a part of, once its key ceremony has finished + * (docs/confederation.md, Phase 12). + * + * Its descriptors are kept as upstream's canonical bytes -- roster, key state, certified genesis -- + * so nothing depends on the build that wrote them, with the `(configSeq, rpdHash, ksdHash)` triple + * upstream says an application must persist to accept only a direct successor later. This + * device's shares are kept only as their recovery packages: "a share has no canonical encoding". + * + * The id is the confederation's room id, derived from its key the way every keyed room's is (D10), + * whether or not that room exists yet. + */ +@Entity(indices = [Index("proposalId")]) +data class Confederation( + @PrimaryKey + val id: HexKey, + /** The confederation's key X, x-only. */ + val publicKey: HexKey, + val proposalId: HexKey, + val ceremonyId: String, + val name: String, + val roster: String, + val keyState: String, + val genesis: String, + val configSeq: Long, + val rosterHash: HexKey, + val keyStateHash: HexKey, + /** This device's roles, by group: each one's recovery package. */ + val recoveryPackages: String, + val createdAt: Instant = Clock.System.now(), +) + +/** A group that is part of a confederation, so a group's screen can find its confederations. */ +@Entity(primaryKeys = ["confederationId", "groupPublicKey"], indices = [Index("groupPublicKey")]) +data class ConfederationMember( + val confederationId: HexKey, + val groupPublicKey: HexKey, +) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt index 22b76fc2..3e857c81 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt @@ -12,6 +12,7 @@ import mobi.giza.compose.identity.Identity import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.Confederation import mobi.giza.compose.database.model.ConfederationCeremony import mobi.giza.compose.database.model.ConfederationCeremonyMessage import mobi.giza.compose.database.model.ConfederationEvent @@ -58,6 +59,9 @@ class DatabaseConfederationRepository( override suspend fun abandonCeremony(sessionId: String) = ConfederationRitualManager.abandon(database, sessionId) + override fun observeConfederationsOf(groupPublicKey: HexKey): Flow> = + database.confederationCeremonyDao().observeConfederationsOf(groupPublicKey) + override suspend fun outcome(proposalId: HexKey): ConfederationManager.Outcome? { val secret = activeIdentity.value?.nostrPrivateKey ?: return null return ConfederationManager.outcome(database, proposalId, secret) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationFormation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationFormation.kt new file mode 100644 index 00000000..8ca1980a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationFormation.kt @@ -0,0 +1,97 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.crypto.confederation.ConfederationKeyState +import fr.acinq.bitcoin.crypto.confederation.ConfederationRoster +import fr.acinq.bitcoin.crypto.confederation.ConfederationTransition +import fr.acinq.bitcoin.utils.Either +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.Confederation +import mobi.giza.compose.database.model.ConfederationCeremony +import mobi.giza.compose.database.model.ConfederationMember +import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder.Plan + +/** + * What a finished key ceremony leaves on a device: the confederation, kept as upstream's canonical + * descriptors and this device's recovery packages (docs/confederation.md, Phase 12). + */ +object ConfederationFormation { + private val logger = Logger.withTag("ConfederationFormation") + + /** The room id a confederation's key derives (D10): the same function as every keyed room's. */ + fun roomIdOf(publicKey: HexKey): HexKey = SharedKeyDerivation.marmotGroupId("02$publicKey") + + /** + * Files the confederation a completed [ceremony] made, once. The genesis is checked against + * the key state before anything is written -- `ConfederationTransition.fromData` verifies + * every role's host signature over it -- so a row here is a confederation every role + * certified, not one this device was told about. + */ + suspend fun onComplete(database: GizaDatabase, ceremony: ConfederationCeremony, plan: Plan, roster: ConfederationRoster): Confederation? { + val keyStateHex = ceremony.keyState ?: return null + val genesisHex = ceremony.genesis ?: return null + val packages = ceremony.recoveryPackages ?: return null + val keyState = (ConfederationKeyState.fromData(ByteVector(keyStateHex), roster) as? Either.Right)?.value ?: return null + val genesis = (ConfederationTransition.fromData(ByteVector(genesisHex), null, keyState) as? Either.Right)?.value ?: run { + logger.e("Ceremony ${ceremony.id}: the genesis does not verify against its key state; not filing it") + return null + } + val publicKey = keyState.publicKey.value.toHex() + val confederation = Confederation( + id = roomIdOf(publicKey), + publicKey = publicKey, + proposalId = plan.proposal.id, + ceremonyId = ceremony.id, + name = plan.proposal.name, + roster = roster.data.toHex(), + keyState = keyStateHex, + genesis = genesis.data.toHex(), + configSeq = roster.configSeq.toLong(), + rosterHash = roster.hash.toHex(), + keyStateHash = keyState.hash.toHex(), + recoveryPackages = packages, + ) + val known = database.confederationCeremonyDao().getConfederation(confederation.id) != null + database.confederationCeremonyDao().upsertConfederation(confederation) + database.confederationCeremonyDao().insertMembers(plan.groups.map { ConfederationMember(confederation.id, it) }) + + if (!known) { + // A line in each of this device's own member groups' rooms. Written here, by an admin's + // device for itself: members who are not admins took no part, and hear of it only from + // a confederation statement the confederation signs (Part C). + plan.groups.forEach { group -> + if (database.chatRoomDao().findChatRoomById(group) == null) return@forEach + database.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = ceremony.coordinatorPublicKey, + isUserMessage = false, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = group, + content = "This group is part of the confederation ${plan.proposal.name}, now formed", + messageType = ChatMessage.TYPE_CONFEDERATION_FORMED, + ) + ) + } + } + logger.i("Filed confederation ${confederation.id.take(12)} (${plan.proposal.name})") + return confederation + } + + /** + * Whether [confederation]'s stored descriptors still read and certify its own key, and its id + * is the room that key derives: what a device checks before it takes the room for this + * confederation's (Phase 13). + */ + fun verifies(confederation: Confederation): Boolean = runCatching { + val roster = (ConfederationRoster.fromData(ByteVector(confederation.roster)) as Either.Right).value + val keyState = (ConfederationKeyState.fromData(ByteVector(confederation.keyState), roster) as Either.Right).value + ConfederationTransition.fromData(ByteVector(confederation.genesis), null, keyState) is Either.Right && + keyState.publicKey.value.toHex() == confederation.publicKey && + roomIdOf(confederation.publicKey) == confederation.id + }.getOrDefault(false) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt index 016fcc9c..acaf91a0 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt @@ -556,11 +556,18 @@ object ConfederationRitualManager { } logger.i("Ceremony ${ceremony.id} complete: the confederation's key is ${ceremony.confederationPublicKey?.take(12)}") announce(database, ceremony, ChatMessage.TYPE_CONFEDERATION_CEREMONY_COMPLETE, "The confederation's key ceremony finished. Its key is made") + ConfederationFormation.onComplete(database, ceremony, plan, roster) } } // ---- helpers --------------------------------------------------------------------------- + /** The roster a ceremony ran over, once every host key is in; null before. */ + internal suspend fun rosterFor(database: GizaDatabase, ceremony: ConfederationCeremony, plan: Plan): ConfederationRoster? { + val hostKeys = perRole(database, ceremony, plan, ConfederationRitualEvents.HOST_KEYS) { PublicKey(ByteVector(it)) } ?: return null + return (plan.roster(hostKeys) as? Either.Right)?.value + } + private suspend fun own(database: GizaDatabase, ceremony: ConfederationCeremony, kind: Kind) = database.confederationCeremonyDao().getMessage(ceremony.id, ceremony.userPublicKey, kind) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt index 32b3768f..9e25b3a9 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt @@ -5,6 +5,7 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf import kotlin.time.Instant +import mobi.giza.compose.database.model.Confederation import mobi.giza.compose.database.model.ConfederationCeremony import mobi.giza.compose.database.model.ConfederationCeremonyMessage import mobi.giza.compose.database.model.ConfederationEvent @@ -85,6 +86,9 @@ interface ConfederationRepository { suspend fun abandonCeremony(sessionId: String) + /** The confederations [groupPublicKey] is part of, on this device. docs/confederation.md, Phase 12. */ + fun observeConfederationsOf(groupPublicKey: HexKey): Flow> + companion object { /** Holds nothing and proposes nothing: for screens and tests with no confederation behind them. */ val NO_OP_CONFEDERATION_REPOSITORY: ConfederationRepository = object : ConfederationRepository { @@ -121,6 +125,7 @@ interface ConfederationRepository { throw UnsupportedOperationException("No confederation here") override suspend fun joinCeremony(sessionId: String) = Unit override suspend fun abandonCeremony(sessionId: String) = Unit + override fun observeConfederationsOf(groupPublicKey: HexKey): Flow> = flowOf(emptyList()) } } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt index 7f527b58..29b663cb 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt @@ -34,6 +34,7 @@ import mobi.giza.compose.repository.ConfederationRepository import mobi.giza.compose.resources.Res import mobi.giza.compose.resources.confederation_accepted import mobi.giza.compose.resources.confederation_expired +import mobi.giza.compose.resources.confederation_formed import mobi.giza.compose.resources.confederation_groups_to_act import mobi.giza.compose.resources.confederation_open import mobi.giza.compose.resources.confederation_proposed_by @@ -174,7 +175,9 @@ private fun ConfederationProposalCard(item: ConfederationsUIState.Item, onClick: ListItem( leadingContent = { Icon(Icons.Default.Hub, contentDescription = Decorative) }, trailingContent = { Icon(Icons.Default.ChevronRight, contentDescription = Decorative) }, - overlineContent = { Text(text = stateLabel(status.state)) }, + overlineContent = { + Text(text = if (item.formed) stringResource(Res.string.confederation_formed) else stateLabel(status.state)) + }, headlineContent = { Text(text = proposal.name, maxLines = 1, overflow = TextOverflow.Ellipsis) }, supportingContent = { Column { 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 dd16f8fd..a0f3aa52 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 @@ -896,6 +896,7 @@ private fun RitualNotice( ChatMessage.TYPE_CONFEDERATION_CEREMONY_STARTED -> Icons.Default.Key ChatMessage.TYPE_CONFEDERATION_CEREMONY_COMPLETE -> Icons.Default.CheckCircle ChatMessage.TYPE_CONFEDERATION_CEREMONY_FAILED -> Icons.Default.ErrorOutline + ChatMessage.TYPE_CONFEDERATION_FORMED -> Icons.Default.Hub else -> Icons.Default.PanTool diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationsViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationsViewModel.kt index aa8a355a..14c00b2b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationsViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationsViewModel.kt @@ -11,6 +11,7 @@ import androidx.lifecycle.viewmodel.viewModelFactory import com.vitorpamplona.quartz.nip01Core.core.HexKey import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.launch import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.ConfederationRepository @@ -44,13 +45,17 @@ class ConfederationsViewModel( chatRepository.canSign(chatRoomId) && confederationRepository.isAdmin(chatRoomId, activeUserPublicKey) - confederationRepository.observeStatusesNaming(chatRoomId).collect { statuses -> + combine( + confederationRepository.observeStatusesNaming(chatRoomId), + confederationRepository.observeConfederationsOf(chatRoomId), + ) { statuses, formed -> statuses to formed.map { it.proposalId }.toSet() }.collect { (statuses, formed) -> confederationsUIState = ConfederationsUIState.Loaded( localChatRoom = localChatRoom, proposals = statuses.map { status -> ConfederationsUIState.Item( status = status, proposerName = confederationRepository.nameOf(status.proposal.proposingGroup, chatRoomId), + formed = status.proposal.id in formed, ) }, canPropose = canPropose, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationsUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationsUIState.kt index 8f5fa118..c311a154 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationsUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationsUIState.kt @@ -14,7 +14,7 @@ sealed interface ConfederationsUIState { ) : ConfederationsUIState /** One proposal, and how to name the group that made it. */ - data class Item(val status: ConfederationStatus, val proposerName: String) + data class Item(val status: ConfederationStatus, val proposerName: String, val formed: Boolean = false) data class Error(val message: String) : ConfederationsUIState diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt index 96afb7f0..5ed14752 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt @@ -161,6 +161,12 @@ class ConfederationCeremonyJvmTest { @Test fun `three groups of three make one key, the same on every device, that signs as the room`() { val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33))) + val agoraAdmin = devices.getValue(npub(secret(12))) + runBlocking { + agoraAdmin.db.chatRoomDao().upsert( + mobi.giza.compose.database.model.ChatRoom(id = groups[0], userPublicKey = agoraAdmin.person, subject = "#Agora", description = null, mlsGroupState = "00") + ) + } val opened = open(host, proposalId) pump() joinAll(opened.id) @@ -172,6 +178,20 @@ class ConfederationCeremonyJvmTest { assertEquals(1, all.values.map { it!!.genesis }.toSet().size, "one certified genesis, assembled on each device") all.values.forEach { assertNull(it!!.dealerSeeds, "dealer seeds erased once dealt") } + // Phase 12: every device files the same confederation, certified, under the room its key derives. + runBlocking { + val formed = devices.values.map { assertNotNull(it.db.confederationCeremonyDao().getConfederationForProposal(proposalId)) } + assertEquals(1, formed.map { it.id }.toSet().size) + formed.forEach { assertTrue(ConfederationFormation.verifies(it)) } + assertEquals(ConfederationFormation.roomIdOf(all.values.first()!!.confederationPublicKey!!), formed.first().id) + assertEquals( + 1, + agoraAdmin.db.chatMessageDao().getChatMessagesByChatRoomId(groups[0]) + .count { it.chatMessage.messageType == mobi.giza.compose.database.model.ChatMessage.TYPE_CONFEDERATION_FORMED }, + "one line in the admin's own group room", + ) + } + val (keyState, held) = shares(opened.id) val threshold = "02" + keyState.publicKey.value.toHex() val derived = SharedKeyDerivation.derive(threshold) diff --git a/docs/confederation.md b/docs/confederation.md index 6506814a..9022839a 100644 --- a/docs/confederation.md +++ b/docs/confederation.md @@ -76,6 +76,7 @@ the reasoning. Where the build chose differently: | 8 | done. `ConfederationManager.outcome` on the coordinator's device opens each acceptance with the active identity's key, checks each list names its group and proposal, counts roles (refusing more than 128, noting more than 16), names any listed group with no public profile on this device as what stands in the way, and lists admins who sit in more than one group. The proposal screen shows it once every group has accepted, ending on "the confederation's key ceremony is not available in this version yet". Withdrawal was built with the answers in Phases 3 and 7. `ConfederationNetworkJvmTest` 5/5, `ConfederationStorageJvmTest` 11/11 | | 10 | done. `ConfederationRosterBuilder` writes upstream's RPD bytes itself, since `ConfederationRoster` has only `fromData`: big-endian, a 96-byte header, 20 bytes a group, 69 a role. `plan` refuses rather than repairs (a list for another group or proposal, a missing acceptance, more than 128 roles). Host keys are `sha256(HOST_KEY_TAG ‖ nsec ‖ group ‖ proposal id)`, so one person holds a different key per role and per confederation. `ConfederationRosterBuilderJvmTest` 7/7: the roster parses, is byte-identical under any input order, and its `dkgLocal` key signs as the room's id | | 11 | done. `ConfederationRitualManager` over upstream's `ConfederationDkg`, in a NIP-17 room the coordinator opens over every admin (with placeholder profiles for members this device has none for). Kinds 30380 (opening), 30381 (host keys), 30382 (dealings), 30383 (roster and broadcast), 30384 (authorizations), 30385 (acknowledgments), 30387 (failure). One message per person per step, one value per role, keyed by group. **No 30386:** every device assembles the certified genesis itself from evidence it already holds, so nobody can hand one over. **No investigation (30388):** a decryption fault names "a participant or the coordinator" and ends the ceremony. Before joining, a device checks the proposal and acceptances are their groups' own, every acceptance opens with its disclosed key, the room is exactly the roster's people, and each group it is in still has the admins it accepted with, compared on their own so a member without a share still checks. Joining is the only approval; dealer seeds are erased once dealt; every role derives its key state itself and the coordinator's roster must match byte for byte. Schema 44. The coordinator opens it by a button on the proposal screen rather than on its own. `ConfederationRitualScreen`, with a join, each step's named waits and abandon. `ConfederationCeremonyJvmTest` 7/7: three groups of three on nine devices reach one key that signs as the room once each recovery package is opened; one person in two groups; a holdout and abandon; a disclosed key that does not open; a substituted roster; admins changed; messages before the opening. jvmTest 1,619 | +| 12 | done. `ConfederationFormation.onComplete` files a `Confederation` (room id, X, roster, key state, genesis, the `(configSeq, rpdHash, ksdHash)` triple, this device's recovery packages) and `ConfederationMember` rows, folded into schema 44 since it has not shipped. The genesis is verified against the key state before anything is written. A line goes into each of this device's own member groups' rooms; nothing is sent to them. **No 30389 key-state event:** every founding member of the room took part and holds the record, so `ConfederationFormation.verifies` checks the stored descriptors instead; a member added later needs one, which waits for Part C's governance. A formed confederation reads "Formed" on the group's list. `ConfederationCeremonyJvmTest` now also checks every device files the same verified confederation under the room its key derives | ---