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:
1 parent
5d6bbcd5e8
commit
8d494ddbd3
11 files changed
+500
-38
No files matched your search
+4
@@ -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>
|
||||
|
||||
|
||||
+3
@@ -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) }
|
||||
|
||||
+117
@@ -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)
|
||||
}
|
||||
+6
-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)
|
||||
}
|
||||
}
|
||||
}
|
||||
+153
-9
@@ -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(
|
||||
|
||||
+16
-1
@@ -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)
|
||||
|
||||
+16
-18
@@ -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()
|
||||
|
||||
+1
-1
@@ -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),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user