diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileNetworkJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileNetworkJvmTest.kt new file mode 100644 index 00000000..17593085 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileNetworkJvmTest.kt @@ -0,0 +1,229 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import fr.acinq.bitcoin.Crypto +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Instant +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.Confederation +import mobi.giza.compose.database.model.ConfederationSigningStage +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState +import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents +import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents + +/** + * docs/confederation-profile.md, Phase 8: the plan end to end. Three groups of three admins, each + * signing by FROST and holding an inbox, form a confederation through the real statements and the + * real key ceremony on nine devices. Then Agora's admin changes its name from the confederation's + * screen's calls: Agora's quorum signs the change to every group's inbox, Polis's quorum endorses it, + * and the confederation signs it with nobody asked again. Every admin of every group reads it, every + * group's room says so, and a member of Polis who is no admin hears it from a relay. + */ +class ConfederationProfileNetworkJvmTest { + private val network = ConfederationTestGroups(keySeries = 4) + private val agora = network.groups[0] + private val polis = network.groups[1] + private val ekklesia = network.groups[2] + private val databases = mutableListOf() + + private lateinit var confederation: Confederation + private val ceremonyRooms = mutableMapOf() + private val confederationRooms = mutableMapOf() + private val received = mutableMapOf>() + + @BeforeTest + fun formed() = runBlocking { + network.setUp() + val people = network.everyDevice.map { it.publicKey } + network.everyDevice.forEach { device -> people.forEach { profile(device.db, it) } } + + // The statements, group to group: Agora proposes, Polis and Ekklesia accept. + network.signed(agora) { device -> + ConfederationManager.proposeConfederation( + device.db, device.room(), device.publicKey, listOf(polis.roomId, ekklesia.roomId), threshold = 2, name = "Atlas", + expiresAt = Clock.System.now().epochSeconds + ConfederationKinds.DEFAULT_EXPIRY_SECONDS, + ).id + } + val proposalId = agora.devices[0].db.confederationDao().getProposals().single().id + 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() + } + network.everyDevice.forEach { ConfederationRitualManager.join(it.db, proposalId, it.publicKey, it.secret) } + pumpCeremony() + confederation = assertNotNull(agora.devices[0].db.confederationCeremonyDao().getConfederationForProposal(proposalId), "formed") + + // The confederation's room on every device: its MLS state is not this test's business. + network.everyDevice.forEach { device -> + device.db.chatRoomDao().upsert(ChatRoom(id = confederation.id, userPublicKey = device.publicKey, subject = "#Atlas", description = null, mlsGroupState = "00")) + confederationRooms[device.publicKey] = device.db.chatRoomDao().findChatRoomById(confederation.id)!! + received[device.publicKey] = mutableSetOf() + } + } + + @AfterTest + fun close() { + ConfederationSigningManager.forgetSignersForTest() + databases.forEach { it.close() } + network.close() + } + + private suspend fun profile(db: GizaDatabase, key: HexKey) { + if (db.profileDao().getProfileByPublicKey(key) != null) return + val eventId = Crypto.sha256(("p" + key).encodeToByteArray()).toHex() + db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = key, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + 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 room: vouchers and the signing, from every device to every other. */ + private suspend fun pumpConfederationRoom() { + var moved = true + while (moved) { + moved = false + for (from in network.everyDevice) for (to in network.everyDevice) { + if (from === to) continue + from.db.marmotInnerEventDao().getByChatRoomAndKinds(confederation.id, ConfederationSigningEvents.ALL.toList()) + .filter { it.publicKey == from.publicKey }.sortedWith(compareBy({ it.createdAt }, { it.kind })) + .forEach { q -> + if (!received.getValue(to.publicKey).add(q.id)) return@forEach + moved = true + to.db.marmotInnerEventDao().upsert(q) + ConfederationSigningManager.process( + to.db, confederationRooms.getValue(to.publicKey), + Event(q.id, q.publicKey, q.createdAt.epochSeconds, q.kind, q.tags, q.content, ""), to.publicKey, to.secret, + ) + } + } + } + } + + private suspend fun sweepEverywhere() = + network.everyDevice.flatMap { ConfederationProfileFollowThrough.sweep(it.db, it.publicKey, it.secret) } + + private suspend fun proposeName(name: String): HexKey { + network.signed(agora) { device -> + ConfederationProfileManager.proposeChange(device.db, device.room(), device.publicKey, confederation.id, emptyArray(), """{"name":"$name","display_name":"$name"}""").id + } + return agora.devices[0].db.confederationDao().getEventsForConfederation(confederation.id) + .filter { it.kind == ConfederationKinds.PROFILE_CHANGE }.maxBy { it.eventCreatedAt }.id + } + + private suspend fun states(changeId: HexKey) = network.everyDevice.map { ConfederationProfileManager.status(it.db, changeId)?.state }.toSet() + + @Test + fun `a change proposed by one group, endorsed by another, is signed and read everywhere`() = runBlocking { + val changeId = proposeName("Atlas of the Coast") + assertEquals(setOf(ConfederationProfileChangeState.OPEN), states(changeId), "every admin of every group holds it") + pumpConfederationRoom() + assertEquals(emptyList(), sweepEverywhere(), "one group's voucher is not enough to start anything") + + network.signed(polis) { ConfederationProfileManager.proposeEndorsement(it.db, it.room(), it.publicKey, changeId).id } + assertEquals(setOf(ConfederationProfileChangeState.ENDORSED), states(changeId)) + pumpConfederationRoom() + + val started = sweepEverywhere() + assertEquals(1, started.size, "the first in the order starts the signing, and only they do") + pumpConfederationRoom() + + network.everyDevice.forEach { device -> + val attempt = device.db.confederationCeremonyDao().getAttempts(confederation.id, device.publicKey).single() + assertEquals(ConfederationSigningStage.COMPLETE, attempt.stage, "${device.name}: ${attempt.failureReason}") + assertTrue(!ConfederationSigningManager.isAwaitingApproval(attempt), "${device.name} was not asked") + assertEquals(ConfederationProfileChangeState.PUBLISHED, ConfederationProfileManager.status(device.db, changeId)?.state, device.name) + assertEquals("Atlas of the Coast", ConfederationProfileManager.profiles(device.db, confederation.id).newestProfile?.name(), device.name) + } + + // Each group's room said what happened, on every one of its admins' devices. + ekklesia.devices.forEach { device -> + val lines = device.db.chatMessageDao().getChatMessagesByChatRoomId(ekklesia.roomId).map { it.chatMessage.messageType } + assertTrue(ChatMessage.TYPE_CONFEDERATION_PROFILE_PROPOSED in lines, "${device.name}: $lines") + assertTrue(ChatMessage.TYPE_CONFEDERATION_PROFILE_ENDORSED in lines, "${device.name}: $lines") + assertTrue(ChatMessage.TYPE_CONFEDERATION_PROFILE_PUBLISHED in lines, "${device.name}: $lines") + } + + // A member of Polis who is no admin: no inbox key, no role, only Polis's room. The charter and + // the profile reach them from a relay. + val signed = Event.fromJson(started.single().let { attempt -> + network.everyDevice.first { it.publicKey == attempt.userPublicKey }.db.confederationCeremonyDao().getAttempt(attempt.id)!!.signedEventJson!! + }) + val charter = signCharter() + val watcher = getRoomDatabase(Room.inMemoryDatabaseBuilder()).also { databases += it } + val watcherKey = "f".repeat(63) + "1" + profile(watcher, watcherKey) + watcher.chatRoomDao().upsert(ChatRoom(id = polis.roomId, userPublicKey = watcherKey, subject = "#Polis", description = null, mlsGroupState = "00")) + assertTrue(ConfederationManager.record(watcher, charter)) + assertTrue(ConfederationManager.record(watcher, signed)) + assertEquals("Atlas of the Coast", ConfederationProfileManager.profiles(watcher, confederation.id).newestProfile?.name()) + assertEquals(1, watcher.chatMessageDao().getChatMessagesByChatRoomId(polis.roomId).count { it.chatMessage.messageType == ChatMessage.TYPE_CONFEDERATION_PROFILE_PUBLISHED }) + assertEquals(MetadataEvent.KIND, signed.kind) + } + + @Test + fun `a change another group objects to and its proposer withdraws is never signed`() = runBlocking { + val changeId = proposeName("Not Atlas") + network.signed(ekklesia) { ConfederationProfileManager.proposeObjection(it.db, it.room(), it.publicKey, changeId, "Keep the name").id } + network.signed(agora) { ConfederationProfileManager.proposeObjection(it.db, it.room(), it.publicKey, changeId).id } + assertEquals(setOf(ConfederationProfileChangeState.WITHDRAWN), states(changeId)) + pumpConfederationRoom() + assertEquals(emptyList(), sweepEverywhere()) + network.everyDevice.forEach { assertEquals(null, ConfederationProfileManager.profiles(it.db, confederation.id).newestProfile) } + } + + /** The confederation's charter, signed the direct way its charter still is: proposed and approved in its room. */ + private suspend fun signCharter(): Event { + val proposer = agora.devices[0] + val (kind, tags, content) = assertNotNull(ConfederationSigningManager.charterTemplate(proposer.db, confederation.id)) + val attempt = ConfederationSigningManager.propose(proposer.db, confederationRooms.getValue(proposer.publicKey), proposer.publicKey, kind, tags, content, proposer.secret) + pumpConfederationRoom() + network.everyDevice.filter { it !== proposer }.forEach { ConfederationSigningManager.approve(it.db, attempt.id, it.secret) } + pumpConfederationRoom() + return Event.fromJson(assertNotNull(proposer.db.confederationCeremonyDao().getAttempt(attempt.id)?.signedEventJson, "the charter is signed")) + } +} diff --git a/docs/README.md b/docs/README.md index ac45fe32..1fbcf58d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -17,7 +17,7 @@ the [retired](./retired/) notes now. | [subgroups.md](./subgroups.md) | a group making another group — the four ceremonies, what the parent's signature actually covers, and why the child's key is fresh rather than derived | | [confederation.md](./confederation.md) | a group made of groups: a phased plan, built behind a flag that is off in release but for its device run and the room's governance. Agreeing to form (Part A), the key ceremony and room (Part B), and the confederation signing its profile, posts and charter (Part C). Groups with a public nostr profile propose, accept or reject a confederation in public, an acceptance carries the group's admins sealed to the coordinator in a way every signer recomputes, and the confederation's DKG and Marmot room follow. Covers why the public events are regular kinds, why nothing can be encrypted from or to a group's npub, how the coordinator is kept from substituting a roster, and why everything after the agreement waits on upstream publishing the distributed rounds. Its coordinator and its public statements have since been replaced (confederation-without-coordinator.md) | | [confederation-without-coordinator.md](./confederation-without-coordinator.md) | a confederation nobody coordinates: a phased plan, built but for its device run and behind flags that are off in release. The proposal and every answer travel as NIP-17 messages between the groups' NIP-4E inboxes, each sealed by its group's quorum, so every admin of every group reads every admin list and computes the outcome, and the key ceremony derives its room and session seed and computes the coordinator's broadcast on every device. Covers why a group could be the DKG's coordinator and does not need to be, why the admin lists stop being a payload encrypted to one person, why a confederation names at most twelve groups, how a group that says different things to different groups is caught, and who makes the confederation's room when nobody is in charge | -| [confederation-profile.md](./confederation-profile.md) | a formed confederation's nostr profile, decided by its groups: a phased plan, not built. The confederation gets its own screen, reached from each member group's screen, and an edit there is a statement by the editing group, sealed by its quorum and sent to every member group's inbox, which the others endorse or object to by their own quorums. Once `T` groups have endorsed, each group's signed voucher is a role holder's consent, so the confederation signs and publishes the profile with nobody asked again. Covers why the rule is `T` of `N`, why a transferable voucher is needed beside the non-transferable seals, who starts the signing, and how the confederation's room and the key ceremony's room come to say what they are | +| [confederation-profile.md](./confederation-profile.md) | a formed confederation's nostr profile, decided by its groups: a phased plan, built but for its device run and behind flags that are off in release. The confederation gets its own screen, reached from each member group's screen, and an edit there is a statement by the editing group, sealed by its quorum and sent to every member group's inbox, which the others endorse or object to by their own quorums. Once `T` groups have endorsed, each group's signed voucher is a role holder's consent, so the confederation signs and publishes the profile with nobody asked again. Covers why the rule is `T` of `N`, why a transferable voucher is needed beside the non-transferable seals, who starts the signing, and how the confederation's room and the key ceremony's room come to say what they are | | [confederation-upstream.md](./confederation-upstream.md) | the work below Giza that unblocks the confederation's Parts B and C: a phased plan, not built, across secp256k1-zkp, secp256k1-kmp and bitcoin-kmp. Covers why the one-process DKG and signing cannot simply be exposed step by step (the coordinator derives everyone's key state, acknowledgment is signed before the share is stored, nonce randomness is derived from the session id), why every DKG step can stay stateless, the storage contract a device follows, and Prefractal as an all-groups-must-sign path that needs no upstream work | | [automatic-key-ceremony.md](./automatic-key-ceremony.md) | joining is the only approval: a phased plan, built but for its device session, that makes a key ceremony run by itself after a member joins. Covers why contributing and confirming were never decisions a person could add to, the resume sweep that replaces the tap, the coordinator's follow-up steps and the one key state a device can sign without asking, and why abandon stays | | [ceremony-creation.md](./ceremony-creation.md) | one place to start a key ceremony — how joining a subgroup's ceremony opened a second one for the parent room, the screen that showed a ceremony and offered to start one in the same button, and the removal of the nip30303 documents, whose kinds collided with the ceremony's, leaving the member chronicle with nothing to carry and nothing to say | diff --git a/docs/confederation-profile.md b/docs/confederation-profile.md index 9edb1b7a..ae4d40d2 100644 --- a/docs/confederation-profile.md +++ b/docs/confederation-profile.md @@ -14,9 +14,25 @@ whose statements, seals and refusals this plan reuses for a new kind of statemen [group-nostr-profile-and-posts.md](./group-nostr-profile-and-posts.md) defines what a group's profile is and how its form works. This plan reuses that form. -Written against `3b0b3c9a`, on 2026-11-22. **Being built** on `claude/confederation-profile`, one -commit per phase; each phase says under it what was built and where it differs from what it planned. -Paths starting `K/` are under `composeApp/src/commonMain/kotlin/mobi/giza/compose/`. +Written against `3b0b3c9a`, on 2026-11-22. **Built, Phases 0 to 8**, on `claude/confederation-profile`, +behind `ExperimentalFeatures.confederation` and `ExperimentalFeatures.groupInbox`, both off in release. +The device run (Phase 9) has not been done. Each phase says under it what was built and where it +differs from what it planned. Paths starting `K/` are under `composeApp/src/commonMain/kotlin/mobi/giza/compose/`. + +| phase | commit | result | +|---|---|---| +| 0 | `3e05a28b` | the plan, and three premises as tests. **A profile change carries the whole kind:0 in every group's seal: 1.1 KB of profile fits twelve groups, 13 KB fits two** | +| 1 | `4994248d` | kinds 9435–9438, the state of a change, and one nullable column (schema 50) rather than three tables | +| 2 | `c293514d` | a group proposes, endorses or objects, sealed to every member group's inbox, its voucher signed in the same session; seven refusals. The charter gains its threshold | +| 3 | `44cbe596` | a line in every member group's room for every statement, in any order | +| 4 | `5d6bbcd5` | the confederation's screen, its profile form and a change's screen, reached from the group's screen | +| 5 | `8d494ddb` | vouchers into the confederation's room; the first in the order starts the signing; nobody asked; crossing attempts and retries; the direct kind:0 path closed | +| 6 | `19cd1aae` | the signed profile owed by every signer, to the public and every group's inbox relays; heard by every member by the confederation's key | +| 7 | `6285033c` | the confederation's room names its groups; the ceremony's room, once formed, leads to the confederation and takes no messages | +| 8 | this commit | the plan end to end on nine devices, formed the real way, and the record. **No device run** | + +Full `jvmTest` 1,903, all passing (from 1,864 before Phase 1); `m3Audit`, `brandAudit` and +`walletAudit` at their budgets; `compileDebugKotlinAndroid` builds. --- @@ -652,6 +668,19 @@ a notification. B endorses. The profile is signed with no further question, publ back on all nine devices and on a non-admin member's device in each group. Then a second change that C objects to and A withdraws. +**Built.** `ConfederationProfileNetworkJvmTest` 2/2, on `ConfederationTestGroups` rather than +`ConfederationNetworkJvmTest`'s fixture: three groups of three admins, each signing by real FROST and +holding a real inbox, **form the confederation the real way** -- Agora's proposal and the two +acceptances sealed group to group, then the key ceremony on all nine devices in the NIP-17 room each +derives -- and then decide its profile. Agora's change reaches every admin of every group; Agora's +voucher alone starts nothing; Polis's endorsement makes it `ENDORSED` everywhere; one device, the first +in the order, starts the signing, and all nine finish it without being asked; every device reads the +new name and the change as `PUBLISHED`; Ekklesia's room has the proposed, endorsed and published lines +on each of its admins' devices; and a member of Polis who is no admin, holding only Polis's room, +hears the charter and the profile from a relay and gets the published line. The second case: Ekklesia +objects, Agora withdraws, and nothing is signed. Notifications are the classifier's, tested in Phase 3, +not again here. + ### Phase 9: the record, and devices This document's header and progress table, as the other confederation plans keep theirs, and a @@ -659,6 +688,12 @@ row-by-row "where the build chose differently". Then a device run: two phones an build, two real groups with inboxes, one change proposed, endorsed, signed and seen on a third client by npub. Record what did not happen. +**The record done; the device run not.** Nothing here has run on a device or a desktop client: no +change has crossed real inboxes between real groups, no confederation has signed a profile across real +phones whose nonces live only in memory, and the timing D6 rests on -- ten minutes a place, role +holders online together -- has only been exercised on a test clock. The ten minutes, the two-hour cap +and the one-minute sweep are guesses until a device run says otherwise. + --- ## What this does not do