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 8a7e8cf4..936afa55 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 @@ -1742,6 +1742,20 @@ abstract class NostrDao( } } + // A confederation's key ceremony, written into a seat group's room or + // carried in by its admin. docs/confederation-dkg-inboxes.md, Phase 4. + ConfederationRitualEvents.isRitualKind(innerEvent.kind) -> { + if (ExperimentalFeatures.confederation) { + ConfederationRitualManager.processFromRoom( + database = database, + groupRoom = localChatRoom, + envelope = innerEvent, + userPublicKey = activeKeyPair.pubKey.toHex(), + nostrPrivateKey = activeKeyPair.privKey!!, + ) + } + } + FrostSigningEvents.isFrostSigningKind(innerEvent.kind) -> FrostSigningManager.processSigningPayload( database = database, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationBridge.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationBridge.kt index 5b3982b6..511473e2 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationBridge.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationBridge.kt @@ -25,6 +25,9 @@ import mobi.giza.compose.database.model.MarmotInnerEvent import mobi.giza.compose.database.repository.DisappearingSettingsStore import mobi.giza.compose.nostr.DisappearingMessages import mobi.giza.compose.nostr.Relays +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents +import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents import mobi.giza.compose.nostr.inbox.InboxAnnouncement import mobi.giza.compose.nostr.inbox.InboxSeal @@ -52,12 +55,57 @@ import mobi.giza.compose.nostr.inbox.InboxWrap * Nothing here decides anything. Every event carried is signed by its author and checked by whoever * receives it (D3), so a carrier can delay or withhold, which an admin could always do, and nothing * more. + * + * **Two scopes** (docs/confederation-dkg-inboxes.md, Phase 4). A formed confederation's signing, + * by its id, in 30398 envelopes; and a running key ceremony, by its proposal's id, in 30379 + * envelopes. A ceremony's carriers need not have joined it: the groups and seats come from the + * statements every admin of every group holds once the proposal is accepted. Every rule after the + * scope is the same. + * + * **Envelopes split by bytes.** One carries what is due up to [ConfederationKinds.MAX_CARRIED_BYTES] + * of content, or [ConfederationSigningEvents.MAX_CARRIED] events, and the rest go in the next: a + * round of dealings is far larger than a relay takes in one wrap. */ object ConfederationBridge { private val logger = Logger.withTag("ConfederationBridge") private val mutex = Mutex() val WAIT_PER_PLACE: Duration = 20.seconds + + /** What a carry is for: a formed confederation's signing, or a running key ceremony. */ + sealed interface CarryScope { + /** The confederation's id for [Signing]; the proposal's id for [Ceremony]. */ + val id: HexKey + val name: String + /** The kind of envelope it travels in. */ + val envelopeKind: Int + + data class Signing(override val id: HexKey) : CarryScope { + override val name get() = ConfederationCarry.SIGNING + override val envelopeKind get() = ConfederationSigningEvents.CARRIED + } + + data class Ceremony(override val id: HexKey) : CarryScope { + override val name get() = ConfederationCarry.CEREMONY + override val envelopeKind get() = ConfederationRitualEvents.CARRIED + } + + companion object { + fun of(name: String, id: HexKey): CarryScope = if (name == ConfederationCarry.CEREMONY) Ceremony(id) else Signing(id) + } + } + + /** The groups and seats [scope] is carried between, or null when this device cannot tell yet. */ + private suspend fun planOf(database: GizaDatabase, scope: CarryScope): ConfederationRosterBuilder.Plan? = when (scope) { + is CarryScope.Signing -> ConfederationSigningManager.held(database, scope.id)?.plan + is CarryScope.Ceremony -> ConfederationRitualManager.carryPlan(database, scope.id) + } + + /** The tag an envelope of [scope] names it by. */ + private fun scopeTag(scope: CarryScope): Array = when (scope) { + is CarryScope.Signing -> ConfederationSigningEvents.confederationTag(scope.id) + is CarryScope.Ceremony -> arrayOf(ConfederationRitualEvents.PROPOSAL_TAG, scope.id) + } private val LOOK_AGAIN: Duration = 5.seconds /** Sweeps every [LOOK_AGAIN] for as long as it runs. */ @@ -74,47 +122,47 @@ object ConfederationBridge { } /** - * [events] about [confederationId] appeared in the room of [groupRoomId] on this device -- heard - * from another member, or written by this device's owner. Owed out, by this device's turn, when its - * owner is one of the group's admins holding its inbox key. + * [events] of [scope] appeared in the room of [groupRoomId] on this device -- heard from another + * member, or written by this device's owner. Owed out, by this device's turn, when its owner is one + * of the group's admins holding its inbox key. */ - suspend fun heardInRoom(database: GizaDatabase, groupRoomId: String, confederationId: HexKey, events: List, userPublicKey: HexKey, now: Instant = Clock.System.now()) { + suspend fun heardInRoom(database: GizaDatabase, groupRoomId: String, scope: CarryScope, events: List, userPublicKey: HexKey, now: Instant = Clock.System.now()) { val dao = database.confederationCeremonyDao() events.forEach { markCarried(database, it.id, groupRoomId, ConfederationCarry.IN, now) } val place = placeOf(database, groupRoomId, userPublicKey) ?: return if (ConfederationManager.announcedInboxKey(database, groupRoomId, userPublicKey) == null) return // Only the group's own word goes out from its room: its seated people's messages and its // voucher. What an admin carried in from the other groups is already where it needs to be. - val held = ConfederationSigningManager.held(database, confederationId) ?: return - val seated = held.plan.seats.filter { it.group == groupRoomId }.map { it.admin }.toSet() + val plan = planOf(database, scope) ?: return + val seated = plan.seats.filter { it.group == groupRoomId }.map { it.admin }.toSet() events.filter { it.pubKey in seated || it.pubKey == groupRoomId }.forEach { event -> dao.insertCarry( ConfederationCarry( eventId = event.id, groupRoomId = groupRoomId, direction = ConfederationCarry.OUT, - confederationId = confederationId, eventJson = event.toJson(), dueAt = now + WAIT_PER_PLACE * place, + confederationId = scope.id, eventJson = event.toJson(), dueAt = now + WAIT_PER_PLACE * place, scope = scope.name, ) ) } } /** - * [events] about [confederationId] came in through [groupRoomId]'s inbox: they have crossed, and - * nobody of the group need carry them out. Owed into the room, by this device's turn, when the - * group has a seated member who is not one of its admins. + * [events] of [scope] came in through [groupRoomId]'s inbox: they have crossed, and nobody of the + * group need carry them out. Owed into the room, by this device's turn, when the group has a seated + * member who is not one of its admins. */ - suspend fun heardInInbox(database: GizaDatabase, groupRoomId: String, confederationId: HexKey, events: List, userPublicKey: HexKey, now: Instant = Clock.System.now()) { + suspend fun heardInInbox(database: GizaDatabase, groupRoomId: String, scope: CarryScope, events: List, userPublicKey: HexKey, now: Instant = Clock.System.now()) { val dao = database.confederationCeremonyDao() events.forEach { markCarried(database, it.id, groupRoomId, ConfederationCarry.OUT, now) } val place = placeOf(database, groupRoomId, userPublicKey) ?: return - val held = ConfederationSigningManager.held(database, confederationId) ?: return + val plan = planOf(database, scope) ?: return val admins = RoomAdmins.of(database, groupRoomId)?.admins ?: return - val seated = held.plan.seats.filter { it.group == groupRoomId }.map { it.admin }.toSet() + val seated = plan.seats.filter { it.group == groupRoomId }.map { it.admin }.toSet() if (seated.all { it in admins }) return events.forEach { event -> dao.insertCarry( ConfederationCarry( eventId = event.id, groupRoomId = groupRoomId, direction = ConfederationCarry.IN, - confederationId = confederationId, eventJson = event.toJson(), dueAt = now + WAIT_PER_PLACE * place, + confederationId = scope.id, eventJson = event.toJson(), dueAt = now + WAIT_PER_PLACE * place, scope = scope.name, ) ) } @@ -134,45 +182,74 @@ object ConfederationBridge { private suspend fun placeOf(database: GizaDatabase, groupRoomId: String, userPublicKey: HexKey): Int? = RoomAdmins.of(database, groupRoomId)?.admins?.sorted()?.indexOf(userPublicKey)?.takeIf { it >= 0 } - /** Carries everything due, in one envelope per group, confederation and direction. Returns how many envelopes went. */ + /** + * Carries everything due, in envelopes per group, scope and direction, each up to the byte budget. + * Returns how many envelopes went. + */ suspend fun sweep(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray, now: Instant = Clock.System.now()): Int = mutex.withLock { val dao = database.confederationCeremonyDao() val due = dao.getDueCarries(now) - due.groupBy { Triple(it.groupRoomId, it.confederationId, it.direction) }.count { (key, rows) -> - val (groupRoomId, confederationId, direction) = key - val events = rows.mapNotNull { Event.fromJsonOrNull(it.eventJson) }.take(ConfederationSigningEvents.MAX_CARRIED) - val sent = runCatching { - if (direction == ConfederationCarry.OUT) carryOut(database, groupRoomId, confederationId, events, userPublicKey, nostrPrivateKey) - else carryIn(database, groupRoomId, confederationId, events, userPublicKey) - }.onFailure { if (it is CancellationException) throw it; logger.w(throwable = it) { "Could not carry ${events.size} event(s) for ${groupRoomId.take(8)}" } } - .getOrDefault(false) - if (sent) events.forEach { markCarried(database, it.id, groupRoomId, direction, now) } - sent + var sent = 0 + due.groupBy { Triple(it.groupRoomId, CarryScope.of(it.scope, it.confederationId), it.direction) }.forEach { (key, rows) -> + val (groupRoomId, scope, direction) = key + envelopes(rows.mapNotNull { Event.fromJsonOrNull(it.eventJson) }).forEach { events -> + val carried = runCatching { + if (direction == ConfederationCarry.OUT) carryOut(database, groupRoomId, scope, events, userPublicKey, nostrPrivateKey) + else carryIn(database, groupRoomId, scope, events, userPublicKey) + }.onFailure { if (it is CancellationException) throw it; logger.w(throwable = it) { "Could not carry ${events.size} event(s) for ${groupRoomId.take(8)}" } } + .getOrDefault(false) + if (carried) { + events.forEach { markCarried(database, it.id, groupRoomId, direction, now) } + sent++ + } + } } + sent + } + + /** + * [events] in envelopes, in order, each at most [ConfederationKinds.MAX_CARRIED_BYTES] of content and + * [ConfederationSigningEvents.MAX_CARRIED] events. An event over the budget on its own goes alone: + * a roster that makes one is refused before anyone deals, and signing never makes one. + */ + internal fun envelopes(events: List): List> { + val out = mutableListOf>() + var current = mutableListOf() + var bytes = 2 + events.forEach { event -> + val size = event.toJson().encodeToByteArray().size + 1 + if (current.isNotEmpty() && (bytes + size > ConfederationKinds.MAX_CARRIED_BYTES || current.size >= ConfederationSigningEvents.MAX_CARRIED)) { + out += current + current = mutableListOf() + bytes = 2 + } + if (size + 2 > ConfederationKinds.MAX_CARRIED_BYTES) logger.w("A carried event ${event.id.take(8)} is ${size} bytes, over the budget on its own; it goes alone") + current += event + bytes += size + } + if (current.isNotEmpty()) out += current + return out } /** One envelope from this person to every member group's inbox, owed under [groupRoomId]. */ private suspend fun carryOut( database: GizaDatabase, groupRoomId: String, - confederationId: HexKey, + scope: CarryScope, events: List, userPublicKey: HexKey, nostrPrivateKey: ByteArray, ): Boolean { - val held = ConfederationSigningManager.held(database, confederationId) ?: return false + val plan = planOf(database, scope) ?: return false val createdAt = TimeUtils.now() - val tags = DisappearingSettingsStore(database).stamp( - groupRoomId, userPublicKey, ConfederationSigningEvents.CARRIED, createdAt, - arrayOf(ConfederationSigningEvents.confederationTag(confederationId)), - ) + val tags = DisappearingSettingsStore(database).stamp(groupRoomId, userPublicKey, scope.envelopeKind, createdAt, arrayOf(scopeTag(scope))) val content = ConfederationSigningEvents.encodeCarried(events) - val id = EventHasher.hashId(userPublicKey, createdAt, ConfederationSigningEvents.CARRIED, tags, content) - val rumor = Event(id, userPublicKey, createdAt, ConfederationSigningEvents.CARRIED, tags, content, "") + val id = EventHasher.hashId(userPublicKey, createdAt, scope.envelopeKind, tags, content) + val rumor = Event(id, userPublicKey, createdAt, scope.envelopeKind, tags, content, "") val rumorExpiry = DisappearingMessages.expirationOf(tags, createdAt) val signer = NostrSignerSync(KeyPair(nostrPrivateKey)) var owed = 0 - held.plan.groups.forEach { group -> + plan.groups.forEach { group -> val key = inboxKeyOf(database, group) ?: run { logger.w("${group.take(8)} has announced no inbox here; its admins will not hear this envelope from ${groupRoomId.take(8)}") return@forEach @@ -198,15 +275,18 @@ object ConfederationBridge { ) owed++ } - if (owed > 0) logger.i("Carried ${events.size} event(s) for ${confederationId.take(8)} out of ${groupRoomId.take(8)} to $owed inbox(es)") + if (owed > 0) logger.i("Carried ${events.size} event(s) of ${scope.name.lowercase()} ${scope.id.take(8)} out of ${groupRoomId.take(8)} to $owed inbox(es)") return owed > 0 } /** One envelope into [groupRoomId]'s room, from this person, for its seated members who read no inbox. */ - private suspend fun carryIn(database: GizaDatabase, groupRoomId: String, confederationId: HexKey, events: List, userPublicKey: HexKey): Boolean { + private suspend fun carryIn(database: GizaDatabase, groupRoomId: String, scope: CarryScope, events: List, userPublicKey: HexKey): Boolean { database.chatRoomDao().findChatRoomById(groupRoomId)?.takeIf { it.chatRoom.mlsGroupState != null } ?: return false - ConfederationSigningManager.queueEnvelope(database, groupRoomId, confederationId, userPublicKey, events) - logger.i("Carried ${events.size} event(s) for ${confederationId.take(8)} into ${groupRoomId.take(8)}'s room") + when (scope) { + is CarryScope.Signing -> ConfederationSigningManager.queueEnvelope(database, groupRoomId, scope.id, userPublicKey, events) + is CarryScope.Ceremony -> ConfederationRitualManager.queueEnvelope(database, groupRoomId, scope.id, userPublicKey, events) + } + logger.i("Carried ${events.size} event(s) of ${scope.name.lowercase()} ${scope.id.take(8)} into ${groupRoomId.take(8)}'s room") return true } 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 2199f41d..c5e14fd0 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt @@ -36,6 +36,7 @@ import mobi.giza.compose.database.model.ConfederationCeremonyHeard import mobi.giza.compose.database.model.ConfederationCeremonyMessage import mobi.giza.compose.database.model.ConfederationCeremonyStage import mobi.giza.compose.database.model.GiftWrapPayload +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 @@ -47,6 +48,7 @@ import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents.Basis import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder.Plan +import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents import mobi.giza.compose.nostr.confederation.ConfederationStatements import mobi.giza.compose.nostr.confederation.ConfederationStatus @@ -121,6 +123,22 @@ object ConfederationRitualManager { fun planOf(ceremony: ConfederationCeremony): Plan? = Basis.decode(ceremony.basisJson)?.let { planFrom(it) as? Either.Right }?.value + /** + * The groups and seats [proposalId]'s ceremony is carried between (docs/confederation-dkg-inboxes.md, + * Phase 4), from the statements alone: what a group's admin carries by, whether or not they have + * joined. Null until every group has accepted on this device. + */ + internal suspend fun carryPlan(database: GizaDatabase, proposalId: HexKey): Plan? = + (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). + */ + private suspend fun roomsFor(database: GizaDatabase, plan: Plan, userPublicKey: HexKey): List = + plan.seatsOf(userPublicKey).map { it.group }.distinct() + .mapNotNull { group -> database.chatRoomDao().findChatRoomById(group)?.takeIf { it.chatRoom.mlsGroupState != null } } + /** * Everything a person checks before they would join, as a reason or the roster's plan: the * basis plans, the statements are accepted in time and nothing this device holds rejects or @@ -287,14 +305,68 @@ object ConfederationRitualManager { 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 + * the other groups' inboxes, and read like any other. A member who is not one of the group's admins + * has nothing to do with the ceremony, and files nothing. + */ + suspend fun processFromRoom( + database: GizaDatabase, + groupRoom: LocalChatRoom, + envelope: Event, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + ) { + if (envelope.kind != ConfederationRitualEvents.CARRIED) return + val roomId = groupRoom.chatRoom.id + if (RoomAdmins.of(database, roomId)?.admins?.contains(userPublicKey) != true) return + val proposalId = ConfederationRitualEvents.parseProposalId(envelope.tags) ?: return + val events = verifiedEvents(envelope) ?: return + ConfederationBridge.heardInRoom(database, roomId, ConfederationBridge.CarryScope.Ceremony(proposalId), events, userPublicKey) + receive(database, events, userPublicKey, nostrPrivateKey) + } + + /** + * An envelope that came in through [inboxRoomId]'s inbox from another group's admin (Phase 4): it + * has crossed, so nobody of this group need carry it out. With [nostrPrivateKey] it is acted on at + * once; without, it is only filed, and replayed when its owner joins or the next message comes. + */ + suspend fun receiveFromInbox(database: GizaDatabase, inboxRoomId: String, envelope: Event, userPublicKey: HexKey, nostrPrivateKey: ByteArray?) { + val proposalId = ConfederationRitualEvents.parseProposalId(envelope.tags) ?: return + val events = verifiedEvents(envelope) ?: return + ConfederationBridge.heardInInbox(database, inboxRoomId, ConfederationBridge.CarryScope.Ceremony(proposalId), events, userPublicKey) + if (nostrPrivateKey == null) { + events.forEach { event -> ConfederationRitualEvents.parseSessionId(event.tags)?.let { hear(database, it, event) } } + return + } + receive(database, events, userPublicKey, nostrPrivateKey) + } + + /** Queues [events] for [groupRoomId]'s room as one envelope from [userPublicKey]: a carrier's, carrying in. */ + internal suspend fun queueEnvelope(database: GizaDatabase, groupRoomId: String, proposalId: HexKey, userPublicKey: HexKey, events: List): Boolean { + val room = database.chatRoomDao().findChatRoomById(groupRoomId)?.takeIf { it.chatRoom.mlsGroupState != null } ?: return false + writeIntoRoom(database, room, proposalId, userPublicKey, events) + 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. + */ + private suspend fun receive(database: GizaDatabase, events: List, userPublicKey: HexKey, nostrPrivateKey: ByteArray) { events.forEach { event -> val sessionId = ConfederationRitualEvents.parseSessionId(event.tags) ?: return@forEach hear(database, sessionId, event) val ceremony = database.confederationCeremonyDao().getCeremony(sessionId)?.takeIf { it.userPublicKey == userPublicKey } ?: return@forEach if (!ceremony.isRunning) return@forEach - if (!record(database, localChatRoom, ceremony, event, nostrPrivateKey)) return@forEach - advance(database, localChatRoom, ceremony.id, nostrPrivateKey) + val room = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return@forEach + if (!record(database, room, ceremony, event, nostrPrivateKey)) return@forEach + advance(database, room, ceremony.id, nostrPrivateKey) } } @@ -713,6 +785,35 @@ object ConfederationRitualManager { 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 -> + writeIntoRoom(database, room, ceremony.proposalId, ceremony.userPublicKey, listOf(signed)) + ConfederationBridge.heardInRoom(database, room.chatRoom.id, ConfederationBridge.CarryScope.Ceremony(ceremony.proposalId), listOf(signed), ceremony.userPublicKey) + } + } + + /** Queues an envelope of [events] for a group's Marmot [room], encrypted to the room as a group event. */ + private suspend fun writeIntoRoom(database: GizaDatabase, room: LocalChatRoom, proposalId: HexKey, userPublicKey: HexKey, events: List) { + // Names the room, so the same events written into two rooms -- by someone seated in two + // groups -- are two envelopes rather than one row overwriting the other. + val tags = arrayOf(arrayOf(ConfederationRitualEvents.PROPOSAL_TAG, proposalId), arrayOf(ConfederationSigningEvents.ROOM_TAG, room.chatRoom.id)) + val content = ConfederationRitualEvents.encodeCarried(events) + val createdAt = Clock.System.now().epochSeconds + val id = EventHasher.hashId(userPublicKey, createdAt, ConfederationRitualEvents.CARRIED, tags, content) + database.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = id, + publicKey = userPublicKey, + kind = ConfederationRitualEvents.CARRIED, + createdAt = Instant.fromEpochSeconds(createdAt), + tags = tags, + content = content, + chatRoomId = room.chatRoom.id, + ) + ) } /** diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt index e4881f3c..b73c28f6 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt @@ -280,7 +280,7 @@ object ConfederationSigningManager { // Into the group's own room, where the group's role holders are (D2); its admins carry it on (D4). val room = database.chatRoomDao().findChatRoomById(voucher.pubKey)?.takeIf { it.chatRoom.mlsGroupState != null } ?: return carry(database, room, held.confederation.id, userPublicKey, listOf(voucher)) - ConfederationBridge.heardInRoom(database, room.chatRoom.id, held.confederation.id, listOf(voucher), userPublicKey) + ConfederationBridge.heardInRoom(database, room.chatRoom.id, ConfederationBridge.CarryScope.Signing(held.confederation.id), listOf(voucher), userPublicKey) } // ---- inbound --------------------------------------------------------------------------- @@ -311,7 +311,7 @@ object ConfederationSigningManager { } val verified = carried.filter { it.verify() } // What the group's admins owe the other groups' inboxes (D4). - ConfederationBridge.heardInRoom(database, localChatRoom.chatRoom.id, confederationId, verified, userPublicKey) + ConfederationBridge.heardInRoom(database, localChatRoom.chatRoom.id, ConfederationBridge.CarryScope.Signing(confederationId), verified, userPublicKey) val sender = Sender(nostrPrivateKey) carried.forEach { receive(database, sender, confederationId, it, userPublicKey) } } @@ -325,7 +325,7 @@ object ConfederationSigningManager { suspend fun receiveFromInbox(database: GizaDatabase, inboxRoomId: String, rumor: Event, userPublicKey: HexKey, nostrPrivateKey: ByteArray?) { val confederationId = ConfederationSigningEvents.parseConfederation(rumor.tags) ?: return val carried = ConfederationSigningEvents.decodeCarried(rumor.content)?.filter { it.verify() } ?: return - ConfederationBridge.heardInInbox(database, inboxRoomId, confederationId, carried, userPublicKey) + ConfederationBridge.heardInInbox(database, inboxRoomId, ConfederationBridge.CarryScope.Signing(confederationId), carried, userPublicKey) if (nostrPrivateKey == null) { carried.forEach { hear(database, confederationId, it) } return @@ -757,7 +757,7 @@ object ConfederationSigningManager { rooms.forEach { room -> carry(database, room, attempt.confederationId, attempt.userPublicKey, listOf(signed)) // This device's owner may be one of the group's admins, who carry it on (D4). - ConfederationBridge.heardInRoom(database, room.chatRoom.id, attempt.confederationId, listOf(signed), attempt.userPublicKey) + ConfederationBridge.heardInRoom(database, room.chatRoom.id, ConfederationBridge.CarryScope.Signing(attempt.confederationId), listOf(signed), attempt.userPublicKey) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt index a723ede1..8b50c50a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt @@ -12,6 +12,7 @@ import mobi.giza.compose.database.model.GroupInboxMessage import mobi.giza.compose.database.model.GroupInboxWrap import mobi.giza.compose.database.model.InboxKey import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationStatements import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents import mobi.giza.compose.nostr.inbox.InboxAnnouncement @@ -109,6 +110,13 @@ object GroupInboxManager { database.groupInboxDao().markOpened(wrap.id, key.generation) return null } + // A confederation's key ceremony, carried here by another group's admin: the ceremony's to + // act on, not a conversation in the inbox (docs/confederation-dkg-inboxes.md, Phase 4). + if (rumor.kind == ConfederationRitualEvents.CARRIED) { + ConfederationRitualManager.receiveFromInbox(database, roomId, rumor, userPublicKey, nostrPrivateKey) + database.groupInboxDao().markOpened(wrap.id, key.generation) + return null + } // A confederation's statement, from one group to the others it names: the confederation's // to file, not a conversation in the inbox (docs/confederation-without-coordinator.md, D7). if (ConfederationStatements.isStatementKind(rumor.kind)) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationKinds.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationKinds.kt index 8ae0217c..22799ffe 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationKinds.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationKinds.kt @@ -77,6 +77,15 @@ object ConfederationKinds { /** Most bytes one statement's signing proposal may carry: about a relay's 64 KiB event, less the MLS framing. */ const val MAX_STATEMENT_BYTES = 60_000 + /** + * Most bytes of content one carried envelope holds (docs/confederation-dkg-inboxes.md, Phase 0): + * NIP-44 pads each layer to a step before base64, so a wrap stays under a relay's 64 KiB only + * while its rumor pads to 28,672 bytes or less. 26,000 leaves room for the escaping inside. + * Also the most one person's single ceremony message may be: an envelope of one event is that + * event and two brackets. + */ + const val MAX_CARRIED_BYTES = 26_000 + /** Most roles, across every group, upstream's roster can carry. */ const val MAX_ROLES = 128 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 3a2d68f0..de0c5b40 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt @@ -461,9 +461,11 @@ class ConfederationCeremonyJvmTest { } } - /** Flipped by Phase 4: the bridge carries a running ceremony's messages, by its proposal. */ + // ---- docs/confederation-dkg-inboxes.md, Phase 4: the groups' rooms and inboxes ----------------- + + /** Phase 1 pinned the opposite: the bridge carried nothing for a proposal. */ @Test - fun `today the bridge carries nothing for a proposal that is not yet a confederation`() { + fun `the bridge carries a running ceremony's messages, by its proposal, before anyone joins`() { setUp() runBlocking { network.withGroupRooms() @@ -472,15 +474,19 @@ class ConfederationCeremonyJvmTest { Clock.System.now().epochSeconds, ConfederationRitualEvents.HOST_KEYS, arrayOf(arrayOf(ConfederationRitualEvents.PROPOSAL_TAG, network.proposalId)), "{}", ) - ConfederationBridge.heardInRoom(admin.db, groups[0], network.proposalId, listOf(signed), admin.person) - assertEquals(0, ConfederationBridge.sweep(admin.db, admin.person, admin.nsec, Clock.System.now() + 10.minutes)) - assertEquals(emptyList(), admin.db.groupInboxDao().observeUnpublished().first()) + ConfederationBridge.heardInRoom(admin.db, groups[0], ConfederationBridge.CarryScope.Ceremony(network.proposalId), listOf(signed), admin.person) + assertEquals(1, ConfederationBridge.sweep(admin.db, admin.person, admin.nsec, Clock.System.now() + 10.minutes)) + val wraps = admin.db.groupInboxDao().observeUnpublished().first() + assertEquals(groups.size, wraps.size, "a wrap to each member group's inbox") + assertEquals(groups.toSet(), wraps.map { it.recipientPublicKey }.toSet()) + assertTrue(wraps.all { network.carriedIn(Event.fromJson(it.eventJson)).single().id == signed.id }) + assertNull(ceremonies().getValue(admin.person), "nobody joined: the carrier needs only the statements") } } - /** Flipped by Phase 4: an envelope is filled to a byte budget, and a large round is several. */ + /** Phase 1 pinned the opposite: one envelope a group, whatever its bytes. */ @Test - fun `today the bridge puts every due event into one envelope a group, whatever its bytes`() { + fun `the bridge fills envelopes to the byte budget, and a large round goes in several`() { val confederation = formed() runBlocking { network.withGroupRooms() @@ -491,12 +497,61 @@ class ConfederationCeremonyJvmTest { arrayOf(mobi.giza.compose.nostr.confederation.ConfederationSigningEvents.confederationTag(confederation.id)), "x".repeat(2_000), ) } - ConfederationBridge.heardInRoom(admin.db, groups[0], confederation.id, events, admin.person) - assertEquals(1, ConfederationBridge.sweep(admin.db, admin.person, admin.nsec, Clock.System.now() + 10.minutes), "one envelope") - assertEquals(groups.size, admin.db.groupInboxDao().observeUnpublished().first().size, "one wrap for each member group, holding all forty") + ConfederationBridge.heardInRoom(admin.db, groups[0], ConfederationBridge.CarryScope.Signing(confederation.id), events, admin.person) + val envelopes = ConfederationBridge.sweep(admin.db, admin.person, admin.nsec, Clock.System.now() + 10.minutes) + assertEquals(4, envelopes, "forty events of 2.4 KB in envelopes of at most 26,000 bytes") + val wraps = admin.db.groupInboxDao().observeUnpublished().first().map { Event.fromJson(it.eventJson) } + assertEquals(envelopes * groups.size, wraps.size) + wraps.forEach { assertTrue(it.toJson().length <= 65_536, "every wrap under a relay's 64 KiB: ${it.toJson().length}") } + val crossed = wraps.filter { it.tags.any { t -> t[0] == "p" && t[1] == groups[1] } }.flatMap { network.carriedIn(it) } + assertEquals(events.map { it.id }, crossed.map { it.id }, "every event once, in order") } } + @Test + fun `the groups' rooms and inboxes alone form the key, each group's part carried by its first admin`() { + 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() + } + 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 -> + val carried = device.db.groupInboxDao().getPublicationsForRoom(group) + if (device.person == firstAdmin) assertTrue(carried.isNotEmpty(), "${network.names[i]}'s first admin carried its part") + else assertEquals(emptyList(), carried, "${network.names[i]}'s other admins carried nothing") + } + } + } + } + + @Test + fun `a ceremony's messages come twice, by NIP-17 and by the inboxes, and form one key`() { + setUp() + runBlocking { + network.withGroupRooms() + network.joinAll() + network.pump() + network.pumpGroups() + } + 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`() { 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 c18f5603..7a914d62 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationPeople.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationPeople.kt @@ -22,6 +22,9 @@ import mobi.giza.compose.database.model.InboxKey import mobi.giza.compose.database.model.InboxKeyState import mobi.giza.compose.nostr.inbox.InboxAnnouncement import mobi.giza.compose.nostr.inbox.InboxWire +import mobi.giza.compose.nostr.inbox.InboxSeal +import mobi.giza.compose.nostr.inbox.InboxWrap +import kotlinx.coroutines.flow.first import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync @@ -34,6 +37,9 @@ import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync * 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. */ +/** 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) + class ConfederationPeople( /** Each group's admins, by the number [secret] makes a person's key from. A number in two groups is one person. */ val adminsByGroup: List>, @@ -195,6 +201,58 @@ class ConfederationPeople( } } + /** The signed events an envelope's content carries, of either scope. */ + fun carriedIn(content: String): List = ConfederationRitualEvents.decodeCarried(content).orEmpty() + + /** The signed events a wrap to one of the groups' inboxes carries, opened with the fixture's inbox secrets. */ + fun carriedIn(wrap: Event): List { + val secrets = inboxSecrets.map { it.value.toByteArray() } + val (index, seal) = InboxWrap.open(wrap, secrets) ?: return emptyList() + val rumor = InboxSeal.open(seal, secrets[index])?.rumor ?: return emptyList() + return if (rumor.kind in ENVELOPES) carriedIn(rumor.content) else emptyList() + } + + /** + * Until nothing moves: each group's room between its members' devices, every admin's turn at + * carrying at [at], and every wrap owed to an inbox to every device -- the confederation's signing + * and, since docs/confederation-dkg-inboxes.md Phase 4, its key ceremony. [hold] keeps back an + * 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 }) { + val online = devices.values.filter { it !in away } + var moved = true + while (moved) { + moved = false + for (from in online) for (group in groups) { + from.db.marmotInnerEventDao().getByChatRoomAndKinds(group, ENVELOPES.toList()) + .filter { it.publicKey == from.person }.sortedWith(compareBy({ it.createdAt }, { it.id })) + .forEach { q -> + if (carriedIn(q.content).any(hold)) return@forEach + online.filter { it !== from }.forEach { to -> + val room = to.db.chatRoomDao().findChatRoomById(group) ?: return@forEach + if (!to.received.add(group + q.id)) return@forEach + moved = true + to.db.marmotInnerEventDao().upsert(q) + val envelope = Event(q.id, q.publicKey, q.createdAt.epochSeconds, q.kind, q.tags, q.content, "") + if (q.kind == ConfederationRitualEvents.CARRIED) ConfederationRitualManager.processFromRoom(to.db, room, envelope, to.person, to.nsec) + else ConfederationSigningManager.process(to.db, room, envelope, to.person, to.nsec) + } + } + } + online.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) + if (carriedIn(wrap).any(hold)) return@forEach + online.forEach { to -> GroupInboxManager.receive(to.db, wrap, to.person, to.nsec) } + from.db.groupInboxDao().markPublished(owed.eventId, Clock.System.now()) + moved = true + } + } + } + } + fun close() { RoomAdmins.override = null devices.values.forEach { it.db.close() } 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 17892288..e8eeb5b6 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt @@ -107,35 +107,7 @@ class ConfederationSigningJvmTest { * or a wrap carrying any event it names; [away] devices neither send nor receive. */ private fun pump(at: Instant? = null, away: Set = emptySet(), hold: (Event) -> Boolean = { false }) = runBlocking { - val online = devices.values.filter { it !in away } - var moved = true - while (moved) { - moved = false - for (from in online) for (group in groups) { - from.db.marmotInnerEventDao().getByChatRoomAndKinds(group, listOf(ConfederationSigningEvents.CARRIED)) - .filter { it.publicKey == from.person }.sortedWith(compareBy({ it.createdAt }, { it.id })) - .forEach { q -> - if (carriedIn(q.content).any(hold)) return@forEach - online.filter { it !== from }.forEach { to -> - val room = to.db.chatRoomDao().findChatRoomById(group) ?: return@forEach - if (!to.received.add(group + q.id)) return@forEach - moved = true - to.db.marmotInnerEventDao().upsert(q) - ConfederationSigningManager.process(to.db, room, Event(q.id, q.publicKey, q.createdAt.epochSeconds, q.kind, q.tags, q.content, ""), to.person, to.nsec) - } - } - } - online.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) - if (carriedIn(wrap).any(hold)) return@forEach - online.forEach { to -> GroupInboxManager.receive(to.db, wrap, to.person, to.nsec) } - from.db.groupInboxDao().markPublished(owed.eventId, Clock.System.now()) - moved = true - } - } - } + network.pumpGroups(at, away.map { it.ceremonyDevice }.toSet(), hold) } /** diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationTestGroups.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationTestGroups.kt index 85113d5c..84dfb1b6 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationTestGroups.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationTestGroups.kt @@ -30,7 +30,11 @@ class ConfederationTestGroups( /** Picks the groups' signing keys: two sets of groups in one test need different ones. */ keySeries: Int = 0, ) { - inner class Group(val index: Int, val name: String, val memberNames: List, val harness: GroupInboxHarness) { + /** + * Nested rather than inner: it needs nothing of the groups around it, and a clean compile of the + * test source set left an inner `Group` without the Compose `${'$'}stable` field its users read. + */ + class Group(val index: Int, val name: String, val memberNames: List, val harness: GroupInboxHarness) { val roomId: HexKey get() = harness.roomId lateinit var devices: List val members: List get() = harness.signers diff --git a/docs/confederation-dkg-inboxes.md b/docs/confederation-dkg-inboxes.md index 9005a1d1..85f6f0b8 100644 --- a/docs/confederation-dkg-inboxes.md +++ b/docs/confederation-dkg-inboxes.md @@ -330,6 +330,10 @@ unchanged, which shows the signatures cost the protocol nothing. Three new cases `T/managers/ConfederationPeople.kt` as `pumpGroups(at, away, hold)`, taking the envelope kinds to ferry. The signing test calls it unchanged, and the ceremony tests use it from here on. +**Done.** As planned, with three differences. The byte split is checked in `ConfederationCeremonyJvmTest` (forty 2.4 KB signing events go as four envelopes, every wrap under 64 KiB, every event once and in order), not in a new `ConfederationBridgeJvmTest`. `GroupSealRoutingJvmTest` gains nothing: it routes FROST seal batches, and a ceremony envelope is a rumor the inbox opens, routed in `GroupInboxManager.open`. And `processFromRoom` reads an envelope only on the device of one of the group's admins, which every seated person is, so a member who is not an admin files nothing. Every ceremony message received by any path goes through one `receive`, which fails out on the ceremony's NIP-17 room while that is still the channel a failure goes back on. `ConfederationPeople.pumpGroups` is the signing test's pump, ferrying both envelope kinds, and `ConfederationSigningJvmTest` calls it. `ConfederationCeremonyJvmTest` 23/23, including the groups' rooms and inboxes forming the key with no NIP-17 pump at all, each group's part carried by its first admin and nobody else. `ConfederationSigningJvmTest` 25/25, `ConfederationSharedSeatsSigningJvmTest` 3/3, `ConfederationProfileNetworkJvmTest` 3/3. Full `jvmTest` 2,030, all passing; `m3Audit` at budget; `compileDebugKotlinAndroid` builds. + +One thing outside the plan: the first clean compile of the test source set in this worktree left `ConfederationTestGroups.Group`, an inner class, without the Compose `$stable` field the classes that hold one read in their static initializers, and `ConfederationDeclineJvmTest` and `ConfederationNetworkJvmTest` failed to load. Earlier runs had used test classes from the build cache. `Group` needs nothing of its outer instance, so it is a nested class now, which Compose handles. + ### Phase 5: the switch (report D5, D8, D10) **No room.** In `K/managers/ConfederationRitualManager.kt`: