feat: a confederation signs the profile its groups endorsed, with nobody asked (confederation-profile, Phase 5)

A group's voucher, signed beside its seals, is carried into the
confederation's room by the group's role holders (kind 30396). Once a
role holder's device holds T groups' vouchers for a change, the first in
the roster's order starts the signing, with ten minutes a place for
those after, and again after a backoff when an attempt fails. Each role
holder's device answers for its seats from what its groups said: yes
where the group vouched, no where it did not. Two attempts at once end
in the one whose id sorts first.

A kind:0 without enough vouchers, or older than one already signed, is
refused, so the confederation's room no longer edits its profile; posts
and the charter keep the direct path. The signed profile is filed under
the confederation and owed to relays by the device that started it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-22 23:51:36 +02:00
1 parent 5d6bbcd5e8
commit 8d494ddbd3
11 files changed
+500 -38

No files matched your search

@@ -76,6 +76,10 @@ interface ConfederationCeremonyDao {
@Query("SELECT * FROM ConfederationSigningAttempt WHERE confederationId = :confederationId ORDER BY createdAt DESC")
fun observeAttempts(confederationId: HexKey): Flow<List<mobi.giza.compose.database.model.ConfederationSigningAttempt>>
/** Every attempt [userPublicKey]'s device holds for [confederationId], oldest first. */
@Query("SELECT * FROM ConfederationSigningAttempt WHERE confederationId = :confederationId AND userPublicKey = :userPublicKey ORDER BY createdAt ASC")
suspend fun getAttempts(confederationId: HexKey, userPublicKey: HexKey): List<mobi.giza.compose.database.model.ConfederationSigningAttempt>
@Query("SELECT * FROM ConfederationSigningAttempt WHERE userPublicKey = :userPublicKey AND stage NOT IN ('COMPLETE', 'FAILED')")
suspend fun getRunningAttempts(userPublicKey: HexKey): List<mobi.giza.compose.database.model.ConfederationSigningAttempt>
@@ -175,6 +175,9 @@ class DatabaseChatRepository(
// A formed confederation's room, made by its coordinator's device.
// docs/confederation.md, Phase 13.
launch { ConfederationFollowThrough.observe(database = database, chatRepository = this@DatabaseChatRepository, keyPair = keyPair) }
// A change to a formed confederation's profile its groups endorsed, signed by the
// confederation with nobody asked. docs/confederation-profile.md, D6.
launch { mobi.giza.compose.managers.ConfederationProfileFollowThrough.observe(database = database, keyPair = keyPair) }
keyPair.privKey?.let { secret ->
launch {
runCatching { ConfederationRitualManager.resumeRunning(database, keyPair.pubKey.toHex(), secret) }
@@ -0,0 +1,117 @@
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 com.vitorpamplona.quartz.nip01Core.core.toHexKey
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import kotlin.coroutines.cancellation.CancellationException
import kotlin.time.Clock
import kotlin.time.Duration
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Instant
import kotlinx.coroutines.delay
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.ConfederationSigningAttempt
import mobi.giza.compose.database.model.ConfederationSigningStage
import mobi.giza.compose.nostr.confederation.ConfederationKinds
import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState
/**
* From a change its groups endorsed to the confederation's signature on it, with nobody asked
* (docs/confederation-profile.md, D6).
*
* Once a role holder's device holds vouchers from `T` groups for a change, somebody has to start the
* signing. Nobody is in charge, so an order says who: the roster's people sorted bytewise, the first
* at once, the `k`-th once `k` [WAIT_PER_PLACE]s have passed since the `T`-th voucher reached their
* device with no attempt for it heard. A failed attempt -- a nonce lost to a restart, a selected
* device gone quiet -- is started again by the same rule, after a delay that doubles from
* [WAIT_PER_PLACE] up to [MAX_BACKOFF], until the change expires.
*/
object ConfederationProfileFollowThrough {
private val logger = Logger.withTag("ConfederationProfileFollowThrough")
private val mutex = Mutex()
val WAIT_PER_PLACE: Duration = 10.minutes
val MAX_BACKOFF: Duration = 2.hours
private val LOOK_AGAIN: Duration = 1.minutes
/** Looks at every change this device holds, every [LOOK_AGAIN], for as long as it runs. */
suspend fun observe(database: GizaDatabase, keyPair: KeyPair) {
val secret = keyPair.privKey ?: return
val me = keyPair.pubKey.toHexKey()
while (true) {
runCatching { sweep(database, me, secret) }.onFailure {
if (it is CancellationException) throw it
logger.e("Could not follow profile changes through", it)
}
delay(LOOK_AGAIN)
}
}
/** One look at every change this device holds. Returns the attempts it started. */
suspend fun sweep(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray, now: Instant = Clock.System.now()): List<ConfederationSigningAttempt> =
database.confederationDao().getProfileChanges().mapNotNull { row ->
runCatching { takeNextStep(database, row.id, userPublicKey, nostrPrivateKey, now) }
.onFailure { if (it is CancellationException) throw it; logger.e("Could not follow ${row.id.take(8)} through", it) }
.getOrNull()
}
/**
* Starts the confederation's signing of [changeId]'s kind:0 if it is [userPublicKey]'s turn, and
* returns the attempt it started; null when there is nothing to do here yet.
*/
suspend fun takeNextStep(
database: GizaDatabase,
changeId: HexKey,
userPublicKey: HexKey,
nostrPrivateKey: ByteArray,
now: Instant = Clock.System.now(),
): ConfederationSigningAttempt? = mutex.withLock {
val change = ConfederationProfileManager.change(database, changeId) ?: return@withLock null
val held = ConfederationSigningManager.held(database, change.confederation) ?: return@withLock null
val place = held.plan.people.sorted().indexOf(userPublicKey).takeIf { it >= 0 } ?: return@withLock null
val room = database.chatRoomDao().findChatRoomById(held.confederation.id) ?: return@withLock null
val status = ConfederationProfileManager.status(database, changeId, now.epochSeconds) ?: return@withLock null
if (status.state != ConfederationProfileChangeState.ENDORSED) return@withLock null
val vouchers = ConfederationSigningManager.vouchersFor(database, held, change.profileId, now.epochSeconds)
if (vouchers.size < held.plan.proposal.threshold) return@withLock null
val attempts = database.confederationCeremonyDao().getAttempts(held.confederation.id, userPublicKey)
.filter { runCatching { Event.fromJson(it.eventJson).id }.getOrNull() == change.profileId }
if (attempts.any { it.isRunning || it.stage == ConfederationSigningStage.COMPLETE }) return@withLock null
val failures = attempts.filter { it.stage == ConfederationSigningStage.FAILED }
val since = if (failures.isEmpty()) {
arrivalOfThreshold(database, change.confederation, vouchers.map { it.id }.toSet(), held.plan.proposal.threshold) ?: return@withLock null
} else {
failures.maxOf { it.updatedAt } + backoff(failures.size)
}
if (now < since + WAIT_PER_PLACE * place) return@withLock null
logger.i("Starting the confederation's signing of change ${changeId.take(8)}, place $place, after ${failures.size} failed attempt(s)")
ConfederationSigningManager.propose(
database, room, userPublicKey, change.profile.kind, change.profile.tags, change.profile.content, nostrPrivateKey,
createdAt = change.profile.createdAt, vouchers = vouchers,
)
}
/** How long after the [failures]-th failure the next attempt waits, before each place's own wait. */
fun backoff(failures: Int): Duration {
var wait = WAIT_PER_PLACE
repeat((failures - 1).coerceAtLeast(0)) { wait = (wait * 2).coerceAtMost(MAX_BACKOFF) }
return wait
}
/** When the [threshold]-th of [voucherIds] reached this device: the moment the change could be signed. */
private suspend fun arrivalOfThreshold(database: GizaDatabase, confederationId: HexKey, voucherIds: Set<HexKey>, threshold: Int): Instant? =
database.confederationDao().getEventsForConfederation(confederationId)
.filter { it.kind == ConfederationKinds.VOUCHER && it.id in voucherIds }
.map { it.receivedAt }
.sorted()
.getOrNull(threshold - 1)
}
@@ -376,6 +376,11 @@ object ConfederationProfileManager {
suspend fun onSigned(database: GizaDatabase, session: FrostSigningSession, rumor: Event, signedEvents: List<Event>) {
recordStatement(database, rumor, seal = null, inboxRoomId = session.chatRoomId)
signedEvents.filter { it.kind == ConfederationKinds.VOUCHER && it.pubKey.equals(session.chatRoomId, ignoreCase = true) }
.forEach { recordVoucher(database, it) }
.forEach { voucher ->
recordVoucher(database, voucher)
// Into the confederation's room, where its role holders act on it (D5): from this
// device, if its owner holds one of the group's seats.
ConfederationSigningManager.postVoucher(database, session.userPublicKey, voucher)
}
}
}
@@ -40,6 +40,8 @@ import mobi.giza.compose.database.model.MarmotInnerEvent
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.extensions.toHex
import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent
import mobi.giza.compose.nostr.confederation.ConfederationKinds
import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements
import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents
import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder
import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder.Plan
@@ -82,6 +84,15 @@ object ConfederationSigningManager {
const val RESTARTED = "A device restarted while signing, so this attempt cannot finish. Propose it again"
/** A kind:0 asked for without enough of its groups' vouchers (docs/confederation-profile.md, D5). */
const val THROUGH_GROUPS = "A confederation's profile changes through its groups, and not enough of them have endorsed this one"
/** A kind:0 older than one the confederation has already signed: relays would keep the newer. */
const val SUPERSEDED = "The confederation has signed a newer profile since"
/** Two attempts over the same kind:0: the one whose id sorts first goes on (D6). */
const val CROSSED = "Another attempt is signing this change"
// ---- what a confederation is on this device ------------------------------------------------
/** Everything this device holds about one confederation, read back from storage. */
@@ -111,7 +122,36 @@ object ConfederationSigningManager {
held(database, confederationId)?.plan?.seatsOf(userPublicKey)?.isNotEmpty() == true
/** Why this device would not sign [event] for [held]'s confederation, or null. */
private fun refusalOf(held: Held, event: Event): String? = when {
private suspend fun refusalOf(database: GizaDatabase, held: Held, event: Event): String? =
basicRefusalOf(held, event) ?: if (event.kind == MetadataEvent.KIND) profileRefusalOf(database, held, event) else null
/**
* A kind:0 is signed only on its groups' word: vouchers from at least `T` member groups, each for
* exactly this kind:0 and not expired, and no newer profile signed since (docs/confederation-profile.md, D5).
*/
private suspend fun profileRefusalOf(database: GizaDatabase, held: Held, event: Event): String? {
if (vouchedGroups(database, held, event.id).size < held.plan.proposal.threshold) return THROUGH_GROUPS
val newest = ConfederationProfileManager.profiles(database, held.confederation.id).newest
if (newest != null && newest.second != event.id && (newest.first > event.createdAt || (newest.first == event.createdAt && newest.second < event.id))) return SUPERSEDED
return null
}
/** The member groups whose unexpired voucher for [profileId] this device holds. */
internal suspend fun vouchedGroups(database: GizaDatabase, held: Held, profileId: HexKey, now: Long = Clock.System.now().epochSeconds): Set<HexKey> =
vouchersFor(database, held, profileId, now).map { it.pubKey }.toSet()
/** The vouchers for [profileId] this device holds, one per member group, unexpired. */
internal suspend fun vouchersFor(database: GizaDatabase, held: Held, profileId: HexKey, now: Long = Clock.System.now().epochSeconds): List<Event> =
database.confederationDao().getEventsForConfederation(held.confederation.id)
.filter { it.kind == ConfederationKinds.VOUCHER }
.map { it.toEvent() }
.filter { voucher ->
val parsed = ConfederationProfileStatements.parseVoucher(voucher)
parsed != null && parsed.profileId == profileId && parsed.expiresAt >= now && voucher.pubKey in held.plan.groups
}
.distinctBy { it.pubKey }
private fun basicRefusalOf(held: Held, event: Event): String? = when {
event.pubKey != held.confederation.id -> "The event is not authored by the confederation"
event.kind !in SIGNABLE_KINDS -> "A confederation signs only its profile, its posts and its charter here"
event.kind == ConfederationCharterEvent.KIND && !isTrueCharter(held, event) ->
@@ -151,13 +191,16 @@ object ConfederationSigningManager {
content: String,
nostrPrivateKey: ByteArray,
createdAt: Long = Clock.System.now().epochSeconds,
/** For a kind:0: the groups' vouchers it is signed on, carried on the proposal (D5). */
vouchers: List<Event> = emptyList(),
): ConfederationSigningAttempt = mutex.withLock {
val roomId = localChatRoom.chatRoom.id
val held = held(database, roomId) ?: throw IllegalStateException("This device holds no confederation for this room")
check(held.plan.seatsOf(userPublicKey).isNotEmpty()) { "Only someone who holds a role in the confederation can propose for it" }
val id = EventHasher.hashId(roomId, createdAt, kind, tags, content)
val event = Event(id, roomId, createdAt, kind, tags, content, "")
refusalOf(held, event)?.let { throw IllegalArgumentException(it) }
vouchers.forEach { ConfederationProfileManager.recordVoucher(database, it) }
refusalOf(database, held, event)?.let { throw IllegalArgumentException(it) }
val attempt = ConfederationSigningAttempt(
id = RandomInstance.bytes(32).toHex(),
@@ -169,13 +212,66 @@ object ConfederationSigningManager {
stage = ConfederationSigningStage.SELECTING,
)
database.confederationCeremonyDao().upsertAttempt(attempt)
announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED, "A proposal for the confederation to sign: ${describe(event)}")
broadcast(database, localChatRoom, attempt, ConfederationSigningEvents.PROPOSAL, event.toJson())
publishAvailability(database, localChatRoom, attempt, held, available = true)
if (event.kind == MetadataEvent.KIND) {
val carried = vouchersFor(database, held, event.id)
announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED, profileLine(database, carried))
broadcast(database, localChatRoom, attempt, ConfederationSigningEvents.PROPOSAL, event.toJson(), carried.map { arrayOf(ConfederationSigningEvents.VOUCHER_TAG, it.toJson()) })
publishAvailabilityByGroup(database, localChatRoom, attempt, held, carried.map { it.pubKey }.toSet())
settleCrossing(database, localChatRoom, held, attempt, event.id)
} else {
announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED, "A proposal for the confederation to sign: ${describe(event)}")
broadcast(database, localChatRoom, attempt, ConfederationSigningEvents.PROPOSAL, event.toJson())
publishAvailability(database, localChatRoom, attempt, held, available = true)
}
advance(database, localChatRoom, attempt.id, nostrPrivateKey)
database.confederationCeremonyDao().getAttempt(attempt.id)!!
}
/** The line a profile's signing writes in the confederation's room: whose word it is signed on. */
private suspend fun profileLine(database: GizaDatabase, vouchers: List<Event>): String =
"Signing the profile endorsed by " + vouchers.map { ConfederationManager.nameOf(database, it.pubKey) }.joinToString()
/**
* Two attempts over one kind:0 -- two people in the order who both thought it their turn -- end in
* the one whose id sorts first, on every device; the others are ended out loud (D6).
*/
private suspend fun settleCrossing(database: GizaDatabase, room: LocalChatRoom, held: Held, attempt: ConfederationSigningAttempt, eventId: HexKey) {
val running = database.confederationCeremonyDao().getAttempts(held.confederation.id, attempt.userPublicKey)
.filter { it.isRunning && runCatching { Event.fromJson(it.eventJson).id }.getOrNull() == eventId }
if (running.size < 2) return
val keep = running.minBy { it.id }
running.filter { it.id != keep.id }.forEach { failOut(database, room, it, CROSSED) }
}
// ---- vouchers --------------------------------------------------------------------------------
/**
* Carries [voucher], which this device's group just signed, into the confederation's room for
* [userPublicKey], who holds a seat in that group: what the other role holders act on (D5).
* Several of the group's role holders send the same one; receivers keep one.
*/
suspend fun postVoucher(database: GizaDatabase, userPublicKey: HexKey, voucher: Event) {
val parsed = ConfederationProfileStatements.parseVoucher(voucher) ?: return
val held = held(database, parsed.confederation) ?: return
if (held.plan.seatsOf(userPublicKey).none { it.group == voucher.pubKey }) return
val room = database.chatRoomDao().findChatRoomById(held.confederation.id) ?: return
val createdAt = Clock.System.now().epochSeconds
val content = voucher.toJson()
val tags = emptyArray<Array<String>>()
val id = EventHasher.hashId(userPublicKey, createdAt, ConfederationSigningEvents.VOUCHER, tags, content)
database.marmotInnerEventDao().upsert(
MarmotInnerEvent(
id = id,
publicKey = userPublicKey,
kind = ConfederationSigningEvents.VOUCHER,
createdAt = Instant.fromEpochSeconds(createdAt),
tags = tags,
content = content,
chatRoomId = room.chatRoom.id,
)
)
}
// ---- inbound ---------------------------------------------------------------------------
suspend fun process(
@@ -185,6 +281,15 @@ object ConfederationSigningManager {
userPublicKey: HexKey,
nostrPrivateKey: ByteArray,
) = mutex.withLock {
if (innerEvent.kind == ConfederationSigningEvents.VOUCHER) {
// From a role holder of the group that signed it; kept if it is that group's own.
val held = held(database, localChatRoom.chatRoom.id) ?: return@withLock
val voucher = Event.fromJsonOrNull(innerEvent.content) ?: return@withLock
if (held.plan.seatsOf(innerEvent.pubKey).none { it.group == voucher.pubKey }) return@withLock
if (ConfederationProfileStatements.parseVoucher(voucher)?.confederation != held.confederation.id) return@withLock
ConfederationProfileManager.recordVoucher(database, voucher)
return@withLock
}
val attemptId = ConfederationSigningEvents.parseSessionId(innerEvent.tags) ?: return@withLock
val held = held(database, localChatRoom.chatRoom.id) ?: run {
logger.i("Signing message for ${localChatRoom.chatRoom.id.take(12)}, which is no confederation here; leaving it stored")
@@ -222,7 +327,8 @@ object ConfederationSigningManager {
userPublicKey = userPublicKey,
eventJson = event.toJson(),
)
val refusal = refusalOf(held, event)
ConfederationSigningEvents.parseVouchers(innerEvent.tags).forEach { ConfederationProfileManager.recordVoucher(database, it) }
val refusal = refusalOf(database, held, event)
if (refusal != null) {
// Declined out loud, as a FROST member declines what it cannot check: this person's
// roles will not sign, and the group can tell that from a phone in a pocket.
@@ -232,11 +338,35 @@ object ConfederationSigningManager {
return database.confederationCeremonyDao().getAttempt(attemptId)
}
database.confederationCeremonyDao().upsertAttempt(attempt)
if (event.kind == MetadataEvent.KIND) {
// Nobody is asked: each seat's group has already said, by its voucher or by not giving
// one (docs/confederation-profile.md, D5).
val vouchers = vouchersFor(database, held, event.id)
announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED, profileLine(database, vouchers))
publishAvailabilityByGroup(database, localChatRoom, attempt, held, vouchers.map { it.pubKey }.toSet())
replayStoredMessages(database, held, attempt)
settleCrossing(database, localChatRoom, held, attempt, event.id)
return database.confederationCeremonyDao().getAttempt(attemptId)
}
announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED, "A proposal for the confederation to sign: ${describe(event)}")
replayStoredMessages(database, held, attempt)
return database.confederationCeremonyDao().getAttempt(attemptId)
}
/**
* This person's answer for each of their seats, from what their groups said: yes where the seat's
* group vouched for the event, no where it did not. Says it as approved or declined, so nobody
* is asked.
*/
private suspend fun publishAvailabilityByGroup(database: GizaDatabase, room: LocalChatRoom, attempt: ConfederationSigningAttempt, held: Held, vouched: Set<HexKey>) {
if (own(database, attempt, ConfederationSigningEvents.AVAILABILITY) != null) return
val seats = held.plan.seatsOf(attempt.userPublicKey)
val answers = seats.associate { it.group to if (it.group in vouched) ConfederationSigningEvents.YES else ConfederationSigningEvents.NO }
val now = Clock.System.now()
update(database, attempt) { if (answers.values.any { it == ConfederationSigningEvents.YES }) it.copy(approvedAt = now) else it.copy(declinedAt = now) }
publishOwn(database, room, attempt, ConfederationSigningEvents.AVAILABILITY, ConfederationRitualEvents.encodeByGroup(answers))
}
/**
* Files one message. Per-person messages only from a person holding a role, with a value for
* exactly their roles; the session only from the proposer; a failure from anyone with a role.
@@ -274,7 +404,7 @@ object ConfederationSigningManager {
val room = database.chatRoomDao().findChatRoomById(attempt.confederationId) ?: return@withLock
val held = held(database, attempt.confederationId) ?: return@withLock
// Checked again: what is signed has to be what this device would sign now.
refusalOf(held, Event.fromJson(attempt.eventJson))?.let { why ->
refusalOf(database, held, Event.fromJson(attempt.eventJson))?.let { why ->
update(database, attempt) { it.copy(declinedAt = Clock.System.now(), failureReason = why) }
publishAvailability(database, room, attempt, held, available = false)
return@withLock
@@ -435,6 +565,13 @@ object ConfederationSigningManager {
ConfederationManager.record(database, signed)
if (attempt.proposerPublicKey == attempt.userPublicKey) database.confederationDao().markOwn(signed.id, attempt.id)
}
// A profile its groups decided: filed under the confederation beside the change it came from,
// and owed to relays by the device that started the signing (docs/confederation-profile.md, D7).
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)
}
logger.i("Confederation ${held.confederation.id.take(12)} signed ${signed.id.take(8)}")
}
@@ -505,8 +642,15 @@ object ConfederationSigningManager {
}
/** Queues a rumor for the confederation's Marmot room, encrypted to the room as a group event. */
private suspend fun broadcast(database: GizaDatabase, room: LocalChatRoom, attempt: ConfederationSigningAttempt, kind: Kind, content: String) {
val tags = arrayOf(ConfederationSigningEvents.sessionTag(attempt.id))
private suspend fun broadcast(
database: GizaDatabase,
room: LocalChatRoom,
attempt: ConfederationSigningAttempt,
kind: Kind,
content: String,
extraTags: List<Array<String>> = emptyList(),
) {
val tags = (listOf(ConfederationSigningEvents.sessionTag(attempt.id)) + extraTags).toTypedArray()
val createdAt = Clock.System.now().epochSeconds
val id = EventHasher.hashId(attempt.userPublicKey, createdAt, kind, tags, content)
database.marmotInnerEventDao().upsert(
@@ -21,6 +21,7 @@ import kotlinx.serialization.json.put
* | 30393 | each selected | per role: its public nonce |
* | 30394 | each selected | per role: its confirmation of the transcript and the event |
* | 30395 | each selected | per role: its member partial |
* | 30396 | a role holder | a group's signed voucher for a kind:0 (docs/confederation-profile.md) |
* | 30399 | anyone | failure, with a reason |
*
* Only the selection needs a coordinator: approvals arrive in a different order on every device,
@@ -38,7 +39,21 @@ object ConfederationSigningEvents {
const val PARTIALS: Kind = 30395
const val FAILURE: Kind = 30399
val ALL: Set<Kind> = setOf(PROPOSAL, AVAILABILITY, SESSION, NONCES, CONFIRMATIONS, PARTIALS, FAILURE)
/**
* A group's voucher for a kind:0 its confederation is to sign, carried into the confederation's
* room by the group's role holders once the group has signed it (docs/confederation-profile.md,
* D5). No attempt yet, so no session tag: it is what an attempt is started from.
*/
const val VOUCHER: Kind = 30396
/** On a 30390 over a kind:0: one signed 9438 per group that vouched for it. */
const val VOUCHER_TAG = "voucher"
val ALL: Set<Kind> = setOf(PROPOSAL, AVAILABILITY, SESSION, NONCES, CONFIRMATIONS, PARTIALS, VOUCHER, FAILURE)
/** The vouchers a 30390 carries, as the events they are. */
fun parseVouchers(tags: Array<Array<String>>): List<com.vitorpamplona.quartz.nip01Core.core.Event> =
tags.filter { it.size >= 2 && it[0] == VOUCHER_TAG }.mapNotNull { com.vitorpamplona.quartz.nip01Core.core.Event.fromJsonOrNull(it[1]) }
/** Sent once per person, a value per role. */
val PER_PERSON: Set<Kind> = setOf(AVAILABILITY, NONCES, CONFIRMATIONS, PARTIALS)
@@ -48,9 +48,11 @@ class EditGroupNostrProfileViewModel(
val isActionPending: MutableState<Boolean> = mutableStateOf(false)
/** Whether this room is a confederation's, whose statements the confederation signs. Read at load. */
var isConfederation: Boolean = false
private set
/**
* Never, now: a confederation's profile is not edited from its room but proposed by one of its
* groups (docs/confederation-profile.md, D5). Kept so the screen's routing reads the same.
*/
val isConfederation: Boolean = false
fun initiateEditGroupNostrProfile() {
viewModelScope.launch(Dispatchers.IO) {
@@ -64,9 +66,11 @@ class EditGroupNostrProfileViewModel(
groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId),
// The same condition the group detail screen gates the entry
// point on.
// Not a confederation's room: its profile changes through its groups, from
// its own screen (docs/confederation-profile.md, D5).
canSign = GroupStatementCapability.roomIsOpen(localChatRoom) &&
(frostSigningRepository.canSign(chatRoomId) ||
chatRepository.canSignAsConfederation(chatRoomId).also { isConfederation = it }),
frostSigningRepository.canSign(chatRoomId) &&
!chatRepository.canSignAsConfederation(chatRoomId),
)
}
}
@@ -113,19 +117,13 @@ class EditGroupNostrProfileViewModel(
viewModelScope.launch(Dispatchers.IO) {
val session = runCatching {
// A confederation's room signs through the confederation, not a FROST
// key: docs/confederation.md, Phase 15.
if (isConfederation) {
chatRepository.proposeAsConfederation(localChatRoom, template.kind, template.tags, template.content)
} else {
frostSigningRepository.proposeSigning(
localChatRoom = localChatRoom,
userPublicKey = activeUserPublicKey,
kind = template.kind,
tags = template.tags,
content = template.content,
)?.id
}
frostSigningRepository.proposeSigning(
localChatRoom = localChatRoom,
userPublicKey = activeUserPublicKey,
kind = template.kind,
tags = template.tags,
content = template.content,
)?.id
}.onFailure { error ->
logger.e("Failed to propose a nostr profile for $chatRoomId", error)
}.getOrNull()
@@ -44,7 +44,7 @@ class GroupNostrProfileViewModel(
localChatRoom = localChatRoom,
groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId),
canSign = GroupStatementCapability.roomIsOpen(localChatRoom) &&
(chatRepository.canSign(chatRoomId) || chatRepository.canSignAsConfederation(chatRoomId)),
chatRepository.canSign(chatRoomId) && !chatRepository.canSignAsConfederation(chatRoomId),
)
}
}
@@ -115,11 +115,15 @@ class ConfederationProfilePremiseJvmTest {
groups.setUp()
val agora = groups.groups[0]
val now = kotlin.time.Clock.System.now().epochSeconds
val tags = arrayOf(arrayOf("confederation", "aa".repeat(32)), arrayOf("profile", "bb".repeat(32)), arrayOf("e", "cc".repeat(32)))
// Signed the way Giza signs one: beside the seals of a change, in the same session
// (Phase 2 declines a voucher asked for on its own). The charter names the two groups.
val atlasKey = ByteArray(32).also { it[0] = 0x4b; it[31] = 1 }
val atlas = InboxWire.publicKeyOf(atlasKey)
val charter = signed(atlasKey, EventTemplate(now - 60, ConfederationKinds.CHARTER,
mobi.giza.compose.nostr.confederation.ConfederationCharterEvent.assembleTags("Atlas", groups.groups.map { it.roomId }, threshold = 2), ""))
groups.everyDevice.forEach { ConfederationManager.record(it.db, charter) }
val sessionId = groups.signed(agora) { device ->
FrostSigningManager.proposeSigningBatch(
device.db, device.room(), device.publicKey, listOf(EventTemplate<Event>(now, 9438, tags, "")),
).id
ConfederationProfileManager.proposeChange(device.db, device.room(), device.publicKey, atlas, emptyArray(), """{"name":"Atlas"}""").id
}
val voucher = agora.devices[2].db.groupSignedEventDao().getByChatRoomIdAndKind(agora.roomId, 9438)
.single { it.frostSigningSessionId == sessionId }.toEvent()
@@ -33,6 +33,11 @@ import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent
import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents
import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState
import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements
import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.minutes
/**
* A confederation signing as itself, one person per device (docs/confederation.md, Phase 14): a
@@ -105,7 +110,7 @@ class ConfederationSigningJvmTest {
}
}
private fun propose(kind: Int = MetadataEvent.KIND, content: String = """{"name":"Atlas","about":"A group of groups"}""") = runBlocking {
private fun propose(kind: Int = TextNoteEvent.KIND, content: String = "The first words of a group of groups") = runBlocking {
ConfederationSigningManager.propose(proposer.db, proposer.room, proposer.person, kind, emptyArray(), content, proposer.nsec)
}
@@ -116,7 +121,7 @@ class ConfederationSigningJvmTest {
private fun attempts(attemptId: String) = runBlocking { devices.values.associate { it.person to it.db.confederationCeremonyDao().getAttempt(attemptId) } }
@Test
fun `the confederation signs its profile, and every device holds it signed as the room`() {
fun `the confederation signs a post, and every device holds it signed as the room`() {
val attempt = propose()
pump()
approve(attempt.id, people - 11)
@@ -129,8 +134,156 @@ class ConfederationSigningJvmTest {
runBlocking {
devices.values.forEach { d ->
val rows = d.db.groupSignedEventDao().getByChatRoomIdAndKind(confederation.id, MetadataEvent.KIND)
assertEquals("Atlas", assertNotNull(GroupNostrProfile.newestAmong(rows, confederation.id)).name())
assertEquals(listOf(signed.first().id), d.db.groupSignedEventDao().getByChatRoomIdAndKind(confederation.id, TextNoteEvent.KIND).map { it.id })
}
}
}
// ---- docs/confederation-profile.md, Phase 5: a profile on its groups' word ------------------
@Test
fun `a profile proposed in the room directly is refused, since it changes through its groups`() {
val failure = assertFailsWith<IllegalArgumentException> { propose(kind = MetadataEvent.KIND, content = """{"name":"Atlas"}""") }
assertEquals(ConfederationSigningManager.THROUGH_GROUPS, failure.message)
}
private val now get() = Clock.System.now().epochSeconds
/** Agora proposes a profile and Polis endorses it, every device holding both, as their inboxes would. */
private fun endorsedChange(content: String = """{"name":"Atlas","about":"A group of groups"}""", endorsers: List<Int> = listOf(1)): ConfederationProfileStatements.Change = runBlocking {
val rumor = ConfederationProfileStatements.change(
groups[0], groups.drop(1), confederation.id, 2, null, emptyArray(), content, now - 5, now + 1000,
)
val change = ConfederationProfileStatements.parseChange(rumor)!!
val answers = endorsers.map { i -> network.groupKeys[i] to ConfederationProfileStatements.endorsement(groups[i], change, now - 4) }
devices.values.forEach { d ->
ConfederationProfileManager.recordStatement(d.db, rumor, ConfederationStatementFixture.seal(network.groupKeys[0], rumor), null)
answers.forEach { (key, answer) -> ConfederationProfileManager.recordStatement(d.db, answer, ConfederationStatementFixture.seal(key, answer), null) }
}
change
}
/** [group]'s voucher for [change], as its quorum signs it, posted into the room by its role holder [poster]. */
private fun vouch(change: ConfederationProfileStatements.Change, group: Int, poster: Int) = runBlocking {
val template = ConfederationProfileStatements.voucherTemplate(change, now - 3)
val key = network.groupKeys[group]
val id = com.vitorpamplona.quartz.nip01Core.crypto.EventHasher.hashId(groups[group], template.createdAt, template.kind, template.tags, template.content)
val voucher = Event(id, groups[group], template.createdAt, template.kind, template.tags, template.content,
com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto.sign(id.hexToByteArray(), key.value.toByteArray()).toHex())
val device = devices.getValue(npub(secret(poster)))
ConfederationProfileManager.recordVoucher(device.db, voucher)
ConfederationSigningManager.postVoucher(device.db, device.person, voucher)
}
/** The role holders in the follow-through's order: the roster's people, sorted. */
private val order get() = devices.values.sortedBy { it.person }
private fun sweep(at: Instant = Clock.System.now(), who: List<Device> = order) = runBlocking {
who.flatMap { ConfederationProfileFollowThrough.sweep(it.db, it.person, it.nsec, at) }
}
private fun profileAttempts(change: ConfederationProfileStatements.Change) = runBlocking {
devices.values.associate { d ->
d.person to d.db.confederationCeremonyDao().getAttempts(confederation.id, d.person)
.filter { Event.fromJson(it.eventJson).id == change.profileId }
}
}
@Test
fun `two groups' vouchers, and the profile is signed with nobody asked`() {
val change = endorsedChange()
vouch(change, group = 0, poster = 11)
vouch(change, group = 1, poster = 21)
pump()
val started = sweep()
assertEquals(1, started.size, "the first in the order starts it, and only they do")
pump()
profileAttempts(change).forEach { (person, list) ->
val attempt = list.single()
assertEquals(ConfederationSigningStage.COMPLETE, attempt.stage, "${person.take(6)}: ${attempt.failureReason}")
assertTrue(!ConfederationSigningManager.isAwaitingApproval(attempt), "nobody is asked")
}
runBlocking {
// Ekklesia did not vouch, so its admins' seats said no.
listOf(31, 32, 33).forEach { n ->
val said = devices.getValue(npub(secret(n))).db.confederationCeremonyDao()
.getSigningMessage(profileAttempts(change).values.first().single().id, npub(secret(n)), ConfederationSigningEvents.AVAILABILITY)
assertEquals(mapOf(groups[2] to ConfederationSigningEvents.NO), ConfederationRitualEvents.decodeByGroup(said!!.payload))
}
devices.values.forEach { d ->
assertEquals(ConfederationProfileChangeState.PUBLISHED, ConfederationProfileManager.status(d.db, change.id)?.state, "on ${d.person.take(6)}")
assertEquals("Atlas", ConfederationProfileManager.profiles(d.db, confederation.id).newestProfile?.name())
}
assertEquals(1, started.single().let { a -> devices.values.first { it.person == a.userPublicKey } }.db.confederationDao().observeUnpublished().first()
.count { it.kind == MetadataEvent.KIND }, "the device that started it owes it to relays")
}
}
@Test
fun `with only one group's voucher there is nothing to start`() {
val change = endorsedChange(endorsers = emptyList())
vouch(change, group = 0, poster = 11)
pump()
assertEquals(emptyList(), sweep(Clock.System.now() + 1.hours))
}
@Test
fun `with the first in the order away, the second starts it ten minutes later`() {
val change = endorsedChange()
vouch(change, group = 0, poster = 11)
vouch(change, group = 1, poster = 21)
pump()
val rest = order.drop(1)
assertEquals(emptyList(), sweep(Clock.System.now() + 5.minutes, rest), "not yet")
val started = sweep(Clock.System.now() + 11.minutes, rest)
assertEquals(listOf(order[1].person), started.map { it.userPublicKey })
}
@Test
fun `an attempt lost to a restart is started again after the backoff, and signs`() {
val change = endorsedChange()
vouch(change, group = 0, poster = 11)
vouch(change, group = 1, poster = 21)
pump()
sweep()
pump(hold = { it.kind == ConfederationSigningEvents.NONCES })
ConfederationSigningManager.forgetSignersForTest()
pump()
profileAttempts(change).values.forEach { assertEquals(ConfederationSigningStage.FAILED, it.single().stage) }
assertEquals(emptyList(), sweep(Clock.System.now() + 5.minutes), "the backoff first")
assertEquals(1, sweep(Clock.System.now() + 11.minutes).size)
pump()
profileAttempts(change).forEach { (person, list) ->
assertEquals(ConfederationSigningStage.COMPLETE, list.last().stage, "${person.take(6)}: ${list.last().failureReason}")
}
}
@Test
fun `two attempts over one change end in the one whose id sorts first`() {
val change = endorsedChange()
vouch(change, group = 0, poster = 11)
vouch(change, group = 1, poster = 21)
pump()
val vouchers = runBlocking { ConfederationSigningManager.vouchersFor(proposer.db, ConfederationSigningManager.held(proposer.db, confederation.id)!!, change.profileId) }
val a = order[0]
val b = order[1]
val attempts = listOf(a, b).map { d ->
runBlocking {
ConfederationSigningManager.propose(d.db, d.room, d.person, 0, change.profile.tags, change.profile.content, d.nsec, change.profile.createdAt, vouchers)
}
}
pump()
val keep = attempts.minBy { it.id }.id
profileAttempts(change).forEach { (person, list) ->
list.forEach { attempt ->
if (attempt.id == keep) {
assertEquals(ConfederationSigningStage.COMPLETE, attempt.stage, "${person.take(6)}: ${attempt.failureReason}")
} else {
assertEquals(ConfederationSigningStage.FAILED, attempt.stage)
}
}
}
}
+19
View File
@@ -573,6 +573,25 @@ Tests: extend `ConfederationSigningJvmTest`, three groups of three on nine devic
- a kind:0 proposed directly in the room, which is refused;
- a role holder who is no longer an admin of B still signs for B's seat on B's voucher.
**Built.** `ConfederationSigningJvmTest` 13/13 (from 7): two groups' vouchers and the profile is signed
on all nine devices with nobody asked, Ekklesia's seats saying no and every device reading the change
as `PUBLISHED`; one group's voucher and nothing starts; the first in the order away and the second
starting ten minutes later; a restart between nonces and confirmations, then the backoff, then a
second attempt that signs; two attempts at once ending in the one whose id sorts first; and Phase 0's
pin flipped (a kind:0 proposed in the room is refused with `THROUGH_GROUPS`). The direct-path cases
now sign a post. Where it differs from the above:
| what the phase said | what it turned out to be |
|---|---|
| the vouchers a 30390 carries, checked on arrival | checked, and **filed** (`recordVoucher`), so `refusalOf` reads them back from the table on approval and at the end: an attempt needs no new column |
| `acceptProposal` sends 30391 "without asking anyone" | and marks the attempt approved, or declined where none of the person's seats vouched, so `isAwaitingApproval` is false and the signing screen asks nothing |
| crossing attempts | settled the moment a device holds two running attempts over one kind:0, on proposing and on arrival: every device fails the same one out loud with `CROSSED` |
| a role holder who is no longer an admin of B | holds by construction: the automatic answer reads only the seat's group's voucher and never the group's admins, so no case was added |
| `ConfederationSigningManager.refusalOf` | also refuses a kind:0 older than one the confederation has already signed (`SUPERSEDED`), which the follow-through would otherwise sign for nothing |
| 30396 | in `ConfederationSigningEvents.ALL`, so it travels as the signing's other messages do; `process` takes it before looking for a session tag, and keeps it only from a role holder of the group that signed it |
| the confederation's room opens `ConfederationScreen` for its profile | its profile screen no longer offers an edit (`GroupNostrProfileViewModel`, `EditGroupNostrProfileViewModel`); the way from that room to the confederation's screen is Phase 7's |
| the voucher premise (Phase 0, check 5) | now signs its voucher beside a real change's seals, since a voucher asked for on its own is declined |
### Phase 6: publishing and hearing (D7)
- The kind:0 owed on the starter's device, sent by `ConfederationPublisher` to the publish set