feat: the confederation's key ceremony, one person per device (confederation, Phase 11)

The coordinator opens a NIP-17 room over every admin of every group and
discloses the key that opens each acceptance. Each device rebuilds the
roster from what the groups signed and checks its own groups' admins
before it will join; joining is the only thing a member is asked, and
every DKG step after it runs from stored inputs over ConfederationDkg.
Each device derives the key state and assembles the certified genesis
itself, and keeps its share as a recovery package.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-22 00:35:38 +02:00
1 parent e1a18f83c5
commit 02f041431a
25 files changed
+7647 -13

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -722,5 +722,20 @@
<string name="this_device_does_not_hold_that_proposal">This device does not hold that proposal</string>
<string name="could_not_ask_the_group_to_answer">Couldn't ask the group to answer</string>
<string name="every_group_accepted_admins_across_groups">Every group accepted. %1$d admins across %2$d groups would hold the confederation's key.</string>
<string name="the_key_ceremony_is_not_available_yet">The confederation's key ceremony is not available in this version yet</string>
<string name="open_the_key_ceremony">Open the key ceremony</string>
<string name="could_not_open_the_key_ceremony">Couldn't open the key ceremony</string>
<string name="join_the_key_ceremony">Join the key ceremony</string>
<string name="joining_gives_you_a_share">Joining gives you a share of the confederation's key for each group you are an admin of. Everything after joining runs by itself.</string>
<string name="abandon_the_key_ceremony">Abandon the key ceremony</string>
<string name="this_device_holds_no_key_ceremony">This device holds no key ceremony for this proposal</string>
<string name="ceremony_step_host_keys">Host keys</string>
<string name="ceremony_step_contributions">Contributions</string>
<string name="ceremony_step_combined">Contributions combined by the coordinator</string>
<string name="ceremony_step_authorizations">Authorizations</string>
<string name="ceremony_step_shares_stored">Shares stored</string>
<string name="ceremony_waiting_on">Waiting on %1$s</string>
<string name="ceremony_step_done">Done</string>
<string name="the_confederations_key_is_made">The confederation's key is made</string>
<string name="the_ceremony_ended">The ceremony ended: %1$s</string>
<string name="group_signs_with">%1$s: %2$d of %3$d admins to sign</string>
</resources>
@@ -9,6 +9,7 @@ import androidx.room3.immediateTransaction
import androidx.room3.useWriterConnection
import mobi.giza.compose.database.converters.GizaConverters
import mobi.giza.compose.database.dao.BroadcastNostrEventReceiptDao
import mobi.giza.compose.database.dao.ConfederationCeremonyDao
import mobi.giza.compose.database.dao.ConfederationDao
import mobi.giza.compose.database.dao.BroadcastNostrEventRequestDao
import mobi.giza.compose.database.dao.ChatMessageBroadcastNostrEventReceiptRelationDao
@@ -65,6 +66,8 @@ import mobi.giza.compose.database.model.ChatMessageBroadcastNostrEventReceiptRel
import mobi.giza.compose.database.model.ChatMessageBroadcastNostrEventRequestRelation
import mobi.giza.compose.database.model.ChatMessageNostrEventRelation
import mobi.giza.compose.database.model.ChatRoom
import mobi.giza.compose.database.model.ConfederationCeremony
import mobi.giza.compose.database.model.ConfederationCeremonyMessage
import mobi.giza.compose.database.model.ConfederationEvent
import mobi.giza.compose.database.model.ConfederationInvitee
import mobi.giza.compose.database.model.ConfederationSigning
@@ -130,6 +133,8 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
ChatMessageBroadcastNostrEventReceiptRelation::class,
ChatMessageNostrEventRelation::class,
ChatRoom::class,
ConfederationCeremony::class,
ConfederationCeremonyMessage::class,
ConfederationEvent::class,
ConfederationInvitee::class,
ConfederationSigning::class,
@@ -180,7 +185,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
UnsignedNostrEvent::class,
Zap::class
],
version = 43,
version = 44,
autoMigrations = [
// v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can
// generate the migration itself — nothing existing changes shape.
@@ -448,6 +453,10 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
// v43 adds the confederation (docs/confederation.md, Phase 4): ConfederationEvent,
// ConfederationInvitee and ConfederationSigning. Three new tables, so Room generates it.
AutoMigration(from = 42, to = 43),
// v44 adds the confederation's key ceremony (docs/confederation.md, Phase 11):
// ConfederationCeremony and ConfederationCeremonyMessage. Two new tables, so Room
// generates it.
AutoMigration(from = 43, to = 44),
]
)
@ConstructedBy(GizaDatabaseConstructor::class)
@@ -476,6 +485,8 @@ abstract class GizaDatabase: RoomDatabase() {
abstract fun confederationDao(): ConfederationDao
abstract fun confederationCeremonyDao(): ConfederationCeremonyDao
abstract fun dkgSessionDao(): DkgSessionDao
abstract fun frostSigningSessionDao(): FrostSigningSessionDao
@@ -0,0 +1,47 @@
package mobi.giza.compose.database.dao
import androidx.room3.Dao
import androidx.room3.Insert
import androidx.room3.OnConflictStrategy
import androidx.room3.Query
import androidx.room3.Upsert
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.Kind
import kotlinx.coroutines.flow.Flow
import mobi.giza.compose.database.model.ConfederationCeremony
import mobi.giza.compose.database.model.ConfederationCeremonyMessage
@Dao
interface ConfederationCeremonyDao {
@Query("SELECT * FROM ConfederationCeremony WHERE id = :id")
suspend fun getCeremony(id: String): ConfederationCeremony?
@Query("SELECT * FROM ConfederationCeremony WHERE id = :id")
fun observeCeremony(id: String): Flow<ConfederationCeremony?>
/** The newest ceremony for a proposal on this device: one per proposal is what runs. */
@Query("SELECT * FROM ConfederationCeremony WHERE proposalId = :proposalId ORDER BY createdAt DESC LIMIT 1")
suspend fun getLatestForProposal(proposalId: HexKey): ConfederationCeremony?
@Query("SELECT * FROM ConfederationCeremony WHERE proposalId = :proposalId ORDER BY createdAt DESC LIMIT 1")
fun observeLatestForProposal(proposalId: HexKey): Flow<ConfederationCeremony?>
@Query("SELECT * FROM ConfederationCeremony WHERE userPublicKey = :userPublicKey AND stage NOT IN ('COMPLETE', 'FAILED')")
suspend fun getRunning(userPublicKey: HexKey): List<ConfederationCeremony>
@Upsert
suspend fun upsert(ceremony: ConfederationCeremony)
@Query("SELECT * FROM ConfederationCeremonyMessage WHERE sessionId = :sessionId")
suspend fun getMessages(sessionId: String): List<ConfederationCeremonyMessage>
@Query("SELECT * FROM ConfederationCeremonyMessage WHERE sessionId = :sessionId")
fun observeMessages(sessionId: String): Flow<List<ConfederationCeremonyMessage>>
@Query("SELECT * FROM ConfederationCeremonyMessage WHERE sessionId = :sessionId AND senderPublicKey = :sender AND kind = :kind")
suspend fun getMessage(sessionId: String, sender: HexKey, kind: Kind): ConfederationCeremonyMessage?
/** Once per sender and kind: a person's message for a step is the same bytes every time it is sent. */
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertMessage(message: ConfederationCeremonyMessage): Long
}
@@ -86,6 +86,9 @@ import mobi.giza.compose.nostr.MarmotProfile
import mobi.giza.compose.extensions.exporterSecret
import mobi.giza.compose.nostr.Relays
import mobi.giza.compose.nostr.dkg.DkgRitualEvents
import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents
import mobi.giza.compose.managers.ConfederationRitualManager
import mobi.giza.compose.ExperimentalFeatures
import mobi.giza.compose.nostr.frost.ShareRefreshEvents
import mobi.giza.compose.nostr.frost.ShareRepairEvents
import mobi.giza.compose.nostr.frost.FrostSigningEvents
@@ -1038,6 +1041,37 @@ abstract class NostrDao(
nostrPrivateKey = activeKeyPair.privKey!!
)
}
} 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.
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!!
)
}
}
} 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
@@ -536,11 +536,19 @@ data class ChatMessage(
const val TYPE_CONFEDERATION_REJECTED = "confederationRejected"
const val TYPE_CONFEDERATION_WITHDRAWN = "confederationWithdrawn"
/** The confederation's key ceremony, in its NIP-17 room (docs/confederation.md, Phase 11). */
const val TYPE_CONFEDERATION_CEREMONY_STARTED = "confederationCeremonyStarted"
const val TYPE_CONFEDERATION_CEREMONY_COMPLETE = "confederationCeremonyComplete"
const val TYPE_CONFEDERATION_CEREMONY_FAILED = "confederationCeremonyFailed"
val CONFEDERATION_TYPES = setOf(
TYPE_CONFEDERATION_PROPOSED,
TYPE_CONFEDERATION_ACCEPTED,
TYPE_CONFEDERATION_REJECTED,
TYPE_CONFEDERATION_WITHDRAWN,
TYPE_CONFEDERATION_CEREMONY_STARTED,
TYPE_CONFEDERATION_CEREMONY_COMPLETE,
TYPE_CONFEDERATION_CEREMONY_FAILED,
)
val GROUP_IDENTITY_TYPES = setOf(
@@ -0,0 +1,89 @@
package mobi.giza.compose.database.model
import androidx.room3.Entity
import androidx.room3.ForeignKey
import androidx.room3.Index
import androidx.room3.PrimaryKey
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.Kind
import kotlin.time.Clock
import kotlin.time.Instant
/**
* One device's part in a confederation's key ceremony (docs/confederation.md, Phase 11).
*
* Inputs, never protocol state, as `DkgSession` keeps them: every step of the DKG is a pure
* function of what is stored here and in [ConfederationCeremonyMessage], so a device that dies
* between rounds recomputes the step on the next message. The stage is a label for screens; what
* runs next is decided by which messages exist.
*
* What upstream's storage contract (docs/confederation-upstream.md) says to keep, and when to let
* 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")],
)
data class ConfederationCeremony(
@PrimaryKey
val id: String,
/** The NIP-17 room the ceremony runs in, over every admin of every group. */
val chatRoomId: String,
val proposalId: HexKey,
val coordinatorPublicKey: HexKey,
val userPublicKey: HexKey,
/** The coordinator's 30380, as sent: the roster's plan is rebuilt from it on every step. */
val openingJson: String,
val stage: ConfederationCeremonyStage = ConfederationCeremonyStage.WAITING_TO_JOIN,
/** When this device's owner joined: the only thing they are asked. */
val approvedAt: Instant? = null,
/** Per role, by group: fresh, single use, erased once the dealings are stored. */
val dealerSeeds: String? = null,
/** Per role, by group: the randomness each recovery package is issued with. */
val recoveryNonces: String? = null,
/** This device's own derivation of the key state, kept before it acknowledges. */
val keyState: String? = null,
val transitionHash: HexKey? = null,
/** The certified genesis transition, assembled here from everybody's evidence. */
val genesis: String? = null,
/** Per role, by group: the 269-byte recovery package the share is kept as. */
val recoveryPackages: String? = null,
/** The confederation's key X, x-only, once it exists. */
val confederationPublicKey: HexKey? = null,
val failureReason: String? = null,
val culprit: HexKey? = null,
val createdAt: Instant = Clock.System.now(),
val updatedAt: Instant = createdAt,
) {
val isRunning: Boolean
get() = stage != ConfederationCeremonyStage.COMPLETE && stage != ConfederationCeremonyStage.FAILED
}
/** Where a ceremony has got to, as a label. */
enum class ConfederationCeremonyStage {
WAITING_TO_JOIN,
COLLECTING_HOST_KEYS,
DEALING,
AUTHORIZING,
ACKNOWLEDGING,
COMPLETE,
FAILED,
}
/** One message a ceremony has received or sent, written once per sender and kind. */
@Entity(
primaryKeys = ["sessionId", "senderPublicKey", "kind"],
foreignKeys = [
ForeignKey(entity = ConfederationCeremony::class, parentColumns = ["id"], childColumns = ["sessionId"], onDelete = ForeignKey.CASCADE)
],
)
data class ConfederationCeremonyMessage(
val sessionId: String,
val senderPublicKey: HexKey,
val kind: Kind,
val payload: String,
val receivedAt: Instant = Clock.System.now(),
)
@@ -79,6 +79,8 @@ import mobi.giza.compose.managers.ShareRepairManager
import mobi.giza.compose.ExperimentalFeatures
import mobi.giza.compose.managers.ChronicleManager
import mobi.giza.compose.managers.FrostSigningManager
import mobi.giza.compose.extensions.toHex
import mobi.giza.compose.managers.ConfederationRitualManager
import mobi.giza.compose.managers.GroupKeyStateManager
import mobi.giza.compose.managers.MarmotGroupCreation
import mobi.giza.compose.managers.SubgroupManager
@@ -159,6 +161,16 @@ class DatabaseChatRepository(
// without a demoted member, a promotion's next steps.
// docs/member-admin-promotion.md, Phases 8 and 9.
launch { GovernanceFollowThrough.observe(database = database, keyPair = keyPair) }
// A confederation's key ceremony this device joined, moved as far as its stored
// messages allow, as ChillDKG's are on resume. docs/confederation.md, Phase 11.
if (ExperimentalFeatures.confederation) {
keyPair.privKey?.let { secret ->
launch {
runCatching { ConfederationRitualManager.resumeRunning(database, keyPair.pubKey.toHex(), secret) }
.onFailure { logger.e("Could not resume confederation ceremonies", it) }
}
}
}
Unit
}
@@ -12,7 +12,13 @@ import mobi.giza.compose.identity.Identity
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.ConfederationCeremony
import mobi.giza.compose.database.model.ConfederationCeremonyMessage
import mobi.giza.compose.database.model.ConfederationEvent
import mobi.giza.compose.managers.ConfederationRitualManager
import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents
import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder
import fr.acinq.bitcoin.utils.Either
import mobi.giza.compose.database.model.FrostSigningSession
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.database.model.types.FrostSigningStage
@@ -29,6 +35,29 @@ class DatabaseConfederationRepository(
/** The identity the app runs as: its key opens the acceptances when it coordinates. */
private val activeIdentity: StateFlow<Identity?> = MutableStateFlow(null),
) : ConfederationRepository {
override fun observeCeremony(proposalId: HexKey): Flow<ConfederationCeremony?> =
database.confederationCeremonyDao().observeLatestForProposal(proposalId)
override fun observeCeremonyMessages(sessionId: String): Flow<List<ConfederationCeremonyMessage>> =
database.confederationCeremonyDao().observeMessages(sessionId)
override fun ceremonyPlan(ceremony: ConfederationCeremony): ConfederationRosterBuilder.Plan? =
ConfederationRitualEvents.Opening.decode(ceremony.openingJson)
?.let { ConfederationRitualManager.planFrom(it) as? Either.Right }
?.value
override suspend fun openCeremony(proposalId: HexKey): ConfederationCeremony {
val secret = activeIdentity.value?.nostrPrivateKey ?: throw IllegalStateException("This identity cannot sign")
return ConfederationRitualManager.open(database, proposalId, secret)
}
override suspend fun joinCeremony(sessionId: String) {
val secret = activeIdentity.value?.nostrPrivateKey ?: return
ConfederationRitualManager.join(database, sessionId, secret.value.toByteArray())
}
override suspend fun abandonCeremony(sessionId: String) = ConfederationRitualManager.abandon(database, sessionId)
override suspend fun outcome(proposalId: HexKey): ConfederationManager.Outcome? {
val secret = activeIdentity.value?.nostrPrivateKey ?: return null
return ConfederationManager.outcome(database, proposalId, secret)
@@ -0,0 +1,727 @@
package mobi.giza.compose.managers
import co.touchlab.kermit.Logger
import com.vitorpamplona.crypto.random.RandomInstance
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 fr.acinq.bitcoin.ByteVector
import fr.acinq.bitcoin.ByteVector32
import fr.acinq.bitcoin.ByteVector64
import fr.acinq.bitcoin.Crypto
import fr.acinq.bitcoin.PrivateKey
import fr.acinq.bitcoin.PublicKey
import fr.acinq.bitcoin.crypto.confederation.ConfederationBroadcast
import fr.acinq.bitcoin.crypto.confederation.ConfederationCiphertexts
import fr.acinq.bitcoin.crypto.confederation.ConfederationDealerRecord
import fr.acinq.bitcoin.crypto.confederation.ConfederationDkg
import fr.acinq.bitcoin.crypto.confederation.ConfederationDkgDealing
import fr.acinq.bitcoin.crypto.confederation.ConfederationEvidenceList
import fr.acinq.bitcoin.crypto.confederation.ConfederationFault
import fr.acinq.bitcoin.crypto.confederation.ConfederationKeyState
import fr.acinq.bitcoin.crypto.confederation.ConfederationRoleId
import fr.acinq.bitcoin.crypto.confederation.ConfederationRoster
import fr.acinq.bitcoin.crypto.confederation.ConfederationTransition
import fr.acinq.bitcoin.utils.Either
import kotlin.time.Clock
import kotlin.time.Instant
import mobi.giza.compose.database.GENESIS_AT
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.ChatMessage
import mobi.giza.compose.database.model.ConfederationCeremony
import mobi.giza.compose.database.model.ConfederationCeremonyMessage
import mobi.giza.compose.database.model.ConfederationCeremonyStage
import mobi.giza.compose.database.model.GiftWrapPayload
import mobi.giza.compose.database.model.NostrEvent
import mobi.giza.compose.database.model.Profile
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.ConfederationProposalAcceptanceEvent
import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent
import mobi.giza.compose.nostr.confederation.ConfederationProposalState
import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents
import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents.Opening
import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder
import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder.Plan
import mobi.giza.compose.nostr.confederation.ConfederationSeal
import mobi.giza.compose.nostr.confederation.ConfederationStatus
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
/**
* Runs a confederation's key ceremony across devices, one person per device (docs/confederation.md,
* Phase 11), over upstream's `ConfederationDkg`.
*
* 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. 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
* themselves (docs/automatic-key-ceremony.md).
*
* What is new is what a participant checks before it will join at all. The coordinator could
* otherwise put a role of its own choosing into another group's segment, so every device rebuilds
* the roster from what the groups signed, opened with the keys the coordinator discloses (D7), and
* checks its own groups' segments against the admins it sees in them now. The coordinator's copy
* of the roster then has to match byte for byte, and every key state is derived by each role
* itself, never accepted from the coordinator.
*
* WARNING: upstream's confederation module is experimental and unaudited. This runs behind
* `ExperimentalFeatures.confederation`, off in release.
*/
object ConfederationRitualManager {
private val logger = Logger.withTag("ConfederationRitualManager")
const val ABANDONED = "Abandoned by a participant"
// ---- opening, on the coordinator's device ---------------------------------------------
/**
* Opens the key ceremony for [proposalId] once every group has accepted it: decrypts the
* acceptances with the coordinator's own key, checks the roster can be built, makes the room
* and sends the opening. Opening is the coordinator's own join. Returns the ceremony already
* running for this proposal, if there is one.
*/
suspend fun open(database: GizaDatabase, proposalId: HexKey, coordinatorSecret: PrivateKey): ConfederationCeremony {
val coordinator = coordinatorSecret.publicKey().xOnly().value.toHex()
database.confederationCeremonyDao().getLatestForProposal(proposalId)
?.takeIf { it.isRunning || it.stage == ConfederationCeremonyStage.COMPLETE }
?.let { return it }
val outcome = ConfederationManager.outcome(database, proposalId, coordinatorSecret)
?: throw IllegalStateException("Only the coordinator can open the key ceremony")
check(outcome.ready) { outcome.problems.joinToString("; ").ifBlank { "The proposal is not ready to form" } }
val status = outcome.status
val proposalEvent = database.confederationDao().getEvent(proposalId)!!.toEvent()
val acceptanceEvents = status.proposal.groupPublicKeys.map { group ->
database.confederationDao().getEvent(status.acceptances.getValue(group).id)!!.toEvent()
}
val keys = status.acceptances.values.associate { acceptance ->
acceptance.id to ConfederationSeal.conversationKey(coordinatorSecret.value.toByteArray(), acceptance.ephemeralPublicKey).toHex()
}
val opening = Opening(
proposalJson = proposalEvent.toJson(),
acceptanceJsons = acceptanceEvents.map { it.toJson() },
conversationKeys = keys,
sessionSeed = RandomInstance.bytes(32).toHex(),
)
val plan = planFrom(opening).let {
when (it) {
is Either.Right -> it.value
is Either.Left -> throw IllegalStateException(it.value)
}
}
ensureProfiles(database, plan.people)
val room = database.nostrNip17Dao().createNip17ChatRoom(
userPublicKey = coordinator,
participantPublicKeys = plan.people,
subject = status.proposal.name,
) ?: throw IllegalStateException("Could not make the ceremony's room")
val ceremony = newCeremony(
sessionId = RandomInstance.bytes(32).toHex(),
chatRoomId = room.chatRoom.id,
proposalId = proposalId,
coordinator = coordinator,
user = coordinator,
opening = opening,
plan = plan,
).copy(approvedAt = Clock.System.now())
database.confederationCeremonyDao().upsert(ceremony)
announce(database, ceremony, ChatMessage.TYPE_CONFEDERATION_CEREMONY_STARTED, "The confederation's key ceremony started")
broadcast(database, room, ceremony, plan, ConfederationRitualEvents.OPENING, opening.encode(), proposalTag = true)
advance(database, room, ceremony.id, coordinatorSecret.value.toByteArray())
return database.confederationCeremonyDao().getCeremony(ceremony.id)!!
}
// ---- 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.
*/
suspend fun process(
database: GizaDatabase,
localChatRoom: LocalChatRoom,
innerEvent: Event,
userPublicKey: HexKey,
nostrPrivateKey: ByteArray,
) {
val sessionId = ConfederationRitualEvents.parseSessionId(innerEvent.tags) ?: run {
logger.w("Ceremony message ${innerEvent.id.take(8)} names no session; dropping")
return
}
val ceremony = if (innerEvent.kind == ConfederationRitualEvents.OPENING) {
acceptOpening(database, localChatRoom, innerEvent, sessionId, userPublicKey)
} else {
// A message routinely arrives before the opening it belongs to. The gift wrap is
// stored by the inbound path, and the opening replays it.
database.confederationCeremonyDao().getCeremony(sessionId)
} ?: return
if (!ceremony.isRunning) return
if (!record(database, ceremony, innerEvent)) return
advance(database, localChatRoom, ceremony.id, nostrPrivateKey)
}
/**
* Files the coordinator's opening, after every check a participant makes before it would join
* (docs/confederation.md, Phase 11). A device whose owner is not in the roster drops it. One
* that finds the opening wrong files the ceremony as failed and says why to everybody, so
* nobody joins a ceremony one of them has found a fault in.
*/
private suspend fun acceptOpening(
database: GizaDatabase,
localChatRoom: LocalChatRoom,
innerEvent: Event,
sessionId: String,
userPublicKey: HexKey,
): ConfederationCeremony? {
database.confederationCeremonyDao().getCeremony(sessionId)?.let { return it }
val opening = Opening.decode(innerEvent.content) ?: run {
logger.w("Ceremony $sessionId: an opening that does not decode; dropping")
return null
}
val proposal = Event.fromJsonOrNull(opening.proposalJson)?.let(ConfederationProposalEvent::parse) ?: run {
logger.w("Ceremony $sessionId: an opening without a readable proposal; dropping")
return null
}
val planOrReason = eligibility(database, opening, innerEvent.pubKey, localChatRoom)
val plan = (planOrReason as? Either.Right)?.value
if (plan != null && userPublicKey !in plan.people) {
logger.i("Ceremony $sessionId does not include this device's owner; dropping")
return null
}
val ceremony = newCeremony(
sessionId = sessionId,
chatRoomId = localChatRoom.chatRoom.id,
proposalId = proposal.id,
coordinator = innerEvent.pubKey,
user = userPublicKey,
opening = opening,
plan = plan,
)
database.confederationCeremonyDao().upsert(ceremony)
when (planOrReason) {
is Either.Left -> {
logger.w("Ceremony $sessionId refused: ${planOrReason.value}")
failOut(database, localChatRoom, ceremony, planOrReason.value, culprit = innerEvent.pubKey)
return null
}
is Either.Right -> {
announce(
database, ceremony, ChatMessage.TYPE_CONFEDERATION_CEREMONY_STARTED,
"The confederation's key ceremony started. Join it to hold a share of its key",
)
replayStoredMessages(database, ceremony)
return database.confederationCeremonyDao().getCeremony(sessionId)
}
}
}
/**
* Everything a participant checks before it would join, as a reason or the roster's plan:
*
* - the proposal and every acceptance are what their groups signed, and the proposal is
* accepted by every group it names, in time, with nothing on this device rejecting it;
* - the sender is the proposal's coordinator;
* - every acceptance opens with the key disclosed for it, to that group's answer (D7);
* - the roster can be planned from them;
* - the room is exactly the people the roster names;
* - each group this device is in still has the admins and threshold it accepted with.
*/
internal suspend fun eligibility(
database: GizaDatabase,
opening: Opening,
sender: HexKey,
localChatRoom: LocalChatRoom,
): Either<String, Plan> {
val proposalEvent = Event.fromJsonOrNull(opening.proposalJson)
?.takeIf { GroupKeyStateEvent.isSignedByRoom(it, it.pubKey) }
?: return Either.Left("The proposal in the opening is not one its group signed")
val proposal = ConfederationProposalEvent.parse(proposalEvent)
?: return Either.Left("The proposal in the opening cannot be read")
if (sender != proposal.coordinator) return Either.Left("The ceremony was opened by someone other than the proposal's coordinator")
val acceptanceEvents = opening.acceptanceJsons.mapNotNull { json ->
Event.fromJsonOrNull(json)?.takeIf { GroupKeyStateEvent.isSignedByRoom(it, it.pubKey) }
}
if (acceptanceEvents.size != opening.acceptanceJsons.size) return Either.Left("An acceptance in the opening is not one its group signed")
val status = ConfederationStatus.of(proposal, acceptanceEvents, Clock.System.now().epochSeconds)
if (status.state != ConfederationProposalState.ACCEPTED) return Either.Left("Not every group has accepted the proposal")
val heldHere = ConfederationManager.status(database, proposal.id)?.state
if (heldHere == ConfederationProposalState.REJECTED || heldHere == ConfederationProposalState.WITHDRAWN) {
return Either.Left("This device holds a rejection or a withdrawal of the proposal")
}
// Filed as a relay's copies would be: they are the groups' own signed statements.
ConfederationManager.record(database, proposalEvent)
acceptanceEvents.forEach { ConfederationManager.record(database, it) }
val plan = when (val planned = planFrom(opening)) {
is Either.Left -> return Either.Left(planned.value)
is Either.Right -> planned.value
}
val room = localChatRoom.localParticipants.map { it.participant.participantPublicKey }.toSet() +
localChatRoom.chatRoom.userPublicKey
if (room != plan.people.toSet()) return Either.Left("The ceremony's room is not exactly the confederation's admins")
// The admins on their own, so a member who holds no share -- and so cannot read the
// threshold the group signs with -- still checks who its group put forward. The
// threshold is compared wherever this device can read it.
plan.groups.forEach { group ->
if (database.chatRoomDao().findChatRoomById(group) == null) return@forEach
val sealed = plan.adminLists.getValue(group)
val admins = RoomAdmins.of(database, group)?.admins ?: return@forEach
val threshold = FrostSigningManager.completedKey(database, group)?.threshold
if (admins.map { it.lowercase() }.sorted() != sealed.admins || (threshold != null && threshold != sealed.threshold)) {
return Either.Left("The admins of ${ConfederationManager.nameOf(database, group)} have changed since it accepted")
}
}
return Either.Right(plan)
}
/** The roster's plan from an opening alone: each acceptance opened with the key disclosed for it. */
internal fun planFrom(opening: Opening): Either<String, Plan> {
val proposal = Event.fromJsonOrNull(opening.proposalJson)?.let(ConfederationProposalEvent::parse)
?: return Either.Left("The proposal in the opening cannot be read")
val lists = mutableMapOf<HexKey, ConfederationAdminList>()
val ids = mutableMapOf<HexKey, HexKey>()
opening.acceptanceJsons.forEach { json ->
val acceptance = Event.fromJsonOrNull(json)?.let(ConfederationProposalAcceptanceEvent::parse)
?: return Either.Left("An acceptance in the opening cannot be read")
val key = opening.conversationKeys[acceptance.id]
?: return Either.Left("No key was disclosed for one group's acceptance")
val list = runCatching { ConfederationSeal.open(key.hexBytes(), acceptance.content) }.getOrNull()
?: return Either.Left("The key disclosed for one group's acceptance does not open it")
if (list.group != acceptance.group || list.proposalId != proposal.id) {
return Either.Left("One group's acceptance opens to another group's or another proposal's admins")
}
lists[acceptance.group] = list
ids[acceptance.group] = acceptance.id
}
return when (val planned = ConfederationRosterBuilder.plan(proposal, lists, ids)) {
is Either.Left -> Either.Left(planned.value.reason)
is Either.Right -> Either.Right(planned.value)
}
}
private fun newCeremony(
sessionId: String,
chatRoomId: String,
proposalId: HexKey,
coordinator: HexKey,
user: HexKey,
opening: Opening,
plan: Plan?,
): ConfederationCeremony {
val groups = plan?.seatsOf(user)?.map { it.group }.orEmpty()
return ConfederationCeremony(
id = sessionId,
chatRoomId = chatRoomId,
proposalId = proposalId,
coordinatorPublicKey = coordinator,
userPublicKey = user,
openingJson = opening.encode(),
// Fresh per role, and persisted: the dealing is a pure function of the seed, which is
// what lets a device that died before sending it send the same one.
dealerSeeds = ConfederationRitualEvents.encodeByGroup(groups.associateWith { RandomInstance.bytes(32).toHex() }),
recoveryNonces = ConfederationRitualEvents.encodeByGroup(groups.associateWith { RandomInstance.bytes(32).toHex() }),
)
}
/**
* Files one message. Returns false when it ended the ceremony. Per-person messages are taken
* only from a person the roster names, carrying a value for exactly the roles they hold; the
* broadcast only from the coordinator; a failure only from someone in the ceremony.
*/
private suspend fun record(database: GizaDatabase, ceremony: ConfederationCeremony, innerEvent: Event): Boolean {
if (innerEvent.kind == ConfederationRitualEvents.OPENING) return true
val plan = (planFrom(Opening.decode(ceremony.openingJson) ?: return true) as? Either.Right)?.value ?: return true
val sender = innerEvent.pubKey
when (innerEvent.kind) {
in ConfederationRitualEvents.PER_PERSON -> {
val groups = plan.seatsOf(sender).map { it.group }.toSet()
if (groups.isEmpty()) {
logger.w("Ceremony ${ceremony.id}: kind ${innerEvent.kind} from ${sender.take(8)}, who holds no role; ignoring")
return true
}
val keys = if (innerEvent.kind == ConfederationRitualEvents.DEALINGS) {
ConfederationRitualEvents.decodeDealings(innerEvent.content)?.keys
} else {
ConfederationRitualEvents.decodeByGroup(innerEvent.content)?.keys
}
if (keys != groups) {
logger.w("Ceremony ${ceremony.id}: kind ${innerEvent.kind} from ${sender.take(8)} is not one value per role; ignoring")
return true
}
database.confederationCeremonyDao().insertMessage(
ConfederationCeremonyMessage(ceremony.id, sender, innerEvent.kind, innerEvent.content)
)
}
ConfederationRitualEvents.BROADCAST -> {
if (sender != ceremony.coordinatorPublicKey) return true
database.confederationCeremonyDao().insertMessage(
ConfederationCeremonyMessage(ceremony.id, sender, innerEvent.kind, innerEvent.content)
)
}
ConfederationRitualEvents.FAILURE -> {
if (sender !in plan.people) return true
fail(database, ceremony, "Ended by ${ConfederationManager.nameOf(database, sender)}: ${innerEvent.content}", sender)
return false
}
}
return true
}
// ---- the member's say --------------------------------------------------------------------
/** Whether this ceremony is waiting on its member to join. */
fun isAwaitingJoin(ceremony: ConfederationCeremony): Boolean = ceremony.isRunning && ceremony.approvedAt == null
/** Joins: the one thing a member is asked. Everything after it runs by itself. */
suspend fun join(database: GizaDatabase, sessionId: String, nostrPrivateKey: ByteArray) {
val ceremony = database.confederationCeremonyDao().getCeremony(sessionId) ?: return
if (!isAwaitingJoin(ceremony)) return
update(database, ceremony) { it.copy(approvedAt = Clock.System.now()) }
val room = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return
advance(database, room, sessionId, nostrPrivateKey)
}
/** Ends a running ceremony for everybody, as any participant may. */
suspend fun abandon(database: GizaDatabase, sessionId: String) {
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)
}
/** 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) }
.onFailure { logger.e("Could not resume ceremony ${ceremony.id}", it) }
}
return running.size
}
// ---- the rounds ----------------------------------------------------------------------------
/**
* Takes every step the stored messages now allow, in protocol order, stopping at the first
* 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) {
var ceremony = database.confederationCeremonyDao().getCeremony(sessionId) ?: return
if (!ceremony.isRunning || ceremony.approvedAt == null) return
val opening = Opening.decode(ceremony.openingJson) ?: return fail(database, ceremony, "The opening cannot be read", null)
val plan = when (val planned = planFrom(opening)) {
is Either.Left -> return failOut(database, localChatRoom, ceremony, planned.value, ceremony.coordinatorPublicKey)
is Either.Right -> planned.value
}
val me = ceremony.userPublicKey
val seats = plan.seatsOf(me)
val host = seats.associate { it.roleId to ConfederationRosterBuilder.hostSecretKey(nostrPrivateKey, it.group, plan.proposal.id) }
val sessionSeed = ByteVector32(opening.sessionSeed)
// 1. This person's host keys, one per role.
if (own(database, ceremony, ConfederationRitualEvents.HOST_KEYS) == null) {
publishOwn(
database, localChatRoom, ceremony, plan, ConfederationRitualEvents.HOST_KEYS,
ConfederationRitualEvents.encodeByGroup(seats.associate { it.group to host.getValue(it.roleId).publicKey().value.toHex() }),
)
}
val hostKeys = perRole(database, ceremony, plan, ConfederationRitualEvents.HOST_KEYS) { PublicKey(ByteVector(it)) }
?: return moveTo(database, ceremony, ConfederationCeremonyStage.COLLECTING_HOST_KEYS)
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.Right -> built.value
}
val rosterHex = roster.data.toHex()
// 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)
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) }
seat.group to ConfederationRitualEvents.Dealing(dealing.record.data.toHex(), dealing.ciphertexts.data.toHex())
}
publishOwn(database, localChatRoom, ceremony, plan, ConfederationRitualEvents.DEALINGS, ConfederationRitualEvents.encodeDealings(dealings))
}
if (ceremony.dealerSeeds != null) ceremony = update(database, ceremony) { it.copy(dealerSeeds = null) }
// 3. The coordinator combines everybody's dealings.
if (me == ceremony.coordinatorPublicKey && own(database, ceremony, ConfederationRitualEvents.BROADCAST) == null) {
val dealings = perRoleDealings(database, ceremony, plan)
?: return moveTo(database, ceremony, ConfederationCeremonyStage.DEALING)
val step = ConfederationDkg.coordinatorStep1(roster, sessionSeed, dealings)
.rightOrFail { return failOut(database, localChatRoom, ceremony, "Combining the dealings failed: $it", null) }
step.fault?.let { return failOut(database, localChatRoom, ceremony, describe(database, plan, it), culpritOf(plan, it)) }
publishOwn(
database, localChatRoom, ceremony, plan, ConfederationRitualEvents.BROADCAST,
ConfederationRitualEvents.Broadcast(rosterHex, step.broadcast!!.data.toHex()).encode(),
)
}
val sent = database.confederationCeremonyDao().getMessage(ceremony.id, ceremony.coordinatorPublicKey, ConfederationRitualEvents.BROADCAST)
?.let { ConfederationRitualEvents.Broadcast.decode(it.payload) }
?: return moveTo(database, ceremony, ConfederationCeremonyStage.DEALING)
if (sent.roster != rosterHex) {
return failOut(database, localChatRoom, ceremony, "The coordinator's roster is not the one this device built", ceremony.coordinatorPublicKey)
}
val broadcast = ConfederationBroadcast(ByteVector(sent.broadcast))
val ownDealings = ConfederationRitualEvents.decodeDealings(own(database, ceremony, ConfederationRitualEvents.DEALINGS)!!.payload)!!
val ownRecord = { group: HexKey -> ConfederationDealerRecord(ByteVector(ownDealings.getValue(group).record)) }
// 4. Each role checks the broadcast, derives the key state itself and authorizes the genesis.
if (own(database, ceremony, ConfederationRitualEvents.AUTHORIZATIONS) == null) {
var keyState: ConfederationKeyState? = null
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)) }
keyState = step.keyState
transitionHash = step.transitionHash
seat.group to step.authorization!!.toHex()
}
ceremony = update(database, ceremony) {
it.copy(
keyState = keyState!!.data.toHex(),
transitionHash = transitionHash!!.toHex(),
confederationPublicKey = keyState!!.publicKey.value.toHex(),
)
}
publishOwn(database, localChatRoom, ceremony, plan, ConfederationRitualEvents.AUTHORIZATIONS, ConfederationRitualEvents.encodeByGroup(authorizations))
}
val keyState = ConfederationKeyState.fromData(ByteVector(ceremony.keyState!!), roster)
.rightOrFail { return failOut(database, localChatRoom, ceremony, "This device's key state no longer reads: $it", null) }
val transitionHash = ByteVector32(ceremony.transitionHash!!)
val authorizations = perRole(database, ceremony, plan, ConfederationRitualEvents.AUTHORIZATIONS) { ByteVector64(it) }
?: return moveTo(database, ceremony, ConfederationCeremonyStage.AUTHORIZING)
val authorizationList = ConfederationDkg.evidenceList(roster, authorizations)
.rightOrFail { return failOut(database, localChatRoom, ceremony, "The authorizations cannot be listed: $it", null) }
// 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)) }
seat.group to step.acknowledgment!!.toHex()
}
publishOwn(database, localChatRoom, ceremony, plan, ConfederationRitualEvents.ACKNOWLEDGMENTS, ConfederationRitualEvents.encodeByGroup(acknowledgments))
}
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) }
// 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)) }
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) }
// 7. Each role's share, kept as its recovery package.
if (ceremony.recoveryPackages == null) {
val nonces = ConfederationRitualEvents.decodeByGroup(ceremony.recoveryNonces!!)!!
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) }
seat.group to result.recovery.data.toHex()
}
ceremony = update(database, ceremony) {
it.copy(recoveryPackages = ConfederationRitualEvents.encodeByGroup(packages), stage = ConfederationCeremonyStage.COMPLETE)
}
logger.i("Ceremony ${ceremony.id} complete: the confederation's key is ${ceremony.confederationPublicKey?.take(12)}")
announce(database, ceremony, ChatMessage.TYPE_CONFEDERATION_CEREMONY_COMPLETE, "The confederation's key ceremony finished. Its key is made")
}
}
// ---- helpers ---------------------------------------------------------------------------
private suspend fun own(database: GizaDatabase, ceremony: ConfederationCeremony, kind: Kind) =
database.confederationCeremonyDao().getMessage(ceremony.id, ceremony.userPublicKey, kind)
/** Every role's value from every person's message of [kind], or null while anybody's is missing. */
private suspend fun <T> perRole(
database: GizaDatabase,
ceremony: ConfederationCeremony,
plan: Plan,
kind: Kind,
read: (String) -> T,
): Map<ConfederationRoleId, T>? {
val byPerson = plan.people.associateWith { person ->
val message = database.confederationCeremonyDao().getMessage(ceremony.id, person, kind) ?: return null
ConfederationRitualEvents.decodeByGroup(message.payload) ?: return null
}
return plan.seats.associate { seat -> seat.roleId to read(byPerson.getValue(seat.admin).getValue(seat.group)) }
}
private suspend fun perRoleDealings(database: GizaDatabase, ceremony: ConfederationCeremony, plan: Plan): Map<ConfederationRoleId, ConfederationDkgDealing>? {
val byPerson = plan.people.associateWith { person ->
val message = database.confederationCeremonyDao().getMessage(ceremony.id, person, ConfederationRitualEvents.DEALINGS) ?: return null
ConfederationRitualEvents.decodeDealings(message.payload) ?: return null
}
return plan.seats.associate { seat ->
val d = byPerson.getValue(seat.admin).getValue(seat.group)
seat.roleId to ConfederationDkgDealing(ConfederationDealerRecord(ByteVector(d.record)), ConfederationCiphertexts(ByteVector(d.ciphertexts)))
}
}
private fun culpritOf(plan: Plan, fault: ConfederationFault): HexKey? = fault.role?.let { plan.seatOf(it)?.admin }
/** A fault said as who and what, for the failure line and the decline everybody sees. */
private suspend fun describe(database: GizaDatabase, plan: Plan, fault: ConfederationFault): String {
val who = fault.role?.let(plan::seatOf)?.let { seat ->
"${ConfederationManager.nameOf(database, seat.admin)} for ${ConfederationManager.nameOf(database, seat.group)}"
}
return when (fault.kind) {
ConfederationFault.Kind.COORDINATOR -> "The coordinator sent something no honest coordinator sends"
ConfederationFault.Kind.ROLE -> "${who ?: "A participant"} sent something no honest participant sends"
ConfederationFault.Kind.ROLE_OR_COORDINATOR -> "A share from ${who ?: "a participant"} did not decrypt; either they or the coordinator is at fault"
ConfederationFault.Kind.UNKNOWN -> "A message from ${who ?: "a participant"} does not verify"
ConfederationFault.Kind.INVALID_CONFIGURATION -> "The roster and keys make no valid key; nobody is at fault"
}
}
private inline fun <T> Either<Throwable, T>.rightOrFail(onLeft: (String) -> Nothing): T = when (this) {
is Either.Right -> value
is Either.Left -> onLeft(value.message ?: value.toString())
}
private suspend fun update(
database: GizaDatabase,
ceremony: ConfederationCeremony,
transform: (ConfederationCeremony) -> ConfederationCeremony,
): ConfederationCeremony {
val current = database.confederationCeremonyDao().getCeremony(ceremony.id) ?: ceremony
val next = transform(current).copy(updatedAt = Clock.System.now())
database.confederationCeremonyDao().upsert(next)
return next
}
private suspend fun moveTo(database: GizaDatabase, ceremony: ConfederationCeremony, stage: ConfederationCeremonyStage) {
if (ceremony.stage != stage) update(database, ceremony) { it.copy(stage = stage) }
}
/** 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?) {
val plan = (planFrom(Opening.decode(ceremony.openingJson) ?: return fail(database, ceremony, reason, culprit)) as? Either.Right)?.value
broadcast(database, localChatRoom, ceremony, plan, ConfederationRitualEvents.FAILURE, reason)
fail(database, ceremony, reason, culprit)
}
private suspend fun fail(database: GizaDatabase, ceremony: ConfederationCeremony, reason: String, culprit: HexKey?) {
val current = database.confederationCeremonyDao().getCeremony(ceremony.id) ?: ceremony
if (!current.isRunning) return
update(database, current) { it.copy(stage = ConfederationCeremonyStage.FAILED, failureReason = reason, culprit = culprit, dealerSeeds = null) }
logger.w("Ceremony ${ceremony.id} failed: $reason")
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)
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. */
private suspend fun broadcast(
database: GizaDatabase,
localChatRoom: LocalChatRoom,
ceremony: ConfederationCeremony,
plan: Plan?,
kind: Kind,
content: String,
proposalTag: Boolean = false,
) {
val people = plan?.people
?: (localChatRoom.localParticipants.map { it.participant.participantPublicKey } + localChatRoom.chatRoom.userPublicKey)
val tags = people.filter { it != ceremony.userPublicKey }.sorted().map { arrayOf("p", it) }.toTypedArray() +
arrayOf(ConfederationRitualEvents.sessionTag(ceremony.id)) +
(if (proposalTag) arrayOf(arrayOf(ConfederationRitualEvents.PROPOSAL_TAG, ceremony.proposalId)) else emptyArray())
val createdAt = Clock.System.now().epochSeconds
val id = EventHasher.hashId(pubKey = ceremony.userPublicKey, createdAt = createdAt, kind = kind, tags = tags, content = content)
database.giftWrapPayloadDao().upsert(
GiftWrapPayload(
id = id,
publicKey = ceremony.userPublicKey,
chatRoomId = localChatRoom.chatRoom.id,
kind = kind,
tags = tags,
content = content,
createdAt = Instant.fromEpochSeconds(createdAt),
)
)
}
/** Feeds in what arrived before the opening did: the inbound path stores every gift wrap first. */
private suspend fun replayStoredMessages(database: GizaDatabase, ceremony: ConfederationCeremony) {
database.giftWrapPayloadDao()
.getByChatRoomAndKinds(ceremony.chatRoomId, (ConfederationRitualEvents.ALL - ConfederationRitualEvents.OPENING).toList())
.filter { ConfederationRitualEvents.parseSessionId(it.tags) == ceremony.id }
.forEach { stored ->
val event = Event(stored.id, stored.publicKey, stored.createdAt.epochSeconds, stored.kind, stored.tags, stored.content, "")
if (!record(database, database.confederationCeremonyDao().getCeremony(ceremony.id) ?: return, event)) 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.coordinatorPublicKey,
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.
*/
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)
)
}
database.profileDao().insertPlaceholderProfile(
Profile(displayName = "LOADING...", publicKey = key, createdAt = GENESIS_AT, nostrEventId = eventId)
)
}
}
private fun String.hexBytes(): ByteArray = ByteVector(this).toByteArray()
}
@@ -0,0 +1,136 @@
package mobi.giza.compose.nostr.confederation
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.Kind
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
/**
* The confederation's key ceremony on the wire (docs/confederation.md, Phase 11): rumors in the
* NIP-17 room the coordinator opens over every admin of every group, gift-wrapped per member
* like the group's own ChillDKG ceremony (docs/shared-key-ceremony.md).
*
* A person who is an admin of two groups holds two roles and sends one message per step,
* carrying a value for each of their roles keyed by group. Every receiver checks the sender is
* that group's admin in the roster before it reads a value.
*
* | kind | from | carries |
* |-------|-------------|----------------------------------------------------------------------|
* | 30380 | coordinator | the opening: the 9430, every 9431, D7's conversation keys, the seed |
* | 30381 | each person | a host public key per role |
* | 30382 | each person | a dealer record and ciphertext vector per role |
* | 30383 | coordinator | the roster as the coordinator built it, and the broadcast |
* | 30384 | each person | an authorization of the genesis per role |
* | 30385 | each person | an acknowledgment per role: its share can be recovered from storage |
* | 30387 | anyone | failure or abandonment, with a reason |
*
* There is no certificate message. Every device assembles the certified genesis itself from
* the authorizations and acknowledgments it already holds: it needs no secret to do it, and a
* device that builds its own cannot be handed someone else's. 30386 is left unused for that
* reason, and 30388 for the investigation a decryption fault would start, which is not built.
*/
object ConfederationRitualEvents {
const val OPENING: Kind = 30380
const val HOST_KEYS: Kind = 30381
const val DEALINGS: Kind = 30382
const val BROADCAST: Kind = 30383
const val AUTHORIZATIONS: Kind = 30384
const val ACKNOWLEDGMENTS: Kind = 30385
const val FAILURE: Kind = 30387
val ALL: Set<Kind> = setOf(OPENING, HOST_KEYS, DEALINGS, BROADCAST, AUTHORIZATIONS, ACKNOWLEDGMENTS, FAILURE)
/** The messages each person sends once, one value per role. */
val PER_PERSON: Set<Kind> = setOf(HOST_KEYS, DEALINGS, AUTHORIZATIONS, ACKNOWLEDGMENTS)
fun isRitualKind(kind: Kind): Boolean = kind in ALL
const val SESSION_TAG = "confederation_ceremony"
const val PROPOSAL_TAG = "confederation_proposal_id"
fun sessionTag(sessionId: String): Array<String> = arrayOf(SESSION_TAG, sessionId)
fun parseSessionId(tags: Array<Array<String>>): String? =
tags.firstOrNull { it.size >= 2 && it[0] == SESSION_TAG }?.get(1)?.takeIf(ConfederationKinds::isHex32)
private val json = Json { ignoreUnknownKeys = false }
/**
* What the coordinator opens the ceremony with: the signed proposal and acceptances, a key that
* opens each acceptance (D7), and the session seed every role's steps take.
*/
data class Opening(
val proposalJson: String,
val acceptanceJsons: List<String>,
/** By acceptance event id: the NIP-44 conversation key that opens it, and nothing else. */
val conversationKeys: Map<HexKey, HexKey>,
val sessionSeed: HexKey,
) {
fun encode(): String = buildJsonObject {
put("v", 1)
put("proposal", proposalJson)
put("acceptances", JsonArray(acceptanceJsons.map(::JsonPrimitive)))
put("keys", JsonObject(conversationKeys.toSortedMap().mapValues { JsonPrimitive(it.value) }))
put("seed", sessionSeed)
}.toString()
companion object {
fun decode(content: String): Opening? = runCatching {
val obj = json.parseToJsonElement(content) as JsonObject
require((obj["v"] as JsonPrimitive).content == "1")
Opening(
proposalJson = (obj["proposal"] as JsonPrimitive).content,
acceptanceJsons = (obj["acceptances"] as JsonArray).map { (it as JsonPrimitive).content },
conversationKeys = (obj["keys"] as JsonObject).mapValues { (it.value as JsonPrimitive).content },
sessionSeed = (obj["seed"] as JsonPrimitive).content.also { require(ConfederationKinds.isHex32(it)) },
)
}.getOrNull()
}
}
/** One value per role, keyed by the role's group: a host key, an authorization, an acknowledgment. */
fun encodeByGroup(values: Map<HexKey, String>): String =
JsonObject(values.toSortedMap().mapValues { JsonPrimitive(it.value) }).toString()
fun decodeByGroup(content: String): Map<HexKey, String>? = runCatching {
(json.parseToJsonElement(content) as JsonObject).mapValues { (it.value as JsonPrimitive).content }
}.getOrNull()
/** A dealing per role, keyed by the role's group. */
data class Dealing(val record: String, val ciphertexts: String)
fun encodeDealings(values: Map<HexKey, Dealing>): String = JsonObject(
values.toSortedMap().mapValues { (_, d) ->
buildJsonObject {
put("record", d.record)
put("ciphertexts", d.ciphertexts)
}
}
).toString()
fun decodeDealings(content: String): Map<HexKey, Dealing>? = runCatching {
(json.parseToJsonElement(content) as JsonObject).mapValues { (_, value) ->
val obj = value as JsonObject
Dealing((obj["record"] as JsonPrimitive).content, (obj["ciphertexts"] as JsonPrimitive).content)
}
}.getOrNull()
/** The coordinator's broadcast, with the roster it was made over so every device can compare its own. */
data class Broadcast(val roster: String, val broadcast: String) {
fun encode(): String = buildJsonObject {
put("roster", roster)
put("broadcast", broadcast)
}.toString()
companion object {
fun decode(content: String): Broadcast? = runCatching {
val obj = json.parseToJsonElement(content) as JsonObject
Broadcast((obj["roster"] as JsonPrimitive).content, (obj["broadcast"] as JsonPrimitive).content)
}.getOrNull()
}
}
}
@@ -5,7 +5,10 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import kotlin.time.Instant
import mobi.giza.compose.database.model.ConfederationCeremony
import mobi.giza.compose.database.model.ConfederationCeremonyMessage
import mobi.giza.compose.database.model.ConfederationEvent
import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder
import mobi.giza.compose.database.model.FrostSigningSession
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.managers.ConfederationManager
@@ -67,6 +70,21 @@ interface ConfederationRepository {
/** A signing session this room has open over an answer to [proposalId], if any: one at a time. */
fun observePendingAnswer(chatRoomId: String, proposalId: HexKey): Flow<FrostSigningSession?>
/** The key ceremony this device holds for [proposalId], as it changes. docs/confederation.md, Phase 11. */
fun observeCeremony(proposalId: HexKey): Flow<ConfederationCeremony?>
fun observeCeremonyMessages(sessionId: String): Flow<List<ConfederationCeremonyMessage>>
/** The roster's plan a ceremony runs over, or null if its opening no longer reads. */
fun ceremonyPlan(ceremony: ConfederationCeremony): ConfederationRosterBuilder.Plan?
/** Opens the key ceremony, on the coordinator's device, once every group has accepted. */
suspend fun openCeremony(proposalId: HexKey): ConfederationCeremony
suspend fun joinCeremony(sessionId: String)
suspend fun abandonCeremony(sessionId: String)
companion object {
/** Holds nothing and proposes nothing: for screens and tests with no confederation behind them. */
val NO_OP_CONFEDERATION_REPOSITORY: ConfederationRepository = object : ConfederationRepository {
@@ -96,6 +114,13 @@ interface ConfederationRepository {
throw UnsupportedOperationException("No confederation here")
override fun observePendingAnswer(chatRoomId: String, proposalId: HexKey): Flow<FrostSigningSession?> = flowOf(null)
override suspend fun outcome(proposalId: HexKey): ConfederationManager.Outcome? = null
override fun observeCeremony(proposalId: HexKey): Flow<ConfederationCeremony?> = flowOf(null)
override fun observeCeremonyMessages(sessionId: String): Flow<List<ConfederationCeremonyMessage>> = flowOf(emptyList())
override fun ceremonyPlan(ceremony: ConfederationCeremony): ConfederationRosterBuilder.Plan? = null
override suspend fun openCeremony(proposalId: HexKey): ConfederationCeremony =
throw UnsupportedOperationException("No confederation here")
override suspend fun joinCeremony(sessionId: String) = Unit
override suspend fun abandonCeremony(sessionId: String) = Unit
}
}
}
@@ -52,7 +52,9 @@ import mobi.giza.compose.resources.confederation_proposal
import mobi.giza.compose.resources.confederation_proposed_by
import mobi.giza.compose.resources.coordinated_by
import mobi.giza.compose.resources.every_group_accepted_admins_across_groups
import mobi.giza.compose.resources.the_key_ceremony_is_not_available_yet
import mobi.giza.compose.resources.key_ceremony
import mobi.giza.compose.resources.open_the_key_ceremony
import mobi.giza.compose.resources.could_not_open_the_key_ceremony
import mobi.giza.compose.resources.could_not_ask_the_group_to_answer
import mobi.giza.compose.resources.open_the_signing_session
import mobi.giza.compose.resources.open_until
@@ -62,6 +64,7 @@ import mobi.giza.compose.resources.propose_withdrawing
import mobi.giza.compose.resources.reason_optional
import mobi.giza.compose.resources.this_device_does_not_hold_that_proposal
import mobi.giza.compose.resources.waiting_for_the_group_to_sign_its_answer
import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRitualRoute
import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute
import mobi.giza.compose.ui.composable.navigation.routes.Route
import mobi.giza.compose.ui.composable.widgets.Decorative
@@ -114,6 +117,7 @@ fun ConfederationProposalScreen(
val notify = rememberNotifier(rememberCoroutineScope())
val couldNotAnswer = stringResource(Res.string.could_not_ask_the_group_to_answer)
val couldNotOpenCeremony = stringResource(Res.string.could_not_open_the_key_ceremony)
val identityCanSign = LocalCanSign.current
val reasonField = rememberTextFieldState()
val state by viewModel.uiState.collectAsState()
@@ -206,11 +210,25 @@ fun ConfederationProposalScreen(
outcome.notes.forEach { note ->
Text(text = note, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Text(
text = stringResource(Res.string.the_key_ceremony_is_not_available_yet),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (outcome.ready && current.ceremony == null && identityCanSign) {
Button(
modifier = Modifier.fillMaxWidth(),
enabled = !current.isActing,
onClick = {
viewModel.openCeremony(
onSuccess = { onNavigateToRoute(ConfederationRitualRoute(activeUserPublicKey, proposalId)) },
onFailure = { notify(couldNotOpenCeremony) },
)
},
) { Text(stringResource(Res.string.open_the_key_ceremony)) }
}
}
// The ceremony itself, on every device that holds one. docs/confederation.md, Phase 11.
if (current.ceremony != null) {
TextButton(onClick = { onNavigateToRoute(ConfederationRitualRoute(activeUserPublicKey, proposalId)) }) {
Text(stringResource(Res.string.key_ceremony))
}
}
current.pendingSessionId?.let { sessionId ->
@@ -0,0 +1,190 @@
package mobi.giza.compose.ui.composable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.HourglassEmpty
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.lifecycle.viewmodel.compose.viewModel
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import mobi.giza.compose.database.model.ConfederationCeremonyStage
import mobi.giza.compose.repository.ConfederationRepository
import mobi.giza.compose.resources.Res
import mobi.giza.compose.resources.abandon_the_key_ceremony
import mobi.giza.compose.resources.ceremony_step_authorizations
import mobi.giza.compose.resources.ceremony_step_combined
import mobi.giza.compose.resources.ceremony_step_contributions
import mobi.giza.compose.resources.ceremony_step_done
import mobi.giza.compose.resources.ceremony_step_host_keys
import mobi.giza.compose.resources.ceremony_step_shares_stored
import mobi.giza.compose.resources.ceremony_waiting_on
import mobi.giza.compose.resources.confederation_groups
import mobi.giza.compose.resources.confederation_groups_to_act
import mobi.giza.compose.resources.group_signs_with
import mobi.giza.compose.resources.join_the_key_ceremony
import mobi.giza.compose.resources.joining_gives_you_a_share
import mobi.giza.compose.resources.key_ceremony
import mobi.giza.compose.resources.the_ceremony_ended
import mobi.giza.compose.resources.the_confederations_key_is_made
import mobi.giza.compose.resources.this_device_holds_no_key_ceremony
import mobi.giza.compose.ui.composable.widgets.Decorative
import mobi.giza.compose.ui.composable.widgets.EmptyState
import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator
import mobi.giza.compose.ui.composable.widgets.LocalCanSign
import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState
import mobi.giza.compose.ui.composable.widgets.NavigateBackButton
import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition
import mobi.giza.compose.ui.theme.readableContent
import mobi.giza.compose.ui.theme.spacing
import mobi.giza.compose.ui.view.model.ConfederationRitualViewModel
import mobi.giza.compose.ui.view.state.ConfederationRitualUIState
import mobi.giza.compose.ui.view.state.ConfederationRitualUIState.StepKind
import org.jetbrains.compose.resources.stringResource
/**
* A confederation's key ceremony (docs/confederation.md, Phase 11): the groups and who holds a role
* for each, the one thing a member is asked -- to join -- and then each step, naming whom it is
* still waiting on. Any participant can abandon a running ceremony; it ends for everybody.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ConfederationRitualScreen(
activeUserPublicKey: HexKey,
proposalId: HexKey,
initialConfederationRitualUIState: ConfederationRitualUIState = ConfederationRitualUIState.Loading,
confederationRepository: ConfederationRepository,
onNavigateBack: () -> Unit,
) {
val viewModel: ConfederationRitualViewModel = viewModel(
factory = ConfederationRitualViewModel.factory(
activeUserPublicKey = activeUserPublicKey,
proposalId = proposalId,
initialConfederationRitualUIState = initialConfederationRitualUIState,
confederationRepository = confederationRepository,
)
)
LaunchedEffect(true) {
if (initialConfederationRitualUIState == ConfederationRitualUIState.Loading) viewModel.initiate()
}
val state by viewModel.uiState.collectAsState()
val identityCanSign = LocalCanSign.current
Scaffold(
snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
topBar = {
TopAppBar(
title = { Text(text = stringResource(Res.string.key_ceremony), maxLines = 1, overflow = TextOverflow.Ellipsis) },
navigationIcon = { NavigateBackButton(onNavigateBack) },
)
},
) { padding ->
ScreenStateTransition(state) { uiState ->
when (val current = uiState) {
ConfederationRitualUIState.Loading -> LoadingDataIndicator(modifier = Modifier.padding(padding))
ConfederationRitualUIState.NotHeld -> EmptyState(
modifier = Modifier.padding(padding),
message = stringResource(Res.string.this_device_holds_no_key_ceremony),
)
is ConfederationRitualUIState.Loaded -> Column(
modifier = Modifier.padding(padding).readableContent().fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(MaterialTheme.spacing.screenMargin),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap),
) {
val ceremony = current.ceremony
Text(text = current.name, style = MaterialTheme.typography.headlineSmall)
Text(text = stringResource(Res.string.confederation_groups_to_act, current.threshold, current.groups.size))
when (ceremony.stage) {
ConfederationCeremonyStage.COMPLETE -> Text(
text = stringResource(Res.string.the_confederations_key_is_made),
style = MaterialTheme.typography.titleMedium,
)
ConfederationCeremonyStage.FAILED -> Text(
text = stringResource(Res.string.the_ceremony_ended, ceremony.failureReason.orEmpty()),
color = MaterialTheme.colorScheme.error,
)
else -> Unit
}
if (current.awaitingJoin && identityCanSign) {
Text(
text = stringResource(Res.string.joining_gives_you_a_share),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Button(modifier = Modifier.fillMaxWidth(), enabled = !current.isActing, onClick = viewModel::join) {
Text(stringResource(Res.string.join_the_key_ceremony))
}
}
HorizontalDivider()
Text(text = stringResource(Res.string.confederation_groups), style = MaterialTheme.typography.titleSmall)
current.groups.forEach { group ->
ListItem(
headlineContent = { Text(stringResource(Res.string.group_signs_with, group.name, group.threshold, group.admins.size)) },
supportingContent = { Text(group.admins.joinToString()) },
)
}
if (ceremony.isRunning) {
HorizontalDivider()
current.steps.forEach { step ->
val done = step.waitingOn.isEmpty()
ListItem(
leadingContent = {
Icon(if (done) Icons.Default.CheckCircle else Icons.Default.HourglassEmpty, contentDescription = Decorative)
},
headlineContent = { Text(stepLabel(step.kind)) },
supportingContent = {
Text(
if (done) stringResource(Res.string.ceremony_step_done)
else stringResource(Res.string.ceremony_waiting_on, step.waitingOn.joinToString())
)
},
)
}
OutlinedButton(modifier = Modifier.fillMaxWidth(), enabled = !current.isActing, onClick = viewModel::abandon) {
Text(stringResource(Res.string.abandon_the_key_ceremony))
}
}
}
}
}
}
}
@Composable
private fun stepLabel(kind: StepKind): String = stringResource(
when (kind) {
StepKind.HOST_KEYS -> Res.string.ceremony_step_host_keys
StepKind.CONTRIBUTIONS -> Res.string.ceremony_step_contributions
StepKind.COMBINED -> Res.string.ceremony_step_combined
StepKind.AUTHORIZATIONS -> Res.string.ceremony_step_authorizations
StepKind.SHARES_STORED -> Res.string.ceremony_step_shares_stored
}
)
@@ -7,6 +7,8 @@ import mobi.giza.compose.ui.composable.BroadcastGroupSignedEventScreen
import mobi.giza.compose.ui.composable.navigation.routes.AddGroupPostRoute
import mobi.giza.compose.ui.composable.navigation.routes.ConfederationsRoute
import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProposalRoute
import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRitualRoute
import mobi.giza.compose.ui.composable.ConfederationRitualScreen
import mobi.giza.compose.ui.composable.ConfederationProposalScreen
import mobi.giza.compose.ui.composable.navigation.routes.ProposeConfederationRoute
import mobi.giza.compose.ui.composable.ConfederationsScreen
@@ -1317,6 +1319,16 @@ fun GizaNavHost(
onNavigateBack = { navController.popBackStack() }
)
}
composable<ConfederationRitualRoute> { backStackEntry ->
val route = backStackEntry.toRoute<ConfederationRitualRoute>()
ConfederationRitualScreen(
activeUserPublicKey = route.activeUserPublicKey,
proposalId = route.proposalId,
confederationRepository = databaseConfederationRepository,
onNavigateBack = { navController.popBackStack() }
)
}
composable<ProposeConfederationRoute> { backStackEntry ->
val route = backStackEntry.toRoute<ProposeConfederationRoute>()
@@ -0,0 +1,10 @@
package mobi.giza.compose.ui.composable.navigation.routes
import kotlinx.serialization.Serializable
/** A confederation's key ceremony, by the proposal it forms. docs/confederation.md, Phase 11. */
@Serializable
data class ConfederationRitualRoute(
val activeUserPublicKey: String,
val proposalId: String,
): Route()
@@ -893,6 +893,9 @@ private fun RitualNotice(
ChatMessage.TYPE_CONFEDERATION_ACCEPTED -> Icons.Default.CheckCircle
ChatMessage.TYPE_CONFEDERATION_REJECTED -> Icons.Default.Block
ChatMessage.TYPE_CONFEDERATION_WITHDRAWN -> Icons.Default.Undo
ChatMessage.TYPE_CONFEDERATION_CEREMONY_STARTED -> Icons.Default.Key
ChatMessage.TYPE_CONFEDERATION_CEREMONY_COMPLETE -> Icons.Default.CheckCircle
ChatMessage.TYPE_CONFEDERATION_CEREMONY_FAILED -> Icons.Default.ErrorOutline
else -> Icons.Default.PanTool
@@ -51,7 +51,8 @@ class ConfederationProposalViewModel(
combine(
confederationRepository.observeStatus(proposalId),
confederationRepository.observePendingAnswer(chatRoomId, proposalId),
) { status, pending -> status to pending }.collect { (status, pending) ->
confederationRepository.observeCeremony(proposalId),
) { status, pending, ceremony -> Triple(status, pending, ceremony) }.collect { (status, pending, ceremony) ->
if (status == null) {
state.value = ConfederationProposalUIState.NotHeld
return@collect
@@ -71,6 +72,7 @@ class ConfederationProposalViewModel(
} else {
null
},
ceremony = ceremony,
)
}
}
@@ -84,6 +86,20 @@ class ConfederationProposalViewModel(
confederationRepository.proposeRejection(loaded.localChatRoom, activeUserPublicKey, proposalId, reason.trim())
}
/** Opens the key ceremony, on the coordinator's device. docs/confederation.md, Phase 11. */
fun openCeremony(onSuccess: () -> Unit, onFailure: () -> Unit) {
val loaded = state.value as? ConfederationProposalUIState.Loaded ?: return
if (loaded.isActing) return
state.update { (it as? ConfederationProposalUIState.Loaded)?.copy(isActing = true) ?: it }
viewModelScope.launch(Dispatchers.IO) {
val opened = runCatching { confederationRepository.openCeremony(proposalId) }
.onFailure { logger.e("Could not open the key ceremony for $proposalId", it) }
.isSuccess
state.update { (it as? ConfederationProposalUIState.Loaded)?.copy(isActing = false) ?: it }
viewModelScope.launch(Dispatchers.Main) { if (opened) onSuccess() else onFailure() }
}
}
fun withdraw(onSuccess: (String) -> Unit, onFailure: () -> Unit) = act(onSuccess, onFailure) { loaded ->
confederationRepository.proposeWithdrawal(loaded.localChatRoom, activeUserPublicKey, proposalId)
}
@@ -0,0 +1,113 @@
package mobi.giza.compose.ui.view.model
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import co.touchlab.kermit.Logger
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents
import mobi.giza.compose.repository.ConfederationRepository
import mobi.giza.compose.ui.view.state.ConfederationRitualUIState
import mobi.giza.compose.ui.view.state.ConfederationRitualUIState.Step
import mobi.giza.compose.ui.view.state.ConfederationRitualUIState.StepKind
/**
* A confederation's key ceremony, watched as its messages arrive (docs/confederation.md,
* Phase 11): who is in it, and for each step whom it is still waiting on, named rather than
* counted, because "17 of 21" does not say whose door to knock on.
*/
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
class ConfederationRitualViewModel(
val activeUserPublicKey: HexKey,
val proposalId: HexKey,
initialConfederationRitualUIState: ConfederationRitualUIState,
val confederationRepository: ConfederationRepository,
) : ViewModel() {
private val logger = Logger.withTag("ConfederationRitualViewModel")
private val state = MutableStateFlow(initialConfederationRitualUIState)
val uiState: StateFlow<ConfederationRitualUIState> = state.asStateFlow()
fun initiate() {
viewModelScope.launch(Dispatchers.IO) {
confederationRepository.observeCeremony(proposalId)
.flatMapLatest { ceremony ->
if (ceremony == null) flowOf(null to emptyList())
else confederationRepository.observeCeremonyMessages(ceremony.id).combine(flowOf(ceremony)) { m, c -> c to m }
}
.collectLatest { (ceremony, messages) ->
if (ceremony == null) {
state.value = ConfederationRitualUIState.NotHeld
return@collectLatest
}
val plan = confederationRepository.ceremonyPlan(ceremony) ?: run {
state.value = ConfederationRitualUIState.NotHeld
return@collectLatest
}
val names = (plan.people + plan.groups).associateWith { confederationRepository.nameOf(it) }
val sent = { kind: Int -> messages.filter { it.kind == kind }.map { it.senderPublicKey }.toSet() }
val waiting = { kind: Int -> plan.people.filterNot { it in sent(kind) }.map { names.getValue(it) } }
val combined = messages.any { it.kind == ConfederationRitualEvents.BROADCAST }
val acting = (state.value as? ConfederationRitualUIState.Loaded)?.isActing == true
state.value = ConfederationRitualUIState.Loaded(
ceremony = ceremony,
name = plan.proposal.name,
groups = plan.groups.map { group ->
val list = plan.adminLists.getValue(group)
ConfederationRitualUIState.GroupRoles(names.getValue(group), list.threshold, list.admins.map { names[it] ?: it.take(8) })
},
threshold = plan.proposal.threshold,
steps = listOf(
Step(StepKind.HOST_KEYS, waiting(ConfederationRitualEvents.HOST_KEYS)),
Step(StepKind.CONTRIBUTIONS, waiting(ConfederationRitualEvents.DEALINGS)),
Step(StepKind.COMBINED, if (combined) emptyList() else listOf(names[ceremony.coordinatorPublicKey] ?: ceremony.coordinatorPublicKey.take(8))),
Step(StepKind.AUTHORIZATIONS, waiting(ConfederationRitualEvents.AUTHORIZATIONS)),
Step(StepKind.SHARES_STORED, waiting(ConfederationRitualEvents.ACKNOWLEDGMENTS)),
),
awaitingJoin = ceremony.isRunning && ceremony.approvedAt == null,
isActing = acting,
)
}
}
}
fun join() = act { confederationRepository.joinCeremony(it) }
fun abandon() = act { confederationRepository.abandonCeremony(it) }
private fun act(action: suspend (String) -> Unit) {
val loaded = state.value as? ConfederationRitualUIState.Loaded ?: return
if (loaded.isActing) return
state.update { (it as? ConfederationRitualUIState.Loaded)?.copy(isActing = true) ?: it }
viewModelScope.launch(Dispatchers.IO) {
runCatching { action(loaded.ceremony.id) }.onFailure { logger.e("Ceremony action failed", it) }
state.update { (it as? ConfederationRitualUIState.Loaded)?.copy(isActing = false) ?: it }
}
}
companion object {
fun factory(
activeUserPublicKey: HexKey,
proposalId: HexKey,
initialConfederationRitualUIState: ConfederationRitualUIState = ConfederationRitualUIState.Loading,
confederationRepository: ConfederationRepository,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
ConfederationRitualViewModel(activeUserPublicKey, proposalId, initialConfederationRitualUIState, confederationRepository)
}
}
}
}
@@ -3,6 +3,7 @@ package mobi.giza.compose.ui.view.state
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.managers.ConfederationManager
import mobi.giza.compose.database.model.ConfederationCeremony
import mobi.giza.compose.nostr.confederation.ConfederationStatus
/** One proposal, seen from one of the groups it names (docs/confederation.md, Phase 7). */
@@ -19,6 +20,8 @@ sealed interface ConfederationProposalUIState {
val isActing: Boolean = false,
/** On the coordinator's device once every group has accepted: what it can say about forming it. */
val outcome: ConfederationManager.Outcome? = null,
/** The key ceremony this device holds for the proposal, once one is open. */
val ceremony: ConfederationCeremony? = null,
) : ConfederationProposalUIState {
private val roomId get() = localChatRoom.chatRoom.id
@@ -0,0 +1,28 @@
package mobi.giza.compose.ui.view.state
import mobi.giza.compose.database.model.ConfederationCeremony
/** A confederation's key ceremony on this device (docs/confederation.md, Phase 11). */
sealed interface ConfederationRitualUIState {
data class Loaded(
val ceremony: ConfederationCeremony,
val name: String,
/** Each group, its threshold, and its admins by name. */
val groups: List<GroupRoles>,
val threshold: Int,
/** Each step, in order, and who it is still waiting on. Empty for a step that is done. */
val steps: List<Step>,
val awaitingJoin: Boolean,
val isActing: Boolean = false,
) : ConfederationRitualUIState
data class GroupRoles(val name: String, val threshold: Int, val admins: List<String>)
enum class StepKind { HOST_KEYS, CONTRIBUTIONS, COMBINED, AUTHORIZATIONS, SHARES_STORED }
data class Step(val kind: StepKind, val waitingOn: List<String>)
data object NotHeld : ConfederationRitualUIState
data object Loading : ConfederationRitualUIState
}
@@ -65,11 +65,11 @@ class ShippedProfileUpgradeJvmTest {
* The schema version this branch builds: 38 for share generations, 39 for share
* refresh and 40 for share repair (docs/frost-share-refresh.md, Phases 6, 7 and
* 10), 41 for governance proposals and 42 for what follows them
* (docs/member-admin-promotion.md, Phases 5, 8 and 9), and 43 for the confederation
* (docs/confederation.md, Phase 4), so the upgrade crosses seven generated migrations
* and the file has to come out at the last.
* (docs/member-admin-promotion.md, Phases 5, 8 and 9), 43 for the confederation
* (docs/confederation.md, Phase 4) and 44 for its key ceremony (Phase 11), so the upgrade
* crosses eight generated migrations and the file has to come out at the last.
*/
private val current = 43
private val current = 44
private val directory: File = Files.createTempDirectory("giza-shipped-profile").toFile()
private val file: File = File(directory, "aux.db")
@@ -0,0 +1,306 @@
package mobi.giza.compose.managers
import androidx.room3.Room
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import fr.acinq.bitcoin.ByteVector
import fr.acinq.bitcoin.ByteVector32
import fr.acinq.bitcoin.Crypto
import fr.acinq.bitcoin.PrivateKey
import fr.acinq.bitcoin.crypto.confederation.Confederation
import fr.acinq.bitcoin.crypto.confederation.ConfederationKeyState
import fr.acinq.bitcoin.crypto.confederation.ConfederationRecoveryPackage
import fr.acinq.bitcoin.crypto.confederation.ConfederationRoleId
import fr.acinq.bitcoin.crypto.confederation.ConfederationRoster
import fr.acinq.bitcoin.crypto.confederation.ConfederationShare
import fr.acinq.bitcoin.crypto.confederation.ConfederationSignerSelection
import fr.acinq.bitcoin.crypto.confederation.ConfederationTweak
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlin.time.Clock
import kotlin.time.Instant
import kotlinx.coroutines.runBlocking
import mobi.giza.compose.ConfederationFixture
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.builder.getRoomDatabase
import mobi.giza.compose.database.model.ConfederationCeremony
import mobi.giza.compose.database.model.ConfederationCeremonyStage
import mobi.giza.compose.database.model.GiftWrapPayload
import mobi.giza.compose.database.model.NostrEvent
import mobi.giza.compose.database.model.Profile
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.extensions.toHex
import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents
import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder
/**
* A confederation's key ceremony across devices, one person to a device (docs/confederation.md,
* Phase 11): gift wraps ferried between devices, every round run by `ConfederationDkg` on the
* device of the role it belongs to, and at the end the same key on every device -- a key that
* signs as the confederation's room, once each device's recovery package is opened back into its
* share.
*/
class ConfederationCeremonyJvmTest {
private fun secret(n: Int) = PrivateKey(ByteArray(32).also { it[0] = 0x61; it[31] = n.toByte() })
private fun npub(key: PrivateKey): HexKey = key.publicKey().xOnly().value.toHex()
private val groupKeys = (1..3).map { secret(it) }
private val groups = groupKeys.map(::npub)
private inner class Device(val secret: PrivateKey, val db: GizaDatabase) {
val person = npub(secret)
lateinit var room: LocalChatRoom
val received = mutableSetOf<String>()
}
private val devices = mutableMapOf<HexKey, Device>()
@AfterTest
fun close() {
RoomAdmins.override = null
devices.values.forEach { it.db.close() }
}
/** Sets up the three groups' admins, a device each, and the signed proposal with every acceptance. */
private fun network(adminsByGroup: List<List<Int>>, coordinatorIndex: Int = adminsByGroup[0][0]): Pair<Device, HexKey> = runBlocking {
val people = adminsByGroup.flatten().distinct().map(::secret)
val coordinator = npub(secret(coordinatorIndex))
val now = Clock.System.now().epochSeconds
val proposal = ConfederationTestGroups.proposal(groupKeys[0], groups, coordinator, createdAt = now - 10, expiresAt = now + 1000)
val acceptances = groupKeys.mapIndexed { i, key ->
ConfederationTestGroups.acceptance(key, proposal, adminsByGroup[i].map { npub(secret(it)) }, threshold = 2)
}
people.forEach { key ->
val db = getRoomDatabase(Room.inMemoryDatabaseBuilder<GizaDatabase>())
(people.map(::npub) + groups).forEach { member ->
val eventId = Crypto.sha256(member.encodeToByteArray()).toHex()
db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = member, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)))
// Every profile resolved: D2's check at the coordinator is Part A's, not this test's.
db.profileDao().upsert(Profile(publicKey = member, nostrEventId = eventId, displayName = member.take(6), createdAt = Instant.fromEpochSeconds(1_790_000_000)))
}
devices[npub(key)] = Device(key, db)
}
val host = devices.getValue(coordinator)
(listOf(proposal) + acceptances).forEach { ConfederationManager.record(host.db, it) }
host to proposal.id
}
/** The coordinator opens; every other device gets the room the opening's p-tags name. */
private fun open(host: Device, proposalId: HexKey): ConfederationCeremony = runBlocking {
val ceremony = ConfederationRitualManager.open(host.db, proposalId, host.secret)
host.room = host.db.chatRoomDao().findChatRoomById(ceremony.chatRoomId)!!
devices.values.filter { it !== host }.forEach { device ->
device.room = device.db.nostrNip17Dao().createNip17ChatRoom(
userPublicKey = device.person,
participantPublicKeys = devices.keys.filter { it != device.person },
subject = "Atlas",
)!!
assertEquals(ceremony.chatRoomId, device.room.chatRoom.id, "every device lands in the same room")
}
ceremony
}
/** Ferries every queued ceremony message to every device it is addressed to, until nothing moves. */
private fun pump(tamper: (GiftWrapPayload) -> GiftWrapPayload = { it }) = runBlocking {
var moved = true
while (moved) {
moved = false
for (from in devices.values) for (to in devices.values) {
if (from === to) continue
from.db.giftWrapPayloadDao().getByChatRoomAndKinds(from.room.chatRoom.id, ConfederationRitualEvents.ALL.toList())
.filter { it.publicKey == from.person }
.sortedBy { it.createdAt }
.forEach { original ->
if (!to.received.add(original.id)) return@forEach
moved = true
val queued = tamper(original)
to.db.giftWrapPayloadDao().upsert(queued.copy(chatRoomId = to.room.chatRoom.id))
ConfederationRitualManager.process(
to.db, to.room,
Event(queued.id, queued.publicKey, queued.createdAt.epochSeconds, queued.kind, queued.tags, queued.content, ""),
to.person, to.secret.value.toByteArray(),
)
}
}
}
}
private fun joinAll(sessionId: String, except: Set<HexKey> = emptySet()) = runBlocking {
devices.values.filter { it.person !in except }.forEach { ConfederationRitualManager.join(it.db, sessionId, it.secret.value.toByteArray()) }
}
private fun ceremonies(sessionId: String) = runBlocking {
devices.values.associate { it.person to it.db.confederationCeremonyDao().getCeremony(sessionId) }
}
/** Every role's share, opened from the recovery package its device kept. */
private fun shares(sessionId: String): Pair<ConfederationKeyState, Map<ConfederationRoleId, Pair<ConfederationShare, PrivateKey>>> = runBlocking {
val any = devices.values.first().db.confederationCeremonyDao().getCeremony(sessionId)!!
val plan = (ConfederationRitualManager.planFrom(ConfederationRitualEvents.Opening.decode(any.openingJson)!!) as fr.acinq.bitcoin.utils.Either.Right).value
val hostKeys = plan.seats.associate { seat ->
seat.roleId to ConfederationRosterBuilder.hostPublicKey(devices.getValue(seat.admin).secret.value.toByteArray(), seat.group, plan.proposal.id)
}
val roster: ConfederationRoster = plan.roster(hostKeys).right!!
val keyState = ConfederationKeyState.fromData(ByteVector(any.keyState!!), roster).right!!
keyState to plan.seats.associate { seat ->
val device = devices.getValue(seat.admin)
val ceremony = device.db.confederationCeremonyDao().getCeremony(sessionId)!!
val hex = ConfederationRitualEvents.decodeByGroup(ceremony.recoveryPackages!!)!!.getValue(seat.group)
val host = ConfederationRosterBuilder.hostSecretKey(device.secret.value.toByteArray(), seat.group, plan.proposal.id)
val recovery = ConfederationRecoveryPackage.fromData(ByteVector(hex), host).right!!
seat.roleId to (recovery.open(host, keyState).right!! to host)
}
}
@Test
fun `three groups of three make one key, the same on every device, that signs as the room`() {
val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33)))
val opened = open(host, proposalId)
pump()
joinAll(opened.id)
pump()
val all = ceremonies(opened.id)
all.forEach { (person, ceremony) -> assertEquals(ConfederationCeremonyStage.COMPLETE, ceremony?.stage, "${person.take(6)}: ${ceremony?.failureReason}") }
assertEquals(1, all.values.map { it!!.confederationPublicKey }.toSet().size, "one key, everywhere")
assertEquals(1, all.values.map { it!!.genesis }.toSet().size, "one certified genesis, assembled on each device")
all.values.forEach { assertNull(it!!.dealerSeeds, "dealer seeds erased once dealt") }
val (keyState, held) = shares(opened.id)
val threshold = "02" + keyState.publicKey.value.toHex()
val derived = SharedKeyDerivation.derive(threshold)
val selection = ConfederationSignerSelection(mapOf(0u to setOf(0u, 1u), 1u to setOf(0u, 2u)))
val message = ByteVector32(Crypto.sha256("the first words of a group of groups".encodeToByteArray()))
val signature = Confederation.signLocal(
keyState, held.mapValues { it.value.first }, held.mapValues { it.value.second }, selection,
derived.tweaks.map { ConfederationTweak(it, isXonly = true) },
ByteVector32(Crypto.sha256("attempt".encodeToByteArray())), message, ConfederationFixture.nonces(3, selection),
).right!!
assertTrue(Crypto.verifySignatureSchnorr(message, signature, derived.publicKey))
assertEquals(SharedKeyDerivation.marmotGroupId(threshold), derived.hex)
}
@Test
fun `a person who is an admin of two groups takes part once, with two roles`() {
val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(11, 22, 23), listOf(31, 32, 33)))
val opened = open(host, proposalId)
assertEquals(8, devices.size)
pump()
joinAll(opened.id)
pump()
ceremonies(opened.id).values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) }
val packages = ConfederationRitualEvents.decodeByGroup(ceremonies(opened.id).getValue(npub(secret(11)))!!.recoveryPackages!!)!!
assertEquals(setOf(groups[0], groups[1]), packages.keys)
}
@Test
fun `nobody moves until they join, and an admin who never joins stalls it until somebody abandons`() {
val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33)))
val opened = open(host, proposalId)
pump()
val holdout = npub(secret(33))
ceremonies(opened.id).filterKeys { it != host.person }.values.forEach { assertTrue(ConfederationRitualManager.isAwaitingJoin(it!!)) }
joinAll(opened.id, except = setOf(holdout))
pump()
ceremonies(opened.id).filterKeys { it != holdout }.values.forEach {
assertEquals(ConfederationCeremonyStage.COLLECTING_HOST_KEYS, it?.stage)
}
runBlocking { ConfederationRitualManager.abandon(devices.getValue(npub(secret(21))).db, opened.id) }
pump()
ceremonies(opened.id).values.forEach { assertEquals(ConfederationCeremonyStage.FAILED, it?.stage) }
}
@Test
fun `a key that does not open an acceptance is refused before anybody joins`() {
val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33)))
val opened = open(host, proposalId)
pump { payload ->
if (payload.kind != ConfederationRitualEvents.OPENING) return@pump payload
val opening = ConfederationRitualEvents.Opening.decode(payload.content)!!
val wrongKeys = opening.conversationKeys.mapValues { "11".repeat(32) }
payload.copy(content = opening.copy(conversationKeys = wrongKeys).encode())
}
ceremonies(opened.id).filterKeys { it != host.person }.values.forEach {
assertNotNull(it)
assertEquals(ConfederationCeremonyStage.FAILED, it.stage)
assertTrue(it.failureReason!!.contains("does not open"), it.failureReason)
assertNull(it.approvedAt, "nobody was asked")
}
assertEquals(ConfederationCeremonyStage.FAILED, ceremonies(opened.id).getValue(host.person)?.stage, "the coordinator hears why")
}
@Test
fun `a coordinator's roster that is not the one every device built ends it`() {
val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33)))
val opened = open(host, proposalId)
pump()
joinAll(opened.id)
pump { payload ->
if (payload.kind != ConfederationRitualEvents.BROADCAST) return@pump payload
val sent = ConfederationRitualEvents.Broadcast.decode(payload.content)!!
payload.copy(content = sent.copy(roster = sent.roster.dropLast(2) + "00").encode())
}
ceremonies(opened.id).filterKeys { it != host.person }.values.forEach {
assertEquals(ConfederationCeremonyStage.FAILED, it?.stage)
}
}
@Test
fun `a device whose group's admins changed since it accepted refuses to join`() {
val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33)))
// Device 22 holds Polis's room, and sees a fourth admin there now.
val polisMember = devices.getValue(npub(secret(22)))
runBlocking {
polisMember.db.chatRoomDao().upsert(
mobi.giza.compose.database.model.ChatRoom(id = groups[1], userPublicKey = polisMember.person, subject = "#Polis", description = null, mlsGroupState = "00")
)
polisMember.db.dkgSessionDao().upsert(
mobi.giza.compose.database.model.DkgSession(
id = "k".repeat(64), chatRoomId = groups[1], coordinatorPublicKey = polisMember.person, userPublicKey = polisMember.person,
threshold = 2, participantCount = 4, stage = mobi.giza.compose.database.model.types.DkgRitualStage.COMPLETE,
hostPublicKey = "02".padEnd(66, '0'), round1Random = "1".repeat(64), round2AuxRandom = "2".repeat(64),
)
)
}
RoomAdmins.override = { id ->
if (id == groups[1]) RoomAdmins(setOf(21, 22, 23, 24).map { npub(secret(it)) }.toSet(), governed = false) else null
}
val opened = open(host, proposalId)
pump()
val refused = ceremonies(opened.id).getValue(polisMember.person)
assertEquals(ConfederationCeremonyStage.FAILED, refused?.stage, "refused")
assertTrue(refused!!.failureReason!!.contains("have changed since it accepted"), refused.failureReason)
}
@Test
fun `messages that arrive before the opening are replayed when it comes`() {
val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33)))
val opened = open(host, proposalId)
val late = devices.getValue(npub(secret(32)))
// Everybody else hears the opening and joins; the late device hears nothing yet.
val others = devices.values.filter { it !== late }
runBlocking {
others.filter { it !== host }.forEach { to ->
host.db.giftWrapPayloadDao().getByChatRoomAndKinds(host.room.chatRoom.id, listOf(ConfederationRitualEvents.OPENING)).forEach { q ->
to.received += q.id
ConfederationRitualManager.process(to.db, to.room, Event(q.id, q.publicKey, q.createdAt.epochSeconds, q.kind, q.tags, q.content, ""), to.person, to.secret.value.toByteArray())
}
}
}
joinAll(opened.id, except = setOf(late.person))
// Then everything, the opening last of all for the late device.
pump { it }
runBlocking { ConfederationRitualManager.join(late.db, opened.id, late.secret.value.toByteArray()) }
pump()
ceremonies(opened.id).values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) }
}
}
@@ -22,6 +22,9 @@ import mobi.giza.compose.repository.NostrRepository
import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost
import mobi.giza.compose.ui.theme.GizaTheme
import mobi.giza.compose.ui.view.state.ConfederationProposalUIState
import mobi.giza.compose.ui.view.state.ConfederationRitualUIState
import mobi.giza.compose.database.model.ConfederationCeremony
import mobi.giza.compose.database.model.ConfederationCeremonyStage
import mobi.giza.compose.ui.view.state.ConfederationsUIState
import mobi.giza.compose.ui.view.state.ProposeConfederationUIState
import mobi.giza.compose.ui.view.state.ProposeConfederationUIState.GroupLookup
@@ -205,4 +208,63 @@ class ConfederationScreensJvmTest {
}
assertions()
}
private fun ceremony(stage: ConfederationCeremonyStage, approved: Boolean, failure: String? = null) = ConfederationCeremony(
id = "s".repeat(64), chatRoomId = roomId, proposalId = "p".padEnd(64, '0'), coordinatorPublicKey = polis,
userPublicKey = "a".repeat(64), openingJson = "{}", stage = stage,
approvedAt = if (approved) kotlin.time.Instant.fromEpochSeconds(1) else null, failureReason = failure,
)
private fun ritual(stage: ConfederationCeremonyStage, approved: Boolean, failure: String? = null, waiting: List<String> = listOf("Bo")) =
ConfederationRitualUIState.Loaded(
ceremony = ceremony(stage, approved, failure),
name = "Atlas",
groups = listOf(
ConfederationRitualUIState.GroupRoles("Polis", 2, listOf("Ana", "Bo", "Cy")),
ConfederationRitualUIState.GroupRoles("Agora", 2, listOf("Di", "Ed", "Fi")),
),
threshold = 2,
steps = ConfederationRitualUIState.StepKind.entries.map { ConfederationRitualUIState.Step(it, if (it.ordinal == 0) waiting else listOf("Ana", "Bo")) },
awaitingJoin = !approved && stage != ConfederationCeremonyStage.FAILED,
)
@Test
fun `a member is asked to join, and told what joining gives them`() = renderRitual(ritual(ConfederationCeremonyStage.WAITING_TO_JOIN, approved = false)) {
onNodeWithText("Join the key ceremony").assertIsDisplayed()
onNodeWithText("Joining gives you a share", substring = true).assertIsDisplayed()
onNodeWithText("Polis: 2 of 3 admins to sign").assertIsDisplayed()
}
@Test
fun `a running ceremony names whom each step waits on, and can be abandoned`() = renderRitual(ritual(ConfederationCeremonyStage.COLLECTING_HOST_KEYS, approved = true)) {
onAllNodesWithText("Join the key ceremony").assertCountEquals(0)
onNodeWithText("Waiting on Bo").assertIsDisplayed()
onNodeWithText("Abandon the key ceremony").assertIsDisplayed()
}
@Test
fun `an ended ceremony says why`() = renderRitual(ritual(ConfederationCeremonyStage.FAILED, approved = true, failure = "Abandoned by a participant")) {
onNodeWithText("The ceremony ended: Abandoned by a participant").assertIsDisplayed()
onAllNodesWithText("Abandon the key ceremony").assertCountEquals(0)
}
private fun renderRitual(state: ConfederationRitualUIState, assertions: ComposeUiTest.() -> Unit) =
runDesktopComposeUiTest(width = 400, height = 3000) {
setContent {
GizaTheme {
ProvideSnackbarHost {
Box(modifier = Modifier.fillMaxSize()) {
ConfederationRitualScreen(
activeUserPublicKey = "a".repeat(64),
proposalId = "p".padEnd(64, '0'),
initialConfederationRitualUIState = state,
confederationRepository = ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY,
onNavigateBack = {},
)
}
}
}
}
assertions()
}
}
+1
View File
@@ -75,6 +75,7 @@ the reasoning. Where the build chose differently:
| 7 | done but for the badge. `ConfederationProposalScreen`, opened from each card: the proposal, its coordinator, every group's answer, and for a member with a share either both answers (in an invited group that has not answered) or withdrawal (in the proposing group), giving way to a pending answer's session. The approval screen shows D6's notes: the groups by name, `T`, the coordinator, what an acceptance discloses, and each listed group with no public profile on this device, as a warning. `ConfederationNetworkJvmTest` 3/3 is the plan's three-group run: real FROST signatures per group, relays as copies, every device on every group agreeing on `REJECTED` and then on `ACCEPTED`, and the coordinator opening each group's admins. It found answers filed before their proposal losing their line, since a proposal and its proposer's acceptance share a second and relay order is by id; a proposal now writes the lines for answers already held. **Not done:** invitations do not feed `observeProposalsAwaitingYou`, which is FROST-session shaped; the transcript line is the notice. jvmTest 1,598 |
| 8 | done. `ConfederationManager.outcome` on the coordinator's device opens each acceptance with the active identity's key, checks each list names its group and proposal, counts roles (refusing more than 128, noting more than 16), names any listed group with no public profile on this device as what stands in the way, and lists admins who sit in more than one group. The proposal screen shows it once every group has accepted, ending on "the confederation's key ceremony is not available in this version yet". Withdrawal was built with the answers in Phases 3 and 7. `ConfederationNetworkJvmTest` 5/5, `ConfederationStorageJvmTest` 11/11 |
| 10 | done. `ConfederationRosterBuilder` writes upstream's RPD bytes itself, since `ConfederationRoster` has only `fromData`: big-endian, a 96-byte header, 20 bytes a group, 69 a role. `plan` refuses rather than repairs (a list for another group or proposal, a missing acceptance, more than 128 roles). Host keys are `sha256(HOST_KEY_TAG ‖ nsec ‖ group ‖ proposal id)`, so one person holds a different key per role and per confederation. `ConfederationRosterBuilderJvmTest` 7/7: the roster parses, is byte-identical under any input order, and its `dkgLocal` key signs as the room's id |
| 11 | done. `ConfederationRitualManager` over upstream's `ConfederationDkg`, in a NIP-17 room the coordinator opens over every admin (with placeholder profiles for members this device has none for). Kinds 30380 (opening), 30381 (host keys), 30382 (dealings), 30383 (roster and broadcast), 30384 (authorizations), 30385 (acknowledgments), 30387 (failure). One message per person per step, one value per role, keyed by group. **No 30386:** every device assembles the certified genesis itself from evidence it already holds, so nobody can hand one over. **No investigation (30388):** a decryption fault names "a participant or the coordinator" and ends the ceremony. Before joining, a device checks the proposal and acceptances are their groups' own, every acceptance opens with its disclosed key, the room is exactly the roster's people, and each group it is in still has the admins it accepted with, compared on their own so a member without a share still checks. Joining is the only approval; dealer seeds are erased once dealt; every role derives its key state itself and the coordinator's roster must match byte for byte. Schema 44. The coordinator opens it by a button on the proposal screen rather than on its own. `ConfederationRitualScreen`, with a join, each step's named waits and abandon. `ConfederationCeremonyJvmTest` 7/7: three groups of three on nine devices reach one key that signs as the room once each recovery package is opened; one person in two groups; a holdout and abandon; a disclosed key that does not open; a substituted roster; admins changed; messages before the opening. jvmTest 1,619 |
---