feat: where a device keeps what it has heard of a confederation (confederation, Phase 4)

Schema 43: ConfederationEvent for every proposal and answer, verified
as its author's before it is filed and never a NostrEvent row;
ConfederationInvitee so a room finds the proposals naming it; and
ConfederationSigning for what a signing session has to remember past
its proposal's arrival.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-21 21:47:05 +02:00
1 parent f1ad108b13
commit 8b38dc8763
8 files changed
+5946 -1

No files matched your search

@@ -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.ConfederationDao
import mobi.giza.compose.database.dao.BroadcastNostrEventRequestDao
import mobi.giza.compose.database.dao.ChatMessageBroadcastNostrEventReceiptRelationDao
import mobi.giza.compose.database.dao.ChatMessageBroadcastNostrEventRequestRelationDao
@@ -64,6 +65,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.ConfederationEvent
import mobi.giza.compose.database.model.ConfederationInvitee
import mobi.giza.compose.database.model.ConfederationSigning
import mobi.giza.compose.database.model.Connection
import mobi.giza.compose.database.model.GiftWrapMessage
import mobi.giza.compose.database.model.GiftWrapPayload
@@ -126,6 +130,9 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
ChatMessageBroadcastNostrEventReceiptRelation::class,
ChatMessageNostrEventRelation::class,
ChatRoom::class,
ConfederationEvent::class,
ConfederationInvitee::class,
ConfederationSigning::class,
DkgParticipantMessage::class,
DkgSession::class,
FrostSignerMessage::class,
@@ -173,7 +180,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
UnsignedNostrEvent::class,
Zap::class
],
version = 42,
version = 43,
autoMigrations = [
// v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can
// generate the migration itself — nothing existing changes shape.
@@ -438,6 +445,9 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
// (docs/member-admin-promotion.md, Phases 8 and 9): two nullable columns, so
// Room generates it.
AutoMigration(from = 41, to = 42),
// 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),
]
)
@ConstructedBy(GizaDatabaseConstructor::class)
@@ -464,6 +474,8 @@ abstract class GizaDatabase: RoomDatabase() {
abstract fun chatRoomDao(): ChatRoomDao
abstract fun confederationDao(): ConfederationDao
abstract fun dkgSessionDao(): DkgSessionDao
abstract fun frostSigningSessionDao(): FrostSigningSessionDao
@@ -0,0 +1,70 @@
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.Transaction
import androidx.room3.Upsert
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlinx.coroutines.flow.Flow
import mobi.giza.compose.database.model.ConfederationEvent
import mobi.giza.compose.database.model.ConfederationInvitee
import mobi.giza.compose.database.model.ConfederationSigning
import mobi.giza.compose.nostr.confederation.ConfederationKinds
@Dao
abstract class ConfederationDao {
@Query("SELECT * FROM ConfederationEvent WHERE id = :id")
abstract suspend fun getEvent(id: HexKey): ConfederationEvent?
/** A proposal and everything said about it. */
@Query("SELECT * FROM ConfederationEvent WHERE proposalId = :proposalId ORDER BY eventCreatedAt ASC, id ASC")
abstract suspend fun getEventsForProposal(proposalId: HexKey): List<ConfederationEvent>
@Query("SELECT * FROM ConfederationEvent WHERE proposalId = :proposalId ORDER BY eventCreatedAt ASC, id ASC")
abstract fun observeEventsForProposal(proposalId: HexKey): Flow<List<ConfederationEvent>>
/** Every proposal naming [groupPublicKey], its own included, newest first. */
@Query(
"SELECT e.* FROM ConfederationEvent e JOIN ConfederationInvitee i ON i.proposalId = e.id " +
"WHERE i.groupPublicKey = :groupPublicKey AND e.kind = ${ConfederationKinds.PROPOSAL} " +
"ORDER BY e.eventCreatedAt DESC, e.id DESC"
)
abstract fun observeProposalsNaming(groupPublicKey: HexKey): Flow<List<ConfederationEvent>>
@Query(
"SELECT e.* FROM ConfederationEvent e JOIN ConfederationInvitee i ON i.proposalId = e.id " +
"WHERE i.groupPublicKey = :groupPublicKey AND e.kind = ${ConfederationKinds.PROPOSAL} " +
"ORDER BY e.eventCreatedAt DESC, e.id DESC"
)
abstract suspend fun getProposalsNaming(groupPublicKey: HexKey): List<ConfederationEvent>
/** Every proposal this device holds, for the relay filter and the coordinator's sweep. */
@Query("SELECT * FROM ConfederationEvent WHERE kind = ${ConfederationKinds.PROPOSAL} ORDER BY eventCreatedAt DESC, id DESC")
abstract suspend fun getProposals(): List<ConfederationEvent>
@Query("SELECT * FROM ConfederationEvent WHERE kind = ${ConfederationKinds.PROPOSAL} ORDER BY eventCreatedAt DESC, id DESC")
abstract fun observeProposals(): Flow<List<ConfederationEvent>>
/** Files an event once. An id is the hash of the event, so a second copy is the same one. */
@Insert(onConflict = OnConflictStrategy.IGNORE)
protected abstract suspend fun insertEvent(event: ConfederationEvent): Long
@Insert(onConflict = OnConflictStrategy.IGNORE)
protected abstract suspend fun insertInvitees(invitees: List<ConfederationInvitee>)
/** Files [event] and, for a proposal, the groups it names. Whether it was new. */
@Transaction
open suspend fun record(event: ConfederationEvent, invitees: List<HexKey> = emptyList()): Boolean {
val inserted = insertEvent(event) != -1L
if (invitees.isNotEmpty()) insertInvitees(invitees.map { ConfederationInvitee(event.id, it) })
return inserted
}
@Query("SELECT * FROM ConfederationSigning WHERE sessionId = :sessionId")
abstract suspend fun getSigning(sessionId: String): ConfederationSigning?
@Upsert
abstract suspend fun upsertSigning(signing: ConfederationSigning)
}
@@ -0,0 +1,78 @@
package mobi.giza.compose.database.model
import androidx.room3.Entity
import androidx.room3.Index
import androidx.room3.PrimaryKey
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.Kind
import kotlin.time.Clock
import kotlin.time.Instant
/**
* A confederation event this device holds: a proposal, or an answer to one
* (docs/confederation.md, Phase 4). Signed by a group's key and verified before it is filed.
*
* One table for all four kinds, because the only question asked of them is "what has been said
* about this proposal", and a proposal's state is computed from the answer to it rather than
* stored (D8).
*
* No foreign key to `ChatRoom`. A proposal names groups this device is not in, and an answer
* comes from one; a dangling reference is the normal state, as it is for `parentChatRoomId`
* (docs/subgroups.md). And never a `NostrEvent` row: that would put a group's confederation
* event in the home feed and make it a `Profile` (docs/group-nostr-profile-and-posts.md, D7).
*/
@Entity(indices = [Index("proposalId"), Index("kind")])
data class ConfederationEvent(
@PrimaryKey
val id: HexKey,
val kind: Kind,
/** The group that signed it. */
val pubKey: HexKey,
/** The proposal it is about: its own id, for a proposal. */
val proposalId: HexKey,
val eventCreatedAt: Long,
val eventJson: String,
val receivedAt: Instant = Clock.System.now(),
) {
fun toEvent(): Event = Event.fromJson(eventJson)
}
/**
* A group a proposal invites, so a room can find the proposals that name it without parsing
* every proposal on the device.
*/
@Entity(primaryKeys = ["proposalId", "groupPublicKey"], indices = [Index("groupPublicKey")])
data class ConfederationInvitee(
val proposalId: HexKey,
val groupPublicKey: HexKey,
)
/**
* What a device needs to remember about a signing session over a confederation event, past
* the moment its proposal arrived (docs/confederation.md, Phases 3 and 4).
*
* - [sealSecret]: the ephemeral secret an acceptance is sealed under. The proposer's device
* needs it to resend the proposal; every signer's, to check the seal again at approval.
* - [proposalJson]: the 9430 an answer answers, carried on the signing proposal, so a signer
* does not depend on having heard it from a relay.
* - [refusal]: why this device declined, said in the decline it publishes.
*/
@Entity(
foreignKeys = [
androidx.room3.ForeignKey(
entity = FrostSigningSession::class,
parentColumns = ["id"],
childColumns = ["sessionId"],
onDelete = androidx.room3.ForeignKey.CASCADE,
)
],
)
data class ConfederationSigning(
@PrimaryKey
val sessionId: String,
val sealSecret: String? = null,
val proposalJson: String? = null,
val refusal: String? = null,
val createdAt: Instant = Clock.System.now(),
)
@@ -0,0 +1,110 @@
package mobi.giza.compose.managers
import co.touchlab.kermit.Logger
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlin.time.Clock
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.ConfederationEvent
import mobi.giza.compose.nostr.confederation.ConfederationAdminList
import mobi.giza.compose.nostr.confederation.ConfederationKinds
import mobi.giza.compose.nostr.confederation.ConfederationProposalAcceptanceEvent
import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent
import mobi.giza.compose.nostr.confederation.ConfederationProposalRejectionEvent
import mobi.giza.compose.nostr.confederation.ConfederationProposalWithdrawalEvent
import mobi.giza.compose.nostr.confederation.ConfederationStatus
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
/**
* The confederation's events on this device: filing them, and reading a proposal's state back
* (docs/confederation.md).
*/
object ConfederationManager {
private val logger = Logger.withTag("ConfederationManager")
/**
* Files [event] if it is a well-formed confederation event that its author's key signed.
* Returns whether it was new.
*
* The author is a group's npub, which is also its room id, so "did this group sign it" is
* [GroupKeyStateEvent.isSignedByRoom] with the event's own author -- a plain nostr signature
* check, since a FROST signature is an ordinary BIP 340 one.
*/
suspend fun record(database: GizaDatabase, event: Event): Boolean {
if (!ConfederationKinds.isConfederationKind(event.kind)) return false
if (!GroupKeyStateEvent.isSignedByRoom(event, event.pubKey)) {
logger.w("Confederation event ${event.id.take(8)} does not verify as its author's; dropping")
return false
}
val (proposalId, invitees) = when (event.kind) {
ConfederationKinds.PROPOSAL -> ConfederationProposalEvent.parse(event)
?.let { it.id to it.groupPublicKeys }
ConfederationKinds.ACCEPTANCE -> ConfederationProposalAcceptanceEvent.parse(event)
?.let { it.proposalId to emptyList() }
ConfederationKinds.REJECTION -> ConfederationProposalRejectionEvent.parse(event)
?.let { it.proposalId to emptyList() }
ConfederationKinds.WITHDRAWAL -> ConfederationProposalWithdrawalEvent.parse(event)
?.let { it.proposalId to emptyList() }
else -> null
} ?: run {
logger.w("Confederation event ${event.id.take(8)} of kind ${event.kind} is not well formed; dropping")
return false
}
return database.confederationDao().record(
ConfederationEvent(
id = event.id,
kind = event.kind,
pubKey = event.pubKey,
proposalId = proposalId,
eventCreatedAt = event.createdAt,
eventJson = event.toJson(),
),
invitees = invitees,
)
}
/** The proposal [proposalId], if this device holds it. */
suspend fun proposal(database: GizaDatabase, proposalId: HexKey): ConfederationProposalEvent.Proposal? =
database.confederationDao().getEvent(proposalId)
?.takeIf { it.kind == ConfederationKinds.PROPOSAL }
?.let { ConfederationProposalEvent.parse(it.toEvent()) }
/** Where [proposalId] stands on this device, or null if this device does not hold it. */
suspend fun status(
database: GizaDatabase,
proposalId: HexKey,
now: Long = Clock.System.now().epochSeconds,
): ConfederationStatus? {
val events = database.confederationDao().getEventsForProposal(proposalId)
val proposal = events.firstOrNull { it.id == proposalId && it.kind == ConfederationKinds.PROPOSAL }
?.let { ConfederationProposalEvent.parse(it.toEvent()) } ?: return null
return statusOf(proposal, events, now)
}
fun statusOf(
proposal: ConfederationProposalEvent.Proposal,
events: List<ConfederationEvent>,
now: Long = Clock.System.now().epochSeconds,
): ConfederationStatus = ConfederationStatus.of(
proposal,
events.filter { it.kind in ConfederationKinds.ANSWERS }.map { it.toEvent() },
now,
)
/**
* What this group would disclose in an acceptance of [proposalId], read off this device's
* own view of it: the room's live admins and the threshold its key signs with. Null when
* this device cannot say -- no admin policy, no key -- or the group could not take part as
* it stands (fewer admins than its threshold, a threshold of one).
*
* The same function on the proposer's device and every signer's, so the list each of them
* seals comes out the same when they see the same group (docs/confederation.md, D5).
*/
suspend fun adminListFor(database: GizaDatabase, chatRoomId: String, proposalId: HexKey): ConfederationAdminList? {
val admins = RoomAdmins.of(database, chatRoomId)?.admins ?: return null
val threshold = FrostSigningManager.completedKey(database, chatRoomId)?.threshold ?: return null
return ConfederationAdminList.of(proposalId, chatRoomId, threshold, admins)
}
}