From 2be378cc51b52dd03956f060f2ab62217e44cd79 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Mon, 23 Nov 2026 12:59:54 +0200 Subject: [PATCH] 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 --- .../giza/compose/database/dao/NostrDao.kt | 11 +- .../DatabaseConfederationRepository.kt | 5 +- .../managers/ConfederationRitualManager.kt | 188 +++++++++++++----- .../ConfederationRitualEvents.kt | 26 ++- .../managers/ConfederationCeremonyJvmTest.kt | 150 +++++++++++--- .../ConfederationDkgInboxesPremiseJvmTest.kt | 6 +- docs/confederation-dkg-inboxes.md | 2 + 7 files changed, 294 insertions(+), 94 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt index 126ca1f2..8a7e8cf4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt @@ -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, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt index 88d78ce4..fe803c69 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt @@ -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> = database.confederationCeremonyDao().observeConfederationsOf(groupPublicKey) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt index 606cd61f..2199f41d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt @@ -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? { + 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(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 } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationRitualEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationRitualEvents.kt index 695df578..642aa102 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationRitualEvents.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationRitualEvents.kt @@ -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 = 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 = setOf(HOST_KEYS, DEALINGS, AUTHORIZATIONS, ACKNOWLEDGMENTS, FAILURE, CARRIED) /** The messages each person sends once, one value per role. */ val PER_PERSON: Set = setOf(HOST_KEYS, DEALINGS, AUTHORIZATIONS, ACKNOWLEDGMENTS) + /** What a [CARRIED] envelope may hold: every message a person signs. */ + val SIGNED: Set = PER_PERSON + FAILURE + + /** [events] as an envelope's content: the same JSON array of signed events signing's envelopes carry. */ + fun encodeCarried(events: List): 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? = ConfederationSigningEvents.decodeCarried(content) + fun isRitualKind(kind: Kind): Boolean = kind in ALL const val SESSION_TAG = "confederation_ceremony" diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt index 50728497..3a2d68f0 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt @@ -86,6 +86,22 @@ class ConfederationCeremonyJvmTest { private fun joinAll(except: Set = emptySet()) = runBlocking { network.joinAll(except) } + /** The signed events an envelope carries. */ + private fun carried(payload: mobi.giza.compose.database.model.GiftWrapPayload): List = + ConfederationRitualEvents.decodeCarried(payload.content).orEmpty() + + /** [payload] carrying [events] instead. */ + private fun carrying(payload: mobi.giza.compose.database.model.GiftWrapPayload, events: List) = + payload.copy(content = ConfederationRitualEvents.encodeCarried(events)) + + /** [event] with [content], signed again by [by]: what its author could send, and no one else. */ + private fun resigned(event: Event, by: ConfederationPeople.Device, content: String): Event = + NostrSignerSync(KeyPair(by.nsec)).sign(event.createdAt, event.kind, event.tags, content) + + /** [payload] as the inbound path hands it over. */ + private fun asEvent(payload: mobi.giza.compose.database.model.GiftWrapPayload) = + Event(payload.id, payload.publicKey, payload.createdAt.epochSeconds, payload.kind, payload.tags, payload.content, "") + private fun ceremonies() = runBlocking { network.ceremonies() } /** Every role's share, opened from the recovery package its device kept. */ @@ -192,7 +208,7 @@ class ConfederationCeremonyJvmTest { } assertNull(ceremonies()[holdout], "nothing is made on a device until its owner joins") - runBlocking { ConfederationRitualManager.abandon(network.device(21).db, ceremonies().getValue(npub(21))!!.id) } + runBlocking { ConfederationRitualManager.abandon(network.device(21).db, ceremonies().getValue(npub(21))!!.id, network.device(21).nsec) } pump() ceremonies().filterKeys { it != holdout }.values.forEach { assertEquals(ConfederationCeremonyStage.FAILED, it?.stage) } @@ -233,7 +249,7 @@ class ConfederationCeremonyJvmTest { fun `an abandoned attempt is tried again as the next, with a new seed, and forms`() { setUp() joinAll() - runBlocking { ConfederationRitualManager.abandon(network.device(11).db, ceremonies().getValue(npub(11))!!.id) } + runBlocking { ConfederationRitualManager.abandon(network.device(11).db, ceremonies().getValue(npub(11))!!.id, network.device(11).nsec) } pump() val first = ceremonies().values.map { it!! } first.forEach { assertEquals(ConfederationCeremonyStage.FAILED, it.stage) } @@ -277,10 +293,12 @@ class ConfederationCeremonyJvmTest { setUp() joinAll() val liar = npub(22) + // The liar signs, for everybody else, an authorization naming a broadcast nobody computed. pump { from, _, payload -> - if (from.person != liar || payload.kind != ConfederationRitualEvents.AUTHORIZATIONS) return@pump payload - val sent = ConfederationRitualEvents.Authorizations.decode(payload.content)!! - payload.copy(content = sent.copy(broadcast = "00".repeat(32)).encode()) + val event = carried(payload).singleOrNull() + if (from.person != liar || event?.kind != ConfederationRitualEvents.AUTHORIZATIONS) return@pump payload + val sent = ConfederationRitualEvents.Authorizations.decode(event.content)!! + carrying(payload, listOf(resigned(event, from, sent.copy(broadcast = "00".repeat(32)).encode()))) } val others = ceremonies().filterKeys { it != liar }.values.map { it!! } others.forEach { assertEquals(ConfederationCeremonyStage.FAILED, it.stage) } @@ -326,13 +344,105 @@ class ConfederationCeremonyJvmTest { fun `a message from someone outside the roster is not read`() { setUp() joinAll() - val outsider = ConfederationStatementFixture.npub(99) - pump { _, to, payload -> - if (to.person == npub(12) && payload.kind == ConfederationRitualEvents.FAILURE) payload.copy(publicKey = outsider) else payload + // An outsider's own signed failure, in an envelope that names the proposal, reaches one device. + runBlocking { + val target = network.device(12) + val ceremony = ceremonies().getValue(target.person)!! + val outsider = ConfederationStatementFixture.key(99) + val failure = NostrSignerSync(KeyPair(outsider.value.toByteArray())).sign( + Clock.System.now().epochSeconds, ConfederationRitualEvents.FAILURE, + arrayOf( + ConfederationRitualEvents.sessionTag(ceremony.id), + arrayOf(ConfederationRitualEvents.PROPOSAL_TAG, network.proposalId), + arrayOf(ConfederationRitualEvents.ATTEMPT_TAG, "1"), + ), + "Ended by a stranger", + ) + val envelope = Event( + "ab".repeat(32), ConfederationStatementFixture.npub(99), failure.createdAt, ConfederationRitualEvents.CARRIED, + arrayOf(arrayOf(ConfederationRitualEvents.PROPOSAL_TAG, network.proposalId)), ConfederationRitualEvents.encodeCarried(listOf(failure)), "", + ) + ConfederationRitualManager.process(target.db, target.room, envelope, target.person, target.nsec) } + pump() ceremonies().values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) } } + // ---- docs/confederation-dkg-inboxes.md, Phase 3: every message signed -------------------------- + + @Test + fun `a message whose content was changed after it was signed is dropped, and the ceremony waits on its author`() { + setUp() + joinAll() + val target = network.device(12) + val author = network.device(21) + pump { from, to, payload -> + val event = carried(payload).singleOrNull() + if (from !== author || to !== target || event?.kind != ConfederationRitualEvents.HOST_KEYS) return@pump payload + val changed = Event(event.id, event.pubKey, event.createdAt, event.kind, event.tags, event.content.replace("\"seed\"", "\"seed\" "), event.sig) + carrying(payload, listOf(changed)) + } + runBlocking { + val ceremony = ceremonies().getValue(target.person)!! + assertEquals(ConfederationCeremonyStage.COLLECTING_HOST_KEYS, ceremony.stage, ceremony.failureReason) + assertNull(target.db.confederationCeremonyDao().getMessage(ceremony.id, author.person, ConfederationRitualEvents.HOST_KEYS), "nothing of the author's is read") + } + ceremonies().values.forEach { assertTrue(it!!.isRunning, "nobody fails it; it waits") } + } + + @Test + fun `a bare unsigned ritual rumor is dropped, and only signed events in an envelope are read`() { + setUp() + joinAll(except = setOf(npub(12))) + runBlocking { + val late = network.device(12) + network.join(late) + val from = network.device(21) + val envelope = from.db.giftWrapPayloadDao().getByChatRoomAndKinds(from.room.chatRoom.id, listOf(ConfederationRitualEvents.CARRIED)) + .first { it.publicKey == from.person && carried(it).single().kind == ConfederationRitualEvents.HOST_KEYS } + val inside = carried(envelope).single() + ConfederationRitualManager.process( + late.db, late.room, Event(inside.id, inside.pubKey, inside.createdAt, inside.kind, inside.tags, inside.content, ""), late.person, late.nsec, + ) + val ceremony = ceremonies().getValue(late.person)!! + assertNull(late.db.confederationCeremonyDao().getMessage(ceremony.id, from.person, ConfederationRitualEvents.HOST_KEYS), "a bare rumor is not read") + + ConfederationRitualManager.process(late.db, late.room, asEvent(envelope), late.person, late.nsec) + assertNotNull(late.db.confederationCeremonyDao().getMessage(ceremony.id, from.person, ConfederationRitualEvents.HOST_KEYS), "the signed one in its envelope is") + } + } + + @Test + fun `one person's two different signed dealings are named, with both events`() { + setUp() + joinAll() + val liar = network.device(22) + val target = network.device(11) + var held: mobi.giza.compose.database.model.GiftWrapPayload? = null + pump { from, to, payload -> + if (from !== liar || to !== target || carried(payload).singleOrNull()?.kind != ConfederationRitualEvents.DEALINGS) return@pump payload + held = payload + null + } + runBlocking { + val original = assertNotNull(held) + val dealing = carried(original).single() + val dealings = ConfederationRitualEvents.decodeDealings(dealing.content)!! + val other = dealings.mapValues { (_, d) -> d.copy(ciphertexts = d.ciphertexts.dropLast(1) + if (d.ciphertexts.last() == '0') "1" else "0") } + val second = resigned(dealing, liar, ConfederationRitualEvents.encodeDealings(other)) + // The honest one first: the second, a different dealing under the same signature's author, + // arrives while the ceremony runs. Altered first, the dealer's own record signature would + // fail it before anything could compare the two. + ConfederationRitualManager.process(target.db, target.room, asEvent(original), target.person, target.nsec) + ConfederationRitualManager.process(target.db, target.room, asEvent(carrying(original, listOf(second))), target.person, target.nsec) + val ceremony = ceremonies().getValue(target.person)!! + assertEquals(ConfederationCeremonyStage.FAILED, ceremony.stage) + assertEquals(liar.person, ceremony.culprit) + assertTrue(ceremony.failureReason!!.contains("sent two different dealings, both signed"), ceremony.failureReason) + assertTrue(ceremony.failureReason!!.contains(second.id.take(12)) && ceremony.failureReason!!.contains(dealing.id.take(12)), ceremony.failureReason) + } + } + // ---- docs/confederation-dkg-inboxes.md, Phase 1: today, pinned to be flipped ----------------- /** Flipped by Phase 5: a message leaves as an envelope in each seat group's room, p-tagged to nobody. */ @@ -342,8 +452,8 @@ class ConfederationCeremonyJvmTest { val first = network.device(11) runBlocking { network.join(first) } runBlocking { - val sent = first.db.giftWrapPayloadDao().getByChatRoomAndKinds(first.room.chatRoom.id, listOf(ConfederationRitualEvents.HOST_KEYS)) - val hostKeys = sent.single { it.publicKey == first.person } + val sent = first.db.giftWrapPayloadDao().getByChatRoomAndKinds(first.room.chatRoom.id, listOf(ConfederationRitualEvents.CARRIED)) + val hostKeys = sent.single { it.publicKey == first.person && carried(it).single().kind == ConfederationRitualEvents.HOST_KEYS } val tagged = hostKeys.tags.filter { it[0] == "p" }.map { it[1] }.toSet() assertEquals(devices.keys - first.person, tagged, "every other person in the roster") assertEquals(mobi.giza.compose.database.model.ChatRoom.deriveChatRoomId(devices.keys.toSet()), first.room.chatRoom.id) @@ -351,26 +461,6 @@ class ConfederationCeremonyJvmTest { } } - /** Flipped by Phase 3: a bare rumor of a ritual kind is dropped, and only signed events in an envelope are read. */ - @Test - fun `today an unsigned ritual rumor from someone in the roster is recorded`() { - setUp() - joinAll(except = setOf(npub(12))) - runBlocking { - val late = network.device(12) - network.join(late) - val from = network.device(21) - val bare = from.db.giftWrapPayloadDao().getByChatRoomAndKinds(from.room.chatRoom.id, listOf(ConfederationRitualEvents.HOST_KEYS)) - .single { it.publicKey == from.person } - assertEquals(null, mobi.giza.compose.nostr.confederation.ConfederationSigningEvents.decodeCarried(bare.content), "a bare value, not an envelope") - ConfederationRitualManager.process( - late.db, late.room, Event(bare.id, bare.publicKey, bare.createdAt.epochSeconds, bare.kind, bare.tags, bare.content, ""), late.person, late.nsec, - ) - val ceremony = ceremonies().getValue(late.person)!! - assertNotNull(late.db.confederationCeremonyDao().getMessage(ceremony.id, from.person, ConfederationRitualEvents.HOST_KEYS), "recorded with no signature") - } - } - /** Flipped by Phase 4: the bridge carries a running ceremony's messages, by its proposal. */ @Test fun `today the bridge carries nothing for a proposal that is not yet a confederation`() { diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationDkgInboxesPremiseJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationDkgInboxesPremiseJvmTest.kt index 863c576e..2511a37a 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationDkgInboxesPremiseJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationDkgInboxesPremiseJvmTest.kt @@ -49,10 +49,12 @@ class ConfederationDkgInboxesPremiseJvmTest { // ---- check 1: the ceremony envelope's kind is free ------------------------------------ @Test - fun `30379 is no kind the app or its retired wallets use`() { + fun `30379 is the ceremony's envelope and no other kind the app or its retired wallets use`() { + // Since Phase 3 it is ConfederationRitualEvents.CARRIED, and only that. + assertEquals(30379, ConfederationRitualEvents.CARRIED) val taken = ConfederationKinds.ALL + ConfederationKinds.CHANGE_KINDS + ConfederationKinds.VOUCHER + ConfederationSigningEvents.ALL + ConfederationSigningEvents.CARRIED + ConfederationSigningEvents.VOUCHER + - ConfederationRitualEvents.ALL + setOf(30380, 30383, 30386, 30388, 30389) + (ConfederationRitualEvents.ALL - ConfederationRitualEvents.CARRIED) + setOf(30380, 30383, 30386, 30388, 30389) assertTrue(30379 !in taken) assertTrue(30379 !in RetiredKinds.WALLET) } diff --git a/docs/confederation-dkg-inboxes.md b/docs/confederation-dkg-inboxes.md index d9acdc97..9005a1d1 100644 --- a/docs/confederation-dkg-inboxes.md +++ b/docs/confederation-dkg-inboxes.md @@ -258,6 +258,8 @@ unchanged, which shows the signatures cost the protocol nothing. Three new cases point of the report: `record` checks a second signed message of a kind it already holds from that person and fails out naming them (`ConfederationRitualManager.describeEquivocation`). +**Done.** As planned, but for the equivocation check, which runs in `record` itself: a second message of a step from one person, different from the first and signed by them, fails the ceremony there, naming the person and both event ids (`describeEquivocation`). It needs the honest message first. A changed dealing that arrives first is caught earlier, by the dealer's own record signature, as before. `record`, `replayStoredMessages`, `failOut`, `publishOwn`, `broadcast` and `abandon` take the key, since each may sign a 30387; `DatabaseConfederationRepository.abandonCeremony` passes the identity's. The envelope also carries the session, proposal and attempt, so `ProtocolRetention` releases a stored envelope with its ceremony as it did a bare rumor. Two existing cases had to change. "Two devices that were dealt different things" now has the liar sign the false authorization, since a changed one is dropped. "A message from someone outside the roster" now sends an outsider's own signed failure, since the old one changed only a gift wrap's author, which no longer says who wrote anything. `ConfederationCeremonyJvmTest` 21/21; full `jvmTest` 2,028, all passing; `m3Audit` at budget. + ### Phase 4: the bridge carries ceremonies, and the seat groups' rooms carry them too (report D2, D4) **The bridge's second scope** (`K/managers/ConfederationBridge.kt`):