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

@@ -2,7 +2,7 @@
"formatVersion": 1,
"database": {
"version": 43,
"identityHash": "9e4c7e383c6e6cdb2f1fc21a2437b271",
"identityHash": "2b9ce862f5ee0c8d4e60c91de974b83c",
"entities": [
{
"tableName": "BroadcastNostrEventReceipt",
@@ -787,7 +787,7 @@
},
{
"tableName": "ConfederationEvent",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `kind` INTEGER NOT NULL, `pubKey` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `eventCreatedAt` INTEGER NOT NULL, `eventJson` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`id`))",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `kind` INTEGER NOT NULL, `pubKey` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `eventCreatedAt` INTEGER NOT NULL, `eventJson` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, `ownSessionId` TEXT, `publishedAt` INTEGER, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
@@ -830,6 +830,16 @@
"columnName": "receivedAt",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "ownSessionId",
"columnName": "ownSessionId",
"affinity": "TEXT"
},
{
"fieldPath": "publishedAt",
"columnName": "publishedAt",
"affinity": "INTEGER"
}
],
"primaryKey": {
@@ -856,6 +866,15 @@
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_kind` ON `${TABLE_NAME}` (`kind`)"
},
{
"name": "index_ConfederationEvent_publishedAt",
"unique": false,
"columnNames": [
"publishedAt"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_publishedAt` ON `${TABLE_NAME}` (`publishedAt`)"
}
]
},
@@ -5508,7 +5527,7 @@
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '9e4c7e383c6e6cdb2f1fc21a2437b271')"
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '2b9ce862f5ee0c8d4e60c91de974b83c')"
]
}
}
@@ -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
@@ -0,0 +1,290 @@
package mobi.giza.compose.managers
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import com.vitorpamplona.quartz.nip01Core.relay.commands.toRelay.ReqCmd
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlin.time.Instant
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import mobi.giza.compose.ExperimentalFeatures
import mobi.giza.compose.database.model.ChatRoom
import mobi.giza.compose.database.model.ConfederationEvent
import mobi.giza.compose.database.model.NostrEvent
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.managers.LiveSubscriptionManager.Companion.CONFEDERATION_SUB_ID
import mobi.giza.compose.network.dto.RelayDTO
import mobi.giza.compose.network.relays.EventPublishTransport
import mobi.giza.compose.network.relays.LiveSubscriptionTransport
import mobi.giza.compose.network.relays.NostrPublishResult
import mobi.giza.compose.network.sockets.NostrIncomingMessage
import mobi.giza.compose.nostr.Relays
import mobi.giza.compose.nostr.confederation.ConfederationKinds
import mobi.giza.compose.repository.ChatRepository
import mobi.giza.compose.repository.ConfederationRepository
import mobi.giza.compose.repository.NostrRepository
/**
* The confederation on the wire (docs/confederation.md, Phase 5): what the live subscription
* asks for, where what arrives goes, and the publisher that keeps at an owed event until a
* relay takes it.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class ConfederationRelayTest {
private val keyPair = KeyPair()
private val me = keyPair.pubKey.toHexString()
@AfterTest
fun reset() {
ExperimentalFeatures.confederationOverride = null
}
// --- the subscription
@Test
fun `it asks every public relay for what names our rooms and what answers open proposals`() = runTest {
ExperimentalFeatures.confederationOverride = true
val transport = ConfederationLiveTransport()
val repository = FakeConfederationRepository(openIds = listOf("p1"))
val running = start(transport, listOf(room("room-a"), room("dm", mlsGroupState = null)), repository)
settle()
val opened = transport.opened.filter { it.reqCommand.subId == CONFEDERATION_SUB_ID }
assertEquals(Relays.eventPublishRelaySet.map { it.url }.toSet(), opened.map { it.relayUrl }.toSet())
val filters = opened.first().reqCommand.filters
assertEquals(mapOf("p" to listOf("room-a")), filters[0].tags, "a NIP-17 room is never named")
assertEquals(ConfederationKinds.ALL.toList(), filters[0].kinds)
assertEquals(mapOf("e" to listOf("p1")), filters[1].tags)
assertEquals(ConfederationKinds.ANSWERS.toList(), filters[1].kinds)
running.cancelAndJoin()
}
@Test
fun `a new proposal widens what it asks for`() = runTest {
ExperimentalFeatures.confederationOverride = true
val transport = ConfederationLiveTransport()
val repository = FakeConfederationRepository(openIds = emptyList())
val running = start(transport, listOf(room("room-a")), repository)
settle()
repository.openIds.value = listOf("p2")
settle()
val latest = transport.opened.last { it.reqCommand.subId == CONFEDERATION_SUB_ID }
assertEquals(mapOf("e" to listOf("p2")), latest.reqCommand.filters[1].tags)
running.cancelAndJoin()
}
@Test
fun `what arrives is filed as the confederation's, never as a nostr event`() = runTest {
ExperimentalFeatures.confederationOverride = true
val transport = ConfederationLiveTransport()
val repository = FakeConfederationRepository(openIds = emptyList())
val nostr = ConfederationRecordingNostr()
val running = start(transport, listOf(room("room-a")), repository, nostr)
settle()
val subscription = transport.opened.first { it.reqCommand.subId == CONFEDERATION_SUB_ID }
subscription.messages.emit(
NostrIncomingMessage.EventMessage(subscriptionId = CONFEDERATION_SUB_ID, nostrEvent = wire("ev-1"))
)
settle()
assertEquals(listOf("ev-1"), repository.recorded.map { it.id })
assertEquals(emptyList(), nostr.saved)
running.cancelAndJoin()
}
@Test
fun `with the feature off it asks for nothing`() = runTest {
ExperimentalFeatures.confederationOverride = false
val transport = ConfederationLiveTransport()
val running = start(transport, listOf(room("room-a")), FakeConfederationRepository(openIds = listOf("p1")))
settle()
assertTrue(transport.opened.none { it.reqCommand.subId == CONFEDERATION_SUB_ID })
running.cancelAndJoin()
}
// --- the publisher
@Test
fun `an owed event goes to the publish set and the proposal's hints, and is marked once a relay takes it`() = runTest {
val repository = FakeConfederationRepository(openIds = emptyList(), hints = listOf("wss://hint.example"))
repository.owed.value = listOf(owed("ev-1"))
val transport = ConfederationFakePublisher(accept = true)
val running = launch { ConfederationPublisher(repository, transport).run() }
settle()
val asked = transport.asked.single()
assertTrue("wss://hint.example" in asked.second)
assertTrue(Relays.eventPublishRelaySet.map { it.url }.all { it in asked.second })
assertEquals(listOf("ev-1"), repository.published)
running.cancelAndJoin()
}
@Test
fun `an event no relay takes is tried again, later`() = runTest {
val repository = FakeConfederationRepository(openIds = emptyList())
repository.owed.value = listOf(owed("ev-1"))
val transport = ConfederationFakePublisher(accept = false)
val running = launch { ConfederationPublisher(repository, transport, firstRetry = 1.minutes).run() }
settle()
assertEquals(1, transport.asked.size)
settle(30.seconds)
assertEquals(1, transport.asked.size, "not before the back-off")
transport.accept = true
settle(1.minutes)
assertEquals(2, transport.asked.size)
assertEquals(listOf("ev-1"), repository.published)
running.cancelAndJoin()
}
// --- harness
private fun TestScope.settle(duration: Duration = 1.seconds) {
advanceTimeBy(duration)
runCurrent()
}
private fun TestScope.start(
transport: ConfederationLiveTransport,
rooms: List<LocalChatRoom>,
repository: ConfederationRepository,
nostr: ConfederationRecordingNostr = ConfederationRecordingNostr(),
) = launch {
LiveSubscriptionManager(
relaysSocketManager = transport,
nostrRepository = nostr,
chatRepository = ConfederationRooms(MutableStateFlow(rooms)),
isForeground = MutableStateFlow(true),
confederationRepository = repository,
).observe(keyPair)
}
private fun room(id: String, mlsGroupState: String? = "state") = LocalChatRoom(
chatRoom = ChatRoom(id = id, userPublicKey = me, subject = null, description = null, mlsGroupState = mlsGroupState)
)
private fun wire(id: String) = NostrEvent(
id = id, pubKey = "a".repeat(64), createdAt = Instant.fromEpochSeconds(1_000),
kind = ConfederationKinds.PROPOSAL, tags = emptyArray(), content = "", sig = "",
)
private fun owed(id: String) = ConfederationEvent(
id = id, kind = ConfederationKinds.ACCEPTANCE, pubKey = "a".repeat(64), proposalId = "p1",
eventCreatedAt = 1_000,
eventJson = Event(id, "a".repeat(64), 1_000, ConfederationKinds.ACCEPTANCE, emptyArray(), "", "").toJson(),
ownSessionId = "s1",
)
}
private class ConfederationLiveSubscription(val reqCommand: ReqCmd, val relayUrl: String) {
val messages = MutableSharedFlow<NostrIncomingMessage>(extraBufferCapacity = 32)
}
private class ConfederationLiveTransport : LiveSubscriptionTransport {
val opened = mutableListOf<ConfederationLiveSubscription>()
override suspend fun openLiveSubscription(reqCommand: ReqCmd, relayUrl: String): Flow<NostrIncomingMessage> =
ConfederationLiveSubscription(reqCommand, relayUrl).also { opened += it }.messages.asSharedFlow()
override suspend fun updateLiveSubscription(reqCommand: ReqCmd, relayUrl: String) = Unit
override suspend fun closeLiveSubscription(subId: String, relayUrl: String) = Unit
override suspend fun reconnectAll() = Unit
}
private class ConfederationFakePublisher(var accept: Boolean) : EventPublishTransport {
/** (event id, relays asked) */
val asked = mutableListOf<Pair<String, Set<String>>>()
override suspend fun publishEvent(nostrEvent: NostrEvent, relays: Set<RelayDTO>): Flow<NostrPublishResult> {
asked += nostrEvent.id to relays.map { it.url }.toSet()
val ok = accept
return flow {
relays.forEach { relay ->
emit(
NostrPublishResult(
result = NostrIncomingMessage.OkMessage(eventId = nostrEvent.id, success = ok, message = ""),
relayUrl = relay.url,
)
)
}
}
}
}
private class FakeConfederationRepository(
openIds: List<HexKey>,
private val hints: List<String> = emptyList(),
) : ConfederationRepository {
val openIds = MutableStateFlow(openIds)
val owed = MutableStateFlow<List<ConfederationEvent>>(emptyList())
val recorded = mutableListOf<Event>()
val published = mutableListOf<HexKey>()
override suspend fun record(event: Event): Boolean {
recorded += event
return true
}
override fun observeUnpublished(): Flow<List<ConfederationEvent>> = owed
override suspend fun markPublished(eventId: HexKey, at: Instant) {
published += eventId
owed.value = owed.value.filterNot { it.id == eventId }
}
override fun observeOpenProposalIds(): Flow<List<HexKey>> = openIds
override suspend fun relayHintsFor(proposalId: HexKey): List<String> = hints
}
private class ConfederationRooms(private val rooms: StateFlow<List<LocalChatRoom>>) : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY {
override suspend fun observeChatRoomListByPublicKey(publicKey: String): Flow<List<LocalChatRoom>> = rooms
override suspend fun getChatRoomListByPublicKey(publicKey: String): List<LocalChatRoom> = rooms.value
}
private class ConfederationRecordingNostr : NostrRepository by NostrRepository.NO_OP_NOSTR_REPOSITORY {
val saved = mutableListOf<String>()
override suspend fun saveNostrEvent(
nostrEvent: NostrEvent,
relayURL: String,
synchronizationRelayURLs: List<String>,
level: Int,
activeKeyPair: KeyPair,
) {
saved += nostrEvent.id
}
override suspend fun queueNegentropySynchronizeRequest(
negentropySynchronizeRequests: List<mobi.giza.compose.database.model.NegentropySynchronizeRequest>,
) = Unit
}
@@ -12,6 +12,8 @@ import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.builder.getRoomDatabase
import mobi.giza.compose.database.model.FrostSigningSession
import mobi.giza.compose.database.model.types.FrostSigningSubject
import mobi.giza.compose.managers.ConfederationTestGroups.key
import mobi.giza.compose.managers.ConfederationTestGroups.npub
import mobi.giza.compose.nostr.confederation.ConfederationProposalState
@@ -81,4 +83,35 @@ class ConfederationStorageJvmTest {
ConfederationManager.record(db, proposal)
assertEquals(ConfederationProposalState.REJECTED, ConfederationManager.status(db, proposal.id)?.state)
}
private fun session(coordinator: String, user: String) = FrostSigningSession(
id = "s".repeat(64),
chatRoomId = npub(1),
coordinatorPublicKey = coordinator,
userPublicKey = user,
dkgSessionId = "k".repeat(64),
threshold = 2,
participantCount = 3,
signerId = 1,
derivationPath = null,
subject = FrostSigningSubject.EVENTS,
)
@Test
fun `what the group signed is filed, and owed to relays by the device that proposed it`() = runBlocking {
ConfederationManager.onSigned(db, session(coordinator = coordinator, user = coordinator), listOf(proposal))
val owed = db.confederationDao().observeUnpublished().first()
assertEquals(listOf(proposal.id), owed.map { it.id })
assertEquals("s".repeat(64), owed.single().ownSessionId)
db.confederationDao().markPublished(proposal.id, kotlin.time.Clock.System.now())
assertEquals(emptyList(), db.confederationDao().observeUnpublished().first())
}
@Test
fun `on a device that only signed, it is filed and owed to nobody`() = runBlocking {
ConfederationManager.onSigned(db, session(coordinator = coordinator, user = npub(10)), listOf(proposal))
assertEquals(proposal.id, db.confederationDao().getEvent(proposal.id)?.id)
assertEquals(emptyList(), db.confederationDao().observeUnpublished().first())
}
}
+1
View File
@@ -47,6 +47,7 @@ wait on upstream (see the next section).
| 2 | done. `nostr/confederation/`: `ConfederationKinds`, the proposal, acceptance, rejection and withdrawal events, `ConfederationAdminList` (decodes only its own encoding), `ConfederationSeal`, `ConfederationStatus`, five tag classes. `ConfederationEventsTest` 27/27; `RetiredKindsTest` checks the family is nobody else's and regular. An answer counts only if made by the proposal's expiry, so `ACCEPTED` does not depend on when a device heard. The seal tag rides the FROST proposal through `ConfederationSealTag` rather than `FrostSigningEvents.assembleTags` |
| 3 | done. `ConfederationRefusal` in all four places in `FrostSigningManager`: on arrival, again at approval (the admins can change while a member decides), as the decline's reason, and in the resend, which carries the seal again. Two tags ride the FROST proposal: `confederation_seal` and, for an answer, `confederation_proposal`, the signed 9430 it answers, so a signer does not depend on its relays (verified and filed like a relay's copy). `proposeSigningBatch` takes `proposalTags`. `ConfederationManager.proposeConfederation`, `proposeAcceptance`, `proposeRejection` and `proposeWithdrawal` build them. `ProposedEvent` summarises the four kinds. `ConfederationDeclineJvmTest` 16/16 replaces the Phase 1 pin. The warnings half of D6 waits for the approval screen (Phase 7). Full jvmTest 1,569, all passing once `ShippedProfileUpgradeJvmTest` was moved to 43 |
| 4 | done, before 3, because the refusals need somewhere to keep the seal and the reason past arrival. Schema 43: `ConfederationEvent` (every kind in one table, keyed by event id, indexed by the proposal it is about), `ConfederationInvitee` (which proposals name a group) and `ConfederationSigning` (per signing session: the seal secret, the carried proposal, the refusal). No `ConfederationGroup` cache: D2's lookups land in the existing `Profile` rows. `ConfederationManager.record` verifies the author's signature and files; `status` computes D8 from the rows. The repository waits for Phase 6, its first caller. `ConfederationStorageJvmTest` 5/5 |
| 5 | done. `ExperimentalFeatures.confederation`, on in development builds. `LiveSubscriptionManager` holds `live-confederation` on the publish set while it is on: every confederation kind `#p`-tagged to one of our Marmot rooms, and every answer `#e`-tagged to a proposal not yet expired, re-sent when either changes. What arrives goes to `ConfederationRepository.record`, never `saveNostrEvent`. `FrostSigningManager.complete` calls `ConfederationManager.onSigned`, which files the signed events on every device and, on the coordinator's, marks them owed (`ConfederationEvent.ownSessionId`, `publishedAt`, folded into schema 43 since it has not shipped). `ConfederationPublisher`, run by `SynchronizationViewModel`, sends owed events to the publish set and the proposal's hints and backs off from a minute to half an hour until a relay takes each. `BROADCASTABLE_KINDS` gains 9430–9433. `ChatMessage.applyInnerEvent` draws nothing for these kinds rather than a raw-JSON bubble. `ConfederationRelayTest` 6/6, `ConfederationStorageJvmTest` 7/7 |
---