From 057d0b79d9ac6e152b94502d69cbdbc5251d2176 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 01:41:46 +0200 Subject: [PATCH] feat: the group's inbox key, made by its admins at threshold 1 (group-inbox, Phase 4) InboxKeyRitualManager runs ChillDKG at t = 1 over the room's admins as MLS inner events on 30410-30416, so every admin ends with the same secret and the group a key nobody chose alone. Nobody is asked: an admin's device takes part on arrival, and a proposal over anyone but the admins as this device reads them fails out loud with the difference named. A member who is not an admin watches and holds nothing. The secret is checked against the key on every run and written once to InboxKey; the sweep resumes a ceremony left mid-round. The ceremony's screen moves to Phase 7 with the inbox's others. Co-Authored-By: Claude Opus 5.5 --- .../mobi/giza/compose/ExperimentalFeatures.kt | 13 + .../giza/compose/database/dao/NostrDao.kt | 17 + .../compose/database/model/ChatMessage.kt | 24 +- .../repository/DatabaseNostrRepository.kt | 5 + .../compose/managers/InboxFollowThrough.kt | 15 + .../compose/managers/InboxKeyRitualManager.kt | 557 ++++++++++++++++++ .../compose/managers/GroupInboxHarness.kt | 175 ++++++ .../compose/managers/InboxKeyRitualJvmTest.kt | 202 +++++++ 8 files changed, 1007 insertions(+), 1 deletion(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxFollowThrough.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxHarness.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxKeyRitualJvmTest.kt diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt index 0de7ed92..38495efb 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt @@ -28,6 +28,19 @@ object ExperimentalFeatures { */ val confederation: Boolean get() = confederationOverride ?: isDevelopmentBuild() + + /** Set by a test that has to see the build a release would be. */ + var groupInboxOverride: Boolean? = null + + /** + * A group that can be written to privately (docs/group-inbox.md): an inbox key its admins + * make together and the group announces, the messages sent to it, and replies the quorum + * signs. Off in a release while NIP-4E is a draft: off, the app offers no inbox, starts no + * ceremony and listens for nothing. A device still declines, out loud, an inbox + * announcement or a reply it finds wrong -- that is a refusal, not a feature. + */ + val groupInbox: Boolean + get() = groupInboxOverride ?: isDevelopmentBuild() } /** Whether this is a debug or development build of the app, rather than a release. */ diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt index aefdadb5..b3e1f83a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt @@ -88,6 +88,8 @@ import mobi.giza.compose.nostr.Relays import mobi.giza.compose.nostr.dkg.DkgRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.managers.ConfederationRitualManager +import mobi.giza.compose.managers.InboxKeyRitualManager +import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.nostr.frost.ShareRefreshEvents import mobi.giza.compose.nostr.frost.ShareRepairEvents @@ -1703,6 +1705,21 @@ abstract class NostrDao( nostrPrivateKey = activeKeyPair.privKey!! ) + // The group's inbox key, made by its admins in the group's own + // room (docs/group-inbox.md, D3). Off with the feature: a release + // build takes no part in a ceremony for a key it would not use. + InboxKeyRitualEvents.isInboxKeyKind(innerEvent.kind) -> { + if (ExperimentalFeatures.groupInbox) { + InboxKeyRitualManager.process( + database = database, + localChatRoom = localChatRoom, + innerEvent = innerEvent, + userPublicKey = activeKeyPair.pubKey.toHex(), + nostrPrivateKey = activeKeyPair.privKey!! + ) + } + } + // And a repair, in the same room (Phase 10). ShareRepairEvents.isShareRepairKind(innerEvent.kind) -> ShareRepairManager.processRepairPayload( 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 16f51b26..8012d5b1 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 @@ -4,6 +4,7 @@ import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import mobi.giza.compose.nostr.GroupNostrProfile import mobi.giza.compose.nostr.RetiredKinds import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents import androidx.room3.Entity import androidx.room3.ForeignKey @@ -555,6 +556,23 @@ data class ChatMessage( TYPE_CONFEDERATION_FORMED, ) + /** + * The group's inbox (docs/group-inbox.md): its key ceremony starting, finishing or + * failing, written by `InboxKeyRitualManager` on every device in the room. Three lines a + * ceremony rather than a ladder per step: nobody is asked anything in it, so there is + * nobody whose door the ladder would tell a member to knock on until it stalls, and the + * ceremony's screen names them then. + */ + const val TYPE_INBOX_KEY_STARTED = "inboxKeyStarted" + const val TYPE_INBOX_KEY_COMPLETE = "inboxKeyComplete" + const val TYPE_INBOX_KEY_FAILED = "inboxKeyFailed" + + val INBOX_TYPES = setOf( + TYPE_INBOX_KEY_STARTED, + TYPE_INBOX_KEY_COMPLETE, + TYPE_INBOX_KEY_FAILED, + ) + val GROUP_IDENTITY_TYPES = setOf( TYPE_GROUP_PROFILE_SIGNED, TYPE_LEGACY_GROUP_RELAYS_SIGNED, @@ -562,7 +580,7 @@ data class ChatMessage( TYPE_LEGACY_GROUP_SCHEMA_SIGNED, TYPE_LEGACY_GROUP_ENTRY_CURATED, TYPE_WALLET_NOT_TAKEN_PART_IN, - ) + CONFEDERATION_TYPES + ) + CONFEDERATION_TYPES + INBOX_TYPES /** * Every subgroup line, for the one check the transcript dispatches on. @@ -1269,6 +1287,10 @@ data class ChatMessage( in ShareRefreshEvents.ALL -> null in ShareRepairEvents.ALL -> null + // The inbox key ceremony's messages (docs/group-inbox.md). + // `InboxKeyRitualManager` files them and writes its own lines. + in InboxKeyRitualEvents.ALL -> null + ChatEvent.KIND -> { ChatMessage( giftWrapPayloadId = null, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt index 7d105ec7..16f3416a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt @@ -61,6 +61,7 @@ import kotlinx.coroutines.sync.withLock import mobi.giza.compose.managers.ChillDkgRitualManager import mobi.giza.compose.managers.FrostSigningManager import mobi.giza.compose.managers.ShareRefreshManager +import mobi.giza.compose.managers.InboxKeyRitualManager import com.vitorpamplona.quartz.nip01Core.core.toHexKey import mobi.giza.compose.identity.Identity @@ -158,6 +159,10 @@ class DatabaseNostrRepository( ) + FrostSigningManager.resumeVouched( database = database, userPublicKey = userPublicKey, + ) + InboxKeyRitualManager.resumeRunning( + database = database, + userPublicKey = userPublicKey, + nostrPrivateKey = privateKey ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxFollowThrough.kt new file mode 100644 index 00000000..5cda7ba7 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxFollowThrough.kt @@ -0,0 +1,15 @@ +package mobi.giza.compose.managers + +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.InboxKeyCeremony +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom + +/** + * What follows an inbox key ceremony on the device that coordinated it (docs/group-inbox.md, + * D5 and D6): proposing the group's announcement of the key it made. + */ +object InboxFollowThrough { + /** Called once, on every participant's device, when [ceremony] has made its key. */ + @Suppress("UNUSED_PARAMETER", "RedundantSuspendModifier") + suspend fun onKeyMade(database: GizaDatabase, localChatRoom: LocalChatRoom, ceremony: InboxKeyCeremony) = Unit +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt new file mode 100644 index 00000000..33e4e9c1 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt @@ -0,0 +1,557 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.crypto.random.RandomInstance +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.ByteVector64 +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import fr.acinq.bitcoin.crypto.dkg.chill.ChillDKG +import fr.acinq.secp256k1.ChilldkgFault +import kotlin.time.Clock +import kotlin.time.Instant +import kotlinx.coroutines.CancellationException +import mobi.giza.compose.ExperimentalFeatures +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.InboxKey +import mobi.giza.compose.database.model.InboxKeyCeremony +import mobi.giza.compose.database.model.InboxKeyCeremonyMessage +import mobi.giza.compose.database.model.InboxKeyCeremonyStage +import mobi.giza.compose.database.model.MarmotInnerEvent +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents +import mobi.giza.compose.nostr.inbox.InboxWire + +/** + * The group's inbox key ceremony (docs/group-inbox.md, D2, D3 and D4): ChillDKG at threshold 1 + * over the room's admins, which leaves every one of them holding the same secret `e` and the + * group a public key `E` nobody chose alone. + * + * The rounds are [ChillDkgRitualManager]'s, on kinds and tables of their own, with three + * differences: + * + * - **The participants are the room's admins**, exactly. Every device checks the proposal's + * `p` tags against its own reading of the room's admin policy, and a disagreement ends the + * ceremony out loud with the difference named. + * - **Nobody is asked.** Being an admin is the decision to hold the key; deciding to *have* an + * inbox is the group signing its announcement (D5). An admin's device takes part on arrival. + * - **The output is a whole secret**, written once to [InboxKey]. Nothing that looks for a + * signing key reads that table. + * + * Every message is an MLS inner event in the group's own room. Every member receives them all; + * ChillDKG encrypts each contribution to its recipients' host keys, so a member who is not an + * admin learns `E` and nothing else, and files three lines in the transcript. + */ +object InboxKeyRitualManager { + private val logger = Logger.withTag("InboxKeyRitualManager") + + /** + * A hash input, spelled the house way. Bound to the room so the host key an admin uses for + * one group's inbox says nothing about another's, and to nothing else, so the nsec alone + * recovers it. + */ + private const val HOST_KEY_TAG = "mantra/inbox-key/host-key/v1" + + const val MINIMUM_ADMINS = 2 + + const val ABANDONED = "Abandoned by an admin" + + fun deriveHostSecretKey(nostrPrivateKey: ByteArray, chatRoomId: String): PrivateKey = + PrivateKey(Crypto.sha256(HOST_KEY_TAG.encodeToByteArray() + nostrPrivateKey + chatRoomId.hexToByteArray())) + + fun deriveHostPublicKey(nostrPrivateKey: ByteArray, chatRoomId: String): PublicKey = + ChillDKG.hostPublicKey(deriveHostSecretKey(nostrPrivateKey, chatRoomId)) + + /** + * Why [userPublicKey] cannot open an inbox key ceremony in [localChatRoom] now, or null if + * they can. Read by the screens, so a button that could only fail is never offered. + */ + suspend fun refusal(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey): String? { + if (!ExperimentalFeatures.groupInbox) return "This build has no group inbox" + val room = localChatRoom.chatRoom + if (room.mlsGroupState == null || room.leftGroupAt != null) return "Only a group's own room can have an inbox" + val key = FrostSigningManager.completedKey(database, room.id) + ?: return "The group has no key to announce an inbox with" + val admins = RoomAdmins.of(database, room.id)?.admins ?: return "This device cannot read who the group's admins are" + if (userPublicKey !in admins) return "Only an admin can set up the group's inbox" + if (admins.size < MINIMUM_ADMINS) return "The group needs at least $MINIMUM_ADMINS admins for an inbox" + when (val hold = ShareRefreshManager.rotationHold(database, localChatRoom, key)) { + is RotationHold.Running, is RotationHold.AdminChangeInFlight, is RotationHold.Enrolling -> return hold.reason.replaceFirstChar { it.uppercase() } + else -> Unit + } + return null + } + + /** The generation a new ceremony in [chatRoomId] makes: one past any this device has seen. */ + suspend fun nextGeneration(database: GizaDatabase, chatRoomId: String, userPublicKey: HexKey): Int { + val keys = database.inboxKeyDao().getKeys(chatRoomId, userPublicKey).maxOfOrNull { it.generation } + val ceremony = database.inboxKeyDao().getLatestCeremony(chatRoomId, userPublicKey) + ?.takeIf { it.stage == InboxKeyCeremonyStage.COMPLETE }?.generation + return listOfNotNull(keys, ceremony).maxOrNull()?.plus(1) ?: 0 + } + + /** + * Opens a ceremony over the room's current admins, making this device its coordinator. A + * ceremony already running in the room is handed back instead of a second one. Throws with + * [refusal]'s reason when the room cannot have one. + */ + suspend fun propose( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + ): InboxKeyCeremony { + val roomId = localChatRoom.chatRoom.id + database.inboxKeyDao().getRunningCeremoniesIn(roomId).firstOrNull { it.userPublicKey == userPublicKey }?.let { return it } + + refusal(database, localChatRoom, userPublicKey)?.let { throw IllegalStateException(it) } + val admins = RoomAdmins.of(database, roomId)!!.admins + + val ceremony = InboxKeyCeremony( + id = RandomInstance.bytes(32).toHex(), + chatRoomId = roomId, + generation = nextGeneration(database, roomId, userPublicKey), + coordinatorPublicKey = userPublicKey, + userPublicKey = userPublicKey, + participantPublicKeys = InboxKeyCeremony.formatParticipants(admins), + hostPublicKey = deriveHostPublicKey(nostrPrivateKey, roomId).value.toHex(), + round1Random = RandomInstance.bytes(32).toHex(), + round2AuxRandom = RandomInstance.bytes(32).toHex(), + ) + database.inboxKeyDao().upsertCeremony(ceremony) + announceStarted(database, ceremony) + logger.i("Proposing inbox key ceremony ${ceremony.id.take(8)} at generation ${ceremony.generation} over ${admins.size} admins") + + broadcast( + database, localChatRoom, ceremony, InboxKeyRitualEvents.PROPOSAL, "", + proposal = true, + ) + advance(database, localChatRoom, ceremony.id, nostrPrivateKey) + return database.inboxKeyDao().getCeremony(ceremony.id)!! + } + + /** + * Feeds one inbound ceremony message in and moves the ceremony as far as it will go. Safe to + * call twice with the same message: every write is keyed and every step recomputed. + */ + suspend fun process( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + innerEvent: Event, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + ) { + val sessionId = InboxKeyRitualEvents.parseSessionId(innerEvent.tags) ?: run { + logger.w("Inbox key message ${innerEvent.id.take(8)} names no session; dropping") + return + } + + val ceremony = if (innerEvent.kind == InboxKeyRitualEvents.PROPOSAL) { + accept(database, localChatRoom, innerEvent, sessionId, userPublicKey, nostrPrivateKey) + } else { + // Relays and MLS hand messages back in no particular order; a round can arrive + // before its proposal. It is already stored as an inner event, and [accept] + // replays it once the proposal turns up. + database.inboxKeyDao().getCeremony(sessionId) + } ?: return + + if (!ceremony.isRunning) return + if (!record(database, ceremony, innerEvent)) return + if (ceremony.isParticipant()) advance(database, localChatRoom, ceremony.id, nostrPrivateKey) + } + + /** + * Moves every inbox key ceremony [userPublicKey] takes part in as far as its stored + * messages allow, for a ceremony left mid-round by a crash. Returns how many it looked at. + */ + suspend fun resumeRunning(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray): Int { + val running = database.inboxKeyDao().getRunningCeremonies(userPublicKey).filter { it.isParticipant() } + running.forEach { ceremony -> + val room = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return@forEach + advance(database, room, ceremony.id, nostrPrivateKey) + } + return running.size + } + + /** + * Ends a running ceremony for everyone in it. Only an admin it names can: a member who was + * never in it walking away is not the ceremony failing. Returns whether it was ended. + */ + suspend fun abandon(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String): Boolean { + val ceremony = database.inboxKeyDao().getCeremony(sessionId) ?: return false + if (!ceremony.isRunning || !ceremony.isParticipant()) return false + fail(database, ceremony, ABANDONED, ceremony.userPublicKey) + broadcast(database, localChatRoom, ceremony, InboxKeyRitualEvents.FAILURE, ABANDONED) + return true + } + + // ---- arrival ------------------------------------------------------------------------------- + + private suspend fun accept( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + innerEvent: Event, + sessionId: String, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + ): InboxKeyCeremony? { + database.inboxKeyDao().getCeremony(sessionId)?.let { return it } + val roomId = localChatRoom.chatRoom.id + + if (localChatRoom.chatRoom.mlsGroupState == null) { + logger.w("Inbox key proposal ${sessionId.take(8)} outside a Marmot room; dropping") + return null + } + val generation = InboxKeyRitualEvents.parseGeneration(innerEvent.tags) + val named = InboxKeyRitualEvents.parseParticipants(innerEvent.tags) + if (generation == null || named == null || InboxKeyRitualEvents.parseThreshold(innerEvent.tags) != InboxKeyRitualEvents.THRESHOLD) { + logger.w("Inbox key proposal ${sessionId.take(8)} is malformed; dropping") + return null + } + val participants = (named + innerEvent.pubKey).distinct().sorted() + + val base = InboxKeyCeremony( + id = sessionId, + chatRoomId = roomId, + generation = generation, + coordinatorPublicKey = innerEvent.pubKey, + userPublicKey = userPublicKey, + participantPublicKeys = InboxKeyCeremony.formatParticipants(participants), + ) + + // A member who is not named only watches: it files the lines, and holds nothing. + val mine = if (userPublicKey in participants) { + base.copy( + hostPublicKey = deriveHostPublicKey(nostrPrivateKey, roomId).value.toHex(), + round1Random = RandomInstance.bytes(32).toHex(), + round2AuxRandom = RandomInstance.bytes(32).toHex(), + ) + } else { + base + } + database.inboxKeyDao().upsertCeremony(mine) + announceStarted(database, mine) + + // D4: the participants are the admins, exactly, as this device reads them. A + // ceremony over anyone else would hand the group's mail to whoever the coordinator + // put in it, or leave an admin without it. An admin the proposal left out says so as + // loudly as a named one does. + val admins = RoomAdmins.of(database, roomId)?.admins + val mismatch = when { + admins == null -> null // nothing to compare with; the others will + admins.toSet() != participants.toSet() -> describeMismatch(admins, participants) + else -> null + } + if (mismatch != null && (userPublicKey in participants || userPublicKey in admins.orEmpty())) { + logger.w("Inbox key ceremony ${sessionId.take(8)}: $mismatch") + fail(database, mine, mismatch, userPublicKey) + broadcast(database, localChatRoom, mine, InboxKeyRitualEvents.FAILURE, mismatch) + return database.inboxKeyDao().getCeremony(sessionId) + } + + replayStored(database, localChatRoom, mine) + return database.inboxKeyDao().getCeremony(sessionId) + } + + private fun describeMismatch(admins: Set, participants: List): String { + val missing = admins - participants.toSet() + val extra = participants.toSet() - admins + return buildList { + if (missing.isNotEmpty()) add("leaves out ${missing.size} admin${if (missing.size == 1) "" else "s"} (${missing.sorted().joinToString { it.take(8) }})") + if (extra.isNotEmpty()) add("names ${extra.size} who ${if (extra.size == 1) "is not an admin" else "are not admins"} (${extra.sorted().joinToString { it.take(8) }})") + }.joinToString(" and ", prefix = "The inbox key ceremony ") + } + + /** Every message of [ceremony] that arrived before its proposal, read back out of the room's inner events. */ + private suspend fun replayStored(database: GizaDatabase, localChatRoom: LocalChatRoom, ceremony: InboxKeyCeremony) { + val stored = database.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId = ceremony.chatRoomId, kinds = (InboxKeyRitualEvents.ALL - InboxKeyRitualEvents.PROPOSAL).toList()) + .filter { InboxKeyRitualEvents.parseSessionId(it.tags) == ceremony.id } + stored.forEach { row -> + val event = Event(row.id, row.publicKey, row.createdAt.epochSeconds, row.kind, row.tags, row.content, "") + if (!record(database, ceremony, event)) return + } + } + + /** + * Files one message. Returns false when it ends the ceremony. Round messages count only + * from a participant, the coordinator's aggregates only from the coordinator: taking either + * from anyone else would let any member stall the ceremony by getting a bogus one in first. + */ + private suspend fun record(database: GizaDatabase, ceremony: InboxKeyCeremony, innerEvent: Event): Boolean { + val participants = ceremony.participants() + val sender = innerEvent.pubKey + when (innerEvent.kind) { + InboxKeyRitualEvents.PROPOSAL -> Unit + InboxKeyRitualEvents.HOST_KEY, InboxKeyRitualEvents.ROUND_1, InboxKeyRitualEvents.ROUND_2 -> { + if (sender !in participants) return true + store(database, ceremony, sender, innerEvent.kind, innerEvent.content) + } + InboxKeyRitualEvents.COORDINATOR_ROUND_1 -> { + if (sender != ceremony.coordinatorPublicKey) return true + store(database, ceremony, sender, innerEvent.kind, innerEvent.content) + } + InboxKeyRitualEvents.CERTIFICATE -> { + if (sender != ceremony.coordinatorPublicKey) return true + store(database, ceremony, sender, innerEvent.kind, innerEvent.content) + // A member who only watches cannot check the certificate; the admins can, and + // will fail it out loud if it is wrong. The watcher's line says it was issued. + if (!ceremony.isParticipant()) { + val current = database.inboxKeyDao().getCeremony(ceremony.id) ?: ceremony + if (current.isRunning) { + database.inboxKeyDao().upsertCeremony(current.copy(stage = InboxKeyCeremonyStage.COMPLETE, updatedAt = Clock.System.now())) + announce(database, current, ChatMessage.TYPE_INBOX_KEY_COMPLETE, "The group's admins finished making its inbox key.", current.coordinatorPublicKey) + } + } + } + InboxKeyRitualEvents.FAILURE -> { + if (sender !in participants && sender !in (RoomAdmins.of(database, ceremony.chatRoomId)?.admins ?: emptySet())) return true + fail(database, ceremony, innerEvent.content.ifBlank { ABANDONED }, sender) + return false + } + } + return true + } + + private suspend fun store(database: GizaDatabase, ceremony: InboxKeyCeremony, sender: HexKey, kind: Kind, payload: String) { + val inserted = database.inboxKeyDao().insertMessage(InboxKeyCeremonyMessage(ceremony.id, sender, kind, payload)) + if (inserted > 0) { + database.inboxKeyDao().getCeremony(ceremony.id)?.let { + database.inboxKeyDao().upsertCeremony(it.copy(lastMessageAt = Clock.System.now(), updatedAt = Clock.System.now())) + } + } + } + + // ---- the rounds ---------------------------------------------------------------------------- + + /** + * Takes every step the stored messages allow, stopping at the first one still waiting on + * somebody. Each step asks whether its output exists rather than what the stage says, so a + * re-entry repeats no work and skips none. + */ + private suspend fun advance(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) { + val start = database.inboxKeyDao().getCeremony(sessionId) ?: return + if (!start.isRunning || !start.isParticipant()) return + val roomId = start.chatRoomId + val hostSecret = deriveHostSecretKey(nostrPrivateKey, roomId) + val threshold = InboxKeyRitualEvents.THRESHOLD + + try { + if (own(database, start, InboxKeyRitualEvents.HOST_KEY) == null) { + publishOwn(database, localChatRoom, start, InboxKeyRitualEvents.HOST_KEY, requireNotNull(start.hostPublicKey)) + } + val hostPublicKeys = hostPublicKeys(database, start) ?: return + + val step1 = ChillDKG.participantStep1(hostSecret, hostPublicKeys, threshold, ByteVector32(requireNotNull(start.round1Random))) + if (own(database, start, InboxKeyRitualEvents.ROUND_1) == null) { + publishOwn(database, localChatRoom, start, InboxKeyRitualEvents.ROUND_1, step1.message.toHex()) + } + moveTo(database, start, InboxKeyCeremonyStage.ROUND_1) + + if (start.isCoordinator() && coordinatorMessage(database, start, InboxKeyRitualEvents.COORDINATOR_ROUND_1) == null) { + val pmsgs1 = ordered(database, start, InboxKeyRitualEvents.ROUND_1) ?: return + val cmsg1 = coordinatorStep1(pmsgs1, hostPublicKeys).message.toHex() + publishOwn(database, localChatRoom, start, InboxKeyRitualEvents.COORDINATOR_ROUND_1, cmsg1) + } + val cmsg1 = coordinatorMessage(database, start, InboxKeyRitualEvents.COORDINATOR_ROUND_1) ?: return + + // The check that stops a coordinator substituting a key the admins never + // contributed to: participantStep2 faults on a mismatch, and the catch below fails + // the ceremony for everyone. + val step2 = ChillDKG.participantStep2(hostSecret, step1.state, ByteVector(cmsg1.hexToByteArray()), ByteVector32(requireNotNull(start.round2AuxRandom))) + step2.fault.raiseIfFaulty("round 2") + if (own(database, start, InboxKeyRitualEvents.ROUND_2) == null) { + publishOwn(database, localChatRoom, start, InboxKeyRitualEvents.ROUND_2, step2.certEqSignature.toHex()) + } + moveTo(database, start, InboxKeyCeremonyStage.ROUND_2) + + if (start.isCoordinator() && coordinatorMessage(database, start, InboxKeyRitualEvents.CERTIFICATE) == null) { + val pmsgs2 = ordered(database, start, InboxKeyRitualEvents.ROUND_2) ?: return + val pmsgs1 = ordered(database, start, InboxKeyRitualEvents.ROUND_1) ?: return + val certified = ChillDKG.coordinatorFinalize(coordinatorStep1(pmsgs1, hostPublicKeys).state, pmsgs2.map { ByteVector64(it) }, threshold) + certified.fault.raiseIfFaulty("certificate") + publishOwn(database, localChatRoom, start, InboxKeyRitualEvents.CERTIFICATE, certified.certificate.toHex()) + } + val certificate = coordinatorMessage(database, start, InboxKeyRitualEvents.CERTIFICATE) ?: return + + val output = ChillDKG.participantFinalize(step2.state, ByteVector(certificate.hexToByteArray()), hostPublicKeys.size, threshold) + output.fault.raiseIfFaulty("finalize") + + // D2's premise, checked on every run rather than trusted from Phase 0: at t = 1 + // the share is the whole secret, so it has to be the discrete log of the key. + val secret = requireNotNull(output.secretShare) { "the ceremony left no secret" } + val thresholdKey = requireNotNull(output.thresholdPublicKey) { "the ceremony left no key" } + check(secret.publicKey() == thresholdKey) { "the inbox key's secret is not its key's: the ceremony was not at threshold 1" } + val secretBytes = secret.value.toByteArray() + val inboxKey = InboxWire.publicKeyOf(secretBytes) + + database.inboxKeyDao().upsertKey( + InboxKey( + chatRoomId = roomId, + userPublicKey = start.userPublicKey, + generation = start.generation, + publicKey = inboxKey, + secretKey = secretBytes.toHex(), + recoveryData = output.recovery?.toHex(), + ceremonyId = start.id, + ) + ) + val done = (database.inboxKeyDao().getCeremony(sessionId) ?: start) + .copy(stage = InboxKeyCeremonyStage.COMPLETE, inboxPublicKey = inboxKey, updatedAt = Clock.System.now()) + database.inboxKeyDao().upsertCeremony(done) + announce( + database, done, ChatMessage.TYPE_INBOX_KEY_COMPLETE, + "The group's admins made its inbox key. It reaches nobody until the group announces it.", + done.coordinatorPublicKey, + ) + logger.i("Inbox key ceremony ${sessionId.take(8)} complete: generation ${done.generation}") + InboxFollowThrough.onKeyMade(database, localChatRoom, done) + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + logger.e("Inbox key ceremony ${sessionId.take(8)} failed", e) + val reason = e.message ?: "The inbox key ceremony failed" + val current = database.inboxKeyDao().getCeremony(sessionId) ?: start + fail(database, current, reason, current.userPublicKey) + broadcast(database, localChatRoom, current, InboxKeyRitualEvents.FAILURE, reason) + } + } + + /** The participants' host keys, sorted, or null while any is outstanding. */ + private suspend fun hostPublicKeys(database: GizaDatabase, ceremony: InboxKeyCeremony): List? { + val participants = ceremony.participants() + val hostKeys = database.inboxKeyDao().getMessages(ceremony.id) + .filter { it.kind == InboxKeyRitualEvents.HOST_KEY && it.senderPublicKey in participants } + if (hostKeys.size < participants.size) return null + return hostKeys.map { it.payload.lowercase() }.sorted().map { PublicKey(ByteVector(it.hexToByteArray())) } + } + + /** A round's messages, one per participant, in host-key order; null while any is missing. */ + private suspend fun ordered(database: GizaDatabase, ceremony: InboxKeyCeremony, kind: Kind): List? { + val messages = database.inboxKeyDao().getMessages(ceremony.id) + val hostKeyOf = messages.filter { it.kind == InboxKeyRitualEvents.HOST_KEY }.associate { it.senderPublicKey to it.payload.lowercase() } + val participants = ceremony.participants() + val round = participants.map { participant -> + val message = messages.firstOrNull { it.kind == kind && it.senderPublicKey == participant } ?: return null + val hostKey = hostKeyOf[participant] ?: return null + hostKey to message.payload + } + return round.sortedBy { it.first }.map { it.second.hexToByteArray() } + } + + private fun coordinatorStep1(pmsgs1: List, hostPublicKeys: List) = + ChillDKG.coordinatorStep1(pmsgs1.map { ByteVector(it) }, hostPublicKeys, InboxKeyRitualEvents.THRESHOLD) + .also { it.fault.raiseIfFaulty("coordinator round 1") } + + private fun ChilldkgFault.raiseIfFaulty(step: String) { + if (isOk) return + val culprit = participantIndex?.let { " (participant $it)" } ?: "" + val reason = when (code) { + ChilldkgFault.FAULTY_COORDINATOR -> "the coordinator is faulty" + ChilldkgFault.FAULTY_PARTICIPANT -> "a participant is faulty" + ChilldkgFault.FAULTY_PARTICIPANT_OR_COORDINATOR -> "a participant or the coordinator is faulty" + ChilldkgFault.UNKNOWN_FAULTY_PARTICIPANT_OR_COORDINATOR -> "an unidentified participant or the coordinator is faulty" + ChilldkgFault.INVALID_INPUT -> "invalid input" + else -> "unrecognised fault code $code" + } + throw IllegalStateException("The inbox key ceremony's $step failed: $reason$culprit") + } + + private suspend fun own(database: GizaDatabase, ceremony: InboxKeyCeremony, kind: Kind) = + database.inboxKeyDao().getMessage(ceremony.id, ceremony.userPublicKey, kind) + + private suspend fun coordinatorMessage(database: GizaDatabase, ceremony: InboxKeyCeremony, kind: Kind): String? = + database.inboxKeyDao().getMessage(ceremony.id, ceremony.coordinatorPublicKey, kind)?.payload + + private suspend fun moveTo(database: GizaDatabase, ceremony: InboxKeyCeremony, stage: InboxKeyCeremonyStage) { + val current = database.inboxKeyDao().getCeremony(ceremony.id) ?: return + if (!current.isRunning || current.stage.ordinal >= stage.ordinal) return + database.inboxKeyDao().upsertCeremony(current.copy(stage = stage, updatedAt = Clock.System.now())) + } + + private suspend fun fail(database: GizaDatabase, ceremony: InboxKeyCeremony, reason: String, culprit: HexKey) { + val current = database.inboxKeyDao().getCeremony(ceremony.id) ?: ceremony + if (current.stage == InboxKeyCeremonyStage.FAILED) return + database.inboxKeyDao().upsertCeremony( + current.copy(stage = InboxKeyCeremonyStage.FAILED, failureReason = reason, culprit = culprit, updatedAt = Clock.System.now()) + ) + announce(database, current, ChatMessage.TYPE_INBOX_KEY_FAILED, "ended the inbox key ceremony: $reason. No key was made, and it is safe to run it again.", culprit) + } + + // ---- the wire ------------------------------------------------------------------------------ + + /** Sends one of this device's messages and records it, so its own is in every aggregation. */ + private suspend fun publishOwn(database: GizaDatabase, localChatRoom: LocalChatRoom, ceremony: InboxKeyCeremony, kind: Kind, content: String) { + broadcast(database, localChatRoom, ceremony, kind, content) + store(database, ceremony, ceremony.userPublicKey, kind, content) + } + + /** + * Queues one ceremony message as an MLS inner event for the room, the path chat messages + * take. The proposal carries the admins as `p` tags, the participant set every device + * rebuilds; nothing later needs them. + */ + private suspend fun broadcast( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + ceremony: InboxKeyCeremony, + kind: Kind, + content: String, + proposal: Boolean = false, + ) { + val tags = InboxKeyRitualEvents.assembleTags( + sessionId = ceremony.id, + generation = if (proposal) ceremony.generation else null, + participants = if (proposal) ceremony.participants().filterNot { it == ceremony.userPublicKey } else emptyList(), + ) + val createdAt = Clock.System.now().epochSeconds + val id = EventHasher.hashId(ceremony.userPublicKey, createdAt, kind, tags, content) + database.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = id, + publicKey = ceremony.userPublicKey, + kind = kind, + createdAt = Instant.fromEpochSeconds(createdAt), + tags = tags, + content = content, + chatRoomId = localChatRoom.chatRoom.id, + ) + ) + } + + // ---- the transcript ------------------------------------------------------------------------ + + private suspend fun announceStarted(database: GizaDatabase, ceremony: InboxKeyCeremony) { + val n = ceremony.participants().size + val text = if (ceremony.generation == 0) { + "started making the group's inbox key with its $n admins. Every admin will hold it, and it finishes once all of them have taken part." + } else { + "started changing the group's inbox key with its $n admins. Every admin will hold the new one, and it finishes once all of them have taken part." + } + announce(database, ceremony, ChatMessage.TYPE_INBOX_KEY_STARTED, text, ceremony.coordinatorPublicKey) + } + + private suspend fun announce(database: GizaDatabase, ceremony: InboxKeyCeremony, type: String, content: String, actor: HexKey) { + database.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = actor, + isUserMessage = actor == ceremony.userPublicKey, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = ceremony.chatRoomId, + content = content, + messageType = type, + ) + ) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxHarness.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxHarness.kt new file mode 100644 index 00000000..6dc7963d --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxHarness.kt @@ -0,0 +1,175 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.crypto.frost.Frost +import fr.acinq.bitcoin.crypto.frost.KeyMaterial +import mobi.giza.compose.ExperimentalFeatures +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.DkgParticipantMessage +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.MarmotInnerEvent +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.dkg.DkgRitualEvents +import mobi.giza.compose.nostr.frost.FrostSigningEvents +import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents + +/** + * One keyed group, a device per member, for the group inbox's tests (docs/group-inbox.md). + * + * Every member has a real nostr key, because the inbox ceremony derives its host keys from the + * nsec and the inbox opens NIP-44 with real secrets. The group's signing key stands in for a + * finished ceremony (a trusted dealer, as `SignedGroupKeyStateTest` has it), and the room is a + * Marmot one by its column -- nothing here runs MLS, so what a device sends is read off its + * inner events and handed to the others by [pump], stored first, as the inbound path would. + * + * Who a device sees as the room's admins is [admins], through [RoomAdmins.override]. + */ +class GroupInboxHarness( + names: List = listOf("alice", "bob", "carol"), + /** Members of the room who are not admins and hold no share. */ + watchers: List = emptyList(), + val threshold: Int = 2, +) { + val secrets: Map = (names + watchers).associateWith { Crypto.sha256("giza inbox $it".encodeToByteArray()) } + val keyOf: Map = secrets.mapValues { KeyPair(it.value).pubKey.toHexKey() } + val signers: List = names.map { keyOf.getValue(it) } + val everyone: List = (names + watchers).map { keyOf.getValue(it) } + + val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( + thresholdSecretKey = PrivateKey(ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1")), + nParticipants = names.size, + threshold = threshold, + ) + val thresholdPublicKey = keyMaterial.thresholdPublicKey.value.toHex() + val roomId: String = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + private val ceremonyId = "ceremony".padEnd(64, '0') + // Chosen to sort as the signers read, so signer i holds share i. + private val signingHostKeys = names.indices.map { "2${('a' + it)}".padEnd(66, '0') } + + /** Who every device reads as the room's admins. */ + var admins: Set = signers.toSet() + + val devices = mutableListOf() + + init { + ExperimentalFeatures.groupInboxOverride = true + RoomAdmins.override = { id -> if (id == roomId) RoomAdmins(admins, governed = false) else null } + } + + fun close() { + devices.forEach { it.db.close() } + RoomAdmins.override = null + ExperimentalFeatures.groupInboxOverride = null + } + + inner class Device(val name: String, val publicKey: HexKey, val secret: ByteArray, val db: GizaDatabase) { + /** Inner events already handed to this device, so a pump terminates. */ + val received = mutableSetOf() + + suspend fun room(): LocalChatRoom = db.chatRoomDao().findChatRoomById(roomId)!! + + suspend fun keys() = db.inboxKeyDao().getKeys(roomId, publicKey) + + suspend fun ceremony(id: String) = db.inboxKeyDao().getCeremony(id) + + suspend fun lines(types: Set) = + db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage }.filter { it.messageType in types } + } + + suspend fun device(name: String): Device { + val publicKey = keyOf.getValue(name) + val db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + everyone.forEach { member -> + val eventId = "e$member".take(64) + db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = member, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = member, nostrEventId = eventId)) + } + db.chatRoomDao().upsert( + ChatRoom( + id = roomId, + userPublicKey = publicKey, + subject = "#Ekklesia", + description = SharedKeyDerivation.describe("Admins of the group."), + mlsGroupState = "00", + ) + ) + + val signerIndex = signers.indexOf(publicKey) + if (signerIndex >= 0) { + db.dkgSessionDao().upsert( + DkgSession( + id = ceremonyId, + chatRoomId = roomId, + coordinatorPublicKey = signers.first(), + userPublicKey = publicKey, + threshold = threshold, + participantCount = signers.size, + stage = DkgRitualStage.COMPLETE, + hostPublicKey = signingHostKeys[signerIndex], + round1Random = "1".repeat(64), + round2AuxRandom = "2".repeat(64), + thresholdPublicKey = thresholdPublicKey, + secretShare = keyMaterial.secretShares[signerIndex].value.toHex(), + publicShares = keyMaterial.publicShares.joinToString(",") { it.value.toHex() }, + ) + ) + signers.forEachIndexed { index, signer -> + db.dkgSessionDao().upsert( + DkgParticipantMessage(sessionId = ceremonyId, participantPublicKey = signer, kind = DkgRitualEvents.HOST_KEY, payload = signingHostKeys[index]) + ) + } + } + return Device(name, publicKey, secrets.getValue(name), db).also { devices += it } + } + + /** The kinds [pump] carries between devices. */ + var carried: Set = FrostSigningEvents.ALL + InboxKeyRitualEvents.ALL + + private suspend fun outbox(device: Device): List = + device.db.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId = roomId, kinds = carried.toList()) + .filter { it.publicKey == device.publicKey } + .sortedWith(compareBy({ it.createdAt }, { it.kind })) + + /** + * Hands everything each device has sent to every other, until nobody has anything new. + * [except] devices are offline: they neither send nor receive. + */ + suspend fun pump(vararg between: Device = devices.toTypedArray(), except: Set = emptySet()) { + val online = between.filter { it !in except } + var moved = true + while (moved) { + moved = false + for (from in online) for (to in online) { + if (from === to) continue + outbox(from).forEach { row -> + if (!to.received.add(row.id)) return@forEach + moved = true + to.db.marmotInnerEventDao().upsert(row.copy()) + val event = Event(row.id, row.publicKey, row.createdAt.epochSeconds, row.kind, row.tags, row.content, "") + val room = to.room() + when { + FrostSigningEvents.isFrostSigningKind(row.kind) -> + FrostSigningManager.processSigningPayload(to.db, room, event, to.publicKey) + InboxKeyRitualEvents.isInboxKeyKind(row.kind) -> + InboxKeyRitualManager.process(to.db, room, event, to.publicKey, to.secret) + } + } + } + } + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxKeyRitualJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxKeyRitualJvmTest.kt new file mode 100644 index 00000000..3378262f --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxKeyRitualJvmTest.kt @@ -0,0 +1,202 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.ExperimentalFeatures +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.InboxKeyCeremonyStage +import mobi.giza.compose.database.model.InboxKeyState +import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents +import mobi.giza.compose.nostr.inbox.InboxWire + +/** + * The group's inbox key ceremony across devices (docs/group-inbox.md, Phase 4): three admins + * and a member who is not one, each on their own database, with what each sends handed to the + * others. + */ +class InboxKeyRitualJvmTest { + private val harness = GroupInboxHarness(watchers = listOf("dineo")) + + @AfterTest + fun close() = harness.close() + + private suspend fun group() = listOf("alice", "bob", "carol", "dineo").map { harness.device(it) } + + @Test + fun `every admin ends with the same secret, and it is the key the ceremony made`() = runBlocking { + val (alice, bob, carol, dineo) = group() + + val ceremony = InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + assertEquals(0, ceremony.generation) + harness.pump() + + val keys = listOf(alice, bob, carol).map { assertNotNull(it.keys().singleOrNull(), "${it.name} holds the key") } + assertEquals(1, keys.map { it.secretKey }.distinct().size, "every admin holds one secret") + keys.forEach { key -> + assertEquals(InboxKeyState.HELD, key.state, "made, not yet announced") + assertEquals(key.publicKey, InboxWire.publicKeyOf(assertNotNull(key.secretKey).hexToByteArray())) + assertNotNull(key.recoveryData) + } + listOf(alice, bob, carol).forEach { + assertEquals(InboxKeyCeremonyStage.COMPLETE, it.ceremony(ceremony.id)?.stage) + assertEquals(keys.first().publicKey, it.ceremony(ceremony.id)?.inboxPublicKey) + } + + // The member who is not an admin watched it happen and holds nothing. + assertEquals(emptyList(), dineo.keys()) + assertEquals(InboxKeyCeremonyStage.COMPLETE, dineo.ceremony(ceremony.id)?.stage) + assertEquals(1, dineo.lines(setOf(ChatMessage.TYPE_INBOX_KEY_STARTED)).size) + assertEquals(1, dineo.lines(setOf(ChatMessage.TYPE_INBOX_KEY_COMPLETE)).size) + } + + @Test + fun `nobody is asked, and each device says it once`() = runBlocking { + val (alice, bob, carol, _) = group() + InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + harness.pump() + harness.pump() // redelivery changes nothing + + listOf(alice, bob, carol).forEach { device -> + assertEquals(1, device.lines(setOf(ChatMessage.TYPE_INBOX_KEY_STARTED)).size) + assertEquals(1, device.lines(setOf(ChatMessage.TYPE_INBOX_KEY_COMPLETE)).size) + assertEquals(0, device.lines(setOf(ChatMessage.TYPE_INBOX_KEY_FAILED)).size) + } + } + + @Test + fun `a proposal that leaves out an admin fails out loud on every device`() = runBlocking { + val (alice, bob, carol, dineo) = group() + // Alice's device does not yet see Carol as an admin; everyone else does. + harness.admins = setOf(alice.publicKey, bob.publicKey) + val ceremony = InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + harness.admins = setOf(alice.publicKey, bob.publicKey, carol.publicKey) + harness.pump() + + listOf(alice, bob, carol, dineo).forEach { device -> + val seen = assertNotNull(device.ceremony(ceremony.id)) + assertEquals(InboxKeyCeremonyStage.FAILED, seen.stage, "${device.name} sees it failed") + assertTrue(seen.failureReason.orEmpty().contains("leaves out 1 admin"), seen.failureReason) + assertEquals(emptyList(), device.keys()) + } + } + + @Test + fun `a proposal that names someone who is not an admin fails out loud`() = runBlocking { + val (alice, bob, carol, dineo) = group() + harness.admins = setOf(alice.publicKey, bob.publicKey, carol.publicKey, dineo.publicKey) + val ceremony = InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + harness.admins = setOf(alice.publicKey, bob.publicKey, carol.publicKey) + harness.pump() + + listOf(bob, carol).forEach { device -> + val seen = assertNotNull(device.ceremony(ceremony.id)) + assertEquals(InboxKeyCeremonyStage.FAILED, seen.stage) + assertTrue(seen.failureReason.orEmpty().contains("is not an admin"), seen.failureReason) + } + assertEquals(emptyList(), dineo.keys()) + } + + @Test + fun `a ceremony interrupted mid-round finishes when its admins come back`() = runBlocking { + val (alice, bob, carol, dineo) = group() + val ceremony = InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + // Carol is offline for the first rounds: the rest can go no further than her host key. + harness.pump(except = setOf(carol)) + assertEquals(emptyList(), alice.keys()) + assertTrue(assertNotNull(alice.ceremony(ceremony.id)).isRunning) + + harness.pump() + assertEquals(1, alice.keys().size) + assertEquals(alice.keys().single().publicKey, carol.keys().single().publicKey) + assertEquals(alice.keys().single().publicKey, bob.keys().single().publicKey) + assertEquals(emptyList(), dineo.keys()) + } + + @Test + fun `a message delivered before its proposal is replayed, not lost`() = runBlocking { + val (alice, bob, _, _) = group() + InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + + // Bob gets Alice's host key ahead of her proposal. + val rows = alice.db.marmotInnerEventDao().getByChatRoomAndKinds(harness.roomId, InboxKeyRitualEvents.ALL.toList()) + val hostKey = rows.single { it.kind == InboxKeyRitualEvents.HOST_KEY } + val proposal = rows.single { it.kind == InboxKeyRitualEvents.PROPOSAL } + listOf(hostKey, proposal).forEach { row -> + bob.db.marmotInnerEventDao().upsert(row) + bob.received += row.id + InboxKeyRitualManager.process( + bob.db, bob.room(), + com.vitorpamplona.quartz.nip01Core.core.Event(row.id, row.publicKey, row.createdAt.epochSeconds, row.kind, row.tags, row.content, ""), + bob.publicKey, bob.secret, + ) + } + val ceremonyOnBob = assertNotNull(bob.db.inboxKeyDao().getLatestCeremony(harness.roomId, bob.publicKey)) + assertNotNull(bob.db.inboxKeyDao().getMessage(ceremonyOnBob.id, alice.publicKey, InboxKeyRitualEvents.HOST_KEY)) + + harness.pump() + assertEquals(alice.keys().single().publicKey, bob.keys().single().publicKey) + } + + @Test + fun `an admin can abandon a ceremony, and nobody else can`() = runBlocking { + val (alice, bob, carol, dineo) = group() + val ceremony = InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + harness.pump(except = setOf(carol)) + + assertTrue(!InboxKeyRitualManager.abandon(dineo.db, dineo.room(), ceremony.id), "a member who is not in it cannot end it") + assertTrue(InboxKeyRitualManager.abandon(bob.db, bob.room(), ceremony.id)) + harness.pump() + + listOf(alice, bob, carol, dineo).forEach { + assertEquals(InboxKeyCeremonyStage.FAILED, it.ceremony(ceremony.id)?.stage, "${it.name} sees it ended") + assertEquals(emptyList(), it.keys()) + } + } + + @Test + fun `only an admin can start one, one at a time, and not in a release build`() = runBlocking { + val (alice, _, _, dineo) = group() + + assertNotNull(InboxKeyRitualManager.refusal(dineo.db, dineo.room(), dineo.publicKey)) + assertFailsWith { InboxKeyRitualManager.propose(dineo.db, dineo.room(), dineo.publicKey, dineo.secret) } + + assertNull(InboxKeyRitualManager.refusal(alice.db, alice.room(), alice.publicKey)) + val first = InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + val again = InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + assertEquals(first.id, again.id, "a running ceremony is handed back, not doubled") + + ExperimentalFeatures.groupInboxOverride = false + assertNotNull(InboxKeyRitualManager.refusal(alice.db, alice.room(), alice.publicKey)) + } + + @Test + fun `a second ceremony makes the next generation, and a different key`() = runBlocking { + val (alice, bob, _, _) = group() + InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + harness.pump() + val second = InboxKeyRitualManager.propose(bob.db, bob.room(), bob.publicKey, bob.secret) + assertEquals(1, second.generation) + harness.pump() + + val keys = alice.keys() + assertEquals(listOf(1, 0), keys.map { it.generation }) + assertTrue(keys[0].publicKey != keys[1].publicKey) + assertEquals(bob.keys().map { it.publicKey }, keys.map { it.publicKey }) + } + + @Test + fun `host keys are bound to the room and come from the nsec alone`() { + val secret = harness.secrets.getValue("alice") + val here = InboxKeyRitualManager.deriveHostPublicKey(secret, harness.roomId) + assertEquals(here, InboxKeyRitualManager.deriveHostPublicKey(secret, harness.roomId)) + assertTrue(here != InboxKeyRitualManager.deriveHostPublicKey(secret, "1".repeat(64))) + assertTrue(here != ChillDkgRitualManager.deriveHostPublicKey(secret), "not the signing ceremony's host key") + } +}