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 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-23 13:45:36 +02:00
1 parent 8bf7145fa6
commit 266bee2ae0
14 files changed
+386 -471

No files matched your search

@@ -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
@@ -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
@@ -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,
/**
@@ -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<LocalChatRoom> =
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<HexKey, Int> {
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<Event>, 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<HexKey>) {
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)
)
}
}