feat: the confederation's new profile reaches relays and every member group (confederation-profile, Phase 6)
The signed kind:0 is owed by every device that signed it and sent to the public relays and every member group's inbox relays. The live confederation subscription also asks for each known confederation's own kind:0, by its key, so a member who is not an admin and holds only the charter hears the new profile, and each member group's room says so: "Atlas has a new profile". An older profile heard late changes nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8d494ddbd3
commit
19cd1aaee6
12 files changed
+238
-7
No files matched your search
@@ -90,6 +90,10 @@ abstract class ConfederationDao {
|
||||
@Query("DELETE FROM ConfederationEvent WHERE id = :id")
|
||||
abstract suspend fun deleteEvent(id: HexKey)
|
||||
|
||||
/** Every confederation that has signed a charter this device holds. */
|
||||
@Query("SELECT DISTINCT pubKey FROM ConfederationEvent WHERE kind = ${ConfederationKinds.CHARTER}")
|
||||
abstract fun observeCharterAuthors(): Flow<List<HexKey>>
|
||||
|
||||
/** The charters [confederationId] has signed that this device holds, newest first. */
|
||||
@Query("SELECT * FROM ConfederationEvent WHERE kind = ${ConfederationKinds.CHARTER} AND pubKey = :confederationId ORDER BY eventCreatedAt DESC, id DESC")
|
||||
abstract suspend fun getCharters(confederationId: HexKey): List<ConfederationEvent>
|
||||
|
||||
+9
@@ -131,6 +131,15 @@ class DatabaseConfederationRepository(
|
||||
ConfederationProfileManager.statusesFrom(rows, ConfederationProfileManager.profiles(database, confederationId), Clock.System.now().epochSeconds)
|
||||
}
|
||||
|
||||
override fun observeKnownConfederations(): Flow<List<HexKey>> =
|
||||
combine(
|
||||
database.confederationCeremonyDao().observeConfederations(),
|
||||
database.confederationDao().observeCharterAuthors(),
|
||||
) { recorded, chartered -> (recorded.map { it.id } + chartered).distinct().sorted() }.distinctUntilChanged()
|
||||
|
||||
override suspend fun extraRelaysFor(event: ConfederationEvent): List<String> =
|
||||
if (event.kind == MetadataEvent.KIND) ConfederationProfileManager.publishRelaysFor(database, event.pubKey) else emptyList()
|
||||
|
||||
override suspend fun membership(confederationId: HexKey): ConfederationProfileManager.Membership? =
|
||||
ConfederationProfileManager.membership(database, confederationId)
|
||||
|
||||
|
||||
@@ -48,6 +48,8 @@ object ConfederationManager {
|
||||
* filed this way: it arrives through an inbox, as [recordStatement].
|
||||
*/
|
||||
suspend fun record(database: GizaDatabase, event: Event): Boolean {
|
||||
// A formed confederation's profile, heard on a relay (docs/confederation-profile.md, D7).
|
||||
if (event.kind == com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent.KIND) return ConfederationProfileManager.hearProfile(database, event)
|
||||
if (event.kind != ConfederationKinds.CHARTER) return false
|
||||
if (!GroupKeyStateEvent.isSignedByRoom(event, event.pubKey)) {
|
||||
logger.w("Charter ${event.id.take(8)} does not verify as its author's; dropping")
|
||||
|
||||
+56
-2
@@ -165,17 +165,71 @@ object ConfederationProfileManager {
|
||||
logger.w("Profile ${signed.id.take(8)} is not a kind:0 its author signed; dropping")
|
||||
return false
|
||||
}
|
||||
return database.confederationDao().record(
|
||||
val change = changeId ?: database.confederationDao().getEventsForConfederation(signed.pubKey)
|
||||
.firstOrNull { it.kind == ConfederationKinds.PROFILE_CHANGE && ConfederationProfileStatements.parseChange(it.toEvent())?.profileId == signed.id }?.id
|
||||
val filed = database.confederationDao().record(
|
||||
ConfederationEvent(
|
||||
id = signed.id,
|
||||
kind = signed.kind,
|
||||
pubKey = signed.pubKey,
|
||||
proposalId = changeId ?: signed.id,
|
||||
proposalId = change ?: signed.id,
|
||||
eventCreatedAt = signed.createdAt,
|
||||
eventJson = signed.toJson(),
|
||||
confederationId = signed.pubKey,
|
||||
)
|
||||
)
|
||||
if (filed) runCatching { announcePublished(database, signed) }
|
||||
.onFailure { logger.w(throwable = it) { "Filed profile ${signed.id.take(8)} but could not write its line" } }
|
||||
return filed
|
||||
}
|
||||
|
||||
/**
|
||||
* A kind:0 heard on a relay: filed if its author is a confederation this device knows, by record
|
||||
* or charter, and its key signed it (D7). How a member who is not an admin learns of a new profile.
|
||||
*/
|
||||
suspend fun hearProfile(database: GizaDatabase, event: Event): Boolean {
|
||||
if (event.kind != MetadataEvent.KIND) return false
|
||||
if (membership(database, event.pubKey) == null) return false
|
||||
return recordProfile(database, event)
|
||||
}
|
||||
|
||||
/**
|
||||
* "Atlas has a new profile", in each member group's room this device holds, once per profile and
|
||||
* only for the newest: an older one arriving late changes nothing a reader sees. The line carries
|
||||
* the confederation's id, so it opens the confederation.
|
||||
*/
|
||||
private suspend fun announcePublished(database: GizaDatabase, signed: Event) {
|
||||
val profiles = profiles(database, signed.pubKey)
|
||||
if (profiles.newest?.second != signed.id) return
|
||||
val membership = membership(database, signed.pubKey) ?: return
|
||||
val newName = ConfederationProfileRefusal.metadataOf(signed)?.anyName()?.takeIf { it.isNotBlank() }
|
||||
membership.groups.mapNotNull { database.chatRoomDao().findChatRoomById(it) }.forEach { room ->
|
||||
database.chatMessageDao().upsert(
|
||||
ChatMessage(
|
||||
senderPublicKey = signed.pubKey,
|
||||
isUserMessage = false,
|
||||
giftWrapPayloadId = null,
|
||||
marmotGroupEventId = null,
|
||||
marmotInnerEventId = null,
|
||||
chatRoomId = room.chatRoom.id,
|
||||
content = if (newName != null && newName != membership.name) "${membership.name} has a new profile, as $newName" else "${membership.name} has a new profile",
|
||||
messageType = ChatMessage.TYPE_CONFEDERATION_PROFILE_PUBLISHED,
|
||||
createdAt = Instant.fromEpochSeconds(signed.createdAt),
|
||||
frostSigningSessionId = signed.pubKey,
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a confederation's signed profile is sent besides the public relays: each member group's
|
||||
* inbox relays, which its members' devices already read (D7).
|
||||
*/
|
||||
suspend fun publishRelaysFor(database: GizaDatabase, confederationId: HexKey): List<String> {
|
||||
val membership = membership(database, confederationId) ?: return emptyList()
|
||||
return membership.groups.flatMap { group ->
|
||||
InboxAnnouncements.relaysOf(database, group).ifEmpty { InboxReplies.announcedRelaysOf(database, group) }
|
||||
}.map { it.url }.distinct()
|
||||
}
|
||||
|
||||
// ---- reading ---------------------------------------------------------------------------------
|
||||
|
||||
+1
-1
@@ -56,7 +56,7 @@ class ConfederationPublisher(
|
||||
|
||||
/** 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 }
|
||||
val targets = (Relays.eventPublishRelaySet.map { it.url } + repository.extraRelaysFor(event))
|
||||
.map { it.trim() }
|
||||
.filter { it.startsWith("wss://") || it.startsWith("ws://") }
|
||||
.distinct()
|
||||
|
||||
+3
-1
@@ -570,7 +570,9 @@ object ConfederationSigningManager {
|
||||
if (signed.kind == MetadataEvent.KIND) {
|
||||
val changeId = vouchersFor(database, held, signed.id, now = 0).firstNotNullOfOrNull { ConfederationProfileStatements.parseVoucher(it)?.changeId }
|
||||
ConfederationProfileManager.recordProfile(database, signed, changeId)
|
||||
if (attempt.proposerPublicKey == attempt.userPublicKey) database.confederationDao().markOwn(signed.id, attempt.id)
|
||||
// Owed by every device that signed it, not only the one that started it: the same event
|
||||
// from several devices is one event to a relay, and nobody waits on one phone (D7, as built).
|
||||
database.confederationDao().markOwn(signed.id, attempt.id)
|
||||
}
|
||||
logger.i("Confederation ${held.confederation.id.take(12)} signed ${signed.id.take(8)}")
|
||||
}
|
||||
|
||||
@@ -242,6 +242,11 @@ object InboxReplies {
|
||||
}
|
||||
|
||||
/** Where [publicKey] reads private mail: their 10050, as this device last heard it. */
|
||||
/** The inbox relays [publicKey] has announced, as this device has heard them; nothing if none. */
|
||||
internal suspend fun announcedRelaysOf(database: GizaDatabase, publicKey: HexKey): List<NormalizedRelayUrl> =
|
||||
database.nostrEventDao().getNostrEventByPublicKeyAndKind(publicKey, InboxAnnouncement.RELAYS_KIND)
|
||||
?.toEvent()?.let { InboxAnnouncement.announcedRelaysOf(it) }.orEmpty()
|
||||
|
||||
private suspend fun relaysOf(database: GizaDatabase, publicKey: HexKey): List<NormalizedRelayUrl> =
|
||||
database.nostrEventDao().getNostrEventByPublicKeyAndKind(publicKey, InboxAnnouncement.RELAYS_KIND)
|
||||
?.toEvent()?.let { InboxAnnouncement.announcedRelaysOf(it) }
|
||||
|
||||
+10
-3
@@ -3,6 +3,7 @@ package mobi.giza.compose.managers
|
||||
import co.touchlab.kermit.Logger
|
||||
import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent
|
||||
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
|
||||
import com.vitorpamplona.quartz.nip01Core.relay.commands.toRelay.ReqCmd
|
||||
@@ -234,9 +235,13 @@ class LiveSubscriptionManager(
|
||||
* public; what groups say to each other about forming one goes between their inboxes
|
||||
* (docs/confederation-without-coordinator.md, D12).
|
||||
*/
|
||||
internal fun confederationFilters(roomIds: List<HexKey>): List<Filter> =
|
||||
internal fun confederationFilters(roomIds: List<HexKey>, confederationIds: List<HexKey> = emptyList()): List<Filter> =
|
||||
roomIds.chunked(MAX_CONFEDERATION_IDS).map { chunk ->
|
||||
Filter(kinds = listOf(ConfederationKinds.CHARTER), tags = mapOf("p" to chunk), limit = INITIAL_GROUP_HISTORY_LIMIT)
|
||||
} + confederationIds.distinct().sorted().chunked(MAX_CONFEDERATION_IDS).map { chunk ->
|
||||
// Each known confederation's own profile: how every member of every member group
|
||||
// hears it changed (docs/confederation-profile.md, D7). Replaceable, so one each.
|
||||
Filter(kinds = listOf(MetadataEvent.KIND), authors = chunk, limit = chunk.size)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -423,8 +428,10 @@ class LiveSubscriptionManager(
|
||||
*/
|
||||
@OptIn(FlowPreview::class)
|
||||
private suspend fun followConfederations(publicKey: HexKey, keyPair: KeyPair, repository: ConfederationRepository) {
|
||||
chatRepository.observeChatRoomListByPublicKey(publicKey).map(::confederationRoomIdsFrom).distinctUntilChanged()
|
||||
.map(::confederationFilters)
|
||||
combine(
|
||||
chatRepository.observeChatRoomListByPublicKey(publicKey).map(::confederationRoomIdsFrom).distinctUntilChanged(),
|
||||
repository.observeKnownConfederations(),
|
||||
) { roomIds, confederationIds -> confederationFilters(roomIds, confederationIds) }
|
||||
.distinctUntilChanged()
|
||||
.debounce(GROUP_CHANGE_DEBOUNCE)
|
||||
.collectLatest { filters ->
|
||||
|
||||
+6
@@ -123,6 +123,12 @@ interface ConfederationRepository {
|
||||
/** One change to a confederation's profile, as it changes; null while this device does not hold it. */
|
||||
fun observeProfileChange(changeId: HexKey): Flow<ConfederationProfileChangeStatus?> = flowOf(null)
|
||||
|
||||
/** Every formed confederation this device knows of, by record or charter: whose kind:0 the relays are asked for (D7). */
|
||||
fun observeKnownConfederations(): Flow<List<HexKey>> = flowOf(emptyList())
|
||||
|
||||
/** Relays an owed event goes to besides the public ones: a confederation's profile, to each member group's inbox relays. */
|
||||
suspend fun extraRelaysFor(event: ConfederationEvent): List<String> = emptyList()
|
||||
|
||||
/** A formed confederation as this device knows it: by its record, or by its charter. docs/confederation-profile.md, D1. */
|
||||
suspend fun membership(confederationId: HexKey): ConfederationProfileManager.Membership? = null
|
||||
|
||||
|
||||
@@ -58,6 +58,15 @@ class ConfederationRelayTest {
|
||||
ExperimentalFeatures.confederationOverride = null
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a known confederation adds one filter for its own profile, by its key`() {
|
||||
val atlas = "ab".repeat(32)
|
||||
val filters = LiveSubscriptionManager.confederationFilters(listOf("room-a"), listOf(atlas))
|
||||
assertEquals(2, filters.size)
|
||||
assertEquals(listOf(0), filters[1].kinds, "docs/confederation-profile.md, D7")
|
||||
assertEquals(listOf(atlas), filters[1].authors)
|
||||
}
|
||||
|
||||
// --- the subscription
|
||||
|
||||
@Test
|
||||
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package mobi.giza.compose.managers
|
||||
|
||||
import androidx.room3.Room
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Event
|
||||
import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
|
||||
import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
|
||||
import com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto
|
||||
import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent
|
||||
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer
|
||||
import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate
|
||||
import fr.acinq.bitcoin.PrivateKey
|
||||
import kotlin.test.AfterTest
|
||||
import kotlin.test.BeforeTest
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertTrue
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Instant
|
||||
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.ChatMessage
|
||||
import mobi.giza.compose.database.model.ChatRoom
|
||||
import mobi.giza.compose.database.model.NostrEvent
|
||||
import mobi.giza.compose.database.model.Profile
|
||||
import mobi.giza.compose.database.repository.DatabaseConfederationRepository
|
||||
import mobi.giza.compose.extensions.toHex
|
||||
import mobi.giza.compose.managers.ConfederationStatementFixture.key
|
||||
import mobi.giza.compose.managers.ConfederationStatementFixture.npub
|
||||
import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent
|
||||
import mobi.giza.compose.nostr.confederation.ConfederationKinds
|
||||
import mobi.giza.compose.nostr.inbox.InboxAnnouncement
|
||||
|
||||
/**
|
||||
* The confederation's profile on the public wire (docs/confederation-profile.md, Phase 6): a device
|
||||
* that holds only the charter -- a member of a member group who is not an admin -- hears the signed
|
||||
* profile off a relay, files it, and says so in its group's room; and an owed profile goes to every
|
||||
* member group's inbox relays as well as the public ones.
|
||||
*/
|
||||
class ConfederationProfileRelayJvmTest {
|
||||
private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder<GizaDatabase>())
|
||||
private val repository = DatabaseConfederationRepository(db, kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined))
|
||||
|
||||
private val agora = key(1)
|
||||
private val polis = key(2)
|
||||
private val atlasKey = key(9)
|
||||
private val atlas = npub(atlasKey)
|
||||
private val me = npub(key(20))
|
||||
private val now = Clock.System.now().epochSeconds
|
||||
|
||||
@BeforeTest
|
||||
fun setUp() = runBlocking<Unit> {
|
||||
db.nostrEventDao().upsert(NostrEvent(id = "e$me".take(64), pubKey = me, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)))
|
||||
db.profileDao().upsert(Profile(publicKey = me, nostrEventId = "e$me".take(64)))
|
||||
// A member of Polis, and nothing more: no record of the confederation, no inbox key.
|
||||
db.chatRoomDao().upsert(ChatRoom(id = npub(polis), userPublicKey = me, subject = "#Polis", description = null, mlsGroupState = "00"))
|
||||
val tags = ConfederationCharterEvent.assembleTags("Atlas", listOf(npub(agora), npub(polis)), threshold = 2)
|
||||
assertTrue(ConfederationManager.record(db, signed(atlasKey, EventTemplate(now - 60, ConfederationKinds.CHARTER, tags, ""))))
|
||||
}
|
||||
|
||||
@AfterTest
|
||||
fun close() = db.close()
|
||||
|
||||
private fun signed(by: PrivateKey, template: EventTemplate<Event>): Event {
|
||||
val pubKey = npub(by)
|
||||
val id = EventHasher.hashId(pubKey, template.createdAt, template.kind, template.tags, template.content)
|
||||
return Event(id, pubKey, template.createdAt, template.kind, template.tags, template.content, Nip01Crypto.sign(id.hexToByteArray(), by.value.toByteArray()).toHex())
|
||||
}
|
||||
|
||||
private fun profile(content: String, at: Long = now, by: PrivateKey = atlasKey) = signed(by, EventTemplate(at, MetadataEvent.KIND, emptyArray(), content))
|
||||
|
||||
private suspend fun publishedLines() = db.chatMessageDao().getChatMessagesByChatRoomId(npub(polis))
|
||||
.map { it.chatMessage }.filter { it.messageType == ChatMessage.TYPE_CONFEDERATION_PROFILE_PUBLISHED }
|
||||
|
||||
@Test
|
||||
fun `a member with only the charter hears the profile, and its group's room says so`() = runBlocking<Unit> {
|
||||
assertTrue(repository.record(profile("""{"name":"Atlas of the Coast"}""")), "filed from the relay")
|
||||
assertEquals("Atlas of the Coast", repository.observeProfile(atlas).first()?.name())
|
||||
val line = publishedLines().single()
|
||||
assertEquals("Atlas has a new profile, as Atlas of the Coast", line.content)
|
||||
assertEquals(atlas, line.frostSigningSessionId, "the line opens the confederation")
|
||||
assertEquals(listOf(atlas), repository.observeKnownConfederations().first(), "and the relays are asked for it by its key")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an older profile heard late changes nothing a reader sees`() = runBlocking<Unit> {
|
||||
repository.record(profile("""{"name":"Atlas of the Coast"}""", at = now))
|
||||
repository.record(profile("""{"name":"Atlas"}""", at = now - 100))
|
||||
assertEquals("Atlas of the Coast", repository.observeProfile(atlas).first()?.name())
|
||||
assertEquals(1, publishedLines().size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a kind 0 from anyone but a known confederation is not the confederation's`() = runBlocking<Unit> {
|
||||
assertFalse(repository.record(profile("""{"name":"Someone"}""", by = key(30))))
|
||||
assertFalse(repository.record(Event(profile("{}").id, atlas, now, 0, emptyArray(), "{}", "00".repeat(64))), "nor one its key did not sign")
|
||||
assertEquals(emptyList(), publishedLines())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an owed profile goes to every member group's inbox relays as well`() = runBlocking<Unit> {
|
||||
val relays = listOf("wss://agora.example.com", "wss://polis.example.com")
|
||||
listOf(agora, polis).zip(relays).forEach { (group, url) ->
|
||||
val announcement = signed(group, InboxAnnouncement.relaysTemplate(listOf(RelayUrlNormalizer.normalizeOrNull(url)!!), now - 30))
|
||||
db.nostrEventDao().upsert(
|
||||
NostrEvent(
|
||||
id = announcement.id, pubKey = announcement.pubKey, kind = announcement.kind, tags = announcement.tags,
|
||||
content = announcement.content, sig = announcement.sig, createdAt = Instant.fromEpochSeconds(announcement.createdAt),
|
||||
)
|
||||
)
|
||||
}
|
||||
repository.record(profile("""{"name":"Atlas"}"""))
|
||||
val row = db.confederationDao().getEventsForConfederation(atlas).single { it.kind == MetadataEvent.KIND }
|
||||
assertEquals(relays.map { "$it/" }.toSet(), repository.extraRelaysFor(row).toSet())
|
||||
}
|
||||
}
|
||||
@@ -606,6 +606,21 @@ Tests: `ConfederationProfileRelayTest`, with the relay as a copy, covering that
|
||||
is not an admin and holds no role sees the new profile on the confederation's screen, and that a
|
||||
later change published before an earlier one supersedes it.
|
||||
|
||||
**Built.** `ConfederationProfileRelayJvmTest` 4/4: a device holding only the charter hears the profile
|
||||
off a relay, reads it as the confederation's newest, and writes "Atlas has a new profile, as …" in its
|
||||
group's room, opening the confederation; an older profile heard late changes nothing a reader sees;
|
||||
a kind:0 from anyone but a known confederation, or one its key did not sign, is not filed; an owed
|
||||
profile goes to every member group's announced inbox relays too. `ConfederationRelayTest` gains the
|
||||
filter by author. Supersession was already Phase 1's and is tested there. Where it differs from the
|
||||
above:
|
||||
|
||||
| what the phase said | what it turned out to be |
|
||||
|---|---|
|
||||
| owed on the starter's device, the others as a fallback after an hour | **owed by every device that signed it.** The same event from several devices is one event to a relay, and a fallback would have needed a way to tell that nobody else's copy got out, which nothing here can see |
|
||||
| "the published line on every member's device, from the kind:0 off relays" | from wherever the kind:0 is first filed -- the signing's end on a role holder's device, a relay everywhere else -- and only for the newest profile held |
|
||||
| the subscription's confederation ids | `ConfederationRepository.observeKnownConfederations`: every `Confederation` row and every charter's author, so the filter follows a charter as it arrives |
|
||||
| a kind:0 off a relay | `ConfederationManager.record` hands it to `ConfederationProfileManager.hearProfile`, which files it only for a confederation this device knows by record or charter |
|
||||
|
||||
### Phase 7: rooms that say what they are (D9, D10)
|
||||
|
||||
- The confederation's room: members labelled by group, the **Groups** card, and the sentence about
|
||||
|
||||
Reference in new issue
Block a user