feat: every ceremony message is signed by its author and travels in an envelope (confederation-dkg-inboxes, Phase 3)

A key ceremony message is now a signed event, never published, inside a 30379 envelope: the
ceremony's sibling of signing's 30398, a kind of its own for the ceremony's expiry floor. The
NIP-17 room still carries the envelopes. A receiver verifies each event before anything else,
drops a bare rumor of a ritual kind, and files what it reads as heard.

A person who signs two different messages for one step is named with both event ids, which
anyone holding them can check, where a NIP-17 seal could be denied. Abandoning takes the key,
since the failure it sends is signed.

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:59:54 +02:00
1 parent 58442efdd8
commit 2be378cc51
7 files changed
+294 -94

No files matched your search

@@ -1093,11 +1093,12 @@ abstract class NostrDao(
)
}
} else if (ConfederationRitualEvents.isRitualKind(decryptedGiftWrapPayload.kind)) {
// A confederation's key ceremony, in the NIP-17 room its
// coordinator opened over every admin of every group
// (docs/confederation.md, Phase 11). The room is made on
// demand from the p-tags, as for a group's own ceremony,
// and the manager is idempotent.
// 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,
@@ -77,7 +77,10 @@ class DatabaseConfederationRepository(
return (joinable as? Either.Right)?.value
}
override suspend fun abandonCeremony(sessionId: String) = ConfederationRitualManager.abandon(database, sessionId)
override suspend fun abandonCeremony(sessionId: String) {
val secret = activeIdentity.value?.nostrPrivateKey ?: throw IllegalStateException("This identity cannot take part")
ConfederationRitualManager.abandon(database, sessionId, secret.value.toByteArray())
}
override fun observeConfederationsOf(groupPublicKey: HexKey): Flow<List<Confederation>> =
database.confederationCeremonyDao().observeConfederationsOf(groupPublicKey)
@@ -7,6 +7,9 @@ import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.Kind
import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import com.vitorpamplona.quartz.nip01Core.crypto.verify
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
import fr.acinq.bitcoin.ByteVector
import fr.acinq.bitcoin.ByteVector32
import fr.acinq.bitcoin.ByteVector64
@@ -219,7 +222,7 @@ object ConfederationRitualManager {
database, ceremony, ChatMessage.TYPE_CONFEDERATION_CEREMONY_STARTED,
if (attempt == 1) "The confederation's key ceremony started" else "The confederation's key ceremony started again, as attempt $attempt",
)
replayStoredMessages(database, ceremony)
replayStoredMessages(database, ceremony, nostrPrivateKey)
database.confederationCeremonyDao().getCeremony(ceremony.id)?.takeIf { it.isRunning }?.let {
advance(database, room, it.id, nostrPrivateKey)
}
@@ -244,11 +247,11 @@ object ConfederationRitualManager {
)
}
/** Ends a running ceremony for everybody, as any participant may. */
suspend fun abandon(database: GizaDatabase, sessionId: String) {
/** 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)
failOut(database, room, ceremony, ABANDONED, culprit = null, nostrPrivateKey)
}
/** Moves every running ceremony [userPublicKey] is in as far as its stored messages allow. */
@@ -265,9 +268,12 @@ object ConfederationRitualManager {
// ---- inbound ---------------------------------------------------------------------------
/**
* Feeds one inbound ceremony message in and moves the ceremony as far as it will go. Safe to
* call twice with the same message. A message for a ceremony this device has not joined is
* left where the inbound path stored it, and replayed when its owner joins.
* 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,
@@ -276,16 +282,46 @@ object ConfederationRitualManager {
userPublicKey: HexKey,
nostrPrivateKey: ByteArray,
) {
val sessionId = ConfederationRitualEvents.parseSessionId(innerEvent.tags) ?: run {
logger.w("Ceremony message ${innerEvent.id.take(8)} names no session; dropping")
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
}
hear(database, sessionId, innerEvent)
val ceremony = database.confederationCeremonyDao().getCeremony(sessionId)?.takeIf { it.userPublicKey == userPublicKey }
?: return
if (!ceremony.isRunning) return
if (!record(database, localChatRoom, ceremony, innerEvent)) return
advance(database, localChatRoom, ceremony.id, nostrPrivateKey)
val events = verifiedEvents(innerEvent) ?: return
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)
}
}
/**
* The events [envelope] carries that this device will read: each signed by its author, of a kind a
* person signs, naming a session, and about the proposal the envelope names. Null when the envelope
* names no proposal or carries nothing readable.
*/
private fun verifiedEvents(envelope: Event): List<Event>? {
val proposalId = ConfederationRitualEvents.parseProposalId(envelope.tags) ?: run {
logger.w("Envelope ${envelope.id.take(8)} names no proposal; dropping")
return null
}
val carried = ConfederationRitualEvents.decodeCarried(envelope.content) ?: run {
logger.w("Envelope ${envelope.id.take(8)} carries nothing readable; dropping")
return null
}
return carried.filter { event ->
when {
!event.verify() -> false.also { logger.w("A carried ceremony message ${event.id.take(8)} does not verify as ${event.pubKey.take(8)}'s; dropping") }
event.kind !in ConfederationRitualEvents.SIGNED -> false
ConfederationRitualEvents.parseProposalId(event.tags) != proposalId -> false.also {
logger.w("Ceremony message ${event.id.take(8)} is about another proposal than its envelope; dropping")
}
else -> true
}
}
}
/**
@@ -305,7 +341,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): Boolean {
private suspend fun record(database: GizaDatabase, room: LocalChatRoom, ceremony: ConfederationCeremony, innerEvent: Event, nostrPrivateKey: ByteArray): Boolean {
val plan = planOf(ceremony) ?: return true
val sender = innerEvent.pubKey
@@ -326,7 +362,7 @@ object ConfederationRitualManager {
failOut(
database, room, ceremony,
"${ConfederationManager.nameOf(database, sender)} holds a different statement from ${named.joinToString()} than this device does",
culprit = null,
culprit = null, nostrPrivateKey,
)
return false
}
@@ -340,6 +376,13 @@ object ConfederationRitualManager {
logger.w("Ceremony ${ceremony.id}: kind ${innerEvent.kind} from ${sender.take(8)} is not one value per role; ignoring")
return true
}
// One message per person per step, and a person's message is the same bytes each time
// 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)
return false
}
database.confederationCeremonyDao().insertMessage(
ConfederationCeremonyMessage(ceremony.id, sender, innerEvent.kind, innerEvent.content)
)
@@ -380,6 +423,7 @@ object ConfederationRitualManager {
attestation = ceremony.attestationRef!!,
statements = plan.acceptanceIds,
).encode(),
nostrPrivateKey,
)
}
val hostMessages = plan.people.associateWith { person ->
@@ -389,7 +433,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)
is Either.Left -> return failOut(database, localChatRoom, 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.
@@ -398,13 +442,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)
?: return failOut(database, localChatRoom, 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) }
.rightOrFail { return failOut(database, localChatRoom, 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))
publishOwn(database, localChatRoom, ceremony, plan, ConfederationRitualEvents.DEALINGS, ConfederationRitualEvents.encodeDealings(dealings), nostrPrivateKey)
}
if (ceremony.dealerSeeds != null) ceremony = update(database, ceremony) { it.copy(dealerSeeds = null) }
@@ -412,8 +456,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) }
combined.fault?.let { return failOut(database, localChatRoom, ceremony, describe(database, plan, it), culpritOf(plan, it)) }
.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) }
val broadcast = ConfederationBroadcast(ByteVector(combined.broadcast!!.toByteArray()))
val broadcastHash = Crypto.sha256(broadcast.toByteArray()).toHex()
val ownDealings = ConfederationRitualEvents.decodeDealings(own(database, ceremony, ConfederationRitualEvents.DEALINGS)!!.payload)!!
@@ -425,8 +469,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) }
step.fault?.let { return failOut(database, localChatRoom, ceremony, describe(database, plan, it), culpritOf(plan, it)) }
.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) }
keyState = step.keyState
transitionHash = step.transitionHash
seat.group to step.authorization!!.toHex()
@@ -441,6 +485,7 @@ object ConfederationRitualManager {
publishOwn(
database, localChatRoom, ceremony, plan, ConfederationRitualEvents.AUTHORIZATIONS,
ConfederationRitualEvents.Authorizations(authorizations, broadcastHash).encode(),
nostrPrivateKey,
)
}
val authorizationMessages = plan.people.associateWith { person ->
@@ -451,41 +496,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)
return failOut(database, localChatRoom, 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) }
.rightOrFail { return failOut(database, localChatRoom, 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) }
.rightOrFail { return failOut(database, localChatRoom, 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) }
step.fault?.let { return failOut(database, localChatRoom, ceremony, describe(database, plan, it), culpritOf(plan, it)) }
.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) }
seat.group to step.acknowledgment!!.toHex()
}
publishOwn(database, localChatRoom, ceremony, plan, ConfederationRitualEvents.ACKNOWLEDGMENTS, ConfederationRitualEvents.encodeByGroup(acknowledgments))
publishOwn(database, localChatRoom, 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) }
.rightOrFail { return failOut(database, localChatRoom, 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) }
step.fault?.let { return failOut(database, localChatRoom, ceremony, describe(database, plan, it), culpritOf(plan, it)) }
.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) }
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) }
.rightOrFail { return failOut(database, localChatRoom, ceremony, "The genesis does not verify: $it", null, nostrPrivateKey) }
// 7. Each role's share, kept as its recovery package.
if (ceremony.recoveryPackages == null) {
@@ -493,7 +538,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) }
).rightOrFail { return failOut(database, localChatRoom, ceremony, "Finalizing this device's share failed: $it", null, nostrPrivateKey) }
seat.group to result.recovery.data.toHex()
}
ceremony = update(database, ceremony) {
@@ -546,6 +591,24 @@ object ConfederationRitualManager {
}
}
/**
* Two different messages of one step from one person, both signed by them: said as who, which
* step, and the two event ids, which anyone holding them can check (docs/confederation-dkg-inboxes.md,
* Phase 3). A NIP-17 seal could be denied; a signed event cannot.
*/
private suspend fun describeEquivocation(database: GizaDatabase, ceremony: ConfederationCeremony, sender: HexKey, second: Event): String {
val first = database.confederationCeremonyDao().getCeremonyHeardForSession(ceremony.id)
.firstOrNull { it.pubKey == sender && it.kind == second.kind && it.id != second.id }?.id
val step = when (second.kind) {
ConfederationRitualEvents.HOST_KEYS -> "host keys"
ConfederationRitualEvents.DEALINGS -> "dealings"
ConfederationRitualEvents.AUTHORIZATIONS -> "authorizations"
else -> "acknowledgments"
}
val ids = listOfNotNull(first, second.id).joinToString(" and ") { it.take(12) }
return "${ConfederationManager.nameOf(database, sender)} sent two different $step, both signed ($ids)"
}
private fun culpritOf(plan: Plan, fault: ConfederationFault): HexKey? = fault.role?.let { plan.seatOf(it)?.admin }
/**
@@ -587,8 +650,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?) {
broadcast(database, localChatRoom, ceremony, planOf(ceremony), ConfederationRitualEvents.FAILURE, reason)
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)
fail(database, ceremony, reason, culprit)
}
@@ -600,12 +663,18 @@ 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) {
broadcast(database, localChatRoom, ceremony, plan, kind, content)
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)
database.confederationCeremonyDao().insertMessage(ConfederationCeremonyMessage(ceremony.id, ceremony.userPublicKey, kind, content))
}
/** Queues a rumor for the room's gift wraps, p-tagged to every other person in the roster. */
/**
* 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.
*/
private suspend fun broadcast(
database: GizaDatabase,
localChatRoom: LocalChatRoom,
@@ -613,27 +682,34 @@ object ConfederationRitualManager {
plan: Plan?,
kind: Kind,
content: String,
nostrPrivateKey: ByteArray,
) {
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() + arrayOf(
val ceremonyTags = arrayOf(
ConfederationRitualEvents.sessionTag(ceremony.id),
arrayOf(ConfederationRitualEvents.PROPOSAL_TAG, ceremony.proposalId),
arrayOf(ConfederationRitualEvents.ATTEMPT_TAG, ceremony.attempt.toString()),
)
val signed = NostrSignerSync(KeyPair(nostrPrivateKey)).sign<Event>(Clock.System.now().epochSeconds, kind, ceremonyTags, content)
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, kind, createdAt, baseTags)
val id = EventHasher.hashId(pubKey = ceremony.userPublicKey, createdAt = createdAt, kind = kind, tags = tags, content = content)
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 = kind,
kind = ConfederationRitualEvents.CARRIED,
tags = tags,
content = content,
content = envelope,
createdAt = Instant.fromEpochSeconds(createdAt),
)
)
@@ -641,23 +717,25 @@ 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 gift wraps the inbound path stored before
* there was anywhere to hear them.
* (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.
*/
private suspend fun replayStoredMessages(database: GizaDatabase, ceremony: ConfederationCeremony) {
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)
.mapNotNull { Event.fromJsonOrNull(it.eventJson) }
val wrapped = database.giftWrapPayloadDao()
.getByKinds(ConfederationRitualEvents.ALL.toList())
.getByKinds(listOf(ConfederationRitualEvents.CARRIED))
.filter { ConfederationRitualEvents.parseSessionId(it.tags) == ceremony.id }
.map { Event(it.id, it.publicKey, it.createdAt.epochSeconds, it.kind, it.tags, it.content, "") }
.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 }
.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)) return
if (!record(database, room, database.confederationCeremonyDao().getCeremony(ceremony.id) ?: return, event, nostrPrivateKey)) return
}
}
@@ -37,6 +37,13 @@ import kotlinx.serialization.json.put
* Every message names the ceremony (its id, derived from the statements and the attempt), the
* proposal and the attempt, so a device that does not hold every statement yet keeps it until it
* does.
*
* **Every message is a signed event, carried** (docs/confederation-dkg-inboxes.md, Phase 3), as the
* confederation's signing messages are: signed by its author's own nostr key, never published, and
* sent inside a [CARRIED] envelope whose content is a JSON array of such events. Whoever carries an
* envelope cannot change what is in it, and a receiver checks each event's signature before it
* reads anything. The signature is what binds a person's host keys to them, where a NIP-17 seal
* used to.
*/
object ConfederationRitualEvents {
const val HOST_KEYS: Kind = 30381
@@ -45,11 +52,28 @@ object ConfederationRitualEvents {
const val ACKNOWLEDGMENTS: Kind = 30385
const val FAILURE: Kind = 30387
val ALL: Set<Kind> = setOf(HOST_KEYS, DEALINGS, AUTHORIZATIONS, ACKNOWLEDGMENTS, FAILURE)
/**
* Signed ceremony messages, carried (docs/confederation-dkg-inboxes.md): the one kind of the
* ceremony that travels. The ceremony's sibling of `ConfederationSigningEvents.CARRIED` (30398),
* a kind of its own because the two expire on different floors and `DisappearingMessages.classOf`
* is a function of the kind: a ceremony waits for every admin, signing for a day.
*/
const val CARRIED: Kind = 30379
val ALL: Set<Kind> = setOf(HOST_KEYS, DEALINGS, AUTHORIZATIONS, ACKNOWLEDGMENTS, FAILURE, CARRIED)
/** The messages each person sends once, one value per role. */
val PER_PERSON: Set<Kind> = setOf(HOST_KEYS, DEALINGS, AUTHORIZATIONS, ACKNOWLEDGMENTS)
/** What a [CARRIED] envelope may hold: every message a person signs. */
val SIGNED: Set<Kind> = PER_PERSON + FAILURE
/** [events] as an envelope's content: the same JSON array of signed events signing's envelopes carry. */
fun encodeCarried(events: List<com.vitorpamplona.quartz.nip01Core.core.Event>): String = ConfederationSigningEvents.encodeCarried(events)
/** The events an envelope carries, unverified; null when it is not an array of events or carries too many. */
fun decodeCarried(content: String): List<com.vitorpamplona.quartz.nip01Core.core.Event>? = ConfederationSigningEvents.decodeCarried(content)
fun isRitualKind(kind: Kind): Boolean = kind in ALL
const val SESSION_TAG = "confederation_ceremony"