From 266bee2ae00e3f06bdc91ae502e9e0e3b7ac1fb3 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Mon, 23 Nov 2026 13:45:36 +0200 Subject: [PATCH] feat: the key ceremony runs in no NIP-17 room, only the groups' rooms and inboxes (confederation-dkg-inboxes, Phase 5) Joining makes no room. A person's messages go only into their seat groups' rooms, and each group's admins carry them to every inbox. A failure goes back the same way, and the ceremony's lines are written into those rooms. ConfederationCeremony loses chatRoomId and its key onto ChatRoom, folded into schema 54. A ritual kind arriving as a gift wrap is dropped. Joining now needs this device to hold the inbox key and the room of each of its seat groups. A roster whose largest message would not fit one envelope is refused, computed from the exact size of a dealing before anyone deals. The ceremony tests run on the groups alone, including a carrier away, two of a group's three not carrying, a seat without its inbox key, a round split across envelopes and a roster too large. The profile network test forms its confederation over real group rooms and inboxes. Co-Authored-By: Claude Opus 5.5 --- .../54.json | 34 +- .../giza/compose/database/dao/NostrDao.kt | 36 +- .../ConfederationCeremonyInboxMigration.kt | 8 +- .../database/model/ConfederationCeremony.kt | 11 +- .../managers/ConfederationRitualManager.kt | 261 +++++------- .../managers/ConfederationCeremonyJvmTest.kt | 378 ++++++++++-------- .../compose/managers/ConfederationPeople.kt | 47 +-- .../ConfederationProfileNetworkJvmTest.kt | 36 +- .../ConfederationSharedSeatsSigningJvmTest.kt | 2 +- .../managers/ConfederationSigningJvmTest.kt | 21 +- .../managers/ConfederationStorageJvmTest.kt | 6 +- .../compose/managers/GroupInboxHarness.kt | 6 +- .../composable/ConfederationScreensJvmTest.kt | 2 +- docs/confederation-dkg-inboxes.md | 9 + 14 files changed, 386 insertions(+), 471 deletions(-) diff --git a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/54.json b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/54.json index 7ff40035..f67b7f64 100644 --- a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/54.json +++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/54.json @@ -2,7 +2,7 @@ "formatVersion": 1, "database": { "version": 54, - "identityHash": "86fa78ce882d1fa00f01f24bbf7d8097", + "identityHash": "05a5d3376140d29581bcca0b6bc66810", "entities": [ { "tableName": "BroadcastNostrEventReceipt", @@ -978,7 +978,7 @@ }, { "tableName": "ConfederationCeremony", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `basisJson` TEXT NOT NULL, `attempt` INTEGER NOT NULL DEFAULT 1, `attestationRef` TEXT, `seedContribution` TEXT, `stage` TEXT NOT NULL, `approvedAt` INTEGER, `dealerSeeds` TEXT, `recoveryNonces` TEXT, `keyState` TEXT, `transitionHash` TEXT, `genesis` TEXT, `recoveryPackages` TEXT, `confederationPublicKey` TEXT, `failureReason` TEXT, `culprit` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `basisJson` TEXT NOT NULL, `attempt` INTEGER NOT NULL DEFAULT 1, `attestationRef` TEXT, `seedContribution` TEXT, `stage` TEXT NOT NULL, `approvedAt` INTEGER, `dealerSeeds` TEXT, `recoveryNonces` TEXT, `keyState` TEXT, `transitionHash` TEXT, `genesis` TEXT, `recoveryPackages` TEXT, `confederationPublicKey` TEXT, `failureReason` TEXT, `culprit` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`))", "fields": [ { "fieldPath": "id", @@ -986,12 +986,6 @@ "affinity": "TEXT", "notNull": true }, - { - "fieldPath": "chatRoomId", - "columnName": "chatRoomId", - "affinity": "TEXT", - "notNull": true - }, { "fieldPath": "proposalId", "columnName": "proposalId", @@ -1103,15 +1097,6 @@ ] }, "indices": [ - { - "name": "index_ConfederationCeremony_chatRoomId", - "unique": false, - "columnNames": [ - "chatRoomId" - ], - "orders": [], - "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationCeremony_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" - }, { "name": "index_ConfederationCeremony_proposalId", "unique": false, @@ -1121,19 +1106,6 @@ "orders": [], "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationCeremony_proposalId` ON `${TABLE_NAME}` (`proposalId`)" } - ], - "foreignKeys": [ - { - "table": "ChatRoom", - "onDelete": "CASCADE", - "onUpdate": "NO ACTION", - "columns": [ - "chatRoomId" - ], - "referencedColumns": [ - "id" - ] - } ] }, { @@ -7737,7 +7709,7 @@ ], "setupQueries": [ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", - "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '86fa78ce882d1fa00f01f24bbf7d8097')" + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '05a5d3376140d29581bcca0b6bc66810')" ] } } \ No newline at end of file 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 936afa55..08c87844 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 @@ -1093,37 +1093,11 @@ abstract class NostrDao( ) } } else if (ConfederationRitualEvents.isRitualKind(decryptedGiftWrapPayload.kind)) { - // A confederation's key ceremony, in the NIP-17 room over - // every admin of every group (docs/confederation.md, Phase 11), - // as envelopes of signed events (docs/confederation-dkg-inboxes.md, - // Phase 3): the manager reads only those, and drops a bare - // ritual rumor. The room is made on demand from the p-tags, as - // for a group's own ceremony, and the manager is idempotent. - if (ExperimentalFeatures.confederation) { - val localChatRoom = getOrCreateNip17ChatRoom( - decryptedGiftWrapPayload = decryptedGiftWrapPayload, - activeKeyPair = activeKeyPair, - nostrEventId = nostrEvent.id, - relayURL = relayURL - ) - if (localChatRoom != null) { - ConfederationRitualManager.process( - database = database, - localChatRoom = localChatRoom, - innerEvent = Event( - id = decryptedGiftWrapPayload.id, - pubKey = decryptedGiftWrapPayload.publicKey, - createdAt = decryptedGiftWrapPayload.createdAt.epochSeconds, - kind = decryptedGiftWrapPayload.kind, - tags = decryptedGiftWrapPayload.tags, - content = decryptedGiftWrapPayload.content, - sig = "" - ), - userPublicKey = activeKeyPair.pubKey.toHex(), - nostrPrivateKey = activeKeyPair.privKey!! - ) - } - } + // A confederation's key ceremony runs in no NIP-17 room any more: its + // rounds travel through the groups' own rooms and inboxes + // (docs/confederation-dkg-inboxes.md, Phase 5). Nothing that speaks + // for anyone sends one as a gift wrap, so no room is made for it. + logger.w("A key ceremony message came as a gift wrap; ceremonies run in the groups' rooms now, so it is dropped") } else if (FrostSigningEvents.isFrostSigningKind(decryptedGiftWrapPayload.kind)) { // A FROST signing message for one of our NIP-17 // groups, which is where a group makes its first diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/migrations/ConfederationCeremonyInboxMigration.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/migrations/ConfederationCeremonyInboxMigration.kt index d5622a05..f628d980 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/migrations/ConfederationCeremonyInboxMigration.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/migrations/ConfederationCeremonyInboxMigration.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.database.migrations +import androidx.room3.DeleteColumn import androidx.room3.migration.AutoMigrationSpec /** @@ -8,7 +9,10 @@ import androidx.room3.migration.AutoMigrationSpec * * Phase 2 adds only shapes Room migrates itself: the `ConfederationCeremonyHeard` table, and * `ConfederationCarry.scope`, whose default makes every row already there a signing's, which every - * one of them is. The spec exists from the start so Phases 5 and 7, which drop the ceremony's room - * column and the rooms themselves, fold into this version rather than adding two more. + * one of them is. + * + * Phase 5 drops `ConfederationCeremony.chatRoomId` and its key onto `ChatRoom`: a ceremony runs in no + * room. Room rebuilds the table without the key and keeps every row. */ +@DeleteColumn(tableName = "ConfederationCeremony", columnName = "chatRoomId") class ConfederationCeremonyInboxMigration : AutoMigrationSpec diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ConfederationCeremony.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ConfederationCeremony.kt index 0478add7..c31c9b29 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ConfederationCeremony.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ConfederationCeremony.kt @@ -23,17 +23,12 @@ import kotlin.time.Instant * go of it, is followed column by column: the dealer seeds are erased once this device's dealings * are stored, and the key state is written before the acknowledgment that promises it is kept. */ -@Entity( - foreignKeys = [ - ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE) - ], - indices = [Index("chatRoomId"), Index("proposalId")], -) +@Entity(indices = [Index("proposalId")]) data class ConfederationCeremony( @PrimaryKey val id: String, - /** The NIP-17 room the ceremony runs in, over every admin of every group. */ - val chatRoomId: String, + // No room: the rounds travel through the groups' own rooms and inboxes + // (docs/confederation-dkg-inboxes.md, Phase 5), so nothing about a ceremony hangs off one. val proposalId: HexKey, val userPublicKey: HexKey, /** diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt index c5e14fd0..601a2012 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt @@ -43,6 +43,7 @@ import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.confederation.ConfederationAdminList import mobi.giza.compose.nostr.confederation.ConfederationAttestation +import mobi.giza.compose.nostr.confederation.ConfederationKinds import mobi.giza.compose.nostr.confederation.ConfederationProposalState import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents.Basis @@ -57,8 +58,7 @@ import mobi.giza.compose.nostr.confederation.ConfederationStatus * Phase 11), over upstream's `ConfederationDkg`, with nobody coordinating it * (docs/confederation-without-coordinator.md, D8 to D10). * - * The shape is `ChillDkgRitualManager`'s and for its reasons. The ceremony runs in a NIP-17 room - * over every admin of every group, on gift-wrapped rumors, and every step is a pure function of what + * The shape is `ChillDkgRitualManager`'s and for its reasons. Every step is a pure function of what * this device has stored, so [advance] decides what to do next from which messages exist, never * from the stage, and a device that dies between rounds picks up on the next message or the next * [resumeRunning]. Joining is the only thing a member is asked; the rounds after it run by @@ -74,6 +74,11 @@ import mobi.giza.compose.nostr.confederation.ConfederationStatus * - **The broadcast** is computed by every device from the dealings it holds; it takes no secret. * Each 30384 carries its hash, so two devices that were dealt different things find out by name. * + * **No room of its own** (docs/confederation-dkg-inboxes.md). Each person's messages are signed events + * written into the Marmot room of each group they hold a seat in; each group's admins carry them, one + * at a time in order, to every member group's inbox ([ConfederationBridge]). Every person in a + * ceremony is an admin of their groups and reads their inbox, so nothing has to be carried back in. + * * WARNING: upstream's confederation module is experimental and unaudited. This runs behind * `ExperimentalFeatures.confederation`, off in release. */ @@ -132,8 +137,8 @@ object ConfederationRitualManager { (basisFor(database, proposalId) as? Either.Right)?.value?.let { planFrom(it) as? Either.Right }?.value /** - * Where [userPublicKey]'s ceremony messages go besides the NIP-17 room: the room of every group they - * hold a seat in, that this device holds as a Marmot room. Each group's admins carry them on (Phase 4). + * Where [userPublicKey]'s ceremony messages go: the room of every group they hold a seat in, that + * this device holds as a Marmot room. Each group's admins carry them on. */ private suspend fun roomsFor(database: GizaDatabase, plan: Plan, userPublicKey: HexKey): List = plan.seatsOf(userPublicKey).map { it.group }.distinct() @@ -166,9 +171,39 @@ object ConfederationRitualManager { return Either.Left("The admins of ${ConfederationManager.nameOf(database, group)} have changed since it accepted") } } + // Every message has to fit one envelope a relay takes (docs/confederation-dkg-inboxes.md, Phase 0). + val largest = largestMessageBytes(plan) + if (largest.second > ConfederationKinds.MAX_CARRIED_BYTES) { + return Either.Left( + "This confederation has too many admins for ${ConfederationManager.nameOf(database, largest.first)}, " + + "who sits in ${plan.seatsOf(largest.first).size} of its groups, to send their part", + ) + } + // The rounds are read through the groups' inboxes, and written into the groups' rooms. + plan.seatsOf(userPublicKey).map { it.group }.distinct().forEach { group -> + if (ConfederationManager.announcedInboxKey(database, group, userPublicKey) == null) { + return Either.Left("This device can't read the groups' messages yet. Set up ${ConfederationManager.nameOf(database, group)}'s inbox first.") + } + if (database.chatRoomDao().findChatRoomById(group)?.chatRoom?.mlsGroupState == null) { + return Either.Left("This device doesn't hold ${ConfederationManager.nameOf(database, group)}'s room") + } + } return Either.Right(plan) } + /** + * The person whose dealings message is the largest this roster makes, and its size in bytes as a + * signed event: one role's 30382 value is exactly `2 · (210 + 33T + Σ_g (4 + 33(t_g − 1)) + 32R) + 89` + * bytes (docs/confederation-dkg-inboxes.md, Phase 0, check 3), a person sends one for each seat, and + * the event around them, its id, key, signature and three tags, is under 600. + */ + internal fun largestMessageBytes(plan: Plan): Pair { + val roles = plan.seats.size + val inner = plan.groups.sumOf { 4 + 33 * (plan.adminLists.getValue(it).threshold - 1) } + val perRole = 2 * (210 + 33 * plan.proposal.threshold + inner + 32 * roles) + 89 + return plan.people.map { person -> person to plan.seatsOf(person).size * perRole + 600 }.maxBy { it.second } + } + // ---- joining, and trying again ---------------------------------------------------------- /** Whether this ceremony is waiting on its member to join. */ @@ -212,7 +247,7 @@ object ConfederationRitualManager { if (latest != null && latest.stage == ConfederationCeremonyStage.COMPLETE) return latest if (latest != null && latest.isRunning) { if (latest.approvedAt == null) update(database, latest) { it.copy(approvedAt = Clock.System.now()) } - database.chatRoomDao().findChatRoomById(latest.chatRoomId)?.let { advance(database, it, latest.id, nostrPrivateKey) } + advance(database, latest.id, nostrPrivateKey) return database.confederationCeremonyDao().getCeremony(latest.id)!! } @@ -226,15 +261,8 @@ object ConfederationRitualManager { } val attempt = (latest?.attempt ?: 0) + 1 - ensureProfiles(database, plan.people) - // Every device makes the same room: its id is the set of its people (D8). - val room = database.nostrNip17Dao().createNip17ChatRoom( - userPublicKey = userPublicKey, - participantPublicKeys = plan.people.filter { it != userPublicKey }, - subject = plan.proposal.name, - ) ?: throw IllegalStateException("Could not make the ceremony's room") - - val ceremony = newCeremony(database, room.chatRoom.id, userPublicKey, basis, plan, attempt).copy(approvedAt = Clock.System.now()) + // No room is made: the rounds go into the person's own groups' rooms (docs/confederation-dkg-inboxes.md). + val ceremony = newCeremony(userPublicKey, basis, plan, attempt).copy(approvedAt = Clock.System.now()) database.confederationCeremonyDao().upsert(ceremony) announce( database, ceremony, ChatMessage.TYPE_CONFEDERATION_CEREMONY_STARTED, @@ -242,16 +270,15 @@ object ConfederationRitualManager { ) replayStoredMessages(database, ceremony, nostrPrivateKey) database.confederationCeremonyDao().getCeremony(ceremony.id)?.takeIf { it.isRunning }?.let { - advance(database, room, it.id, nostrPrivateKey) + advance(database, it.id, nostrPrivateKey) } return database.confederationCeremonyDao().getCeremony(ceremony.id)!! } - private fun newCeremony(database: GizaDatabase, chatRoomId: String, user: HexKey, basis: Basis, plan: Plan, attempt: Int): ConfederationCeremony { + private fun newCeremony(user: HexKey, basis: Basis, plan: Plan, attempt: Int): ConfederationCeremony { val groups = plan.seatsOf(user).map { it.group } return ConfederationCeremony( id = ConfederationAttestation.ceremonyId(plan.proposal.id, attempt), - chatRoomId = chatRoomId, proposalId = plan.proposal.id, userPublicKey = user, basisJson = basis.encode(), @@ -268,16 +295,14 @@ object ConfederationRitualManager { /** Ends a running ceremony for everybody, as any participant may: the failure is signed, so it takes the key. */ suspend fun abandon(database: GizaDatabase, sessionId: String, nostrPrivateKey: ByteArray) { val ceremony = database.confederationCeremonyDao().getCeremony(sessionId)?.takeIf { it.isRunning } ?: return - val room = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return - failOut(database, room, ceremony, ABANDONED, culprit = null, nostrPrivateKey) + failOut(database, ceremony, ABANDONED, culprit = null, nostrPrivateKey) } /** Moves every running ceremony [userPublicKey] is in as far as its stored messages allow. */ suspend fun resumeRunning(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray): Int { val running = database.confederationCeremonyDao().getRunning(userPublicKey) running.forEach { ceremony -> - val room = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return@forEach - runCatching { advance(database, room, ceremony.id, nostrPrivateKey) } + runCatching { advance(database, ceremony.id, nostrPrivateKey) } .onFailure { logger.e("Could not resume ceremony ${ceremony.id}", it) } } return running.size @@ -285,29 +310,6 @@ object ConfederationRitualManager { // ---- inbound --------------------------------------------------------------------------- - /** - * Feeds one inbound envelope in and moves each ceremony it touches as far as it will go. Safe to - * call twice with the same envelope. Only an envelope of signed events is read - * (docs/confederation-dkg-inboxes.md, Phase 3): a bare rumor of a ritual kind is from a build that - * no longer speaks for anyone, and is dropped. Each event is verified, filed as heard, and read - * only by a ceremony this device's owner has joined; one for a ceremony not joined here waits in - * what was heard, and is replayed when its owner joins. - */ - suspend fun process( - database: GizaDatabase, - localChatRoom: LocalChatRoom, - innerEvent: Event, - userPublicKey: HexKey, - nostrPrivateKey: ByteArray, - ) { - if (innerEvent.kind != ConfederationRitualEvents.CARRIED) { - logger.w("Ceremony message kind ${innerEvent.kind} from ${innerEvent.pubKey.take(8)} is not a carried, signed one; dropping") - return - } - val events = verifiedEvents(innerEvent) ?: return - receive(database, events, userPublicKey, nostrPrivateKey) - } - /** * An envelope heard in [groupRoom], a group's own Marmot room (docs/confederation-dkg-inboxes.md, * Phase 4): written there by a seated person, or carried in by an admin. What the group's admins owe @@ -353,10 +355,7 @@ object ConfederationRitualManager { return true } - /** - * Each of [events], verified already, filed as heard and read by the ceremony this device's owner has - * joined, if any, through the ceremony's NIP-17 room while it is still the channel a failure goes back on. - */ + /** Each of [events], verified already, filed as heard and read by the ceremony this device's owner has joined, if any. */ private suspend fun receive(database: GizaDatabase, events: List, userPublicKey: HexKey, nostrPrivateKey: ByteArray) { events.forEach { event -> val sessionId = ConfederationRitualEvents.parseSessionId(event.tags) ?: return@forEach @@ -364,9 +363,8 @@ object ConfederationRitualManager { val ceremony = database.confederationCeremonyDao().getCeremony(sessionId)?.takeIf { it.userPublicKey == userPublicKey } ?: return@forEach if (!ceremony.isRunning) return@forEach - val room = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return@forEach - if (!record(database, room, ceremony, event, nostrPrivateKey)) return@forEach - advance(database, room, ceremony.id, nostrPrivateKey) + if (!record(database, ceremony, event, nostrPrivateKey)) return@forEach + advance(database, ceremony.id, nostrPrivateKey) } } @@ -413,7 +411,7 @@ object ConfederationRitualManager { * only from a person the roster names, carrying a value for exactly the roles they hold; a * failure only from someone in the ceremony. */ - private suspend fun record(database: GizaDatabase, room: LocalChatRoom, ceremony: ConfederationCeremony, innerEvent: Event, nostrPrivateKey: ByteArray): Boolean { + private suspend fun record(database: GizaDatabase, ceremony: ConfederationCeremony, innerEvent: Event, nostrPrivateKey: ByteArray): Boolean { val plan = planOf(ceremony) ?: return true val sender = innerEvent.pubKey @@ -432,7 +430,7 @@ object ConfederationRitualManager { val differing = plan.acceptanceIds.filter { (group, id) -> hostKeys.statements[group] != id }.keys val named = differing.map { ConfederationManager.nameOf(database, it) }.ifEmpty { listOf("one of the groups") } failOut( - database, room, ceremony, + database, ceremony, "${ConfederationManager.nameOf(database, sender)} holds a different statement from ${named.joinToString()} than this device does", culprit = null, nostrPrivateKey, ) @@ -452,7 +450,7 @@ object ConfederationRitualManager { // it is sent. Two different ones, each signed, are proof the person said two things. val held = database.confederationCeremonyDao().getMessage(ceremony.id, sender, innerEvent.kind) if (held != null && held.payload != innerEvent.content) { - failOut(database, room, ceremony, describeEquivocation(database, ceremony, sender, innerEvent), culprit = sender, nostrPrivateKey) + failOut(database, ceremony, describeEquivocation(database, ceremony, sender, innerEvent), culprit = sender, nostrPrivateKey) return false } database.confederationCeremonyDao().insertMessage( @@ -476,7 +474,7 @@ object ConfederationRitualManager { * still waiting on somebody. Each step asks whether its output exists, not what the stage * says, so re-entering after a crash or a redelivery repeats no work and skips none. */ - private suspend fun advance(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) { + private suspend fun advance(database: GizaDatabase, sessionId: String, nostrPrivateKey: ByteArray) { var ceremony = database.confederationCeremonyDao().getCeremony(sessionId) ?: return if (!ceremony.isRunning || ceremony.approvedAt == null) return @@ -488,7 +486,7 @@ object ConfederationRitualManager { // 1. This person's host keys, one per role, with their part of the seed and the attestation. if (own(database, ceremony, ConfederationRitualEvents.HOST_KEYS) == null) { publishOwn( - database, localChatRoom, ceremony, plan, ConfederationRitualEvents.HOST_KEYS, + database, ceremony, plan, ConfederationRitualEvents.HOST_KEYS, ConfederationRitualEvents.HostKeys( keys = seats.associate { it.group to host.getValue(it.roleId).publicKey().value.toHex() }, seed = ceremony.seedContribution!!, @@ -505,7 +503,7 @@ object ConfederationRitualManager { } val hostKeys = plan.seats.associate { seat -> seat.roleId to PublicKey(ByteVector(hostMessages.getValue(seat.admin).keys.getValue(seat.group))) } val roster = when (val built = plan.roster(hostKeys)) { - is Either.Left -> return failOut(database, localChatRoom, ceremony, "The roster cannot be built: ${built.value.message}", null, nostrPrivateKey) + is Either.Left -> return failOut(database, ceremony, "The roster cannot be built: ${built.value.message}", null, nostrPrivateKey) is Either.Right -> built.value } // D9: everybody's seed, in roster order, after every host key is in and before anybody deals. @@ -514,13 +512,13 @@ object ConfederationRitualManager { // 2. This person's dealings. The seeds go once the dealings are stored. if (own(database, ceremony, ConfederationRitualEvents.DEALINGS) == null) { val seeds = ceremony.dealerSeeds?.let(ConfederationRitualEvents::decodeByGroup) - ?: return failOut(database, localChatRoom, ceremony, "This device lost its dealer seed before dealing", me, nostrPrivateKey) + ?: return failOut(database, ceremony, "This device lost its dealer seed before dealing", me, nostrPrivateKey) val dealings = seats.associate { seat -> val dealing = ConfederationDkg.participantStep1(roster, seat.roleId, host.getValue(seat.roleId), ByteVector32(seeds.getValue(seat.group)), sessionSeed) - .rightOrFail { return failOut(database, localChatRoom, ceremony, "Dealing failed: $it", null, nostrPrivateKey) } + .rightOrFail { return failOut(database, ceremony, "Dealing failed: $it", null, nostrPrivateKey) } seat.group to ConfederationRitualEvents.Dealing(dealing.record.data.toHex(), dealing.ciphertexts.data.toHex()) } - publishOwn(database, localChatRoom, ceremony, plan, ConfederationRitualEvents.DEALINGS, ConfederationRitualEvents.encodeDealings(dealings), nostrPrivateKey) + publishOwn(database, ceremony, plan, ConfederationRitualEvents.DEALINGS, ConfederationRitualEvents.encodeDealings(dealings), nostrPrivateKey) } if (ceremony.dealerSeeds != null) ceremony = update(database, ceremony) { it.copy(dealerSeeds = null) } @@ -528,8 +526,8 @@ object ConfederationRitualManager { val dealings = perRoleDealings(database, ceremony, plan) ?: return moveTo(database, ceremony, ConfederationCeremonyStage.DEALING) val combined = ConfederationDkg.coordinatorStep1(roster, sessionSeed, dealings) - .rightOrFail { return failOut(database, localChatRoom, ceremony, "Combining the dealings failed: $it", null, nostrPrivateKey) } - combined.fault?.let { return failOut(database, localChatRoom, ceremony, describe(database, plan, it), culpritOf(plan, it), nostrPrivateKey) } + .rightOrFail { return failOut(database, ceremony, "Combining the dealings failed: $it", null, nostrPrivateKey) } + combined.fault?.let { return failOut(database, ceremony, describe(database, plan, it), culpritOf(plan, it), nostrPrivateKey) } val broadcast = ConfederationBroadcast(ByteVector(combined.broadcast!!.toByteArray())) val broadcastHash = Crypto.sha256(broadcast.toByteArray()).toHex() val ownDealings = ConfederationRitualEvents.decodeDealings(own(database, ceremony, ConfederationRitualEvents.DEALINGS)!!.payload)!! @@ -541,8 +539,8 @@ object ConfederationRitualManager { var transitionHash: ByteVector32? = null val authorizations = seats.associate { seat -> val step = ConfederationDkg.participantStep2(roster, seat.roleId, host.getValue(seat.roleId), sessionSeed, ownRecord(seat.group), broadcast) - .rightOrFail { return failOut(database, localChatRoom, ceremony, "Checking the broadcast failed: $it", null, nostrPrivateKey) } - step.fault?.let { return failOut(database, localChatRoom, ceremony, describe(database, plan, it), culpritOf(plan, it), nostrPrivateKey) } + .rightOrFail { return failOut(database, ceremony, "Checking the broadcast failed: $it", null, nostrPrivateKey) } + step.fault?.let { return failOut(database, ceremony, describe(database, plan, it), culpritOf(plan, it), nostrPrivateKey) } keyState = step.keyState transitionHash = step.transitionHash seat.group to step.authorization!!.toHex() @@ -555,7 +553,7 @@ object ConfederationRitualManager { ) } publishOwn( - database, localChatRoom, ceremony, plan, ConfederationRitualEvents.AUTHORIZATIONS, + database, ceremony, plan, ConfederationRitualEvents.AUTHORIZATIONS, ConfederationRitualEvents.Authorizations(authorizations, broadcastHash).encode(), nostrPrivateKey, ) @@ -568,41 +566,41 @@ object ConfederationRitualManager { // Two devices dealt different things computed different broadcasts: say who, before a signature fails on it. authorizationMessages.filterValues { it.broadcast != broadcastHash }.keys.takeIf { it.isNotEmpty() }?.let { others -> val names = others.map { ConfederationManager.nameOf(database, it) } - return failOut(database, localChatRoom, ceremony, "${names.joinToString()} received different dealings than this device did", null, nostrPrivateKey) + return failOut(database, ceremony, "${names.joinToString()} received different dealings than this device did", null, nostrPrivateKey) } val keyState = ConfederationKeyState.fromData(ByteVector(ceremony.keyState!!), roster) - .rightOrFail { return failOut(database, localChatRoom, ceremony, "This device's key state no longer reads: $it", null, nostrPrivateKey) } + .rightOrFail { return failOut(database, ceremony, "This device's key state no longer reads: $it", null, nostrPrivateKey) } val transitionHash = ByteVector32(ceremony.transitionHash!!) val authorizations = plan.seats.associate { seat -> seat.roleId to ByteVector64(authorizationMessages.getValue(seat.admin).values.getValue(seat.group)) } val authorizationList = ConfederationDkg.evidenceList(roster, authorizations) - .rightOrFail { return failOut(database, localChatRoom, ceremony, "The authorizations cannot be listed: $it", null, nostrPrivateKey) } + .rightOrFail { return failOut(database, ceremony, "The authorizations cannot be listed: $it", null, nostrPrivateKey) } // 5. Each role acknowledges, having stored what its share is recomputed from. if (own(database, ceremony, ConfederationRitualEvents.ACKNOWLEDGMENTS) == null) { val acknowledgments = seats.associate { seat -> val step = ConfederationDkg.participantAcknowledge(roster, seat.roleId, host.getValue(seat.roleId), transitionHash, authorizationList) - .rightOrFail { return failOut(database, localChatRoom, ceremony, "Acknowledging failed: $it", null, nostrPrivateKey) } - step.fault?.let { return failOut(database, localChatRoom, ceremony, describe(database, plan, it), culpritOf(plan, it), nostrPrivateKey) } + .rightOrFail { return failOut(database, ceremony, "Acknowledging failed: $it", null, nostrPrivateKey) } + step.fault?.let { return failOut(database, ceremony, describe(database, plan, it), culpritOf(plan, it), nostrPrivateKey) } seat.group to step.acknowledgment!!.toHex() } - publishOwn(database, localChatRoom, ceremony, plan, ConfederationRitualEvents.ACKNOWLEDGMENTS, ConfederationRitualEvents.encodeByGroup(acknowledgments), nostrPrivateKey) + publishOwn(database, ceremony, plan, ConfederationRitualEvents.ACKNOWLEDGMENTS, ConfederationRitualEvents.encodeByGroup(acknowledgments), nostrPrivateKey) } val acknowledgments = perRole(database, ceremony, plan, ConfederationRitualEvents.ACKNOWLEDGMENTS) { ByteVector64(it) } ?: return moveTo(database, ceremony, ConfederationCeremonyStage.ACKNOWLEDGING) val acknowledgmentList = ConfederationDkg.evidenceList(roster, acknowledgments) - .rightOrFail { return failOut(database, localChatRoom, ceremony, "The acknowledgments cannot be listed: $it", null, nostrPrivateKey) } + .rightOrFail { return failOut(database, ceremony, "The acknowledgments cannot be listed: $it", null, nostrPrivateKey) } // 6. The certified genesis, assembled here: no secret is needed, and nobody can hand one over. if (ceremony.genesis == null) { val step = ConfederationDkg.coordinatorFinalize(keyState, authorizationList, acknowledgmentList) - .rightOrFail { return failOut(database, localChatRoom, ceremony, "Certifying the genesis failed: $it", null, nostrPrivateKey) } - step.fault?.let { return failOut(database, localChatRoom, ceremony, describe(database, plan, it), culpritOf(plan, it), nostrPrivateKey) } + .rightOrFail { return failOut(database, ceremony, "Certifying the genesis failed: $it", null, nostrPrivateKey) } + step.fault?.let { return failOut(database, ceremony, describe(database, plan, it), culpritOf(plan, it), nostrPrivateKey) } ceremony = update(database, ceremony) { it.copy(genesis = step.genesis!!.data.toHex()) } } val genesis = ConfederationTransition.fromData(ByteVector(ceremony.genesis!!), null, keyState) - .rightOrFail { return failOut(database, localChatRoom, ceremony, "The genesis does not verify: $it", null, nostrPrivateKey) } + .rightOrFail { return failOut(database, ceremony, "The genesis does not verify: $it", null, nostrPrivateKey) } // 7. Each role's share, kept as its recovery package. if (ceremony.recoveryPackages == null) { @@ -610,7 +608,7 @@ object ConfederationRitualManager { val packages = seats.associate { seat -> val result = ConfederationDkg.participantFinalize( genesis, keyState, seat.roleId, host.getValue(seat.roleId), ownRecord(seat.group), broadcast, ByteVector32(nonces.getValue(seat.group)), - ).rightOrFail { return failOut(database, localChatRoom, ceremony, "Finalizing this device's share failed: $it", null, nostrPrivateKey) } + ).rightOrFail { return failOut(database, ceremony, "Finalizing this device's share failed: $it", null, nostrPrivateKey) } seat.group to result.recovery.data.toHex() } ceremony = update(database, ceremony) { @@ -722,8 +720,8 @@ object ConfederationRitualManager { } /** Says the ceremony is over to everybody, then ends it here. */ - private suspend fun failOut(database: GizaDatabase, localChatRoom: LocalChatRoom, ceremony: ConfederationCeremony, reason: String, culprit: HexKey?, nostrPrivateKey: ByteArray) { - broadcast(database, localChatRoom, ceremony, planOf(ceremony), ConfederationRitualEvents.FAILURE, reason, nostrPrivateKey) + private suspend fun failOut(database: GizaDatabase, ceremony: ConfederationCeremony, reason: String, culprit: HexKey?, nostrPrivateKey: ByteArray) { + broadcast(database, ceremony, planOf(ceremony), ConfederationRitualEvents.FAILURE, reason, nostrPrivateKey) fail(database, ceremony, reason, culprit) } @@ -735,21 +733,19 @@ object ConfederationRitualManager { announce(database, current, ChatMessage.TYPE_CONFEDERATION_CEREMONY_FAILED, "The confederation's key ceremony ended: $reason") } - private suspend fun publishOwn(database: GizaDatabase, localChatRoom: LocalChatRoom, ceremony: ConfederationCeremony, plan: Plan, kind: Kind, content: String, nostrPrivateKey: ByteArray) { - broadcast(database, localChatRoom, ceremony, plan, kind, content, nostrPrivateKey) + private suspend fun publishOwn(database: GizaDatabase, ceremony: ConfederationCeremony, plan: Plan, kind: Kind, content: String, nostrPrivateKey: ByteArray) { + broadcast(database, ceremony, plan, kind, content, nostrPrivateKey) database.confederationCeremonyDao().insertMessage(ConfederationCeremonyMessage(ceremony.id, ceremony.userPublicKey, kind, content)) } /** - * Signs one message as this device's owner and queues it, carried (Phase 3): the signed event in - * a [ConfederationRitualEvents.CARRIED] envelope, queued for the room's gift wraps and p-tagged to - * every other person in the roster, as long as the NIP-17 room is the channel. The event names - * its session, proposal and attempt, so it means the same wherever it is carried; the envelope - * names them too, so a stored envelope is released with its ceremony. + * Signs one message as this device's owner and writes it, carried: the signed event in a + * [ConfederationRitualEvents.CARRIED] envelope, into the room of every group the person holds a seat + * in, whose admins carry it to every group's inbox. This device's owner is one of those admins. The + * event names its session, proposal and attempt, so it means the same wherever it is carried. */ private suspend fun broadcast( database: GizaDatabase, - localChatRoom: LocalChatRoom, ceremony: ConfederationCeremony, plan: Plan?, kind: Kind, @@ -765,31 +761,9 @@ object ConfederationRitualManager { check(signed.pubKey == ceremony.userPublicKey) { "A ceremony message has to be signed by the person whose ceremony it is" } hear(database, ceremony.id, signed) - val people = plan?.people - ?: (localChatRoom.localParticipants.map { it.participant.participantPublicKey } + localChatRoom.chatRoom.userPublicKey) - val baseTags = people.filter { it != ceremony.userPublicKey }.sorted().map { arrayOf("p", it) }.toTypedArray() + ceremonyTags - val envelope = ConfederationRitualEvents.encodeCarried(listOf(signed)) - val createdAt = Clock.System.now().epochSeconds - // Expires after at least the ceremony floor, stamped before the id is hashed - // (docs/disappearing-messages.md, D2). - val tags = DisappearingSettingsStore(database).stamp(localChatRoom.chatRoom.id, ceremony.userPublicKey, ConfederationRitualEvents.CARRIED, createdAt, baseTags) - val id = EventHasher.hashId(pubKey = ceremony.userPublicKey, createdAt = createdAt, kind = ConfederationRitualEvents.CARRIED, tags = tags, content = envelope) - database.giftWrapPayloadDao().upsert( - GiftWrapPayload( - id = id, - publicKey = ceremony.userPublicKey, - chatRoomId = localChatRoom.chatRoom.id, - kind = ConfederationRitualEvents.CARRIED, - tags = tags, - content = envelope, - createdAt = Instant.fromEpochSeconds(createdAt), - ) - ) - - // And into the room of every group the person holds a seat in, whose admins carry it to every - // group's inbox (Phase 4). This device's owner is one of those admins. - val seatPlan = plan ?: return - roomsFor(database, seatPlan, ceremony.userPublicKey).forEach { room -> + val rooms = plan?.let { roomsFor(database, it, ceremony.userPublicKey) }.orEmpty() + if (rooms.isEmpty()) logger.w("Ceremony message kind $kind for ${ceremony.id.take(8)}: this device holds none of its owner's groups' rooms, so it goes nowhere") + rooms.forEach { room -> writeIntoRoom(database, room, ceremony.proposalId, ceremony.userPublicKey, listOf(signed)) ConfederationBridge.heardInRoom(database, room.chatRoom.id, ConfederationBridge.CarryScope.Ceremony(ceremony.proposalId), listOf(signed), ceremony.userPublicKey) } @@ -817,61 +791,42 @@ object ConfederationRitualManager { } /** - * Feeds in what arrived before this device's owner joined: what was heard, by any path - * (docs/confederation-dkg-inboxes.md, Phase 2), and the envelopes the inbound path stored as gift - * wraps before there was anywhere to hear them. Everything is verified again: what was stored as - * heard may be from before messages were signed. + * Feeds in what arrived before this device's owner joined: what was heard, by any path, verified + * again (docs/confederation-dkg-inboxes.md, Phase 2). */ private suspend fun replayStoredMessages(database: GizaDatabase, ceremony: ConfederationCeremony, nostrPrivateKey: ByteArray) { - val room = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return - val heard = database.confederationCeremonyDao().getCeremonyHeardForSession(ceremony.id) + database.confederationCeremonyDao().getCeremonyHeardForSession(ceremony.id) .mapNotNull { Event.fromJsonOrNull(it.eventJson) } - val wrapped = database.giftWrapPayloadDao() - .getByKinds(listOf(ConfederationRitualEvents.CARRIED)) - .filter { ConfederationRitualEvents.parseSessionId(it.tags) == ceremony.id } - .flatMap { verifiedEvents(Event(it.id, it.publicKey, it.createdAt.epochSeconds, it.kind, it.tags, it.content, "")).orEmpty() } - (heard + wrapped) .distinctBy { it.id } .filter { it.pubKey != ceremony.userPublicKey && it.kind in ConfederationRitualEvents.SIGNED && it.verify() } - .filter { ConfederationRitualEvents.parseSessionId(it.tags) == ceremony.id } .sortedBy { it.createdAt } .forEach { event -> - if (!record(database, room, database.confederationCeremonyDao().getCeremony(ceremony.id) ?: return, event, nostrPrivateKey)) return + if (!record(database, database.confederationCeremonyDao().getCeremony(ceremony.id) ?: return, event, nostrPrivateKey)) return } } - /** A system line in the ceremony's room. */ - private suspend fun announce(database: GizaDatabase, ceremony: ConfederationCeremony, type: String, content: String) { - database.chatMessageDao().upsert( - ChatMessage( - senderPublicKey = ceremony.userPublicKey, - isUserMessage = false, - giftWrapPayloadId = null, - marmotGroupEventId = null, - marmotInnerEventId = null, - chatRoomId = ceremony.chatRoomId, - content = content, - messageType = type, - ) - ) - } - /** - * A placeholder profile for every member this device has none for: a room's members and its - * owner are foreign keys onto `Profile`, as `NostrDao.getOrCreateNip17ChatRoom` says. The - * placeholder hangs off a kind:0 dated at genesis, which any real profile replaces. + * A line about [ceremony] in the room of every group its person holds a seat in, written by this + * device for itself and sent nowhere (docs/confederation-dkg-inboxes.md): where an admin looks, now + * that the ceremony has no room. It carries the proposal's id, which is what the line opens. */ - private suspend fun ensureProfiles(database: GizaDatabase, keys: List) { - keys.forEach { key -> - if (database.profileDao().getProfileByPublicKey(key) != null) return@forEach - val eventId = Crypto.sha256("giza/placeholder-profile/$key".encodeToByteArray()).toHex() - if (database.nostrEventDao().getNostrEventById(eventId) == null) { - database.nostrEventDao().insert( - NostrEvent(id = eventId, pubKey = key, kind = 0, tags = emptyArray(), content = "{}", sig = "", createdAt = GENESIS_AT) + private suspend fun announce(database: GizaDatabase, ceremony: ConfederationCeremony, type: String, content: String) { + val plan = planOf(ceremony) ?: return + roomsFor(database, plan, ceremony.userPublicKey).forEach { room -> + database.chatMessageDao().upsert( + ChatMessage( + // The proposal, so the line opens its ceremony. Not a FROST session: the column has + // no key onto one, and the transcript reads it by the line's type. + frostSigningSessionId = ceremony.proposalId, + senderPublicKey = ceremony.userPublicKey, + isUserMessage = false, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = room.chatRoom.id, + content = content, + messageType = type, ) - } - database.profileDao().insertPlaceholderProfile( - Profile(displayName = "LOADING...", publicKey = key, createdAt = GENESIS_AT, nostrEventId = eventId) ) } } 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 de0c5b40..02002456 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt @@ -50,14 +50,17 @@ import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder +import mobi.giza.compose.database.model.ChatRoom /** * A confederation's key ceremony across devices, one person to a device, with nobody coordinating - * it (docs/confederation.md, Phase 11, and docs/confederation-without-coordinator.md, Phase 7): - * every admin joins on their own once their device holds every group's statement, gift wraps are - * ferried between devices, every round is run by `ConfederationDkg` on the device of the role it - * belongs to -- the broadcast included -- and at the end the same key on every device, a key that - * signs as the confederation's room once each device's recovery package is opened into its share. + * it (docs/confederation.md, Phase 11, and docs/confederation-without-coordinator.md, Phase 7) and no + * room of its own (docs/confederation-dkg-inboxes.md): every admin joins on their own once their + * device holds every group's statement, each person's signed messages go into their groups' own + * rooms, each group's admins carry them to every group's inbox, every round is run by + * `ConfederationDkg` on the device of the role it belongs to -- the broadcast included -- and at the + * end the same key on every device, a key that signs as the confederation once each device's + * recovery package is opened into its share. */ class ConfederationCeremonyJvmTest { private var people: ConfederationPeople? = null @@ -81,28 +84,47 @@ class ConfederationCeremonyJvmTest { if (statementsFor == null) network.setUp() else network.setUp(statementsFor) } - private fun pump(tamper: (ConfederationPeople.Device, ConfederationPeople.Device, mobi.giza.compose.database.model.GiftWrapPayload) -> mobi.giza.compose.database.model.GiftWrapPayload? = { _, _, it -> it }) = - runBlocking { network.pump(tamper) } + /** The groups' rooms, the admins' turns at carrying at [at], and the inboxes, until nothing moves. */ + private fun pump(at: Instant? = null, hold: (Event) -> Boolean = { false }, noCarry: Set = emptySet()) = + runBlocking { network.pumpGroups(at = at, hold = hold, noCarry = noCarry) } private fun joinAll(except: Set = emptySet()) = runBlocking { network.joinAll(except) } - /** The signed events an envelope carries. */ - private fun carried(payload: mobi.giza.compose.database.model.GiftWrapPayload): List = - ConfederationRitualEvents.decodeCarried(payload.content).orEmpty() - - /** [payload] carrying [events] instead. */ - private fun carrying(payload: mobi.giza.compose.database.model.GiftWrapPayload, events: List) = - payload.copy(content = ConfederationRitualEvents.encodeCarried(events)) + private fun ceremonies() = runBlocking { network.ceremonies() } /** [event] with [content], signed again by [by]: what its author could send, and no one else. */ private fun resigned(event: Event, by: ConfederationPeople.Device, content: String): Event = NostrSignerSync(KeyPair(by.nsec)).sign(event.createdAt, event.kind, event.tags, content) - /** [payload] as the inbound path hands it over. */ - private fun asEvent(payload: mobi.giza.compose.database.model.GiftWrapPayload) = - Event(payload.id, payload.publicKey, payload.createdAt.epochSeconds, payload.kind, payload.tags, payload.content, "") + /** An envelope of [events] naming the proposal, as a carrier would send it. */ + private fun envelope(events: List): Event = Event( + "ab".repeat(32), events.first().pubKey, events.first().createdAt, ConfederationRitualEvents.CARRIED, + arrayOf(arrayOf(ConfederationRitualEvents.PROPOSAL_TAG, network.proposalId)), ConfederationRitualEvents.encodeCarried(events), "", + ) - private fun ceremonies() = runBlocking { network.ceremonies() } + /** [events] reaching [device] alone, through the inbox of one of its groups. */ + private fun deliverTo(device: ConfederationPeople.Device, events: List) = runBlocking { + ConfederationRitualManager.receiveFromInbox(device.db, groups[network.groupsOf(device).first()], envelope(events), device.person, device.nsec) + } + + /** [device]'s own signed message of [kind], as it filed it when it sent it. */ + private fun own(device: ConfederationPeople.Device, kind: Int): Event = runBlocking { + Event.fromJson( + device.db.confederationCeremonyDao().getCeremonyHeardForProposal(network.proposalId) + .first { it.pubKey == device.person && it.kind == kind }.eventJson + ) + } + + /** The admins of group [i], in the order they take turns at carrying. */ + private fun carriers(i: Int): List = network.admins(i).map(network::device).sortedBy { it.person } + + /** + * An admin of group [i] who is not its first: their messages cross only when another admin carries + * them, so a hold on them in the room, and no turns of their own, keeps them back. + */ + private fun notFirstAdmin(i: Int): ConfederationPeople.Device = carriers(i)[1] + + private fun from(device: ConfederationPeople.Device, kind: Int): (Event) -> Boolean = { it.pubKey == device.person && it.kind == kind } /** Every role's share, opened from the recovery package its device kept. */ private fun shares(): Pair>> = runBlocking { @@ -123,27 +145,31 @@ class ConfederationCeremonyJvmTest { } } + /** No device holds a NIP-17 room over the roster's people. */ + private fun assertNoCeremonyRoom() = runBlocking { + val id = ChatRoom.deriveChatRoomId(devices.keys.toSet()) + devices.values.forEach { device -> + assertNull(device.db.chatRoomDao().findChatRoomById(id), "${device.person.take(6)} holds no NIP-17 room over the roster") + assertEquals(emptyList(), device.db.giftWrapPayloadDao().getByKinds(ConfederationRitualEvents.ALL.toList()), "nothing goes as a gift wrap") + } + } + @Test - fun `three groups of three make one key, the same on every device, that signs as the room`() { + fun `three groups of three make one key, the same on every device, that signs as the confederation`() { setUp() val agoraAdmin = network.device(12) - runBlocking { - agoraAdmin.db.chatRoomDao().upsert( - mobi.giza.compose.database.model.ChatRoom(id = groups[0], userPublicKey = agoraAdmin.person, subject = "&Agora", description = null, mlsGroupState = "00") - ) - } joinAll() pump() val all = ceremonies() all.forEach { (person, ceremony) -> assertEquals(ConfederationCeremonyStage.COMPLETE, ceremony?.stage, "${person.take(6)}: ${ceremony?.failureReason}") } assertEquals(1, all.values.map { it!!.id }.toSet().size, "one ceremony id, derived on every device") - assertEquals(1, all.values.map { it!!.chatRoomId }.toSet().size, "one room, whoever made it") assertEquals(1, all.values.map { it!!.confederationPublicKey }.toSet().size, "one key, everywhere") assertEquals(1, all.values.map { it!!.genesis }.toSet().size, "one certified genesis, assembled on each device") all.values.forEach { assertNull(it!!.dealerSeeds, "dealer seeds erased once dealt") } + assertNoCeremonyRoom() - // Phase 12: every device files the same confederation, certified, under the room its key derives. + // Phase 12: every device files the same confederation, certified, under the id its key derives. runBlocking { val formed = devices.values.map { assertNotNull(it.db.confederationCeremonyDao().getConfederationForProposal(network.proposalId)) } assertEquals(1, formed.map { it.id }.toSet().size) @@ -178,8 +204,8 @@ class ConfederationCeremonyJvmTest { pump() runBlocking { devices.values.forEach { device -> - val kinds = device.db.giftWrapPayloadDao().getByChatRoomAndKinds(device.room.chatRoom.id, listOf(30380, 30383)) - assertEquals(emptyList(), kinds.map { it.kind }, "on ${device.person.take(6)}") + val kinds = device.db.confederationCeremonyDao().getCeremonyHeardForProposal(network.proposalId).map { it.kind }.toSet() + assertTrue(30380 !in kinds && 30383 !in kinds, "on ${device.person.take(6)}: $kinds") } } ceremonies().values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) } @@ -195,6 +221,16 @@ class ConfederationCeremonyJvmTest { ceremonies().values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) } val packages = ConfederationRitualEvents.decodeByGroup(ceremonies().getValue(npub(11))!!.recoveryPackages!!)!! assertEquals(setOf(groups[0], groups[1]), packages.keys) + runBlocking { + val shared = network.device(11) + listOf(groups[0], groups[1]).forEach { group -> + assertTrue( + shared.db.marmotInnerEventDao().getByChatRoomAndKinds(group, listOf(ConfederationRitualEvents.CARRIED)) + .any { e -> network.carriedIn(e.content).any { it.pubKey == shared.person && it.kind == ConfederationRitualEvents.HOST_KEYS } }, + "written into both of their groups' rooms", + ) + } + } } @Test @@ -217,18 +253,13 @@ class ConfederationCeremonyJvmTest { } @Test - fun `a member who has not joined finds the ceremony from the room the others' messages made, and can join from it`() { + fun `a member who has not joined is offered it from the proposal, and joining replays what their groups heard`() { setUp() val late = network.device(32) joinAll(except = setOf(late.person)) pump() runBlocking { assertNull(ceremonies()[late.person], "nothing is made on a device until its owner joins") - val link = assertNotNull(repository(late).keyCeremonyOfRoom(late.room.chatRoom.id), "the room says what it is for") - assertEquals(network.proposalId, link.proposalId) - assertFalse(link.joined) - assertNull(repository(late).keyCeremonyOfRoom(groups[0]), "a room with no ceremony messages carries none") - val plan = assertIs>( ConfederationRitualManager.joinable(late.db, network.proposalId, late.person) ).value @@ -237,9 +268,8 @@ class ConfederationCeremonyJvmTest { ConfederationRitualManager.joinable(late.db, network.proposalId, ConfederationStatementFixture.npub(99)), "someone who holds no role is not offered the join", ) - + assertTrue(late.db.confederationCeremonyDao().getCeremonyHeardForProposal(network.proposalId).isNotEmpty(), "heard before joining") network.join(late) - assertTrue(repository(late).keyCeremonyOfRoom(late.room.chatRoom.id)!!.joined) } pump() ceremonies().values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) } @@ -291,17 +321,18 @@ class ConfederationCeremonyJvmTest { @Test fun `two devices that were dealt different things are named at the authorizations`() { setUp() + val liar = notFirstAdmin(1) joinAll() - val liar = npub(22) - // The liar signs, for everybody else, an authorization naming a broadcast nobody computed. - pump { from, _, payload -> - val event = carried(payload).singleOrNull() - if (from.person != liar || event?.kind != ConfederationRitualEvents.AUTHORIZATIONS) return@pump payload - val sent = ConfederationRitualEvents.Authorizations.decode(event.content)!! - carrying(payload, listOf(resigned(event, from, sent.copy(broadcast = "00".repeat(32)).encode()))) - } - val others = ceremonies().filterKeys { it != liar }.values.map { it!! } - others.forEach { assertEquals(ConfederationCeremonyStage.FAILED, it.stage) } + // The liar's own authorization never crosses; everybody else gets one, signed by the liar, + // naming a broadcast nobody computed. + pump(hold = from(liar, ConfederationRitualEvents.AUTHORIZATIONS), noCarry = setOf(liar)) + val honest = own(liar, ConfederationRitualEvents.AUTHORIZATIONS) + val sent = ConfederationRitualEvents.Authorizations.decode(honest.content)!! + val lie = resigned(honest, liar, sent.copy(broadcast = "00".repeat(32)).encode()) + devices.values.filter { it !== liar }.forEach { deliverTo(it, listOf(lie)) } + + val others = ceremonies().filterKeys { it != liar.person }.values.map { it!! } + others.forEach { assertEquals(ConfederationCeremonyStage.FAILED, it.stage, it.failureReason) } assertTrue(others.any { it.failureReason!!.contains("received different dealings than this device did") }, others.map { it.failureReason }.toString()) } @@ -309,11 +340,6 @@ class ConfederationCeremonyJvmTest { fun `a device whose group's admins changed since it accepted cannot join`() { setUp() val polisMember = network.device(22) - runBlocking { - polisMember.db.chatRoomDao().upsert( - mobi.giza.compose.database.model.ChatRoom(id = groups[1], userPublicKey = polisMember.person, subject = "&Polis", description = null, mlsGroupState = "00") - ) - } RoomAdmins.override = { id -> if (id == groups[1]) RoomAdmins(setOf(21, 22, 23, 24).map { npub(it) }.toSet(), governed = false) else null } @@ -345,25 +371,19 @@ class ConfederationCeremonyJvmTest { setUp() joinAll() // An outsider's own signed failure, in an envelope that names the proposal, reaches one device. - runBlocking { - val target = network.device(12) - val ceremony = ceremonies().getValue(target.person)!! - val outsider = ConfederationStatementFixture.key(99) - val failure = NostrSignerSync(KeyPair(outsider.value.toByteArray())).sign( - Clock.System.now().epochSeconds, ConfederationRitualEvents.FAILURE, - arrayOf( - ConfederationRitualEvents.sessionTag(ceremony.id), - arrayOf(ConfederationRitualEvents.PROPOSAL_TAG, network.proposalId), - arrayOf(ConfederationRitualEvents.ATTEMPT_TAG, "1"), - ), - "Ended by a stranger", - ) - val envelope = Event( - "ab".repeat(32), ConfederationStatementFixture.npub(99), failure.createdAt, ConfederationRitualEvents.CARRIED, - arrayOf(arrayOf(ConfederationRitualEvents.PROPOSAL_TAG, network.proposalId)), ConfederationRitualEvents.encodeCarried(listOf(failure)), "", - ) - ConfederationRitualManager.process(target.db, target.room, envelope, target.person, target.nsec) - } + val target = network.device(12) + val ceremony = ceremonies().getValue(target.person)!! + val outsider = ConfederationStatementFixture.key(99) + val failure = NostrSignerSync(KeyPair(outsider.value.toByteArray())).sign( + Clock.System.now().epochSeconds, ConfederationRitualEvents.FAILURE, + arrayOf( + ConfederationRitualEvents.sessionTag(ceremony.id), + arrayOf(ConfederationRitualEvents.PROPOSAL_TAG, network.proposalId), + arrayOf(ConfederationRitualEvents.ATTEMPT_TAG, "1"), + ), + "Ended by a stranger", + ) + deliverTo(target, listOf(failure)) pump() ceremonies().values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) } } @@ -373,15 +393,13 @@ class ConfederationCeremonyJvmTest { @Test fun `a message whose content was changed after it was signed is dropped, and the ceremony waits on its author`() { setUp() - joinAll() + val author = notFirstAdmin(1) val target = network.device(12) - val author = network.device(21) - pump { from, to, payload -> - val event = carried(payload).singleOrNull() - if (from !== author || to !== target || event?.kind != ConfederationRitualEvents.HOST_KEYS) return@pump payload - val changed = Event(event.id, event.pubKey, event.createdAt, event.kind, event.tags, event.content.replace("\"seed\"", "\"seed\" "), event.sig) - carrying(payload, listOf(changed)) - } + joinAll() + pump(hold = from(author, ConfederationRitualEvents.HOST_KEYS), noCarry = setOf(author)) + val signed = own(author, ConfederationRitualEvents.HOST_KEYS) + val changed = Event(signed.id, signed.pubKey, signed.createdAt, signed.kind, signed.tags, signed.content.replace("\"seed\"", "\"seed\" "), signed.sig) + deliverTo(target, listOf(changed)) runBlocking { val ceremony = ceremonies().getValue(target.person)!! assertEquals(ConfederationCeremonyStage.COLLECTING_HOST_KEYS, ceremony.stage, ceremony.failureReason) @@ -393,21 +411,18 @@ class ConfederationCeremonyJvmTest { @Test fun `a bare unsigned ritual rumor is dropped, and only signed events in an envelope are read`() { setUp() - joinAll(except = setOf(npub(12))) + val late = network.device(12) + val from = network.device(21) + joinAll() runBlocking { - val late = network.device(12) - network.join(late) - val from = network.device(21) - val envelope = from.db.giftWrapPayloadDao().getByChatRoomAndKinds(from.room.chatRoom.id, listOf(ConfederationRitualEvents.CARRIED)) - .first { it.publicKey == from.person && carried(it).single().kind == ConfederationRitualEvents.HOST_KEYS } - val inside = carried(envelope).single() - ConfederationRitualManager.process( - late.db, late.room, Event(inside.id, inside.pubKey, inside.createdAt, inside.kind, inside.tags, inside.content, ""), late.person, late.nsec, - ) val ceremony = ceremonies().getValue(late.person)!! + val signed = own(from, ConfederationRitualEvents.HOST_KEYS) + val room = assertNotNull(late.db.chatRoomDao().findChatRoomById(groups[0])) + ConfederationRitualManager.processFromRoom( + late.db, room, Event(signed.id, signed.pubKey, signed.createdAt, signed.kind, signed.tags, signed.content, ""), late.person, late.nsec, + ) assertNull(late.db.confederationCeremonyDao().getMessage(ceremony.id, from.person, ConfederationRitualEvents.HOST_KEYS), "a bare rumor is not read") - - ConfederationRitualManager.process(late.db, late.room, asEvent(envelope), late.person, late.nsec) + deliverTo(late, listOf(signed)) assertNotNull(late.db.confederationCeremonyDao().getMessage(ceremony.id, from.person, ConfederationRitualEvents.HOST_KEYS), "the signed one in its envelope is") } } @@ -415,60 +430,62 @@ class ConfederationCeremonyJvmTest { @Test fun `one person's two different signed dealings are named, with both events`() { setUp() - joinAll() - val liar = network.device(22) + val liar = notFirstAdmin(1) val target = network.device(11) - var held: mobi.giza.compose.database.model.GiftWrapPayload? = null - pump { from, to, payload -> - if (from !== liar || to !== target || carried(payload).singleOrNull()?.kind != ConfederationRitualEvents.DEALINGS) return@pump payload - held = payload - null - } - runBlocking { - val original = assertNotNull(held) - val dealing = carried(original).single() - val dealings = ConfederationRitualEvents.decodeDealings(dealing.content)!! - val other = dealings.mapValues { (_, d) -> d.copy(ciphertexts = d.ciphertexts.dropLast(1) + if (d.ciphertexts.last() == '0') "1" else "0") } - val second = resigned(dealing, liar, ConfederationRitualEvents.encodeDealings(other)) - // The honest one first: the second, a different dealing under the same signature's author, - // arrives while the ceremony runs. Altered first, the dealer's own record signature would - // fail it before anything could compare the two. - ConfederationRitualManager.process(target.db, target.room, asEvent(original), target.person, target.nsec) - ConfederationRitualManager.process(target.db, target.room, asEvent(carrying(original, listOf(second))), target.person, target.nsec) - val ceremony = ceremonies().getValue(target.person)!! - assertEquals(ConfederationCeremonyStage.FAILED, ceremony.stage) - assertEquals(liar.person, ceremony.culprit) - assertTrue(ceremony.failureReason!!.contains("sent two different dealings, both signed"), ceremony.failureReason) - assertTrue(ceremony.failureReason!!.contains(second.id.take(12)) && ceremony.failureReason!!.contains(dealing.id.take(12)), ceremony.failureReason) - } + joinAll() + pump(hold = from(liar, ConfederationRitualEvents.DEALINGS), noCarry = setOf(liar)) + val dealing = own(liar, ConfederationRitualEvents.DEALINGS) + val dealings = ConfederationRitualEvents.decodeDealings(dealing.content)!! + val other = dealings.mapValues { (_, d) -> d.copy(ciphertexts = d.ciphertexts.dropLast(1) + if (d.ciphertexts.last() == '0') "1" else "0") } + val second = resigned(dealing, liar, ConfederationRitualEvents.encodeDealings(other)) + // The honest one first: the second, a different dealing from the same author, arrives while the + // ceremony runs. Altered first, the dealer's own record signature would fail it before anything + // could compare the two. + deliverTo(target, listOf(dealing)) + deliverTo(target, listOf(second)) + val ceremony = ceremonies().getValue(target.person)!! + assertEquals(ConfederationCeremonyStage.FAILED, ceremony.stage) + assertEquals(liar.person, ceremony.culprit) + assertTrue(ceremony.failureReason!!.contains("sent two different dealings, both signed"), ceremony.failureReason) + assertTrue(ceremony.failureReason!!.contains(second.id.take(12)) && ceremony.failureReason!!.contains(dealing.id.take(12)), ceremony.failureReason) } - // ---- docs/confederation-dkg-inboxes.md, Phase 1: today, pinned to be flipped ----------------- + // ---- docs/confederation-dkg-inboxes.md, Phases 1 and 5: no room, pinned and flipped ----------- - /** Flipped by Phase 5: a message leaves as an envelope in each seat group's room, p-tagged to nobody. */ + /** Phase 1 pinned the opposite: one gift wrap p-tagged to every other person, in the room of the people. */ @Test - fun `today a ceremony message leaves as one gift wrap p-tagged to every other person, in the room of the people`() { + fun `a ceremony message leaves as an envelope in each seat group's room, p-tagged to nobody, and no NIP-17 room is made`() { setUp() val first = network.device(11) runBlocking { network.join(first) } runBlocking { - val sent = first.db.giftWrapPayloadDao().getByChatRoomAndKinds(first.room.chatRoom.id, listOf(ConfederationRitualEvents.CARRIED)) - val hostKeys = sent.single { it.publicKey == first.person && carried(it).single().kind == ConfederationRitualEvents.HOST_KEYS } - val tagged = hostKeys.tags.filter { it[0] == "p" }.map { it[1] }.toSet() - assertEquals(devices.keys - first.person, tagged, "every other person in the roster") - assertEquals(mobi.giza.compose.database.model.ChatRoom.deriveChatRoomId(devices.keys.toSet()), first.room.chatRoom.id) - assertEquals(first.room.chatRoom.id, ceremonies().getValue(first.person)!!.chatRoomId) + val written = first.db.marmotInnerEventDao().getByChatRoomAndKinds(groups[0], listOf(ConfederationRitualEvents.CARRIED)) + .flatMap { network.carriedIn(it.content) } + val hostKeys = written.single { it.pubKey == first.person && it.kind == ConfederationRitualEvents.HOST_KEYS } + assertTrue(hostKeys.tags.none { it[0] == "p" }, "addressed to nobody: it goes to the groups") + } + assertNoCeremonyRoom() + } + + /** Phase 1 pinned the opposite: a ceremony row could not exist without its room. */ + @Test + fun `a ceremony is stored with no room at all`() { + setUp() + runBlocking { + val device = network.device(11) + val stray = ConfederationCeremony(id = "ce".repeat(32), proposalId = network.proposalId, userPublicKey = device.person, basisJson = "{}") + device.db.confederationCeremonyDao().upsert(stray) + assertNotNull(device.db.confederationCeremonyDao().getCeremony(stray.id)) } } - // ---- docs/confederation-dkg-inboxes.md, Phase 4: the groups' rooms and inboxes ----------------- + // ---- docs/confederation-dkg-inboxes.md, Phases 4 and 5: the groups' rooms and inboxes ----------- /** Phase 1 pinned the opposite: the bridge carried nothing for a proposal. */ @Test fun `the bridge carries a running ceremony's messages, by its proposal, before anyone joins`() { setUp() runBlocking { - network.withGroupRooms() val admin = network.device(11) val signed = NostrSignerSync(KeyPair(admin.nsec)).sign( Clock.System.now().epochSeconds, ConfederationRitualEvents.HOST_KEYS, @@ -489,7 +506,6 @@ class ConfederationCeremonyJvmTest { fun `the bridge fills envelopes to the byte budget, and a large round goes in several`() { val confederation = formed() runBlocking { - network.withGroupRooms() val admin = network.device(11) val events = (0 until 40).map { n -> NostrSignerSync(KeyPair(admin.nsec)).sign( @@ -509,29 +525,17 @@ class ConfederationCeremonyJvmTest { } @Test - fun `the groups' rooms and inboxes alone form the key, each group's part carried by its first admin`() { + fun `each group's part is carried by its first admin, and nobody else`() { setUp() - runBlocking { - network.withGroupRooms() - network.joinAll() - // Each person's message is in their own group's room, on their device. - val first = network.device(11) - assertTrue( - first.db.marmotInnerEventDao().getByChatRoomAndKinds(groups[0], listOf(ConfederationRitualEvents.CARRIED)) - .any { e -> network.carriedIn(e.content).any { it.kind == ConfederationRitualEvents.HOST_KEYS && it.pubKey == first.person } }, - ) - // No NIP-17 pump: only the groups' rooms, the admins' turns and the inboxes. - network.pumpGroups() - } + joinAll() + pump() val all = ceremonies() all.forEach { (person, ceremony) -> assertEquals(ConfederationCeremonyStage.COMPLETE, ceremony?.stage, "${person.take(6)}: ${ceremony?.failureReason}") } - assertEquals(1, all.values.map { it!!.confederationPublicKey }.toSet().size, "one key, everywhere") runBlocking { groups.forEachIndexed { i, group -> - val firstAdmin = network.admins(i).map(network::npub).minOf { it } - network.admins(i).map(network::device).forEach { device -> + carriers(i).forEachIndexed { place, device -> val carried = device.db.groupInboxDao().getPublicationsForRoom(group) - if (device.person == firstAdmin) assertTrue(carried.isNotEmpty(), "${network.names[i]}'s first admin carried its part") + if (place == 0) assertTrue(carried.isNotEmpty(), "${network.names[i]}'s first admin carried its part") else assertEquals(emptyList(), carried, "${network.names[i]}'s other admins carried nothing") } } @@ -539,29 +543,83 @@ class ConfederationCeremonyJvmTest { } @Test - fun `a ceremony's messages come twice, by NIP-17 and by the inboxes, and form one key`() { + fun `with a group's first admin not carrying, nothing of that group crosses until the next admin's turn`() { setUp() - runBlocking { - network.withGroupRooms() - network.joinAll() - network.pump() - network.pumpGroups() + val away = carriers(0)[0] + joinAll() + pump(noCarry = setOf(away)) + val agora = network.admins(0).map(network::npub).toSet() + ceremonies().filterKeys { it !in agora }.values.forEach { + assertEquals(ConfederationCeremonyStage.COLLECTING_HOST_KEYS, it?.stage, "Agora's host keys have not crossed: ${it?.failureReason}") + } + ceremonies().values.forEach { assertTrue(it!!.isRunning) } + + pump(at = Clock.System.now() + 10.minutes, noCarry = setOf(away)) + ceremonies().values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) } + runBlocking { + assertEquals(emptyList(), away.db.groupInboxDao().getPublicationsForRoom(groups[0]), "the first admin carried nothing") + assertTrue(carriers(0).drop(1).any { it.db.groupInboxDao().getPublicationsForRoom(groups[0]).isNotEmpty() }, "the others did, at their turns") } - val all = ceremonies() - all.forEach { (person, ceremony) -> assertEquals(ConfederationCeremonyStage.COMPLETE, ceremony?.stage, "${person.take(6)}: ${ceremony?.failureReason}") } - assertEquals(1, all.values.map { it!!.genesis }.toSet().size) } - /** Flipped by Phase 5: the column, and its key onto a room, go. */ @Test - fun `today a ceremony cannot be stored without the room it runs in`() { + fun `with two of a group's admins never carrying, the last carries everyone's at its turn`() { setUp() + val (first, second, third) = carriers(0) + joinAll() + pump(at = Clock.System.now() + 10.minutes, noCarry = setOf(first, second)) + ceremonies().values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) } runBlocking { - val device = network.device(11) - val stray = ConfederationCeremony( - id = "ce".repeat(32), chatRoomId = "no-such-room", proposalId = network.proposalId, userPublicKey = device.person, basisJson = "{}", - ) - kotlin.test.assertFails { device.db.confederationCeremonyDao().upsert(stray) } + assertTrue(third.db.groupInboxDao().getPublicationsForRoom(groups[0]).isNotEmpty()) + listOf(first, second).forEach { assertEquals(emptyList(), it.db.groupInboxDao().getPublicationsForRoom(groups[0])) } + } + } + + @Test + fun `a seat whose device holds no inbox key for its group cannot join, and is told why`() { + setUp() + val device = network.device(12) + runBlocking { device.db.inboxKeyDao().wipeKeys(groups[0], device.person, Clock.System.now()) } + val refused = kotlin.test.assertFailsWith { runBlocking { network.join(device) } } + assertTrue(refused.message!!.contains("Set up Agora's inbox first"), refused.message) + } + + @Test + fun `a group's dealings round larger than an envelope is split, and the key forms`() { + setUp((1..3).map { g -> (1..10).map { 10 * g + it } }) + joinAll() + pump() + ceremonies().values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) } + runBlocking { + // Four rounds, a wrap to each of three inboxes for each envelope: more than twelve is a split. + val first = carriers(0)[0] + val wraps = first.db.groupInboxDao().getPublicationsForRoom(groups[0]) + assertTrue(wraps.size > 4 * groups.size, "${wraps.size} wraps for Agora's four rounds") + wraps.forEach { assertTrue(it.eventJson.length <= 65_536, "every wrap under 64 KiB: ${it.eventJson.length}") } + } + } + + @Test + fun `a roster whose largest message cannot fit an envelope is refused before anyone deals`() = runBlocking { + // Twelve groups of ten, a person seated in three of them: three dealings at 120 roles. + val db = mobi.giza.compose.database.builder.getRoomDatabase(androidx.room3.Room.inMemoryDatabaseBuilder()) + try { + val keys = (1..12).map { ConfederationStatementFixture.key(it) } + val npubs = keys.map(ConfederationStatementFixture::npub) + fun admin(n: Int) = PrivateKey(ByteArray(32).also { it[0] = 0x7a; it[30] = (n shr 8).toByte(); it[31] = n.toByte() }).publicKey().xOnly().value.toHex() + val shared = admin(999) + val lists = (0 until 12).map { g -> (0 until 10).map { admin(g * 10 + it + 1) }.let { if (g < 3) it.drop(1) + shared else it } } + val now = Clock.System.now().epochSeconds + val proposal = ConfederationStatementFixture.proposal(keys[0], npubs, lists[0], threshold = 7, innerThreshold = 6, createdAt = now - 10, expiresAt = now + 1000) + ConfederationStatementFixture.file(db, keys[0], proposal) + keys.drop(1).forEachIndexed { i, key -> + ConfederationStatementFixture.file(db, key, ConfederationStatementFixture.acceptance(key, proposal, lists[i + 1], threshold = 6, createdAt = now - 5)) + } + val refused = assertIs>(ConfederationRitualManager.joinable(db, proposal.id, admin(5))) + assertTrue(refused.value.contains("too many admins"), refused.value) + assertTrue(refused.value.contains("sits in 3 of its groups"), refused.value) + } finally { + db.close() } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationPeople.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationPeople.kt index 7a914d62..c06703e2 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationPeople.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationPeople.kt @@ -34,8 +34,9 @@ import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync * (docs/confederation-without-coordinator.md, D8). The statements come from * [ConfederationStatementFixture]; the inboxes themselves are [ConfederationTestGroups]'s business. * - * Each device makes the ceremony's NIP-17 room up front, as the inbound path would on the first - * message, and [pump] ferries gift wraps between them, stored first. + * Each device holds its groups' own rooms and inbox keys from the start, which the ceremony is read + * and written through (docs/confederation-dkg-inboxes.md, Phase 5), and [pumpGroups] ferries the rooms, + * runs the admins' turns at carrying and delivers the inboxes' wraps. */ /** The envelopes a group's room and its inbox carry: the ceremony's (30379) and signing's (30398). */ private val ENVELOPES = setOf(ConfederationRitualEvents.CARRIED, mobi.giza.compose.nostr.confederation.ConfederationSigningEvents.CARRIED) @@ -56,7 +57,6 @@ class ConfederationPeople( inner class Device(val secret: PrivateKey, val db: GizaDatabase) { val person = npub(secret) - lateinit var room: LocalChatRoom val received = mutableSetOf() val nsec: ByteArray get() = secret.value.toByteArray() } @@ -88,8 +88,8 @@ class ConfederationPeople( val device = Device(key, db) devices[device.person] = device statementsFor(device).forEach { (by, rumor) -> ConfederationStatementFixture.file(db, by, rumor) } - device.room = db.nostrNip17Dao().createNip17ChatRoom(device.person, people.map(::npub).filter { it != device.person }, "Atlas")!! } + withGroupRooms() } fun everyStatement(): List> = listOf(groupKeys[0] to proposal) + groupKeys.drop(1).zip(acceptances) @@ -100,33 +100,8 @@ class ConfederationPeople( db.profileDao().upsert(Profile(publicKey = key, nostrEventId = eventId, displayName = name, createdAt = Instant.fromEpochSeconds(1_790_000_000))) } - /** - * Ferries every queued ceremony message to every other device, until nothing moves. [tamper] - * may change or drop (null) what one device receives from another. - */ - suspend fun pump(tamper: (from: Device, to: Device, payload: GiftWrapPayload) -> GiftWrapPayload? = { _, _, it -> it }) { - var moved = true - while (moved) { - moved = false - for (from in devices.values) for (to in devices.values) { - if (from === to) continue - from.db.giftWrapPayloadDao().getByChatRoomAndKinds(from.room.chatRoom.id, ConfederationRitualEvents.ALL.toList()) - .filter { it.publicKey == from.person } - .sortedBy { it.createdAt } - .forEach { original -> - if (!to.received.add(original.id)) return@forEach - moved = true - val queued = tamper(from, to, original) ?: return@forEach - to.db.giftWrapPayloadDao().upsert(queued.copy(chatRoomId = to.room.chatRoom.id)) - ConfederationRitualManager.process( - to.db, to.room, - Event(queued.id, queued.publicKey, queued.createdAt.epochSeconds, queued.kind, queued.tags, queued.content, ""), - to.person, to.nsec, - ) - } - } - } - } + /** The ceremony and anything else in the groups' rooms and inboxes, until nothing moves: [pumpGroups] at now. */ + suspend fun pump() = pumpGroups() /** Every device but [except] joins: what each admin is offered, nobody opening it first. */ suspend fun joinAll(except: Set = emptySet()) { @@ -219,7 +194,13 @@ class ConfederationPeople( * envelope or a wrap carrying any event it names; [away] devices neither send nor receive. * Lifted from `ConfederationSigningJvmTest`, which calls it unchanged. */ - suspend fun pumpGroups(at: Instant? = null, away: Set = emptySet(), hold: (Event) -> Boolean = { false }) { + suspend fun pumpGroups( + at: Instant? = null, + away: Set = emptySet(), + hold: (Event) -> Boolean = { false }, + /** Devices that take part but never take a turn at carrying: an admin whose app is not running its sweep. */ + noCarry: Set = emptySet(), + ) { val online = devices.values.filter { it !in away } var moved = true while (moved) { @@ -240,7 +221,7 @@ class ConfederationPeople( } } } - online.forEach { d -> if (ConfederationBridge.sweep(d.db, d.person, d.nsec, at ?: Clock.System.now()) > 0) moved = true } + online.filter { it !in noCarry }.forEach { d -> if (ConfederationBridge.sweep(d.db, d.person, d.nsec, at ?: Clock.System.now()) > 0) moved = true } online.forEach { from -> from.db.groupInboxDao().observeUnpublished().first().forEach { owed -> val wrap = Event.fromJson(owed.eventJson) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileNetworkJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileNetworkJvmTest.kt index dc673203..d669ff22 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileNetworkJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileNetworkJvmTest.kt @@ -48,8 +48,6 @@ class ConfederationProfileNetworkJvmTest { private val databases = mutableListOf() private lateinit var confederation: Confederation - private val ceremonyRooms = mutableMapOf() - private val received = mutableMapOf>() @BeforeTest fun formed() = runBlocking { @@ -68,13 +66,10 @@ class ConfederationProfileNetworkJvmTest { network.signed(polis) { ConfederationManager.proposeAcceptance(it.db, it.room(), it.publicKey, proposalId).id } network.signed(ekklesia) { ConfederationManager.proposeAcceptance(it.db, it.room(), it.publicKey, proposalId).id } - // The key ceremony, every admin joining, in the NIP-17 room every device derives. - network.everyDevice.forEach { device -> - ceremonyRooms[device.publicKey] = device.db.nostrNip17Dao().createNip17ChatRoom(device.publicKey, people - device.publicKey, "Atlas")!! - received[device.publicKey] = mutableSetOf() - } + // The key ceremony, every admin joining, through the groups' own rooms and inboxes + // (docs/confederation-dkg-inboxes.md, Phase 5): no NIP-17 room anywhere. network.everyDevice.forEach { ConfederationRitualManager.join(it.db, proposalId, it.publicKey, it.secret) } - pumpCeremony() + network.pumpConfederation() confederation = assertNotNull(agora.devices[0].db.confederationCeremonyDao().getConfederationForProposal(proposalId), "formed") // No room of the confederation's: its signing goes through each group's own room and the @@ -95,31 +90,6 @@ class ConfederationProfileNetworkJvmTest { db.profileDao().upsert(Profile(publicKey = key, nostrEventId = eventId, displayName = key.take(6), createdAt = Instant.fromEpochSeconds(1_790_000_000))) } - /** The ceremony's gift wraps, from every device to every other, until nothing moves. */ - private suspend fun pumpCeremony() { - var moved = true - while (moved) { - moved = false - for (from in network.everyDevice) for (to in network.everyDevice) { - if (from === to) continue - val fromRoom = ceremonyRooms.getValue(from.publicKey) - val toRoom = ceremonyRooms.getValue(to.publicKey) - from.db.giftWrapPayloadDao().getByChatRoomAndKinds(fromRoom.chatRoom.id, ConfederationRitualEvents.ALL.toList()) - .filter { it.publicKey == from.publicKey }.sortedBy { it.createdAt } - .forEach { original -> - if (!received.getValue(to.publicKey).add(original.id)) return@forEach - moved = true - to.db.giftWrapPayloadDao().upsert(original.copy(chatRoomId = toRoom.chatRoom.id)) - ConfederationRitualManager.process( - to.db, toRoom, - Event(original.id, original.publicKey, original.createdAt.epochSeconds, original.kind, original.tags, original.content, ""), - to.publicKey, to.secret, - ) - } - } - } - } - /** The confederation's signing: each group's room, the admins carrying, and the inboxes. */ private suspend fun pumpConfederationRoom() = network.pumpConfederation() diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSharedSeatsSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSharedSeatsSigningJvmTest.kt index c51fd020..cfca6d8f 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSharedSeatsSigningJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSharedSeatsSigningJvmTest.kt @@ -52,7 +52,7 @@ class ConfederationSharedSeatsSigningJvmTest { network.setUp() network.devices.values.forEach { devices[it.person] = Device(it) } network.joinAll() - network.pump() + network.pumpGroups() confederation = assertNotNull(devices.getValue(npub(11)).db.confederationCeremonyDao().getConfederationForProposal(network.proposalId)) // No room of the confederation's: each group's own room, and its inbox key on its admins' devices. network.withGroupRooms() diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt index e8eeb5b6..055a35af 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt @@ -76,7 +76,7 @@ class ConfederationSigningJvmTest { network.devices.values.forEach { devices[it.person] = Device(it) } proposer = devices.getValue(npub(secret(11))) network.joinAll() - network.pump() + network.pumpGroups() confederation = assertNotNull(proposer.db.confederationCeremonyDao().getConfederationForProposal(network.proposalId)) // No room of the confederation's anywhere: each group's own room on its members' devices, and @@ -445,8 +445,15 @@ class ConfederationSigningJvmTest { // ---- docs/confederation-room-removal.md, Phase 4: the bridge, and no room --------------------- /** The groups' admins who carried something out of [group]'s room to the inboxes. */ + /** + * Who carried this group's signing out: the devices owing a wrap under its room that holds a signing + * envelope. The key ceremony that formed the confederation was carried the same way + * (docs/confederation-dkg-inboxes.md), and is not counted. + */ private fun carriersOutOf(group: HexKey) = runBlocking { - devices.values.filter { d -> d.db.groupInboxDao().getPublicationsForRoom(group).isNotEmpty() }.map { it.person } + devices.values.filter { d -> + d.db.groupInboxDao().getPublicationsForRoom(group).any { owed -> carriedIn(Event.fromJson(owed.eventJson)).isNotEmpty() } + }.map { it.person } } private fun stagesOf(attemptId: String, who: Collection = devices.values) = runBlocking { @@ -556,16 +563,6 @@ class ConfederationSigningJvmTest { } } - @Test - fun `once formed, the key ceremony's room leads to the confederation`() = runBlocking { - val device = devices.getValue(npub(secret(11))) - val repository = mobi.giza.compose.database.repository.DatabaseChatRepository(device.db, kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined)) - val link = assertNotNull(repository.keyCeremonyOfRoom(device.ceremonyDevice.room.chatRoom.id)) - val formed = assertNotNull(link.formed, "the ceremony made the confederation") - assertEquals(confederation.id, formed.confederationId) - assertEquals("Atlas", formed.name) - } - // ---- Phase 15: the charter ------------------------------------------------------------ @Test diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt index 40d61e0d..8d1d5f7a 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt @@ -180,12 +180,8 @@ class ConfederationStorageJvmTest { @Test fun `a ceremony's heard messages stay while it runs, and go once it ends or is long unclaimed`() = runBlocking { val dao = db.confederationCeremonyDao() - // A ceremony row still hangs off a room until Phase 5. - db.nostrEventDao().upsert(NostrEvent(id = "e".repeat(64), pubKey = npub(21), kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) - db.profileDao().upsert(Profile(publicKey = npub(21), nostrEventId = "e".repeat(64), displayName = "x", createdAt = kotlin.time.Instant.fromEpochSeconds(1_790_000_000))) - db.chatRoomDao().upsert(ChatRoom(id = "r".repeat(64), userPublicKey = npub(21), subject = "Atlas", description = null, mlsGroupState = null)) fun ceremony(id: Char, stage: mobi.giza.compose.database.model.ConfederationCeremonyStage) = mobi.giza.compose.database.model.ConfederationCeremony( - id = id.toString().repeat(64), chatRoomId = "r".repeat(64), proposalId = proposal.id, userPublicKey = npub(21), basisJson = "{}", stage = stage, + id = id.toString().repeat(64), proposalId = proposal.id, userPublicKey = npub(21), basisJson = "{}", stage = stage, ) dao.upsert(ceremony('1', mobi.giza.compose.database.model.ConfederationCeremonyStage.DEALING)) dao.upsert(ceremony('2', mobi.giza.compose.database.model.ConfederationCeremonyStage.FAILED)) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxHarness.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxHarness.kt index feb54d70..16257cd7 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxHarness.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxHarness.kt @@ -145,7 +145,8 @@ class GroupInboxHarness( } /** The kinds [pump] carries between devices. */ - var carried: Set = FrostSigningEvents.ALL + InboxKeyRitualEvents.ALL + ConfederationSigningEvents.CARRIED + var carried: Set = FrostSigningEvents.ALL + InboxKeyRitualEvents.ALL + ConfederationSigningEvents.CARRIED + + mobi.giza.compose.nostr.confederation.ConfederationRitualEvents.CARRIED private suspend fun outbox(device: Device): List = device.db.marmotInnerEventDao() @@ -178,6 +179,9 @@ class GroupInboxHarness( // A confederation's signing in the group's own room (docs/confederation-room-removal.md, D2). row.kind == ConfederationSigningEvents.CARRIED -> ConfederationSigningManager.process(to.db, room, event, to.publicKey, to.secret) + // And its key ceremony (docs/confederation-dkg-inboxes.md, Phase 5). + row.kind == mobi.giza.compose.nostr.confederation.ConfederationRitualEvents.CARRIED -> + ConfederationRitualManager.processFromRoom(to.db, room, event, to.publicKey, to.secret) } } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt index e2a765d9..a4585189 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt @@ -264,7 +264,7 @@ class ConfederationScreensJvmTest { } private fun ceremony(stage: ConfederationCeremonyStage, approved: Boolean, failure: String? = null) = ConfederationCeremony( - id = "s".repeat(64), chatRoomId = roomId, proposalId = "p".padEnd(64, '0'), + id = "s".repeat(64), proposalId = "p".padEnd(64, '0'), userPublicKey = "a".repeat(64), basisJson = "{}", stage = stage, approvedAt = if (approved) kotlin.time.Instant.fromEpochSeconds(1) else null, failureReason = failure, ) diff --git a/docs/confederation-dkg-inboxes.md b/docs/confederation-dkg-inboxes.md index 85f6f0b8..121083de 100644 --- a/docs/confederation-dkg-inboxes.md +++ b/docs/confederation-dkg-inboxes.md @@ -396,6 +396,15 @@ release, so no peer sends one (report D9). `ConfederationTestGroups.pumpConfederation`, over real inboxes, instead of its own NIP-17 pump. Its three cases pass. +**Done.** As planned, with four differences: + +- **The lines moved here from Phase 6.** `announce` wrote into the ceremony's room, which no longer exists, so it writes into each seat group's room now, carrying the proposal's id in `frostSigningSessionId`. Phase 6 keeps the transcript's handling of those lines. +- **The form does not check size.** `ProposeConfederationViewModel` knows each group's admin count but not who sits in several groups, which only the acceptances say. So the roster is refused at join, from `largestMessageBytes`, which `joinable` reports to the proposal screen before anyone is asked. +- **The large round is 3 groups of 10.** The case is a 30-role roster, whose dealings round of about 33 KB a group splits into two envelopes, rather than one near `MAX_ROLES`: 120 devices are more than a unit test should start. The 120-role refusal is checked on one device's statements alone. +- **The fallback is two cases.** One runs with a group's first admin not carrying; the other with two of its three not carrying, where the last carries everything at its turn. In the second, those two are the other authors, which is the plan's "every admin away but the author". + +`ConfederationPeople` gives every device its groups' rooms and inbox keys in `setUp`, and `pump` is `pumpGroups`. `GroupInboxHarness` ferries 30379. `ConfederationProfileNetworkJvmTest` forms its confederation over real MLS group rooms and real inboxes, with no NIP-17 room. The signing test's "the key ceremony's room leads to the confederation" went with the room, and its count of who carried looks only at signing envelopes, since the ceremony is carried the same way now. Schema 54's export loses `ConfederationCeremony.chatRoomId`. `ConfederationCeremonyJvmTest` 27/27. Full `jvmTest` 2,033, all passing; `m3Audit` at budget; `compileDebugKotlinAndroid` builds. + ### Phase 6: the screens and the lines (report D6) **Lines.** `ConfederationRitualManager.announce` writes into each seat group's room, by this device