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 e713b2bb..75987d93 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 @@ -87,6 +87,33 @@ class DatabaseChatRepository( parentChatRoomId = parentChatRoomId, ) + override suspend fun finishFoundingInvite( + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, + ): MarmotGroupCreation.FoundingInvite = MarmotGroupCreation.finishFoundingInvite( + database = database, + chatRepository = this, + ceremony = ceremony, + ceremonyRoom = ceremonyRoom, + ) + + override suspend fun finishFoundingInvite(chatRoomId: String): MarmotGroupCreation.FoundingInvite { + val (ceremony, ceremonyRoom) = FoundingAdmins.ceremonyOf(database, chatRoomId) + ?: return MarmotGroupCreation.FoundingInvite.NothingToDo + return finishFoundingInvite(ceremony, ceremonyRoom) + } + + override suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set = try { + FoundingAdmins.ceremonyOf(database, localChatRoom.chatRoom.id) + ?.let { (ceremony, ceremonyRoom) -> + MarmotGroupCreation.uninvitedFounders(database, localChatRoom, ceremony, ceremonyRoom) + } + .orEmpty() + } catch (e: Throwable) { + logger.e("Error reading who ${localChatRoom.chatRoom.id}'s founding invite missed", e) + emptySet() + } + override suspend fun followThroughCeremonies(keyPair: KeyPair) = CeremonyFollowThrough.observe(database = database, chatRepository = this, keyPair = keyPair) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt index 0f0fb013..430c9e06 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt @@ -30,7 +30,9 @@ import mobi.giza.compose.repository.ChatRepository * 1. a subgroup's parent certifies the room the key derives -- proposed here, and * signed by the parent's own quorum, which stays their decision; * 2. the group signs what that room will sign with, its key state; - * 3. the room is created and the members welcomed into it. + * 3. the room is created and the members welcomed into it; + * 4. a room whose founding invite never went out has it finished + * (docs/robust-group-admins.md, Phase 4). * * None of the three proposals asks anybody anything: each is a request to the * group, and the coordinator agreed to make it when they opened the ceremony. So @@ -62,7 +64,7 @@ object CeremonyFollowThrough { /** What one call to [takeNextStep] did. */ sealed interface Step { - /** Not this device's to do, or nothing left: not the coordinator, not finished, or the room exists. */ + /** Not this device's to do, or nothing left: not the coordinator, not finished, or the room exists with its founders. */ data object NothingToDo : Step /** Waiting on signatures somebody else gives. */ @@ -74,6 +76,12 @@ object CeremonyFollowThrough { /** The room exists now. */ data class Created(val chatRoomId: String) : Step + /** + * The room existed without its founders, whose invite never went out, and + * now they have been invited; [notAdded] could not be. + */ + data class Invited(val chatRoomId: String, val notAdded: List) : Step + /** The room cannot be created until these members' devices publish a key package. */ data class BlockedOn(val missing: List) : Step @@ -166,11 +174,24 @@ object CeremonyFollowThrough { val thresholdPublicKey = current.thresholdPublicKey ?: return@withLock Step.NothingToDo val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) - if (database.chatRoomDao().findChatRoomById(roomId) != null) return@withLock Step.NothingToDo - val ceremonyRoom = database.chatRoomDao().findChatRoomById(current.chatRoomId) ?: return@withLock Step.Stuck("The room ceremony ${current.id} ran in is gone") + // 4. The room exists: finish its founding invite if it never went out. + // Only a room still at epoch 0 has anything to finish, so nobody who + // left is ever invited back -- see `MarmotGroupCreation.uninvitedFounders`. + if (database.chatRoomDao().findChatRoomById(roomId) != null) { + return@withLock when (val invite = chatRepository.finishFoundingInvite(current, ceremonyRoom)) { + MarmotGroupCreation.FoundingInvite.NothingToDo -> Step.NothingToDo + is MarmotGroupCreation.FoundingInvite.Sent -> { + logger.i("Ceremony ${current.id}: invited ${invite.invited.size} founder(s) to $roomId") + Step.Invited(roomId, invite.notAdded) + } + is MarmotGroupCreation.FoundingInvite.BlockedOn -> Step.BlockedOn(invite.missing) + is MarmotGroupCreation.FoundingInvite.Failed -> Step.Stuck(invite.reason) + } + } + val participants = ChillDkgRitualManager.participantsOf(current, ceremonyRoom) val parent = current.parentChatRoomId diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt index bd5b78b6..b0b5c836 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt @@ -6,6 +6,7 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.ChatMessage import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent /** @@ -94,6 +95,18 @@ object FoundingAdmins { return check } + /** + * The ceremony that made [chatRoomId]'s key, as this device holds it, and the + * room it ran in -- or null where this device holds no key state for the room, + * no record of that ceremony, or no longer the room it ran in. + */ + suspend fun ceremonyOf(database: GizaDatabase, chatRoomId: String): Pair? { + val state = database.groupKeyStateDao().getByChatRoomId(chatRoomId) ?: return null + val ceremony = database.dkgSessionDao().getSessionById(state.dkgSessionId) ?: return null + val ceremonyRoom = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return null + return ceremony to ceremonyRoom + } + /** The ceremony's participants, or null when this device holds no record of them. */ private suspend fun foundersOf(database: GizaDatabase, ceremony: DkgSession?): Set? { ceremony ?: return null diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt index e3623067..2f8c4570 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt @@ -4,6 +4,7 @@ import co.touchlab.kermit.Logger import mobi.giza.compose.nostr.MarmotProfile import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.mls.group.MlsGroup import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope @@ -11,6 +12,7 @@ import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.withTimeoutOrNull import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.Participant import mobi.giza.compose.database.model.DkgSession import mobi.giza.compose.database.model.MarmotKeyPackage import mobi.giza.compose.database.model.intermdiate.LocalChatRoom @@ -177,8 +179,16 @@ object MarmotGroupCreation { // there is a row to file it against. GroupKeyStateManager.adopt(database, groupId) + // Read again now the routing is on file. The row above predates it, and a + // room with no routing row is addressed by its own id -- so on the current + // profile the invite went to a second copy of the group the engine adopted + // under the room id, and the copy at the real address still held only its + // creator. Every later invite then took the founding path: no commit, and + // nobody already in the room told. docs/robust-group-admins.md, Phase 4. + val routedRoom = chatRepository.getChatRoomByIdentifier(groupId) ?: localChatRoom + val notAdded = runCatching { - chatRepository.addMembers(localChatRoom = localChatRoom, peers = addable) + chatRepository.addMembers(localChatRoom = routedRoom, peers = addable) }.onFailure { logger.e("Failed to add members to $groupId", it) }.getOrElse { addable.map { (publicKey, _) -> publicKey } } @@ -257,6 +267,96 @@ object MarmotGroupCreation { ) } + /** What [finishFoundingInvite] did. */ + sealed interface FoundingInvite { + /** Every founding member holds a leaf, or the room is past its founding. */ + data object NothingToDo : FoundingInvite + + /** The founders who were missing were invited; [notAdded] could not be. */ + data class Sent(val chatRoomId: String, val invited: List, val notAdded: List) : FoundingInvite + + /** Some founders have no published key package, so nobody was invited. */ + data class BlockedOn(val missing: List) : FoundingInvite + + data class Failed(val reason: String) : FoundingInvite + } + + /** + * The founding members of [room] its founding invite never reached: listed as + * admins, holding no leaf, in a room nothing has been committed to since it was + * made. + * + * Only at epoch 0. A room is created at epoch 0 and its founding invite is the + * commit that leaves it -- so a room still there is one whose invite failed + * outright, and nobody in it has left or been removed, because either would + * have been a commit. Past epoch 0 a founder without a leaf might be one who + * left, and inviting them back is not this function's to decide + * (docs/robust-group-admins.md, Out of scope). + * + * A device holds a room at epoch 0 only if it made it: everybody else's copy + * comes from a Welcome, which is already past the founding commit. + */ + suspend fun uninvitedFounders( + database: GizaDatabase, + room: LocalChatRoom, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, + ): Set { + val group = liveGroupOf(database, room) ?: return emptySet() + if (group.epoch != 0L) return emptySet() + + val holdingLeaves = Participant.fromMlsGroup(group, room.chatRoom.id, null).map { it.participantPublicKey }.toSet() + return ChillDkgRitualManager.participantsOf(ceremony, ceremonyRoom) - holdingLeaves + } + + /** + * Invites the founding members [room]'s founding invite never reached -- see + * [uninvitedFounders] -- in one commit, as [create] would have. + * + * Every key package first, as at creation: a founder who cannot be invited yet + * holds the rest back rather than leaving the room to a second, partial + * founding. docs/robust-group-admins.md, Phase 4. + */ + suspend fun finishFoundingInvite( + database: GizaDatabase, + chatRepository: ChatRepository, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, + keyPackageLookupTimeout: Long = KEY_PACKAGE_LOOKUP_TIMEOUT, + ): FoundingInvite { + val thresholdPublicKey = ceremony.thresholdPublicKey ?: return FoundingInvite.NothingToDo + val groupId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + val room = chatRepository.getChatRoomByIdentifier(groupId) ?: return FoundingInvite.NothingToDo + + val uninvited = uninvitedFounders(database, room, ceremony, ceremonyRoom) + if (uninvited.isEmpty()) return FoundingInvite.NothingToDo + + val keyPackages = keyPackagesFor(chatRepository, uninvited.toList(), keyPackageLookupTimeout, room.chatRoom.marmotProfile()) + val missing = keyPackages.filter { it.second == null }.map { it.first } + if (missing.isNotEmpty()) { + logger.w("Not finishing $groupId's founding invite: no key package for $missing") + return FoundingInvite.BlockedOn(missing) + } + val addable = keyPackages.mapNotNull { (publicKey, keyPackage) -> keyPackage?.let { publicKey to it } } + + val notAdded = runCatching { + chatRepository.addMembers(localChatRoom = room, peers = addable) + }.onFailure { + logger.e("Failed to finish $groupId's founding invite", it) + }.getOrElse { return FoundingInvite.Failed(it.message ?: "Couldn't invite them. Please try again.") } + + flagAdmins(database, groupId) + logger.i("Finished $groupId's founding invite: ${addable.size - notAdded.size} invited, ${notAdded.size} not") + return FoundingInvite.Sent(groupId, addable.map { it.first }, notAdded) + } + + /** The room's live group: the row's on the legacy profile, the engine's on the current one. */ + private suspend fun liveGroupOf(database: GizaDatabase, room: LocalChatRoom): MlsGroup? = + when (room.chatRoom.marmotProfile()) { + MarmotProfile.LEGACY -> room.chatRoom.toMlsGroup() + MarmotProfile.CURRENT -> database.marmotEngine.groupFor(room.routingId) + } + /** * Writes `adminAt` on the rows of the members this room was created with as * admins. 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 bdb80a06..20d1eee1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -224,6 +224,19 @@ interface ChatRepository { parentChatRoomId: HexKey? = null, ): MarmotGroupCreation.Outcome + /** + * Invites the founding members [ceremony]'s room never reached, when its + * founding invite never went out. See `MarmotGroupCreation.finishFoundingInvite` + * and docs/robust-group-admins.md, Phase 4. + */ + suspend fun finishFoundingInvite(ceremony: DkgSession, ceremonyRoom: LocalChatRoom): MarmotGroupCreation.FoundingInvite + + /** [finishFoundingInvite] for the room [chatRoomId], through the ceremony its key state names. */ + suspend fun finishFoundingInvite(chatRoomId: String): MarmotGroupCreation.FoundingInvite + + /** The founders [localChatRoom]'s founding invite never reached; empty when there are none to reach. */ + suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set + /** * Takes every key ceremony [keyPair] coordinated from a key to a working room, * until cancelled: asks the group to sign its key state (a subgroup's parent to @@ -468,6 +481,14 @@ interface ChatRepository { override suspend fun followThroughCeremonies(keyPair: KeyPair) = Unit + override suspend fun finishFoundingInvite(ceremony: DkgSession, ceremonyRoom: LocalChatRoom) = + MarmotGroupCreation.FoundingInvite.NothingToDo + + override suspend fun finishFoundingInvite(chatRoomId: String) = + MarmotGroupCreation.FoundingInvite.NothingToDo + + override suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set = emptySet() + override suspend fun sendChatMessage( text: String, diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt index 19003418..25e9ad7c 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt @@ -50,6 +50,7 @@ class CeremonyFollowThroughJvmTest { /** The room creations asked for, and what the next one answers. */ private val created = mutableListOf>>() private var outcome: (String) -> MarmotGroupCreation.Outcome = { MarmotGroupCreation.Outcome.Failed("unset") } + private var foundingInvite: MarmotGroupCreation.FoundingInvite = MarmotGroupCreation.FoundingInvite.NothingToDo private val chatRepository = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { override suspend fun createMarmotGroup( @@ -63,6 +64,8 @@ class CeremonyFollowThroughJvmTest { created += groupId to adminPublicKeys return outcome(groupId) } + + override suspend fun finishFoundingInvite(ceremony: DkgSession, ceremonyRoom: LocalChatRoom) = foundingInvite } private val material = keyMaterial("5eed0000000000000000000000000000000000000000000000000000000000e5") @@ -203,6 +206,28 @@ class CeremonyFollowThroughJvmTest { assertTrue(created.isEmpty()) } + /** docs/robust-group-admins.md, Phase 4: a room that exists is asked whether its founding invite went out. */ + @Test + fun `a room whose founding invite never went out has it finished`(): Unit = runBlocking { + val session = finishedCeremony() + signKeyState(session) + GroupFixtures.seedRoom(db, roomOf(material)) + foundingInvite = MarmotGroupCreation.FoundingInvite.Sent(roomOf(material), invited = listOf(alice, bob), notAdded = listOf(bob)) + + assertEquals(CeremonyFollowThrough.Step.Invited(roomOf(material), listOf(bob)), next(session)) + assertTrue(created.isEmpty(), "and no second room") + } + + @Test + fun `a founding invite waiting on key packages says on whom`(): Unit = runBlocking { + val session = finishedCeremony() + signKeyState(session) + GroupFixtures.seedRoom(db, roomOf(material)) + foundingInvite = MarmotGroupCreation.FoundingInvite.BlockedOn(listOf(alice)) + + assertEquals(CeremonyFollowThrough.Step.BlockedOn(listOf(alice)), next(session)) + } + /** * A subgroup's room needs its parent's certificate before its key state can * even be proposed, so that is asked for first -- and then the parent's diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt index 7d7e1774..cd660d8c 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt @@ -26,6 +26,12 @@ import kotlinx.coroutines.runBlocking import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.builder.getRoomDatabase import mobi.giza.compose.database.model.MarmotKeyPackage +import mobi.giza.compose.nostr.Relays +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.types.DkgApprovalStep import mobi.giza.compose.database.repository.DatabaseChatRepository import mobi.giza.compose.database.repository.DatabaseMarmotRepository @@ -84,7 +90,8 @@ class RobustGroupAdminsJvmTest { override fun toString() = publicKey.take(8) } - private val roomId = SharedKeyDerivation.marmotGroupId("02" + KeyPair().pubKey.toHexKey()) + private val foundingThresholdPublicKey = "02" + KeyPair().pubKey.toHexKey() + private val roomId = SharedKeyDerivation.marmotGroupId(foundingThresholdPublicKey) /** * Three phones; the first creates the admin room with all three as its admins, @@ -118,7 +125,7 @@ class RobustGroupAdminsJvmTest { } /** Hands [to] the Welcome [from] queued for it, wrapped as a relay would carry it. */ - private suspend fun welcome(from: Phone, to: Phone) { + private suspend fun welcome(from: Phone, to: Phone, roomId: String = this.roomId) { val payload = from.db.giftWrapPayloadDao().getAllGiftWrapUnsigned() .filter { it.kind == WelcomeEvent.KIND } .single { payload -> payload.tags.any { it.size > 1 && it[1] == to.keyPackage.id } } @@ -192,13 +199,14 @@ class RobustGroupAdminsJvmTest { /** * The boundary docs/robust-group-admins.md, D1 draws: founding, not present. * - * Legacy only until Phase 4. On the current profile `MarmotGroupCreation` invites - * the founders through a room read before its routing id was recorded, so the - * engine's group at the real address still holds only the creator, and a later - * invite takes the founding path -- no commit, and nobody else told. + * On both profiles since Phase 4. Before it, `MarmotGroupCreation` invited the + * founders on the current profile through a room read before its routing id was + * recorded, so the engine's group at the real address still held only the + * creator, and this later invite took the founding path -- no commit, and + * nobody else told. */ @Test - fun `a member added after the founding is not an admin`() = onEveryProfile(listOf(MarmotProfile.LEGACY)) { profile, phones -> + fun `a member added after the founding is not an admin`() = onEveryProfile { profile, phones -> val founders = phones.map { it.publicKey }.toSet() val creator = phones.first() @@ -219,6 +227,119 @@ class RobustGroupAdminsJvmTest { } } + // ---- The founding invite: docs/robust-group-admins.md, Phase 4 ------------- + + private val ceremonyRoomId = "ce1e".repeat(16) + + /** The ceremony [phones] ran, as [owner]'s device holds it: everyone in it, and its key [roomId]'s. */ + private suspend fun ceremonyOn(owner: Phone, phones: List, thresholdPublicKey: HexKey): Pair { + owner.db.chatRoomDao().upsert( + ChatRoom(id = ceremonyRoomId, userPublicKey = owner.publicKey, subject = "Ekklesia", description = null, mlsGroupState = null) + ) + val session = DkgSession( + id = "the-ceremony", + chatRoomId = ceremonyRoomId, + coordinatorPublicKey = owner.publicKey, + userPublicKey = owner.publicKey, + threshold = 2, + participantCount = phones.size, + participantPublicKeys = DkgSession.formatParticipants(phones.map { it.publicKey }.toSet()), + subject = "Ekklesia", + stage = DkgRitualStage.COMPLETE, + hostPublicKey = owner.publicKey, + round1Random = "aa".repeat(32), + round2AuxRandom = "bb".repeat(32), + thresholdPublicKey = thresholdPublicKey, + secretShare = "cc".repeat(32), + ) + owner.db.dkgSessionDao().upsert(session) + return session to assertNotNull(owner.db.chatRoomDao().findChatRoomById(ceremonyRoomId)) + } + + /** + * A room whose founding invite never went out: made, with every founder in + * its policy, and nobody but its creator in its tree -- what `create` leaves + * when `addMembers` throws. + */ + private suspend fun roomWithoutItsInvite(profile: MarmotProfile, phones: List, roomId: String) { + val creator = phones.first() + val created = MarmotGroupFactory.create( + creator = creator.keyPair, + roomId = roomId, + name = "#Ekklesia", + description = SharedKeyDerivation.describe("Admins of Ekklesia."), + adminPublicKeys = phones.map { it.publicKey }, + relays = Relays.DefaultDMRelayList.map { it.url }, + profile = profile, + ) + assertNotNull( + creator.chatRepository.getOrCreateChatRoom( + chatRoomId = roomId, + activeUserPublicKey = creator.publicKey, + relayHint = null, + defaultSubject = "#Ekklesia", + description = null, + mlsGroupState = created.group.saveState().encodeTls().toHex(), + ) + ) + creator.chatRepository.recordMarmotRouting(chatRoomId = roomId, routingId = created.routingId) + } + + @Test + fun `a founding invite that never went out is finished, and every founder is an admin`(): Unit = runBlocking { + listOf(MarmotProfile.LEGACY, MarmotProfile.CURRENT).forEach { profile -> + val phones = List(3) { Phone(profile) } + try { + phones.forEach { it.ready() } + phones.forEach { phone -> phones.forEach { MarmotStandIn.seedProfile(phone.db, it.publicKey) } } + val creator = phones.first() + phones.drop(1).forEach { creator.db.marmotKeyPackageDao().upsert(it.keyPackage) } + + val thresholdPublicKey = "02" + KeyPair().pubKey.toHexKey() + val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + roomWithoutItsInvite(profile, phones, roomId) + val (session, ceremonyRoom) = ceremonyOn(creator, phones, thresholdPublicKey) + + val invite = MarmotGroupCreation.finishFoundingInvite( + creator.db, creator.chatRepository, session, ceremonyRoom, keyPackageLookupTimeout = 2_000L, + ) + val sent = assertIs(invite, "($profile)") + assertEquals(phones.drop(1).map { it.publicKey }.toSet(), sent.invited.toSet(), "($profile)") + assertTrue(sent.notAdded.isEmpty(), "($profile)") + + assertEquals( + MarmotGroupCreation.FoundingInvite.NothingToDo, + MarmotGroupCreation.finishFoundingInvite(creator.db, creator.chatRepository, session, ceremonyRoom, 2_000L), + "and a second run invites nobody ($profile)", + ) + + phones.drop(1).forEach { welcome(from = creator, to = it, roomId = roomId) } + val founders = phones.map { it.publicKey }.toSet() + phones.forEach { phone -> + val room = assertNotNull(phone.db.chatRoomDao().findChatRoomById(roomId), "$phone has no room ($profile)") + val group = assertNotNull(room.chatRoom.toMlsGroup(), "$phone holds no group ($profile)") + assertEquals(founders, group.currentAdminIdentities(), "$phone's admin policy ($profile)") + assertTrue(group.isLocalAdmin(), "$phone is not an admin ($profile)") + } + } finally { + phones.forEach { it.close() } + } + } + } + + /** Past epoch 0 a founder without a leaf may be one who left; that is not this step's to undo. */ + @Test + fun `a room past its founding invites nobody`() = onEveryProfile { profile, phones -> + val creator = phones.first() + val (session, ceremonyRoom) = ceremonyOn(creator, phones, foundingThresholdPublicKey) + + assertEquals( + MarmotGroupCreation.FoundingInvite.NothingToDo, + MarmotGroupCreation.finishFoundingInvite(creator.db, creator.chatRepository, session, ceremonyRoom, 2_000L), + "($profile)", + ) + } + // ---- The ceremony ------------------------------------------------------------ @Test