diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 7a3f6211..b9b806df 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -739,4 +739,5 @@ The ceremony ended: %1$s %1$s: %2$d of %3$d admins to sign Formed + This is the room of the confederation %1$s. Its key is held by the admins of its groups together. Until the confederation can sign, who is in this room cannot change. 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 90af7e4c..016b4102 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 @@ -81,6 +81,8 @@ import mobi.giza.compose.managers.ChronicleManager import mobi.giza.compose.managers.FrostSigningManager import mobi.giza.compose.extensions.toHex import mobi.giza.compose.managers.ConfederationRitualManager +import mobi.giza.compose.managers.ConfederationFormation +import mobi.giza.compose.managers.ConfederationFollowThrough import mobi.giza.compose.managers.GroupKeyStateManager import mobi.giza.compose.managers.MarmotGroupCreation import mobi.giza.compose.managers.SubgroupManager @@ -164,6 +166,9 @@ class DatabaseChatRepository( // A confederation's key ceremony this device joined, moved as far as its stored // messages allow, as ChillDKG's are on resume. docs/confederation.md, Phase 11. if (ExperimentalFeatures.confederation) { + // A formed confederation's room, made by its coordinator's device. + // docs/confederation.md, Phase 13. + launch { ConfederationFollowThrough.observe(database = database, chatRepository = this@DatabaseChatRepository, keyPair = keyPair) } keyPair.privKey?.let { secret -> launch { runCatching { ConfederationRitualManager.resumeRunning(database, keyPair.pubKey.toHex(), secret) } @@ -261,6 +266,11 @@ class DatabaseChatRepository( override suspend fun confederationProposalCount(chatRoomId: String): Int = database.confederationDao().getProposalsNaming(chatRoomId).size + override suspend fun confederationOfRoom(chatRoomId: String): String? = + database.confederationCeremonyDao().getConfederation(chatRoomId) + ?.takeIf { ConfederationFormation.verifies(it) } + ?.name + override suspend fun canSign(chatRoomId: String): Boolean = try { FrostSigningManager.canSign(database, chatRoomId) } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationFollowThrough.kt new file mode 100644 index 00000000..4ad19f89 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationFollowThrough.kt @@ -0,0 +1,110 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import fr.acinq.bitcoin.utils.Either +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.conflate +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.Confederation +import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents +import mobi.giza.compose.repository.ChatRepository + +/** + * The confederation's room, made by the coordinator's device once the key exists + * (docs/confederation.md, Phase 13), in the shape of `CeremonyFollowThrough`. + * + * The room is an ordinary keyed Marmot room: its id is derived from the confederation's key the way + * every keyed room's is (D10), its routing address is random, and every role holder is a member and + * an admin. It is born governed, so every later change to who is in it needs the confederation's + * signature -- which, until Part C, nothing can make. Its founding members are therefore its + * members, and the room says so. + */ +object ConfederationFollowThrough { + private val logger = Logger.withTag("ConfederationFollowThrough") + private val mutex = Mutex() + + /** Follows every confederation this device holds, until cancelled. A key package arriving looks again. */ + suspend fun observe(database: GizaDatabase, chatRepository: ChatRepository, keyPair: KeyPair) { + combine( + database.confederationCeremonyDao().observeConfederations(), + database.marmotKeyPackageDao().observeCount(), + ) { confederations, _ -> confederations } + .conflate() + .collect { confederations -> + confederations.forEach { confederation -> + try { + takeNextStep(database, chatRepository, confederation, keyPair) + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + logger.e("Following confederation ${confederation.id.take(12)} through failed", e) + } + } + } + } + + /** Makes [confederation]'s room if this device coordinated it and the room is not here yet. */ + suspend fun takeNextStep( + database: GizaDatabase, + chatRepository: ChatRepository, + confederation: Confederation, + keyPair: KeyPair, + keyPackageLookupTimeout: Long = MarmotGroupCreation.KEY_PACKAGE_LOOKUP_TIMEOUT, + ): MarmotGroupCreation.Outcome? = mutex.withLock { + if (database.chatRoomDao().findChatRoomById(confederation.id) != null) return@withLock null + val ceremony = database.confederationCeremonyDao().getCeremony(confederation.ceremonyId) ?: return@withLock null + if (ceremony.coordinatorPublicKey != keyPair.pubKey.toHexKey()) return@withLock null + createRoom(database, chatRepository, confederation, keyPair, keyPackageLookupTimeout) + } + + /** + * Creates [confederation]'s room. Any role holder may -- the coordinator's device does it on its + * own -- and anybody else is refused: listing themselves as the creator would put a member into + * a room the confederation never chose. + */ + suspend fun createRoom( + database: GizaDatabase, + chatRepository: ChatRepository, + confederation: Confederation, + keyPair: KeyPair, + keyPackageLookupTimeout: Long = MarmotGroupCreation.KEY_PACKAGE_LOOKUP_TIMEOUT, + ): MarmotGroupCreation.Outcome { + if (!ConfederationFormation.verifies(confederation)) { + return MarmotGroupCreation.Outcome.Failed("This confederation's record does not verify.") + } + val ceremony = database.confederationCeremonyDao().getCeremony(confederation.ceremonyId) + ?: return MarmotGroupCreation.Outcome.Failed("This device holds no ceremony for this confederation.") + val plan = ConfederationRitualEvents.Opening.decode(ceremony.openingJson) + ?.let { ConfederationRitualManager.planFrom(it) as? Either.Right }?.value + ?: return MarmotGroupCreation.Outcome.Failed("This confederation's roster no longer reads.") + val me = keyPair.pubKey.toHexKey() + if (me !in plan.people) { + return MarmotGroupCreation.Outcome.Failed("Only someone who holds a role in the confederation can create its room.") + } + + val outcome = MarmotGroupCreation.create( + database = database, + chatRepository = chatRepository, + groupId = confederation.id, + name = confederation.name, + purpose = "A confederation of ${plan.groups.size} groups, whose key their admins hold together.", + adminPublicKeys = plan.people.toSet(), + minimumAdmins = Quorum.minimumAdmins(plan.proposal.threshold), + userPublicKey = me, + keyPair = keyPair, + keyPackageLookupTimeout = keyPackageLookupTimeout, + ) + when (outcome) { + is MarmotGroupCreation.Outcome.Created -> logger.i("Created confederation room ${confederation.id.take(12)}; not added: ${outcome.notAdded.size}") + is MarmotGroupCreation.Outcome.BlockedOn -> logger.i("Confederation room ${confederation.id.take(12)} waits on ${outcome.missing.size} key package(s)") + is MarmotGroupCreation.Outcome.Failed -> logger.w("Confederation room ${confederation.id.take(12)}: ${outcome.reason}") + is MarmotGroupCreation.Outcome.Existing -> Unit + } + return outcome + } +} 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 19c7c415..a43e518e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -135,6 +135,9 @@ interface ChatRepository { /** How many confederation proposals naming [chatRoomId] this device holds. docs/confederation.md. */ suspend fun confederationProposalCount(chatRoomId: String): Int = 0 + /** The confederation whose room [chatRoomId] is, by name, if its record verifies here. docs/confederation.md, Phase 13. */ + suspend fun confederationOfRoom(chatRoomId: String): String? = null + /** * Why these members cannot hold a subgroup ceremony together, or null when * they can. 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 d0f41f97..79fb2290 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 @@ -16,6 +16,7 @@ import mobi.giza.compose.resources.confederations import mobi.giza.compose.resources.no_confederations_yet import mobi.giza.compose.resources.one_confederation_proposal import mobi.giza.compose.resources.n_confederation_proposals +import mobi.giza.compose.resources.this_is_the_confederations_room import androidx.compose.material.icons.filled.Campaign import mobi.giza.compose.resources.not_described_yet import mobi.giza.compose.resources.no_name_on_this_profile @@ -715,6 +716,20 @@ fun ChatRoomDetailScreen( // The confederations naming this group, and the way into // proposing one (docs/confederation.md). Every member can // read them; the screen behind it gates proposing. + // The confederation's own room: what it is, and why it cannot + // change its members yet. docs/confederation.md, Phase 13. + chatRoomDetailUIState.confederationName?.let { name -> + item { + Card(modifier = Modifier.fillMaxWidth()) { + Text( + modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), + text = stringResource(Res.string.this_is_the_confederations_room, name), + style = MaterialTheme.typography.bodyMedium, + ) + } + } + } + if (ExperimentalFeatures.confederation) { item { ConfederationsRow( 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 ad1a7e2e..d048388b 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 @@ -133,6 +133,7 @@ class ChatRoomDetailViewModel( groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), groupPosts = chatRepository.groupPosts(chatRoomId), confederationProposalCount = chatRepository.confederationProposalCount(chatRoomId), + confederationName = chatRepository.confederationOfRoom(chatRoomId), canProposeAsGroup = canSign && roomIsOpen, subgroupsNeedAWallet = canSign && subgroupsNeedAWallet, canGovern = canGovern, 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 9790ac1a..03a951bd 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 @@ -74,6 +74,8 @@ sealed interface ChatRoomDetailUIState { val groupPosts: List = emptyList(), /** How many confederation proposals naming this group this device holds. docs/confederation.md. */ val confederationProposalCount: Int = 0, + /** The confederation whose room this is, by name: its membership is fixed until it can sign. */ + val confederationName: String? = null, /** * Whether this device could put a profile or a post to the group's quorum: * a Marmot room it has not left, not disbanded, where it holds a share of 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 5ed14752..709e2e80 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt @@ -1,6 +1,17 @@ package mobi.giza.compose.managers import androidx.room3.Room +import mobi.giza.compose.nostr.MarmotProfile +import mobi.giza.compose.database.repository.DatabaseChatRepository +import mobi.giza.compose.database.model.MarmotKeyPackage +import kotlinx.coroutines.IO +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.CoroutineScope +import kotlin.test.assertIs +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.marmot.groups.currentAdminIdentities +import com.vitorpamplona.marmot.appComponents.CurrentProfileGroupFactory import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.ByteVector @@ -323,4 +334,68 @@ class ConfederationCeremonyJvmTest { pump() ceremonies(opened.id).values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) } } + + // ---- Phase 13: the confederation's room ---------------------------------------------- + + private fun formed(): Pair { + val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33))) + val opened = open(host, proposalId) + pump() + joinAll(opened.id) + pump() + return host to runBlocking { assertNotNull(host.db.confederationCeremonyDao().getConfederationForProposal(proposalId)) } + } + + /** Every member's key package on [device], as it would have synced them, but for [except]. */ + private fun keyPackagesOn(device: Device, except: Set = emptySet()) = runBlocking { + devices.values.filter { it !== device && it.person !in except }.forEach { peer -> + val bundle = CurrentProfileGroupFactory.createKeyPackage(NostrSignerInternal(KeyPair(privKey = peer.secret.value.toByteArray()))) + device.db.marmotKeyPackageDao().upsert( + MarmotKeyPackage( + id = peer.person.take(60) + "0000", + publicKey = peer.person, + tlsEncodedMarmotKeyPackage = bundle.keyPackage.toTlsBytes(), + profile = MarmotProfile.CURRENT.wireName, + ) + ) + } + } + + private fun repository(device: Device) = DatabaseChatRepository(device.db, CoroutineScope(Dispatchers.IO)) + + @Test + fun `the coordinator's device makes the room the key derives, with every role holder its admin`() { + val (host, confederation) = formed() + keyPackagesOn(host) + + val outcome = runBlocking { + ConfederationFollowThrough.takeNextStep(host.db, repository(host), confederation, KeyPair(privKey = host.secret.value.toByteArray()), keyPackageLookupTimeout = 2_000L) + } + val created = assertIs(outcome) + assertEquals(confederation.id, created.room.chatRoom.id, "the room is the one the confederation's key derives") + assertEquals("#Atlas", created.room.chatRoom.subject) + val group = assertNotNull(created.room.chatRoom.toMlsGroup()) + assertEquals(devices.keys, group.currentAdminIdentities()) + assertEquals(Quorum.minimumAdmins(2), GovernanceGate.minimumAdmins(group), "born governed: fixed until the confederation can sign") + assertEquals(emptyList(), created.notAdded) + assertEquals("Atlas", runBlocking { repository(host).confederationOfRoom(confederation.id) }) + } + + @Test + fun `a member's key package missing holds the room back, and nobody else's device makes it`() { + val (host, confederation) = formed() + val missing = npub(secret(23)) + keyPackagesOn(host, except = setOf(missing)) + val hostKeys = KeyPair(privKey = host.secret.value.toByteArray()) + + val blocked = runBlocking { ConfederationFollowThrough.takeNextStep(host.db, repository(host), confederation, hostKeys, keyPackageLookupTimeout = 500L) } + assertEquals(listOf(missing), assertIs(blocked).missing) + + val member = devices.getValue(npub(secret(22))) + val memberCopy = runBlocking { assertNotNull(member.db.confederationCeremonyDao().getConfederation(confederation.id)) } + assertNull(runBlocking { ConfederationFollowThrough.takeNextStep(member.db, repository(member), memberCopy, KeyPair(privKey = member.secret.value.toByteArray())) }) + + val outsider = runBlocking { ConfederationFollowThrough.createRoom(host.db, repository(host), confederation, KeyPair(), keyPackageLookupTimeout = 500L) } + assertIs(outsider) + } } diff --git a/docs/confederation.md b/docs/confederation.md index 9022839a..a6628937 100644 --- a/docs/confederation.md +++ b/docs/confederation.md @@ -77,6 +77,7 @@ the reasoning. Where the build chose differently: | 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 | +| 13 | done. `ConfederationFollowThrough` on the coordinator's device makes the room once every member's key package is in, retrying when one arrives, through `MarmotGroupCreation.create` rather than a new `createForConfederation`: id `marmotGroupId(02‖X)`, a random routing address, every role holder a member and an admin, `#name`, born governed with `Quorum.minimumAdmins(T)`. A record that no longer verifies, or a device holding no role, makes no room. Adoption needs no new check: every founding member holds the `Confederation` row under the room's id, and `confederationOfRoom` reads it only if it verifies. The room's screen says whose room it is and that its members are fixed until the confederation can sign. `ConfederationCeremonyJvmTest` 9/9. `./gradlew check` passes, jvmTest 1,621 | ---