feat: what a finished ceremony leaves: the confederation, certified (confederation, Phase 12)

Every device that took part files the confederation under the room id
its key derives, as upstream's canonical roster, key state and genesis,
with its own shares kept as recovery packages. The genesis is verified
against the key state before anything is written, and each of the
device's own member groups gets a line saying it is part of it now.

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:38:20 +02:00
1 parent 02f041431a
commit 615afc30a1
16 files changed
+362 -8

No files matched your search

@@ -738,4 +738,5 @@
<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>
<string name="confederation_formed">Formed</string>
</resources>
@@ -66,7 +66,9 @@ 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.Confederation
import mobi.giza.compose.database.model.ConfederationCeremony
import mobi.giza.compose.database.model.ConfederationMember
import mobi.giza.compose.database.model.ConfederationCeremonyMessage
import mobi.giza.compose.database.model.ConfederationEvent
import mobi.giza.compose.database.model.ConfederationInvitee
@@ -133,7 +135,9 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
ChatMessageBroadcastNostrEventReceiptRelation::class,
ChatMessageNostrEventRelation::class,
ChatRoom::class,
Confederation::class,
ConfederationCeremony::class,
ConfederationMember::class,
ConfederationCeremonyMessage::class,
ConfederationEvent::class,
ConfederationInvitee::class,
@@ -453,9 +457,9 @@ 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.
// v44 adds the confederation's key ceremony and what it forms (docs/confederation.md,
// Phases 11 and 12): ConfederationCeremony, ConfederationCeremonyMessage, Confederation
// and ConfederationMember. New tables only, so Room generates it.
AutoMigration(from = 43, to = 44),
]
)
@@ -44,4 +44,22 @@ interface ConfederationCeremonyDao {
/** 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
@Query("SELECT * FROM Confederation WHERE id = :id")
suspend fun getConfederation(id: HexKey): mobi.giza.compose.database.model.Confederation?
@Query("SELECT * FROM Confederation WHERE proposalId = :proposalId")
suspend fun getConfederationForProposal(proposalId: HexKey): mobi.giza.compose.database.model.Confederation?
@Query("SELECT * FROM Confederation ORDER BY createdAt DESC")
fun observeConfederations(): Flow<List<mobi.giza.compose.database.model.Confederation>>
@Query("SELECT c.* FROM Confederation c JOIN ConfederationMember m ON m.confederationId = c.id WHERE m.groupPublicKey = :groupPublicKey ORDER BY c.createdAt DESC")
fun observeConfederationsOf(groupPublicKey: HexKey): Flow<List<mobi.giza.compose.database.model.Confederation>>
@Upsert
suspend fun upsertConfederation(confederation: mobi.giza.compose.database.model.Confederation)
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertMembers(members: List<mobi.giza.compose.database.model.ConfederationMember>)
}
@@ -541,6 +541,9 @@ data class ChatMessage(
const val TYPE_CONFEDERATION_CEREMONY_COMPLETE = "confederationCeremonyComplete"
const val TYPE_CONFEDERATION_CEREMONY_FAILED = "confederationCeremonyFailed"
/** A group's room, on its admins' devices: the group is now part of a formed confederation (Phase 12). */
const val TYPE_CONFEDERATION_FORMED = "confederationFormed"
val CONFEDERATION_TYPES = setOf(
TYPE_CONFEDERATION_PROPOSED,
TYPE_CONFEDERATION_ACCEPTED,
@@ -549,6 +552,7 @@ data class ChatMessage(
TYPE_CONFEDERATION_CEREMONY_STARTED,
TYPE_CONFEDERATION_CEREMONY_COMPLETE,
TYPE_CONFEDERATION_CEREMONY_FAILED,
TYPE_CONFEDERATION_FORMED,
)
val GROUP_IDENTITY_TYPES = setOf(
@@ -0,0 +1,47 @@
package mobi.giza.compose.database.model
import androidx.room3.Entity
import androidx.room3.Index
import androidx.room3.PrimaryKey
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlin.time.Clock
import kotlin.time.Instant
/**
* A confederation this device holds a part of, once its key ceremony has finished
* (docs/confederation.md, Phase 12).
*
* Its descriptors are kept as upstream's canonical bytes -- roster, key state, certified genesis --
* so nothing depends on the build that wrote them, with the `(configSeq, rpdHash, ksdHash)` triple
* upstream says an application must persist to accept only a direct successor later. This
* device's shares are kept only as their recovery packages: "a share has no canonical encoding".
*
* The id is the confederation's room id, derived from its key the way every keyed room's is (D10),
* whether or not that room exists yet.
*/
@Entity(indices = [Index("proposalId")])
data class Confederation(
@PrimaryKey
val id: HexKey,
/** The confederation's key X, x-only. */
val publicKey: HexKey,
val proposalId: HexKey,
val ceremonyId: String,
val name: String,
val roster: String,
val keyState: String,
val genesis: String,
val configSeq: Long,
val rosterHash: HexKey,
val keyStateHash: HexKey,
/** This device's roles, by group: each one's recovery package. */
val recoveryPackages: String,
val createdAt: Instant = Clock.System.now(),
)
/** A group that is part of a confederation, so a group's screen can find its confederations. */
@Entity(primaryKeys = ["confederationId", "groupPublicKey"], indices = [Index("groupPublicKey")])
data class ConfederationMember(
val confederationId: HexKey,
val groupPublicKey: HexKey,
)
@@ -12,6 +12,7 @@ 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.Confederation
import mobi.giza.compose.database.model.ConfederationCeremony
import mobi.giza.compose.database.model.ConfederationCeremonyMessage
import mobi.giza.compose.database.model.ConfederationEvent
@@ -58,6 +59,9 @@ class DatabaseConfederationRepository(
override suspend fun abandonCeremony(sessionId: String) = ConfederationRitualManager.abandon(database, sessionId)
override fun observeConfederationsOf(groupPublicKey: HexKey): Flow<List<Confederation>> =
database.confederationCeremonyDao().observeConfederationsOf(groupPublicKey)
override suspend fun outcome(proposalId: HexKey): ConfederationManager.Outcome? {
val secret = activeIdentity.value?.nostrPrivateKey ?: return null
return ConfederationManager.outcome(database, proposalId, secret)
@@ -0,0 +1,97 @@
package mobi.giza.compose.managers
import co.touchlab.kermit.Logger
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import fr.acinq.bitcoin.ByteVector
import fr.acinq.bitcoin.crypto.confederation.ConfederationKeyState
import fr.acinq.bitcoin.crypto.confederation.ConfederationRoster
import fr.acinq.bitcoin.crypto.confederation.ConfederationTransition
import fr.acinq.bitcoin.utils.Either
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.ChatMessage
import mobi.giza.compose.database.model.Confederation
import mobi.giza.compose.database.model.ConfederationCeremony
import mobi.giza.compose.database.model.ConfederationMember
import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder.Plan
/**
* What a finished key ceremony leaves on a device: the confederation, kept as upstream's canonical
* descriptors and this device's recovery packages (docs/confederation.md, Phase 12).
*/
object ConfederationFormation {
private val logger = Logger.withTag("ConfederationFormation")
/** The room id a confederation's key derives (D10): the same function as every keyed room's. */
fun roomIdOf(publicKey: HexKey): HexKey = SharedKeyDerivation.marmotGroupId("02$publicKey")
/**
* Files the confederation a completed [ceremony] made, once. The genesis is checked against
* the key state before anything is written -- `ConfederationTransition.fromData` verifies
* every role's host signature over it -- so a row here is a confederation every role
* certified, not one this device was told about.
*/
suspend fun onComplete(database: GizaDatabase, ceremony: ConfederationCeremony, plan: Plan, roster: ConfederationRoster): Confederation? {
val keyStateHex = ceremony.keyState ?: return null
val genesisHex = ceremony.genesis ?: return null
val packages = ceremony.recoveryPackages ?: return null
val keyState = (ConfederationKeyState.fromData(ByteVector(keyStateHex), roster) as? Either.Right)?.value ?: return null
val genesis = (ConfederationTransition.fromData(ByteVector(genesisHex), null, keyState) as? Either.Right)?.value ?: run {
logger.e("Ceremony ${ceremony.id}: the genesis does not verify against its key state; not filing it")
return null
}
val publicKey = keyState.publicKey.value.toHex()
val confederation = Confederation(
id = roomIdOf(publicKey),
publicKey = publicKey,
proposalId = plan.proposal.id,
ceremonyId = ceremony.id,
name = plan.proposal.name,
roster = roster.data.toHex(),
keyState = keyStateHex,
genesis = genesis.data.toHex(),
configSeq = roster.configSeq.toLong(),
rosterHash = roster.hash.toHex(),
keyStateHash = keyState.hash.toHex(),
recoveryPackages = packages,
)
val known = database.confederationCeremonyDao().getConfederation(confederation.id) != null
database.confederationCeremonyDao().upsertConfederation(confederation)
database.confederationCeremonyDao().insertMembers(plan.groups.map { ConfederationMember(confederation.id, it) })
if (!known) {
// A line in each of this device's own member groups' rooms. Written here, by an admin's
// device for itself: members who are not admins took no part, and hear of it only from
// a confederation statement the confederation signs (Part C).
plan.groups.forEach { group ->
if (database.chatRoomDao().findChatRoomById(group) == null) return@forEach
database.chatMessageDao().upsert(
ChatMessage(
senderPublicKey = ceremony.coordinatorPublicKey,
isUserMessage = false,
giftWrapPayloadId = null,
marmotGroupEventId = null,
marmotInnerEventId = null,
chatRoomId = group,
content = "This group is part of the confederation ${plan.proposal.name}, now formed",
messageType = ChatMessage.TYPE_CONFEDERATION_FORMED,
)
)
}
}
logger.i("Filed confederation ${confederation.id.take(12)} (${plan.proposal.name})")
return confederation
}
/**
* Whether [confederation]'s stored descriptors still read and certify its own key, and its id
* is the room that key derives: what a device checks before it takes the room for this
* confederation's (Phase 13).
*/
fun verifies(confederation: Confederation): Boolean = runCatching {
val roster = (ConfederationRoster.fromData(ByteVector(confederation.roster)) as Either.Right).value
val keyState = (ConfederationKeyState.fromData(ByteVector(confederation.keyState), roster) as Either.Right).value
ConfederationTransition.fromData(ByteVector(confederation.genesis), null, keyState) is Either.Right &&
keyState.publicKey.value.toHex() == confederation.publicKey &&
roomIdOf(confederation.publicKey) == confederation.id
}.getOrDefault(false)
}
@@ -556,11 +556,18 @@ object ConfederationRitualManager {
}
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")
ConfederationFormation.onComplete(database, ceremony, plan, roster)
}
}
// ---- helpers ---------------------------------------------------------------------------
/** The roster a ceremony ran over, once every host key is in; null before. */
internal suspend fun rosterFor(database: GizaDatabase, ceremony: ConfederationCeremony, plan: Plan): ConfederationRoster? {
val hostKeys = perRole(database, ceremony, plan, ConfederationRitualEvents.HOST_KEYS) { PublicKey(ByteVector(it)) } ?: return null
return (plan.roster(hostKeys) as? Either.Right)?.value
}
private suspend fun own(database: GizaDatabase, ceremony: ConfederationCeremony, kind: Kind) =
database.confederationCeremonyDao().getMessage(ceremony.id, ceremony.userPublicKey, kind)
@@ -5,6 +5,7 @@ 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.Confederation
import mobi.giza.compose.database.model.ConfederationCeremony
import mobi.giza.compose.database.model.ConfederationCeremonyMessage
import mobi.giza.compose.database.model.ConfederationEvent
@@ -85,6 +86,9 @@ interface ConfederationRepository {
suspend fun abandonCeremony(sessionId: String)
/** The confederations [groupPublicKey] is part of, on this device. docs/confederation.md, Phase 12. */
fun observeConfederationsOf(groupPublicKey: HexKey): Flow<List<Confederation>>
companion object {
/** Holds nothing and proposes nothing: for screens and tests with no confederation behind them. */
val NO_OP_CONFEDERATION_REPOSITORY: ConfederationRepository = object : ConfederationRepository {
@@ -121,6 +125,7 @@ interface ConfederationRepository {
throw UnsupportedOperationException("No confederation here")
override suspend fun joinCeremony(sessionId: String) = Unit
override suspend fun abandonCeremony(sessionId: String) = Unit
override fun observeConfederationsOf(groupPublicKey: HexKey): Flow<List<Confederation>> = flowOf(emptyList())
}
}
}
@@ -34,6 +34,7 @@ import mobi.giza.compose.repository.ConfederationRepository
import mobi.giza.compose.resources.Res
import mobi.giza.compose.resources.confederation_accepted
import mobi.giza.compose.resources.confederation_expired
import mobi.giza.compose.resources.confederation_formed
import mobi.giza.compose.resources.confederation_groups_to_act
import mobi.giza.compose.resources.confederation_open
import mobi.giza.compose.resources.confederation_proposed_by
@@ -174,7 +175,9 @@ private fun ConfederationProposalCard(item: ConfederationsUIState.Item, onClick:
ListItem(
leadingContent = { Icon(Icons.Default.Hub, contentDescription = Decorative) },
trailingContent = { Icon(Icons.Default.ChevronRight, contentDescription = Decorative) },
overlineContent = { Text(text = stateLabel(status.state)) },
overlineContent = {
Text(text = if (item.formed) stringResource(Res.string.confederation_formed) else stateLabel(status.state))
},
headlineContent = { Text(text = proposal.name, maxLines = 1, overflow = TextOverflow.Ellipsis) },
supportingContent = {
Column {
@@ -896,6 +896,7 @@ private fun RitualNotice(
ChatMessage.TYPE_CONFEDERATION_CEREMONY_STARTED -> Icons.Default.Key
ChatMessage.TYPE_CONFEDERATION_CEREMONY_COMPLETE -> Icons.Default.CheckCircle
ChatMessage.TYPE_CONFEDERATION_CEREMONY_FAILED -> Icons.Default.ErrorOutline
ChatMessage.TYPE_CONFEDERATION_FORMED -> Icons.Default.Hub
else -> Icons.Default.PanTool
@@ -11,6 +11,7 @@ import androidx.lifecycle.viewmodel.viewModelFactory
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
import mobi.giza.compose.repository.ChatRepository
import mobi.giza.compose.repository.ConfederationRepository
@@ -44,13 +45,17 @@ class ConfederationsViewModel(
chatRepository.canSign(chatRoomId) &&
confederationRepository.isAdmin(chatRoomId, activeUserPublicKey)
confederationRepository.observeStatusesNaming(chatRoomId).collect { statuses ->
combine(
confederationRepository.observeStatusesNaming(chatRoomId),
confederationRepository.observeConfederationsOf(chatRoomId),
) { statuses, formed -> statuses to formed.map { it.proposalId }.toSet() }.collect { (statuses, formed) ->
confederationsUIState = ConfederationsUIState.Loaded(
localChatRoom = localChatRoom,
proposals = statuses.map { status ->
ConfederationsUIState.Item(
status = status,
proposerName = confederationRepository.nameOf(status.proposal.proposingGroup, chatRoomId),
formed = status.proposal.id in formed,
)
},
canPropose = canPropose,
@@ -14,7 +14,7 @@ sealed interface ConfederationsUIState {
) : ConfederationsUIState
/** One proposal, and how to name the group that made it. */
data class Item(val status: ConfederationStatus, val proposerName: String)
data class Item(val status: ConfederationStatus, val proposerName: String, val formed: Boolean = false)
data class Error(val message: String) : ConfederationsUIState
@@ -161,6 +161,12 @@ class ConfederationCeremonyJvmTest {
@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 agoraAdmin = devices.getValue(npub(secret(12)))
runBlocking {
agoraAdmin.db.chatRoomDao().upsert(
mobi.giza.compose.database.model.ChatRoom(id = groups[0], userPublicKey = agoraAdmin.person, subject = "#Agora", description = null, mlsGroupState = "00")
)
}
val opened = open(host, proposalId)
pump()
joinAll(opened.id)
@@ -172,6 +178,20 @@ class ConfederationCeremonyJvmTest {
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") }
// Phase 12: every device files the same confederation, certified, under the room its key derives.
runBlocking {
val formed = devices.values.map { assertNotNull(it.db.confederationCeremonyDao().getConfederationForProposal(proposalId)) }
assertEquals(1, formed.map { it.id }.toSet().size)
formed.forEach { assertTrue(ConfederationFormation.verifies(it)) }
assertEquals(ConfederationFormation.roomIdOf(all.values.first()!!.confederationPublicKey!!), formed.first().id)
assertEquals(
1,
agoraAdmin.db.chatMessageDao().getChatMessagesByChatRoomId(groups[0])
.count { it.chatMessage.messageType == mobi.giza.compose.database.model.ChatMessage.TYPE_CONFEDERATION_FORMED },
"one line in the admin's own group room",
)
}
val (keyState, held) = shares(opened.id)
val threshold = "02" + keyState.publicKey.value.toHex()
val derived = SharedKeyDerivation.derive(threshold)