feat: confederation events reach relays, and come back from them (confederation, Phase 5)

Behind ExperimentalFeatures.confederation. A live subscription asks
the public relays for what names our rooms and what answers open
proposals, and files it in the confederation's table rather than as a
NostrEvent. What a group signs is filed on every device and owed to
relays by the one that proposed it; a publisher keeps at it until a
relay takes each, and the broadcast screen can send one again.

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:59:52 +02:00
1 parent f7b361c95f
commit bd1b5d56dd
17 files changed
+701 -10

No files matched your search

@@ -16,6 +16,18 @@ object ExperimentalFeatures {
val shareRefresh: Boolean
get() = shareRefreshOverride ?: isDevelopmentBuild()
/** Set by a test that has to see the build a release would be. */
var confederationOverride: Boolean? = null
/**
* Groups agreeing in public to form a confederation (docs/confederation.md). Off in a
* release while upstream calls the confederation module experimental: off, the app
* offers nothing, listens for nothing and publishes nothing. A device still declines,
* out loud, a confederation event it finds wrong -- that is a refusal, not a feature.
*/
val confederation: Boolean
get() = confederationOverride ?: isDevelopmentBuild()
}
/** Whether this is a debug or development build of the app, rather than a release. */
@@ -62,6 +62,16 @@ abstract class ConfederationDao {
return inserted
}
/** Events this device signed for and still owes to relays (D9), oldest first. */
@Query("SELECT * FROM ConfederationEvent WHERE ownSessionId IS NOT NULL AND publishedAt IS NULL ORDER BY eventCreatedAt ASC, id ASC")
abstract fun observeUnpublished(): Flow<List<ConfederationEvent>>
@Query("UPDATE ConfederationEvent SET ownSessionId = :sessionId WHERE id = :id AND ownSessionId IS NULL")
abstract suspend fun markOwn(id: HexKey, sessionId: String)
@Query("UPDATE ConfederationEvent SET publishedAt = :at WHERE id = :id")
abstract suspend fun markPublished(id: HexKey, at: kotlin.time.Instant)
@Query("SELECT * FROM ConfederationSigning WHERE sessionId = :sessionId")
abstract suspend fun getSigning(sessionId: String): ConfederationSigning?
@@ -3,6 +3,7 @@ package mobi.giza.compose.database.model
import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent
import mobi.giza.compose.nostr.GroupNostrProfile
import mobi.giza.compose.nostr.RetiredKinds
import mobi.giza.compose.nostr.confederation.ConfederationKinds
import androidx.room3.Entity
import androidx.room3.ForeignKey
@@ -1401,6 +1402,12 @@ data class ChatMessage(
// which is the only trace an unrecognised payload leaves.
MarmotAppEvent.KIND_SYSTEM, MarmotAppEvent.KIND_EDIT -> null
// A confederation event the group signed. Its lines are written from the
// confederation's own table, which hears the same events from relays as
// well as from a session here, so this arm writes nothing rather than a
// raw-JSON bubble (docs/confederation.md, Phase 5).
in ConfederationKinds.ALL -> null
// Bennu's wallets, which a Bennu member can bring into a room this
// device shares. What announces one is a line saying Giza takes no part;
// everything else -- the wallet's protocol and its traffic -- is none,
@@ -22,7 +22,7 @@ import kotlin.time.Instant
* (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")])
@Entity(indices = [Index("proposalId"), Index("kind"), Index("publishedAt")])
data class ConfederationEvent(
@PrimaryKey
val id: HexKey,
@@ -34,6 +34,14 @@ data class ConfederationEvent(
val eventCreatedAt: Long,
val eventJson: String,
val receivedAt: Instant = Clock.System.now(),
/**
* The signing session this device coordinated to make it, if it did: this device is the
* one that sends it to relays (D9). Null for everything heard from a relay or signed by
* another member's session.
*/
val ownSessionId: String? = null,
/** When a relay first accepted it from this device. Null while it is still owed. */
val publishedAt: Instant? = null,
) {
fun toEvent(): Event = Event.fromJson(eventJson)
}
@@ -0,0 +1,42 @@
package mobi.giza.compose.database.repository
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlin.time.Clock
import kotlin.time.Instant
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.ConfederationEvent
import mobi.giza.compose.managers.ConfederationManager
import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent
import mobi.giza.compose.repository.ConfederationRepository
class DatabaseConfederationRepository(
private val database: GizaDatabase,
private val scope: CoroutineScope,
) : ConfederationRepository {
override suspend fun record(event: Event): Boolean = ConfederationManager.record(database, event)
override fun observeUnpublished(): Flow<List<ConfederationEvent>> =
database.confederationDao().observeUnpublished()
override suspend fun markPublished(eventId: HexKey, at: Instant) =
database.confederationDao().markPublished(eventId, at)
override fun observeOpenProposalIds(): Flow<List<HexKey>> =
database.confederationDao().observeProposals()
.map { rows ->
val now = Clock.System.now().epochSeconds
rows.mapNotNull { ConfederationProposalEvent.parse(it.toEvent()) }
.filterNot { it.isExpiredAt(now) }
.map { it.id }
.sorted()
}
.distinctUntilChanged()
override suspend fun relayHintsFor(proposalId: HexKey): List<String> =
ConfederationManager.proposal(database, proposalId)?.groups?.mapNotNull { it.relayHint }?.distinct().orEmpty()
}
@@ -71,6 +71,19 @@ object ConfederationManager {
)
}
/**
* The group signed [signedEvents] in [session]: file the confederation's among them, as every
* device that completes the session does, and on the device that coordinated it, mark them
* owed to relays (D9). A confederation event exists only to be read on relays, so the
* quorum's approval of one is the decision to send it.
*/
suspend fun onSigned(database: GizaDatabase, session: FrostSigningSession, signedEvents: List<Event>) {
signedEvents.filter { ConfederationKinds.isConfederationKind(it.kind) }.forEach { signed ->
if (!record(database, signed) && database.confederationDao().getEvent(signed.id) == null) return@forEach
if (session.isCoordinator()) database.confederationDao().markOwn(signed.id, session.id)
}
}
/** The proposal [proposalId], if this device holds it. */
suspend fun proposal(database: GizaDatabase, proposalId: HexKey): ConfederationProposalEvent.Proposal? =
database.confederationDao().getEvent(proposalId)
@@ -0,0 +1,101 @@
package mobi.giza.compose.managers
import co.touchlab.kermit.Logger
import kotlin.time.Clock
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.withTimeout
import mobi.giza.compose.database.model.ConfederationEvent
import mobi.giza.compose.database.model.NostrEvent
import mobi.giza.compose.network.dto.RelayDTO
import mobi.giza.compose.network.relays.EventPublishTransport
import mobi.giza.compose.network.relays.RelayPool
import mobi.giza.compose.network.sockets.NostrIncomingMessage
import mobi.giza.compose.nostr.Relays
import mobi.giza.compose.repository.ConfederationRepository
/**
* Sends the confederation events this device signed for to relays, and keeps trying until one
* takes each (docs/confederation.md, D9).
*
* Not through the `BroadcastNostrEventRequest` queue: that hangs off a `NostrEvent` row, and a
* row for a group's event would put it in the home feed and make the group a `Profile`
* (docs/group-nostr-profile-and-posts.md, D7). The owed events live on their own rows instead,
* marked published once a relay accepts them, so a restart picks up where it left off.
*/
class ConfederationPublisher(
private val repository: ConfederationRepository,
private val transport: EventPublishTransport,
private val firstRetry: Duration = 1.minutes,
private val lastRetry: Duration = 30.minutes,
) {
private val logger = Logger.withTag("ConfederationPublisher")
/** Runs until cancelled. */
suspend fun run() {
repository.observeUnpublished().collectLatest { owed ->
var wait = firstRetry
var remaining = owed
while (remaining.isNotEmpty()) {
remaining = remaining.filterNot { publish(it) }
if (remaining.isEmpty()) break
logger.w("${remaining.size} confederation event(s) not yet taken by any relay; trying again in $wait")
delay(wait)
wait = minOf(wait * 2, lastRetry)
}
}
}
/** Sends [event] to every relay it should reach. Whether any accepted it. */
suspend fun publish(event: ConfederationEvent): Boolean {
val targets = (Relays.eventPublishRelaySet.map { it.url } + repository.relayHintsFor(event.proposalId))
.map { it.trim() }
.filter { it.startsWith("wss://") || it.startsWith("ws://") }
.distinct()
val wire = wireEventOf(event)
var accepted = false
try {
withTimeout((RelayPool.PUBLISH_TIMEOUT * 2).milliseconds) {
transport.publishEvent(
nostrEvent = wire,
relays = targets.map { RelayDTO(url = it, read = false, write = true) }.toSet(),
).take(targets.size).collect { result ->
val ok = result.result as? NostrIncomingMessage.OkMessage
if (result.error == null && ok?.success == true) accepted = true
}
}
} catch (e: TimeoutCancellationException) {
// Ordinary: a relay that never answers. Whatever answered in time counts.
} catch (e: CancellationException) {
throw e
} catch (e: Throwable) {
logger.e("Could not send confederation event ${event.id.take(8)}", e)
}
if (accepted) {
repository.markPublished(event.id, Clock.System.now())
logger.i("Confederation event ${event.id.take(8)} of kind ${event.kind} is on a relay")
}
return accepted
}
private companion object {
/** The event as the pool wants it. Never written to the `NostrEvent` table. */
fun wireEventOf(row: ConfederationEvent): NostrEvent = row.toEvent().let {
NostrEvent(
id = it.id,
pubKey = it.pubKey,
kind = it.kind,
tags = it.tags,
content = it.content,
sig = it.sig,
createdAt = kotlin.time.Instant.fromEpochSeconds(it.createdAt),
)
}
}
}
@@ -1418,6 +1418,14 @@ object FrostSigningManager {
logger.e("Signed session ${session.id} but could not publish its change", e)
}
// A confederation event: filed, and owed to relays by the device that
// proposed it. docs/confederation.md, D9.
try {
ConfederationManager.onSigned(database, session, signedEvents)
} catch (e: Throwable) {
logger.e("Signed session ${session.id} but could not file its confederation event", e)
}
announce(
database = database,
session = session,
@@ -37,7 +37,11 @@ import mobi.giza.compose.network.sockets.endsLiveSubscription
import mobi.giza.compose.nostr.MemberProfileSync
import mobi.giza.compose.nostr.Nip17Filters
import mobi.giza.compose.nostr.Relays
import mobi.giza.compose.ExperimentalFeatures
import mobi.giza.compose.nostr.confederation.ConfederationKinds
import mobi.giza.compose.repository.ChatRepository
import mobi.giza.compose.repository.ConfederationRepository
import kotlinx.coroutines.flow.combine
import mobi.giza.compose.repository.NostrRepository
import kotlin.concurrent.Volatile
import kotlin.time.Duration.Companion.milliseconds
@@ -69,6 +73,11 @@ class LiveSubscriptionManager(
private val nostrRepository: NostrRepository,
private val chatRepository: ChatRepository,
private val isForeground: StateFlow<Boolean>,
/**
* Where confederation events heard on a relay are filed, rather than as `NostrEvent` rows
* (docs/confederation.md, Phase 5). Null, or the feature off, and nothing is asked for.
*/
private val confederationRepository: ConfederationRepository? = null,
) {
private val logger = Logger.withTag(TAG)
@@ -84,6 +93,12 @@ class LiveSubscriptionManager(
const val GROUP_SUB_ID_PREFIX = "live-groups-"
/** The confederation's public events, on the public relays they are published to. */
const val CONFEDERATION_SUB_ID = "live-confederation"
/** Ids per tag array in the confederation filter, for the reason [MAX_GROUPS_PER_SUBSCRIPTION] gives. */
private const val MAX_CONFEDERATION_IDS = 100
/**
* Group ids per `#h` filter. One subscription per group would be simpler, but every
* Marmot group here lives on the same DM relay set, so carrying many ids in one
@@ -168,6 +183,31 @@ class LiveSubscriptionManager(
.distinct()
.sorted()
/**
* What the confederation subscription asks for: every confederation event that names one
* of our keyed rooms -- a proposal inviting it, an answer addressed to it -- and every
* answer to a proposal still open on this device, whoever it is addressed to, so a
* proposal's progress is seen by every group on it (docs/confederation.md, Phase 5).
*
* Signed by groups and public, so nothing here is ours to decrypt and nothing is
* p-tagged to a person.
*/
internal fun confederationFilters(roomIds: List<HexKey>, openProposalIds: List<HexKey>): List<Filter> =
roomIds.chunked(MAX_CONFEDERATION_IDS).map { chunk ->
Filter(kinds = ConfederationKinds.ALL.toList(), tags = mapOf("p" to chunk), limit = INITIAL_GROUP_HISTORY_LIMIT)
} + openProposalIds.chunked(MAX_CONFEDERATION_IDS).map { chunk ->
Filter(kinds = ConfederationKinds.ANSWERS.toList(), tags = mapOf("e" to chunk), limit = INITIAL_GROUP_HISTORY_LIMIT)
}
/** The keyed rooms a confederation could name: Marmot rooms we are still in, by their own ids. */
internal fun confederationRoomIdsFrom(rooms: List<LocalChatRoom>): List<HexKey> =
rooms
.filter { it.chatRoom.mlsGroupState != null }
.filter { it.chatRoom.leftGroupAt == null && it.chatRoom.deletedAt == null }
.map { it.chatRoom.id }
.distinct()
.sorted()
internal fun groupChunks(groupIds: List<HexKey>): List<List<HexKey>> =
groupIds.chunked(MAX_GROUPS_PER_SUBSCRIPTION)
@@ -244,6 +284,44 @@ class LiveSubscriptionManager(
}
launch { followGroupMembership(publicKey = publicKey, keyPair = keyPair) }
confederationRepository?.takeIf { ExperimentalFeatures.confederation }?.let { repository ->
launch { followConfederations(publicKey = publicKey, keyPair = keyPair, repository = repository) }
}
}
/**
* Keeps one subscription per public relay open on [confederationFilters], re-sent whenever
* the rooms or the open proposals change. Events go to [repository], never to the
* `NostrEvent` table (docs/confederation.md, Phase 5).
*/
@OptIn(FlowPreview::class)
private suspend fun followConfederations(publicKey: HexKey, keyPair: KeyPair, repository: ConfederationRepository) {
combine(
chatRepository.observeChatRoomListByPublicKey(publicKey).map(::confederationRoomIdsFrom).distinctUntilChanged(),
repository.observeOpenProposalIds(),
) { roomIds, proposalIds -> confederationFilters(roomIds, proposalIds) }
.distinctUntilChanged()
.debounce(GROUP_CHANGE_DEBOUNCE)
.collectLatest { filters ->
if (filters.isEmpty()) return@collectLatest
coroutineScope {
Relays.eventPublishRelaySet.forEach { relay ->
launch {
runLiveSubscription(
subId = CONFEDERATION_SUB_ID,
relayUrl = relay.url,
filters = { filters },
keyPair = keyPair,
onEvent = { nostrEvent, _ ->
runCatching { repository.record(nostrEvent.toEvent()) }
.onFailure { logger.w(throwable = it) { "Could not file confederation event ${nostrEvent.id}" } }
},
)
}
}
}
}
}
/**
@@ -415,6 +493,7 @@ class LiveSubscriptionManager(
relayUrl: String,
filters: () -> List<Filter>,
keyPair: KeyPair,
onEvent: (suspend (NostrEvent, String) -> Unit)? = null,
) {
var reopenDelay = INITIAL_REOPEN_DELAY
@@ -434,6 +513,7 @@ class LiveSubscriptionManager(
relayUrl = relayUrl,
filters = currentFilters,
keyPair = keyPair,
onEvent = onEvent,
)
} catch (error: CancellationException) {
throw error
@@ -480,7 +560,11 @@ class LiveSubscriptionManager(
relayUrl: String,
filters: List<Filter>,
keyPair: KeyPair,
onEvent: (suspend (NostrEvent, String) -> Unit)? = null,
): SubscriptionEnd {
val handle: suspend (NostrEvent) -> Unit = { event ->
if (onEvent != null) onEvent(event, relayUrl) else save(event, relayUrl, keyPair)
}
var reason: String? = null
var reachedEose = false
@@ -493,11 +577,11 @@ class LiveSubscriptionManager(
}.collect { message ->
when (message) {
is NostrIncomingMessage.EventMessage -> {
message.nostrEvent?.let { save(it, relayUrl, keyPair) }
message.nostrEvent?.let { handle(it) }
}
is NostrIncomingMessage.EventsMessage -> {
message.nostrEvents.forEach { save(it, relayUrl, keyPair) }
message.nostrEvents.forEach { handle(it) }
}
is NostrIncomingMessage.EoseMessage -> {
@@ -0,0 +1,27 @@
package mobi.giza.compose.repository
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlinx.coroutines.flow.Flow
import kotlin.time.Instant
import mobi.giza.compose.database.model.ConfederationEvent
/**
* The confederation's events on this device, for the relay layer and the screens
* (docs/confederation.md).
*/
interface ConfederationRepository {
/** Files [event] if it is a confederation event its author signed. Whether it was new. */
suspend fun record(event: Event): Boolean
/** Events this device signed for and still owes to relays (D9). */
fun observeUnpublished(): Flow<List<ConfederationEvent>>
suspend fun markPublished(eventId: HexKey, at: Instant)
/** The proposals not yet past their expiry, by id: what the relay filter asks for answers to. */
fun observeOpenProposalIds(): Flow<List<HexKey>>
/** Where to send an event about [proposalId]: the relays the proposal hints at for its groups. */
suspend fun relayHintsFor(proposalId: HexKey): List<String>
}
@@ -37,6 +37,7 @@ import androidx.navigation.toRoute
import mobi.giza.compose.GizaGlobal
import mobi.giza.compose.database.repository.DatabaseChatRepository
import mobi.giza.compose.database.repository.DatabaseDkgRepository
import mobi.giza.compose.database.repository.DatabaseConfederationRepository
import mobi.giza.compose.database.repository.DatabaseFrostSigningRepository
import mobi.giza.compose.database.repository.DatabaseMarmotRepository
import mobi.giza.compose.database.repository.DatabaseNostrRepository
@@ -207,6 +208,12 @@ fun GizaNavHost(
applicationIOScope
)
}
val databaseConfederationRepository = remember {
DatabaseConfederationRepository(
database = auxDatabaseManager.auxDatabase,
applicationIOScope
)
}
val databaseMarmotRepository = remember {
DatabaseMarmotRepository(
database = auxDatabaseManager.auxDatabase,
@@ -246,7 +253,8 @@ fun GizaNavHost(
nostrRepository = databaseNostrRepository,
chatRepository = databaseChatRepository,
relayRepository = databaseNostrRepository,
scope = applicationIOScope
scope = applicationIOScope,
confederationRepository = databaseConfederationRepository,
)
)
@@ -31,6 +31,7 @@ import mobi.giza.compose.database.model.NostrEvent
import mobi.giza.compose.exceptions.NostrPublishException
import mobi.giza.compose.network.dto.RelayDTO
import mobi.giza.compose.network.relays.EventPublishTransport
import mobi.giza.compose.nostr.confederation.ConfederationKinds
import mobi.giza.compose.network.relays.NostrPublishResult
import mobi.giza.compose.network.relays.RelayPool
import mobi.giza.compose.network.sockets.NostrIncomingMessage
@@ -294,8 +295,12 @@ class BroadcastGroupSignedEventViewModel(
*/
val BROADCAST_TIMEOUT = (RelayPool.PUBLISH_TIMEOUT * 2).milliseconds
/** The kinds this screen will put on a relay: the group's profile and posts. */
val BROADCASTABLE_KINDS: Set<Kind> = setOf(MetadataEvent.KIND, TextNoteEvent.KIND)
/**
* The kinds this screen will put on a relay: the group's profile and posts, and its
* confederation events, which a member sends again by hand when the device that
* signed for them never got them out (docs/confederation.md, D9).
*/
val BROADCASTABLE_KINDS: Set<Kind> = setOf(MetadataEvent.KIND, TextNoteEvent.KIND) + ConfederationKinds.ALL
/**
* Sends [signedEvent] to [targets] and says what each relay answered.
@@ -59,6 +59,9 @@ import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withLock
import mobi.giza.compose.nostr.SignInSync
import kotlinx.coroutines.sync.withPermit
import mobi.giza.compose.ExperimentalFeatures
import mobi.giza.compose.managers.ConfederationPublisher
import mobi.giza.compose.repository.ConfederationRepository
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
@@ -68,6 +71,7 @@ class SynchronizationViewModel(
val chatRepository: ChatRepository,
val relayRepository: RelayRepository,
val scope: CoroutineScope,
val confederationRepository: ConfederationRepository? = null,
): ViewModel() {
val relaysSocketManager = RelaysSocketManager(
@@ -87,8 +91,14 @@ class SynchronizationViewModel(
nostrRepository = nostrRepository,
chatRepository = chatRepository,
isForeground = AppLifecycle.isForeground,
confederationRepository = confederationRepository,
)
/** Sends the confederation events this device signed for (docs/confederation.md, D9). */
private val confederationPublisher = confederationRepository?.let {
ConfederationPublisher(repository = it, transport = relaysSocketManager)
}
companion object {
private const val TAG = "SynchronizationViewModel"
@@ -139,6 +149,7 @@ class SynchronizationViewModel(
chatRepository: ChatRepository,
relayRepository: RelayRepository,
scope: CoroutineScope,
confederationRepository: ConfederationRepository? = null,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
SynchronizationViewModel(
@@ -146,7 +157,8 @@ class SynchronizationViewModel(
nostrRepository = nostrRepository,
chatRepository = chatRepository,
relayRepository = relayRepository,
scope = scope
scope = scope,
confederationRepository = confederationRepository,
)
}
}
@@ -260,6 +272,17 @@ class SynchronizationViewModel(
// belongs here for the same reason the pumps do: it needs the
// active wallet's key pair, and a wallet switch must tear it down.
launch(Dispatchers.IO) { liveSubscriptionManager.observe(keyPair) }
// Confederation events this device signed for, owed to relays
// until one takes them. docs/confederation.md, D9.
confederationPublisher?.takeIf { ExperimentalFeatures.confederation }?.let { publisher ->
launch(Dispatchers.IO) {
runCatching { publisher.run() }
.onFailure {
if (it is CancellationException) throw it
logger.e("Publishing confederation events stopped", it)
}
}
}
// A key ceremony this profile opened, taken from a key to a
// working room without anybody pressing a button: the key
// state proposed, a subgroup's certificate asked for, the