docs: forming a confederation without its NIP-17 room, a report and a plan, and Phase 0's checks (confederation-dkg-inboxes, Phase 0)

The report finds the key ceremony needs no NIP-17 room: its rounds can travel the bridge the
confederation's signing already uses. The plan builds that in eight phases.

Phase 0's checks are kept as ConfederationDkgInboxesPremiseJvmTest: 30379 is free; one role's
dealing size is an exact formula of T, the inner thresholds and the roles; a ceremony room's id
is any NIP-17 chat among the same people; every admin holds the group's inbox key. The byte
budget comes out at 26,000, not the planned 32,000, because NIP-44 pads in steps and a wrap
crosses 64 KiB well before its plaintext limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-23 12:39:02 +02:00
1 parent 24991e1c5c
commit 6a6ce0066c
4 files changed
+1211

No files matched your search

@@ -0,0 +1,217 @@
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.crypto.EventHasher
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent
import fr.acinq.bitcoin.ByteVector32
import fr.acinq.bitcoin.PrivateKey
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.database.GENESIS_AT
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.builder.getRoomDatabase
import mobi.giza.compose.database.model.ChatRoom
import mobi.giza.compose.database.model.NostrEvent
import mobi.giza.compose.database.model.Profile
import mobi.giza.compose.extensions.toHex
import mobi.giza.compose.nostr.RetiredKinds
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.InboxSeal
import mobi.giza.compose.nostr.inbox.InboxWire
import mobi.giza.compose.nostr.inbox.InboxWrap
/**
* What docs/confederation-dkg-inboxes.md rests on, checked before anything is built on it (Phase 0,
* checks 1 to 5). Check 6 is arithmetic, recorded in the plan.
*/
class ConfederationDkgInboxesPremiseJvmTest {
private val databases = mutableListOf<GizaDatabase>()
private var groups: ConfederationTestGroups? = null
@AfterTest
fun close() {
databases.forEach { it.close() }
groups?.close()
}
// ---- check 1: the ceremony envelope's kind is free ------------------------------------
@Test
fun `30379 is no kind the app or its retired wallets use`() {
val taken = ConfederationKinds.ALL + ConfederationKinds.CHANGE_KINDS + ConfederationKinds.VOUCHER +
ConfederationSigningEvents.ALL + ConfederationSigningEvents.CARRIED + ConfederationSigningEvents.VOUCHER +
ConfederationRitualEvents.ALL + setOf(30380, 30383, 30386, 30388, 30389)
assertTrue(30379 !in taken)
assertTrue(30379 !in RetiredKinds.WALLET)
}
// ---- checks 2 and 3: how big a dealings round is, and what it fits in ------------------
/** A plan of [groupCount] groups of [admins] admins each, `T` = [threshold], each group's `t_g` = [inner]. */
private fun plan(groupCount: Int, admins: Int, threshold: Int, inner: Int): Pair<ConfederationRosterBuilder.Plan, Map<HexKey, PrivateKey>> {
val people = (0 until groupCount * admins).associate { n ->
val key = PrivateKey(ByteArray(32).also { it[0] = 0x71; it[30] = (n shr 8).toByte(); it[31] = (n + 1).toByte() })
key.publicKey().xOnly().value.toHex() to key
}
val byGroup = people.keys.chunked(admins)
val groupKeys = (1..groupCount).map { ConfederationStatementFixture.key(it) }
val npubs = groupKeys.map(ConfederationStatementFixture::npub)
val proposal = ConfederationStatementFixture.proposal(groupKeys[0], npubs, byGroup[0], threshold = threshold, innerThreshold = inner)
val acceptances = groupKeys.drop(1).mapIndexed { i, key ->
ConfederationStatementFixture.acceptance(key, proposal, byGroup[i + 1], threshold = inner).toJson()
}
val planned = ConfederationRitualManager.planFrom(ConfederationRitualEvents.Basis(proposal.toJson(), acceptances))
return (planned as fr.acinq.bitcoin.utils.Either.Right).value to people
}
/** One role's 30382 value, as `ConfederationRitualEvents.encodeDealings` writes it, in bytes. */
private fun dealingBytes(groupCount: Int, admins: Int, threshold: Int, inner: Int): Int {
val (plan, people) = plan(groupCount, admins, threshold, inner)
val hostKeys = plan.seats.associate { seat ->
seat.roleId to ConfederationRosterBuilder.hostPublicKey(people.getValue(seat.admin).value.toByteArray(), seat.group, plan.proposal.id)
}
val roster = (plan.roster(hostKeys) as fr.acinq.bitcoin.utils.Either.Right).value
val seat = plan.seats.first()
val host = ConfederationRosterBuilder.hostSecretKey(people.getValue(seat.admin).value.toByteArray(), seat.group, plan.proposal.id)
val dealing = ConfederationDkg.participantStep1(roster, seat.roleId, host, ByteVector32(ByteArray(32) { 7 }), ByteVector32(ByteArray(32) { 9 })).right!!
return ConfederationRitualEvents.encodeDealings(
mapOf(seat.group to ConfederationRitualEvents.Dealing(dealing.record.data.toHex(), dealing.ciphertexts.data.toHex()))
).length
}
private val author = PrivateKey(ByteArray(32).also { it[0] = 0x72; it[31] = 1 })
private val inboxSecret = ByteArray(32).also { it[0] = 0x73; it[31] = 1 }
private val group = ConfederationStatementFixture.npub(9)
/** A signed ritual event of [bytes] of content, as Phase 3 makes them. */
private fun signedEvent(bytes: Int, n: Int): Event =
NostrSignerSync(KeyPair(author.value.toByteArray())).sign(
1_790_000_000L + n, ConfederationRitualEvents.DEALINGS,
arrayOf(arrayOf(ConfederationRitualEvents.SESSION_TAG, "ab".repeat(32))), "{\"g\":\"" + "a".repeat(bytes - 8) + "\"}",
)
/**
* The sizes an envelope of [events] reaches as `ConfederationBridge.carryOut` would send it: the
* envelope's content, the seal's plaintext (the rumor's JSON), and the wrap's JSON. Null for a
* layer NIP-44 refused.
*/
private fun envelopeSizes(events: List<Event>): Triple<Int, Int?, Int?> {
val content = ConfederationSigningEvents.encodeCarried(events)
val pubKey = author.publicKey().xOnly().value.toHex()
val tags = arrayOf(arrayOf(ConfederationRitualEvents.PROPOSAL_TAG, "cd".repeat(32)))
val id = EventHasher.hashId(pubKey, 1_790_000_000L, 30379, tags, content)
val rumor = Event(id, pubKey, 1_790_000_000L, 30379, tags, content, "")
val rumorJson = InboxSeal.rumorJson(rumor)
val key = InboxWire.publicKeyOf(inboxSecret)
val sealed = runCatching { InboxWire.encrypt(rumorJson, InboxWire.conversationKey(author.value.toByteArray(), key)) }.getOrNull()
?: return Triple(content.length, null, null)
val seal = NostrSignerSync(KeyPair(author.value.toByteArray())).sign<SealEvent>(1_789_900_000L, InboxSeal.KIND, emptyArray(), sealed)
val wrap = runCatching { InboxWrap.wrap(seal, group, key) }.getOrNull()
return Triple(content.length, rumorJson.length, wrap?.toJson()?.length)
}
@Test
fun `an envelope of the byte budget seals and wraps under NIP-44's and a relay's limits`() {
// Measured: NIP-44 pads its plaintext to the next step -- a multiple of a power of two
// an eighth the size of the next power of two -- before each base64, so a wrap's size
// jumps rather than grows. A wrap stays under a relay's 64 KiB only while the rumor pads to
// 28,672 bytes or less (its seal then pads to 40,960). 32,000, the plan's first guess, and
// even 28,700 make wraps of 66 KB. 26,000 bytes of content leave room for the escaping
// real dealings carry.
val budget = 26_000
val events = mutableListOf<Event>()
while (ConfederationSigningEvents.encodeCarried(events + signedEvent(1_950, events.size)).length <= budget) {
events += signedEvent(1_950, events.size)
}
val (content, sealPlain, wrap) = envelopeSizes(events)
println("Envelope at the budget: content $content, seal plaintext $sealPlain, wrap $wrap bytes")
assertTrue(content in budget - 3_000..budget, "the envelope fills the budget: $content")
assertNotNull(sealPlain, "the rumor seals")
assertTrue(sealPlain <= 28_672, "the rumor pads to at most 28,672: $sealPlain")
assertNotNull(wrap, "the seal wraps")
assertTrue(wrap <= 65_536, "under a relay's 64 KiB event: $wrap")
// Past the step it does not: 28,700 bytes of content already make a wrap over 64 KiB.
val over = (0 until 12).map { signedEvent(1_950, it) }
val (overContent, _, overWrap) = envelopeSizes(over)
assertTrue(overContent > 28_000 && (overWrap == null || overWrap > 65_536), "past the step the wrap overflows: $overContent, $overWrap")
}
@Test
fun `a dealings round grows with the roles, and one person's message is bounded by their seats`() {
val small = dealingBytes(3, 3, 2, 2)
val sixty = dealingBytes(12, 5, 7, 3)
val big = dealingBytes(12, 10, 7, 6)
println("One role's 30382 value: 9 roles $small, 60 roles $sixty, 120 roles $big bytes")
assertTrue(small < sixty && sixty < big)
// A group's whole round at 120 roles is several envelopes; at 9 roles, one.
assertTrue(big * 10 > 26_000, "a group of ten's dealings at 120 roles need splitting")
assertTrue(small * 3 < 26_000)
// The value is exactly 2 * (210 + 33T + sum(4 + 33(t_g - 1)) + 32R) + 89: what Phase 5's
// eligibility computes a roster's largest message from, before anyone deals.
assertEquals(2 * (210 + 33 * 2 + 3 * (4 + 33) + 32 * 9) + 89, small)
assertEquals(2 * (210 + 33 * 7 + 12 * (4 + 66) + 32 * 60) + 89, sixty)
assertEquals(2 * (210 + 33 * 7 + 12 * (4 + 165) + 32 * 120) + 89, big)
// One person's message at one, two and three seats, as one signed event in one envelope.
val bySeats = (1..3).associateWith { seats ->
val event = NostrSignerSync(KeyPair(author.value.toByteArray())).sign<Event>(
1_790_000_000L, ConfederationRitualEvents.DEALINGS, emptyArray(), "x".repeat(big * seats),
)
envelopeSizes(listOf(event)) to event.toJson().length
}
bySeats.forEach { (seats, sizes) -> println("At 120 roles, $seats seat(s): envelope ${sizes.first}, signed event ${sizes.second} bytes") }
// Two seats at 120 roles fit one envelope and one wrap; three do not, on this path or on
// NIP-17's, which seals and wraps the same way. The line is a signed event of 26,000 bytes.
listOf(1, 2).forEach { seats ->
val (sizes, event) = bySeats.getValue(seats)
assertTrue(event <= 26_000, "$seats seat(s): a signed event of $event")
assertTrue(sizes.third != null && sizes.third!! <= 65_536, "$seats seat(s) wrap: ${sizes.third}")
assertTrue(event < 64 * 1024, "and fit an MLS message into the group's room")
}
val (three, threeEvent) = bySeats.getValue(3)
assertTrue(threeEvent > 26_000 && (three.third == null || three.third!! > 65_536), "three seats at 120 roles do not")
}
// ---- check 4: a founders' chat shares the ceremony room's id ---------------------------
@Test
fun `the ceremony's room is any NIP-17 conversation among exactly the same people`() = runBlocking {
val people = (1..4).map { PrivateKey(ByteArray(32).also { b -> b[0] = 0x74; b[31] = it.toByte() }).publicKey().xOnly().value.toHex() }
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))
}
val room = assertNotNull(db.nostrNip17Dao().createNip17ChatRoom(userPublicKey = people[0], participantPublicKeys = people.drop(1), subject = "Atlas"))
assertEquals(ChatRoom.deriveChatRoomId(people.toSet()), room.chatRoom.id, "the id is the people, not the subject or what the room is for")
}
// ---- check 5: every admin holds the group's inbox key once the inbox is set up ---------
@Test
fun `every admin of every group holds an announced inbox key`() = runBlocking {
val network = ConfederationTestGroups().also { groups = it }
network.setUp()
network.groups.forEach { g ->
g.devices.forEach { device ->
assertNotNull(
ConfederationManager.announcedInboxKey(device.db, g.roomId, device.publicKey),
"${device.publicKey.take(8)} of ${g.name} holds its inbox key",
)
}
}
}
}