test: the premises of a confederation with no coordinator (confederation-without-coordinator, Phase 0)

The broadcast is the same on every device, the ceremony's room id is the set
of its people, and one group's inbox seal opens in another's. A statement's
size grows with the square of the groups: 12 fit, 16 do not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-22 13:23:43 +02:00
1 parent f78bd16b68
commit b2f22f2cd4
2 files changed
+183

No files matched your search

@@ -0,0 +1,172 @@
package mobi.giza.compose.managers
import androidx.room3.Room
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
import com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto
import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate
import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler
import fr.acinq.bitcoin.ByteVector
import fr.acinq.bitcoin.PrivateKey
import fr.acinq.bitcoin.crypto.confederation.ConfederationBroadcast
import fr.acinq.bitcoin.crypto.confederation.ConfederationDkg
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlinx.coroutines.runBlocking
import mobi.giza.compose.ConfederationFixture
import mobi.giza.compose.database.GENESIS_AT
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.builder.getRoomDatabase
import mobi.giza.compose.database.model.NostrEvent
import mobi.giza.compose.database.model.Profile
import mobi.giza.compose.extensions.toHex
import mobi.giza.compose.nostr.confederation.ConfederationKinds
import mobi.giza.compose.nostr.frost.FrostSigningEvents
import mobi.giza.compose.nostr.inbox.InboxAnnouncement
import mobi.giza.compose.nostr.inbox.InboxReplyManifest
import mobi.giza.compose.nostr.inbox.InboxSeal
import mobi.giza.compose.nostr.inbox.InboxWire
import mobi.giza.compose.nostr.inbox.InboxWrap
/**
* What docs/confederation-without-coordinator.md rests on, checked before anything is built on it
* (Phase 0, checks 2 to 5). Check 1 is a question upstream, and check 6 is a reading of the
* welcome path; both are recorded in the plan.
*/
class ConfederationWithoutCoordinatorPremiseJvmTest {
private val roster = ConfederationFixture.roster
private val hostSecrets = ConfederationFixture.hostSecrets
private fun seed(tag: Int, i: Int) = ConfederationFixture.seed(tag, i)
private val databases = mutableListOf<GizaDatabase>()
private var harness: GroupInboxHarness? = null
@AfterTest
fun close() {
databases.forEach { it.close() }
harness?.close()
}
// ---- check 2: the broadcast needs no coordinator --------------------------------------
@Test
fun `every device computes the same broadcast from the same dealings, in any order`() {
val sessionSeed = seed(0x5f, 1)
val dealings = roster.roleIds.withIndex().associate { (i, role) ->
role to ConfederationDkg.participantStep1(roster, role, hostSecrets.getValue(role), seed(0xd2, i), sessionSeed).right!!
}
val here = ConfederationDkg.coordinatorStep1(roster, sessionSeed, dealings).right!!.broadcast!!
val there = ConfederationDkg.coordinatorStep1(roster, sessionSeed, dealings.entries.reversed().associate { it.toPair() }).right!!.broadcast!!
assertEquals(here.data, there.data, "the broadcast is a function of the dealings, not of who computes it")
// Each role goes on with the broadcast it computed itself, and they all agree on the key.
val keys = roster.roleIds.map { role ->
val own = ConfederationDkg.coordinatorStep1(roster, sessionSeed, dealings).right!!.broadcast!!
ConfederationDkg.participantStep2(
roster, role, hostSecrets.getValue(role), sessionSeed, dealings.getValue(role).record,
ConfederationBroadcast(ByteVector(own.toByteArray())),
).right!!.keyState!!.publicKey
}.toSet()
assertEquals(1, keys.size)
}
// ---- check 3: the ceremony's room is the same whoever makes it ------------------------
@Test
fun `two people making the ceremony's room get the same room`() = runBlocking {
val people = (1..4).map { PrivateKey(ByteArray(32).also { b -> b[0] = 0x31; b[31] = it.toByte() }).publicKey().xOnly().value.toHex() }
val ids = people.take(2).map { me ->
val db = getRoomDatabase(Room.inMemoryDatabaseBuilder<GizaDatabase>()).also { databases += it }
people.forEach { key ->
val eventId = "f$key".take(64)
db.nostrEventDao().insert(NostrEvent(id = eventId, pubKey = key, kind = 0, tags = emptyArray(), content = "{}", sig = "", createdAt = GENESIS_AT))
db.profileDao().insertPlaceholderProfile(Profile(displayName = "…", publicKey = key, createdAt = GENESIS_AT, nostrEventId = eventId))
}
assertNotNull(db.nostrNip17Dao().createNip17ChatRoom(userPublicKey = me, participantPublicKeys = people - me)).chatRoom.id
}
assertEquals(1, ids.toSet().size, "the room's id is the set of its people")
}
// ---- check 4: how big a statement to N groups is ------------------------------------------
/** The bytes a FROST proposal for one statement to [groups] groups carries: the seals, the manifest and the rumor. */
private fun statementBytes(groups: Int, admins: Int): Int {
fun key(n: Int, tag: Int) = ByteArray(32).also { it[0] = tag.toByte(); it[30] = (n shr 8).toByte(); it[31] = n.toByte() }
val npubs = (0 until groups).map { InboxWire.publicKeyOf(key(it, 0x51)) }
val inboxSecret = key(0, 0x52)
val adminList = (0 until admins).joinToString(",", "[", "]") { "\"${InboxWire.publicKeyOf(key(it, 0x53))}\"" }
val content = "{\"v\":2,\"group\":\"${npubs[0]}\",\"threshold\":2,\"admins\":$adminList}"
val tags = npubs.drop(1).map { arrayOf("p", it) } + listOf(
arrayOf("threshold", "2"), arrayOf("name", "Atlas"), arrayOf("nonce", "cd".repeat(32)), arrayOf("expiration", "1790604800"),
)
val rumor = RumorAssembler.assembleRumor<Event>(npubs[0], EventTemplate(1_790_000_000, ConfederationKinds.PROPOSAL, tags.toTypedArray(), content))
val recipients = npubs.mapIndexed { i, npub ->
val announced = if (i == 0) InboxWire.publicKeyOf(inboxSecret) else InboxWire.publicKeyOf(key(i, 0x54))
val announcement = if (i == 0) null else signed(key(i, 0x51), InboxAnnouncement.keyTemplate(announced, 1_789_000_000))
Triple(npub, announced, announcement)
}
val seals = recipients.map { (npub, announced, _) ->
val t = InboxSeal.template(rumor, inboxSecret, announced, 1_789_900_000)
val id = EventHasher.hashId(npubs[0], t.createdAt, t.kind, t.tags, t.content)
Event(id, npubs[0], t.createdAt, t.kind, t.tags, t.content, "")
}
val manifest = InboxReplyManifest(0, recipients.map { (npub, key, announcement) -> InboxReplyManifest.Entry(npub, key, announcement?.toJson()) }, 0)
return FrostSigningEvents.encodeProposal(seals).length + manifest.seal(inboxSecret).length + InboxSeal.rumorJson(rumor).length
}
private fun signed(secret: ByteArray, template: EventTemplate<Event>): Event {
val pubKey = InboxWire.publicKeyOf(secret)
val id = EventHasher.hashId(pubKey, template.createdAt, template.kind, template.tags, template.content)
return Event(id, pubKey, template.createdAt, template.kind, template.tags, template.content, Nip01Crypto.sign(id.hexToByteArray(), secret).toHex())
}
@Test
fun `a statement's size grows with the square of the groups, so the picker has to stop well short of 64`() {
val sizes = listOf(2, 4, 8, 12, 16, 24, 32, 64).associateWith { statementBytes(it, admins = 5) }
println("Statement proposal bytes by groups, five admins each: $sizes")
// The budget a statement is held to (ConfederationKinds.MAX_STATEMENT_BYTES once built):
// about a relay's usual 64 KiB event, less the MLS framing around it.
val budget = 60_000
val fits = sizes.filterValues { it <= budget }.keys.max()
assertTrue(fits in 8..24, "between 8 and 24 groups fit; measured $sizes")
assertTrue(sizes.getValue(64) > budget, "64 groups do not")
// An admin list of 128 grows each seal by about eight kilobytes.
assertTrue(statementBytes(4, admins = 128) > statementBytes(4, admins = 5) + 4 * 8_000)
}
// ---- check 5: one group writing to another, as the inbox has it today ------------------
@Test
fun `a seal from one group's inbox key to another's is filed today as an inbox message`() = runBlocking<Unit> {
val b = GroupInboxHarness().also { harness = it }
val devices = listOf("alice", "bob", "carol").map { b.device(it) }
val alice = devices[0]
InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret)
b.pump()
val announcement = alice.db.frostSigningSessionDao().getSessionsForChatRoom(b.roomId).single()
FrostSigningManager.approve(devices[1].db, devices[1].room(), announcement.id)
b.pump()
val bInbox = alice.keys().single().publicKey
// Group A: a key standing in for its quorum, and the inbox key its admins hold.
val aSigner = ByteArray(32).also { it[0] = 0x61; it[31] = 1 }
val aGroup: HexKey = InboxWire.publicKeyOf(aSigner)
val aInbox = ByteArray(32).also { it[0] = 0x62; it[31] = 1 }
val now = kotlin.time.Clock.System.now().epochSeconds
val rumor = RumorAssembler.assembleRumor<Event>(
aGroup,
EventTemplate(now, ConfederationKinds.PROPOSAL, arrayOf(arrayOf("p", b.roomId)), "{\"v\":2}"),
)
val seal = signed(aSigner, InboxSeal.template(rumor, aInbox, bInbox, now - 60))
val wrap = InboxWrap.wrap(seal, b.roomId, bInbox)
val filed = assertNotNull(GroupInboxManager.receive(alice.db, wrap, alice.publicKey), "B's admin opens A's seal with the n tag")
assertEquals(aGroup, filed.senderPublicKey, "and the seal is A's")
assertEquals(ConfederationKinds.PROPOSAL, filed.kind, "filed as an inbox message of a kind the inbox cannot show (Phase 5 flips this)")
}
}