feat: a confederation signs as itself, one person per device (confederation, Phase 14)

Every role holder is asked; the proposer fixes the selection from the
first yeses, and each selected role makes a nonce held in memory only,
confirms and gives its partial. The transcript, the certificate, each
group's partial and the signature need no secret, so every device
computes them and checks the signature against the room's id before
keeping it. A device that restarts mid-attempt ends it out loud.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-22 01:00:30 +02:00
1 parent 5ac4c05352
commit e723e70a59
13 files changed
+7044 -5

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -69,6 +69,8 @@ import mobi.giza.compose.database.model.ChatRoom
import mobi.giza.compose.database.model.Confederation
import mobi.giza.compose.database.model.ConfederationCeremony
import mobi.giza.compose.database.model.ConfederationMember
import mobi.giza.compose.database.model.ConfederationSigningAttempt
import mobi.giza.compose.database.model.ConfederationSigningMessage
import mobi.giza.compose.database.model.ConfederationCeremonyMessage
import mobi.giza.compose.database.model.ConfederationEvent
import mobi.giza.compose.database.model.ConfederationInvitee
@@ -138,6 +140,8 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
Confederation::class,
ConfederationCeremony::class,
ConfederationMember::class,
ConfederationSigningAttempt::class,
ConfederationSigningMessage::class,
ConfederationCeremonyMessage::class,
ConfederationEvent::class,
ConfederationInvitee::class,
@@ -189,7 +193,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
UnsignedNostrEvent::class,
Zap::class
],
version = 44,
version = 45,
autoMigrations = [
// v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can
// generate the migration itself — nothing existing changes shape.
@@ -461,6 +465,9 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
// Phases 11 and 12): ConfederationCeremony, ConfederationCeremonyMessage, Confederation
// and ConfederationMember. New tables only, so Room generates it.
AutoMigration(from = 43, to = 44),
// v45 adds the confederation signing as itself (docs/confederation.md, Phase 14):
// ConfederationSigningAttempt and ConfederationSigningMessage. New tables only.
AutoMigration(from = 44, to = 45),
]
)
@ConstructedBy(GizaDatabaseConstructor::class)
@@ -62,4 +62,31 @@ interface ConfederationCeremonyDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertMembers(members: List<mobi.giza.compose.database.model.ConfederationMember>)
@Query("SELECT * FROM ConfederationSigningAttempt WHERE id = :id")
suspend fun getAttempt(id: String): mobi.giza.compose.database.model.ConfederationSigningAttempt?
@Query("SELECT * FROM ConfederationSigningAttempt WHERE id = :id")
fun observeAttempt(id: String): Flow<mobi.giza.compose.database.model.ConfederationSigningAttempt?>
@Query("SELECT * FROM ConfederationSigningAttempt WHERE confederationId = :confederationId ORDER BY createdAt DESC")
fun observeAttempts(confederationId: HexKey): Flow<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>
@Upsert
suspend fun upsertAttempt(attempt: mobi.giza.compose.database.model.ConfederationSigningAttempt)
@Query("SELECT * FROM ConfederationSigningMessage WHERE attemptId = :attemptId AND senderPublicKey = :sender AND kind = :kind")
suspend fun getSigningMessage(attemptId: String, sender: HexKey, kind: Kind): mobi.giza.compose.database.model.ConfederationSigningMessage?
@Query("SELECT * FROM ConfederationSigningMessage WHERE attemptId = :attemptId")
suspend fun getSigningMessages(attemptId: String): List<mobi.giza.compose.database.model.ConfederationSigningMessage>
@Query("SELECT * FROM ConfederationSigningMessage WHERE attemptId = :attemptId")
fun observeSigningMessages(attemptId: String): Flow<List<mobi.giza.compose.database.model.ConfederationSigningMessage>>
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertSigningMessage(message: mobi.giza.compose.database.model.ConfederationSigningMessage): Long
}
@@ -88,6 +88,8 @@ import mobi.giza.compose.nostr.Relays
import mobi.giza.compose.nostr.dkg.DkgRitualEvents
import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents
import mobi.giza.compose.managers.ConfederationRitualManager
import mobi.giza.compose.managers.ConfederationSigningManager
import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents
import mobi.giza.compose.ExperimentalFeatures
import mobi.giza.compose.nostr.frost.ShareRefreshEvents
import mobi.giza.compose.nostr.frost.ShareRepairEvents
@@ -1675,6 +1677,20 @@ abstract class NostrDao(
Event.fromJsonOrNull(groupEventResult.innerEventJson)
?.let { innerEvent ->
when {
// The confederation signing as itself, in its own room.
// docs/confederation.md, Phase 14.
ConfederationSigningEvents.isSigningKind(innerEvent.kind) -> {
if (ExperimentalFeatures.confederation) {
ConfederationSigningManager.process(
database = database,
localChatRoom = localChatRoom,
innerEvent = innerEvent,
userPublicKey = activeKeyPair.pubKey.toHex(),
nostrPrivateKey = activeKeyPair.privKey!!,
)
}
}
FrostSigningEvents.isFrostSigningKind(innerEvent.kind) ->
FrostSigningManager.processSigningPayload(
database = database,
@@ -4,6 +4,7 @@ import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent
import mobi.giza.compose.nostr.GroupNostrProfile
import mobi.giza.compose.nostr.RetiredKinds
import mobi.giza.compose.nostr.confederation.ConfederationKinds
import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents
import androidx.room3.Entity
import androidx.room3.ForeignKey
@@ -544,6 +545,10 @@ data class ChatMessage(
/** A group's room, on its admins' devices: the group is now part of a formed confederation (Phase 12). */
const val TYPE_CONFEDERATION_FORMED = "confederationFormed"
/** The confederation's room: a proposal for it to sign, and one that did not finish (Phase 14). */
const val TYPE_CONFEDERATION_SIGNING_PROPOSED = "confederationSigningProposed"
const val TYPE_CONFEDERATION_SIGNING_FAILED = "confederationSigningFailed"
val CONFEDERATION_TYPES = setOf(
TYPE_CONFEDERATION_PROPOSED,
TYPE_CONFEDERATION_ACCEPTED,
@@ -553,6 +558,8 @@ data class ChatMessage(
TYPE_CONFEDERATION_CEREMONY_COMPLETE,
TYPE_CONFEDERATION_CEREMONY_FAILED,
TYPE_CONFEDERATION_FORMED,
TYPE_CONFEDERATION_SIGNING_PROPOSED,
TYPE_CONFEDERATION_SIGNING_FAILED,
)
val GROUP_IDENTITY_TYPES = setOf(
@@ -994,7 +1001,8 @@ data class ChatMessage(
event.kind in FrostSigningEvents.ALL ||
event.kind in ShareRefreshEvents.ALL ||
event.kind in ShareRepairEvents.ALL ||
event.kind in GovernanceEvents.ALL
event.kind in GovernanceEvents.ALL ||
event.kind in ConfederationSigningEvents.ALL
)
database.marmotInnerEventDao().upsert(
@@ -0,0 +1,72 @@
package mobi.giza.compose.database.model
import androidx.room3.Entity
import androidx.room3.ForeignKey
import androidx.room3.Index
import androidx.room3.PrimaryKey
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.Kind
import kotlin.time.Clock
import kotlin.time.Instant
/**
* One attempt by a confederation to sign one event (docs/confederation.md, Phase 14).
*
* Unlike a FROST signing session, an attempt cannot outlive a restart once its nonces are out:
* upstream's signer state lives in memory only and must never be persisted, because a restored
* nonce can reveal the share. So this row holds what the attempt is about and what this device has
* said, and a device that comes back to an attempt it was signing in ends it, out loud; the
* proposer starts a new one under a new session id.
*/
@Entity(
foreignKeys = [
ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["confederationId"], onDelete = ForeignKey.CASCADE)
],
indices = [Index("confederationId")],
)
data class ConfederationSigningAttempt(
/** The signing session id, 32 bytes of hex: hashed into D_sign. */
@PrimaryKey
val id: String,
/** The confederation's room, whose id is also the confederation's. */
val confederationId: HexKey,
val proposerPublicKey: HexKey,
val userPublicKey: HexKey,
/** The unsigned event, authored by the room, with its id. */
val eventJson: String,
val stage: ConfederationSigningStage = ConfederationSigningStage.AWAITING_APPROVAL,
val approvedAt: Instant? = null,
val declinedAt: Instant? = null,
/** The event, signed, once it is. */
val signedEventJson: String? = null,
val failureReason: String? = null,
val createdAt: Instant = Clock.System.now(),
val updatedAt: Instant = createdAt,
) {
val isRunning: Boolean
get() = stage != ConfederationSigningStage.COMPLETE && stage != ConfederationSigningStage.FAILED
}
enum class ConfederationSigningStage {
AWAITING_APPROVAL,
SELECTING,
NONCES,
CONFIRMING,
SIGNING,
COMPLETE,
FAILED,
}
@Entity(
primaryKeys = ["attemptId", "senderPublicKey", "kind"],
foreignKeys = [
ForeignKey(entity = ConfederationSigningAttempt::class, parentColumns = ["id"], childColumns = ["attemptId"], onDelete = ForeignKey.CASCADE)
],
)
data class ConfederationSigningMessage(
val attemptId: String,
val senderPublicKey: HexKey,
val kind: Kind,
val payload: String,
val receivedAt: Instant = Clock.System.now(),
)
@@ -81,6 +81,7 @@ import mobi.giza.compose.managers.ChronicleManager
import mobi.giza.compose.managers.FrostSigningManager
import mobi.giza.compose.extensions.toHex
import mobi.giza.compose.managers.ConfederationRitualManager
import mobi.giza.compose.managers.ConfederationSigningManager
import mobi.giza.compose.managers.ConfederationFormation
import mobi.giza.compose.managers.ConfederationFollowThrough
import mobi.giza.compose.managers.GroupKeyStateManager
@@ -173,6 +174,9 @@ class DatabaseChatRepository(
launch {
runCatching { ConfederationRitualManager.resumeRunning(database, keyPair.pubKey.toHex(), secret) }
.onFailure { logger.e("Could not resume confederation ceremonies", it) }
// An attempt this device was signing in cannot survive a restart: ended out loud.
runCatching { ConfederationSigningManager.resumeRunning(database, keyPair.pubKey.toHex(), secret) }
.onFailure { logger.e("Could not resume confederation signing", it) }
}
}
}
@@ -0,0 +1,567 @@
package mobi.giza.compose.managers
import co.touchlab.kermit.Logger
import com.vitorpamplona.crypto.random.RandomInstance
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.Kind
import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent
import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent
import fr.acinq.bitcoin.ByteVector
import fr.acinq.bitcoin.ByteVector32
import fr.acinq.bitcoin.ByteVector64
import fr.acinq.bitcoin.Crypto
import fr.acinq.bitcoin.XonlyPublicKey
import fr.acinq.bitcoin.crypto.confederation.ConfederationConfirmationCertificate
import fr.acinq.bitcoin.crypto.confederation.ConfederationKeyState
import fr.acinq.bitcoin.crypto.confederation.ConfederationRecoveryPackage
import fr.acinq.bitcoin.crypto.confederation.ConfederationRoleId
import fr.acinq.bitcoin.crypto.confederation.ConfederationRoster
import fr.acinq.bitcoin.crypto.confederation.ConfederationShare
import fr.acinq.bitcoin.crypto.confederation.ConfederationSigner
import fr.acinq.bitcoin.crypto.confederation.ConfederationSignerSelection
import fr.acinq.bitcoin.crypto.confederation.ConfederationSigning
import fr.acinq.bitcoin.crypto.confederation.ConfederationSigningSession
import fr.acinq.bitcoin.crypto.confederation.ConfederationTweak
import fr.acinq.bitcoin.utils.Either
import kotlin.time.Clock
import kotlin.time.Instant
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.ChatMessage
import mobi.giza.compose.database.model.Confederation
import mobi.giza.compose.database.model.ConfederationSigningAttempt
import mobi.giza.compose.database.model.ConfederationSigningMessage
import mobi.giza.compose.database.model.ConfederationSigningStage
import mobi.giza.compose.database.model.GroupSignedEvent
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.ConfederationRitualEvents
import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder
import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder.Plan
import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents
/**
* A confederation signing an event as itself, one person per device (docs/confederation.md,
* Phase 14), over upstream's Option A signing, in the confederation's own Marmot room.
*
* Every role holder is asked, as a FROST member is: approving says this person's roles will sign.
* The proposer, who coordinates, fixes the selection from the first yeses -- at least `T` groups,
* at least `t_g` admins in each -- and then each selected role makes a nonce, confirms the
* transcript and the event, and gives its partial. Everything that takes no secret is computed on
* every device from the public messages, so each device builds the signature itself and checks it
* against the room's id before it keeps it.
*
* **A signer lives in memory only.** Upstream's state holds a secret nonce that must never be
* stored, restored or used twice, so [signers] is this process's and nothing else's. A device that
* restarts after sending a nonce can no longer confirm or sign; it ends the attempt, out loud, and
* the proposer starts a fresh one under a new session id. That is the opposite of
* `FrostSigningManager`, which stores its nonce randomness, and it is upstream's rule (F-24).
*
* The room signs as its own id: the key's tweaks are `SharedKeyDerivation`'s, as for every keyed
* room (D10).
*
* WARNING: upstream's confederation module is experimental and unaudited. This runs behind
* `ExperimentalFeatures.confederation`, off in release.
*/
object ConfederationSigningManager {
private val logger = Logger.withTag("ConfederationSigningManager")
private val mutex = Mutex()
/** Live signer states, by user, attempt and role. In memory only, by design. */
private val signers = mutableMapOf<String, ConfederationSigner>()
private fun signerKey(user: HexKey, attemptId: String, role: ConfederationRoleId) = "$user/$attemptId/${role.groupId}:${role.adminId}"
/** The kinds a confederation signs here: its profile and its posts (Phase 15). */
val SIGNABLE_KINDS: Set<Kind> = setOf(MetadataEvent.KIND, TextNoteEvent.KIND)
const val RESTARTED = "A device restarted while signing, so this attempt cannot finish. Propose it again"
// ---- what a confederation is on this device ------------------------------------------------
/** Everything this device holds about one confederation, read back from storage. */
internal class Held(
val confederation: Confederation,
val plan: Plan,
val roster: ConfederationRoster,
val keyState: ConfederationKeyState,
val tweaks: List<ConfederationTweak>,
val roomKey: XonlyPublicKey,
)
internal suspend fun held(database: GizaDatabase, confederationId: HexKey): Held? {
val confederation = database.confederationCeremonyDao().getConfederation(confederationId)
?.takeIf(ConfederationFormation::verifies) ?: return null
val ceremony = database.confederationCeremonyDao().getCeremony(confederation.ceremonyId) ?: return null
val plan = ConfederationRitualEvents.Opening.decode(ceremony.openingJson)
?.let { ConfederationRitualManager.planFrom(it) as? Either.Right }?.value ?: return null
val roster = (ConfederationRoster.fromData(ByteVector(confederation.roster)) as? Either.Right)?.value ?: return null
val keyState = (ConfederationKeyState.fromData(ByteVector(confederation.keyState), roster) as? Either.Right)?.value ?: return null
val derived = SharedKeyDerivation.derive("02${confederation.publicKey}")
if (derived.hex != confederationId) return null
return Held(confederation, plan, roster, keyState, derived.tweaks.map { ConfederationTweak(it, isXonly = true) }, derived.publicKey)
}
/** Whether this device holds a role in [confederationId], and so can propose and sign for it. */
suspend fun canSign(database: GizaDatabase, confederationId: HexKey, userPublicKey: HexKey): Boolean =
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 {
event.pubKey != held.confederation.id -> "The event is not authored by the confederation"
event.kind !in SIGNABLE_KINDS -> "A confederation signs only its profile and its posts here"
event.kind == MetadataEvent.KIND && GroupStatementRefusal.isUnreadableProfile(event.tags, event.content) -> GroupStatementRefusal.REASON
event.kind == TextNoteEvent.KIND && GroupStatementRefusal.isBlankPost(event.content) -> GroupStatementRefusal.REASON
EventHasher.hashId(event.pubKey, event.createdAt, event.kind, event.tags, event.content) != event.id -> "The event's id is not the hash of its fields"
else -> null
}
// ---- proposing -------------------------------------------------------------------------
/** Proposes that the confederation whose room is [localChatRoom] sign one event. Proposing is the proposer's approval. */
suspend fun propose(
database: GizaDatabase,
localChatRoom: LocalChatRoom,
userPublicKey: HexKey,
kind: Kind,
tags: Array<Array<String>>,
content: String,
nostrPrivateKey: ByteArray,
createdAt: Long = Clock.System.now().epochSeconds,
): 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) }
val attempt = ConfederationSigningAttempt(
id = RandomInstance.bytes(32).toHex(),
confederationId = roomId,
proposerPublicKey = userPublicKey,
userPublicKey = userPublicKey,
eventJson = event.toJson(),
approvedAt = Clock.System.now(),
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)
advance(database, localChatRoom, attempt.id, nostrPrivateKey)
database.confederationCeremonyDao().getAttempt(attempt.id)!!
}
// ---- inbound ---------------------------------------------------------------------------
suspend fun process(
database: GizaDatabase,
localChatRoom: LocalChatRoom,
innerEvent: Event,
userPublicKey: HexKey,
nostrPrivateKey: ByteArray,
) = mutex.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")
return@withLock
}
val attempt = if (innerEvent.kind == ConfederationSigningEvents.PROPOSAL) {
acceptProposal(database, localChatRoom, held, innerEvent, attemptId, userPublicKey)
} else {
database.confederationCeremonyDao().getAttempt(attemptId)
} ?: return@withLock
if (!attempt.isRunning) return@withLock
if (!record(database, held, attempt, innerEvent)) return@withLock
advance(database, localChatRoom, attempt.id, nostrPrivateKey)
}
private suspend fun acceptProposal(
database: GizaDatabase,
localChatRoom: LocalChatRoom,
held: Held,
innerEvent: Event,
attemptId: String,
userPublicKey: HexKey,
): ConfederationSigningAttempt? {
database.confederationCeremonyDao().getAttempt(attemptId)?.let { return it }
if (held.plan.seatsOf(innerEvent.pubKey).isEmpty()) {
logger.w("Signing proposal $attemptId from ${innerEvent.pubKey.take(8)}, who holds no role; dropping")
return null
}
if (held.plan.seatsOf(userPublicKey).isEmpty()) return null
val event = Event.fromJsonOrNull(innerEvent.content) ?: return null
val attempt = ConfederationSigningAttempt(
id = attemptId,
confederationId = held.confederation.id,
proposerPublicKey = innerEvent.pubKey,
userPublicKey = userPublicKey,
eventJson = event.toJson(),
)
val refusal = refusalOf(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.
logger.w("Signing proposal $attemptId refused: $refusal")
database.confederationCeremonyDao().upsertAttempt(attempt.copy(declinedAt = Clock.System.now(), failureReason = refusal))
publishAvailability(database, localChatRoom, attempt, held, available = false)
return database.confederationCeremonyDao().getAttempt(attemptId)
}
database.confederationCeremonyDao().upsertAttempt(attempt)
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)
}
/**
* 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.
* Returns false when it ended the attempt.
*/
private suspend fun record(database: GizaDatabase, held: Held, attempt: ConfederationSigningAttempt, innerEvent: Event): Boolean {
val sender = innerEvent.pubKey
val groups = held.plan.seatsOf(sender).map { it.group }.toSet()
when (innerEvent.kind) {
in ConfederationSigningEvents.PER_PERSON -> {
if (groups.isEmpty()) return true
if (ConfederationRitualEvents.decodeByGroup(innerEvent.content)?.keys != groups) return true
database.confederationCeremonyDao().insertSigningMessage(ConfederationSigningMessage(attempt.id, sender, innerEvent.kind, innerEvent.content))
}
ConfederationSigningEvents.SESSION -> {
if (sender != attempt.proposerPublicKey) return true
database.confederationCeremonyDao().insertSigningMessage(ConfederationSigningMessage(attempt.id, sender, innerEvent.kind, innerEvent.content))
}
ConfederationSigningEvents.FAILURE -> {
if (groups.isEmpty()) return true
fail(database, attempt, "Ended by ${ConfederationManager.nameOf(database, sender)}: ${innerEvent.content}")
return false
}
}
return true
}
// ---- the member's say --------------------------------------------------------------------
fun isAwaitingApproval(attempt: ConfederationSigningAttempt): Boolean =
attempt.isRunning && attempt.approvedAt == null && attempt.declinedAt == null
suspend fun approve(database: GizaDatabase, attemptId: String, nostrPrivateKey: ByteArray) = mutex.withLock {
val attempt = database.confederationCeremonyDao().getAttempt(attemptId)?.takeIf(::isAwaitingApproval) ?: return@withLock
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 ->
update(database, attempt) { it.copy(declinedAt = Clock.System.now(), failureReason = why) }
publishAvailability(database, room, attempt, held, available = false)
return@withLock
}
update(database, attempt) { it.copy(approvedAt = Clock.System.now()) }
publishAvailability(database, room, attempt, held, available = true)
advance(database, room, attemptId, nostrPrivateKey)
}
suspend fun decline(database: GizaDatabase, attemptId: String) = mutex.withLock {
val attempt = database.confederationCeremonyDao().getAttempt(attemptId)?.takeIf(::isAwaitingApproval) ?: return@withLock
val room = database.chatRoomDao().findChatRoomById(attempt.confederationId) ?: return@withLock
val held = held(database, attempt.confederationId) ?: return@withLock
update(database, attempt) { it.copy(declinedAt = Clock.System.now()) }
publishAvailability(database, room, attempt, held, available = false)
advance(database, room, attemptId, ByteArray(0))
}
/**
* After a restart: an attempt this device sent nonces in and has not finished cannot finish
* now, since the nonces went with the process. Ends each out loud. Others are moved on.
*/
suspend fun resumeRunning(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray): Int = mutex.withLock {
val running = database.confederationCeremonyDao().getRunningAttempts(userPublicKey)
running.forEach { attempt ->
val room = database.chatRoomDao().findChatRoomById(attempt.confederationId) ?: return@forEach
runCatching { advance(database, room, attempt.id, nostrPrivateKey) }
.onFailure { logger.e("Could not resume signing attempt ${attempt.id}", it) }
}
running.size
}
// ---- the rounds ----------------------------------------------------------------------------
private suspend fun advance(database: GizaDatabase, room: LocalChatRoom, attemptId: String, nostrPrivateKey: ByteArray) {
val attempt = database.confederationCeremonyDao().getAttempt(attemptId)?.takeIf { it.isRunning } ?: return
val held = held(database, attempt.confederationId) ?: return
val me = attempt.userPublicKey
val plan = held.plan
val event = Event.fromJson(attempt.eventJson)
val message = ByteVector32(event.id)
// 1. The proposer fixes the selection from the yeses, once there are enough.
if (me == attempt.proposerPublicKey && own(database, attempt, ConfederationSigningEvents.SESSION) == null) {
val availability = availability(database, attempt, plan)
val selection = select(held, availability)
if (selection == null) {
if (!stillPossible(held, availability)) {
return failOut(database, room, attempt, "Not enough admins of enough groups are willing to sign")
}
return moveTo(database, attempt, ConfederationSigningStage.SELECTING)
}
val session = ConfederationSigningSession.create(held.keyState, ByteVector32(attempt.id), selection, held.tweaks)
.rightOrFail { return failOut(database, room, attempt, "The signing session cannot be made: $it") }
publishOwn(database, room, attempt, ConfederationSigningEvents.SESSION,
ConfederationSigningEvents.Session(selection.groups, session.dSign.toHex()).encode())
}
val sent = database.confederationCeremonyDao().getSigningMessage(attempt.id, attempt.proposerPublicKey, ConfederationSigningEvents.SESSION)
?.let { ConfederationSigningEvents.Session.decode(it.payload) }
?: return moveTo(database, attempt, ConfederationSigningStage.SELECTING)
val selection = ConfederationSignerSelection(sent.selection)
val session = ConfederationSigningSession.create(held.keyState, ByteVector32(attempt.id), selection, held.tweaks)
.rightOrFail { return failOut(database, room, attempt, "The proposer's selection is not one this confederation can sign with: $it") }
if (!session.check(ByteVector(sent.dSign))) {
return failOut(database, room, attempt, "The proposer's signing session is not the one this device derives")
}
val selected = session.signers.mapNotNull { plan.seatOf(it) }
val people = selected.map { it.admin }.distinct()
val mine = selected.filter { it.admin == me }
val host = { seat: ConfederationRosterBuilder.Seat -> ConfederationRosterBuilder.hostSecretKey(nostrPrivateKey, seat.group, plan.proposal.id) }
// 2. Each selected role's nonce, made now and held in memory only.
if (mine.isNotEmpty() && own(database, attempt, ConfederationSigningEvents.NONCES) == null) {
val nonces = mine.associate { seat ->
val share = shareOf(held, seat, host(seat)) ?: return failOut(database, room, attempt, "This device's share no longer opens")
val signer = ConfederationSigning.generateNonce(session, seat.roleId, share, ByteVector32(RandomInstance.bytes(32)))
.rightOrFail { return failOut(database, room, attempt, "A nonce could not be made: $it") }
signers[signerKey(me, attempt.id, seat.roleId)] = signer
seat.group to signer.publicNonce.toHex()
}
publishOwn(database, room, attempt, ConfederationSigningEvents.NONCES, ConfederationRitualEvents.encodeByGroup(nonces))
}
val nonces = perRole(database, attempt, selected, people, ConfederationSigningEvents.NONCES) { ByteVector(it) }
?: return moveTo(database, attempt, ConfederationSigningStage.NONCES)
val transcript = ConfederationSigning.transcript(session, nonces)
.rightOrFail { return failOut(database, room, attempt, "The nonce transcript cannot be built: $it") }
// 3. Each selected role confirms the transcript and the event.
if (mine.isNotEmpty() && own(database, attempt, ConfederationSigningEvents.CONFIRMATIONS) == null) {
val confirmations = mine.associate { seat ->
val signer = signers[signerKey(me, attempt.id, seat.roleId)] ?: return failOut(database, room, attempt, RESTARTED)
seat.group to ConfederationSigning.confirm(signer, transcript, message, host(seat))
.rightOrFail { return failOut(database, room, attempt, "Confirming failed: $it") }.toHex()
}
publishOwn(database, room, attempt, ConfederationSigningEvents.CONFIRMATIONS, ConfederationRitualEvents.encodeByGroup(confirmations))
}
val confirmations = perRole(database, attempt, selected, people, ConfederationSigningEvents.CONFIRMATIONS) { ByteVector64(it) }
?: return moveTo(database, attempt, ConfederationSigningStage.CONFIRMING)
val certificate = ConfederationSigning.certificate(session, transcript, message, confirmations)
.rightOrFail { return failOut(database, room, attempt, "The confirmations cannot be certified: $it") }
if (!ConfederationSigning.verifyCertificate(session, transcript, message, certificate)) {
return failOut(database, room, attempt, "A confirmation does not verify")
}
// 4. Each selected role's partial: the signer is spent here, whatever happens.
if (mine.isNotEmpty() && own(database, attempt, ConfederationSigningEvents.PARTIALS) == null) {
val partials = mine.associate { seat ->
val signer = signers.remove(signerKey(me, attempt.id, seat.roleId)) ?: return failOut(database, room, attempt, RESTARTED)
val share = shareOf(held, seat, host(seat)) ?: return failOut(database, room, attempt, "This device's share no longer opens")
seat.group to ConfederationSigning.sign(signer, share, transcript, message, certificate)
.rightOrFail { return failOut(database, room, attempt, "Signing failed: $it") }.toHex()
}
publishOwn(database, room, attempt, ConfederationSigningEvents.PARTIALS, ConfederationRitualEvents.encodeByGroup(partials))
}
val partials = perRole(database, attempt, selected, people, ConfederationSigningEvents.PARTIALS) { ByteVector32(it) }
?: return moveTo(database, attempt, ConfederationSigningStage.SIGNING)
// 5. Every group's partial and the signature, on every device.
complete(database, room, attempt, held, session, transcript, certificate, message, event, partials)
}
private suspend fun complete(
database: GizaDatabase,
room: LocalChatRoom,
attempt: ConfederationSigningAttempt,
held: Held,
session: ConfederationSigningSession,
transcript: fr.acinq.bitcoin.crypto.confederation.ConfederationNonceTranscript,
certificate: ConfederationConfirmationCertificate,
message: ByteVector32,
event: Event,
partials: Map<ConfederationRoleId, ByteVector32>,
) {
val groupPartials = session.groups.associateWith { groupId ->
ConfederationSigning.aggregateGroup(session, transcript, message, certificate, groupId, partials.filterKeys { it.groupId == groupId })
.rightOrFail { culprit -> return failOut(database, room, attempt, "Group ${held.plan.groups.getOrNull(groupId.toInt())?.let { ConfederationManager.nameOf(database, it) }}'s partial does not add up: $culprit") }
}
val signature = ConfederationSigning.aggregate(session, transcript, message, certificate, groupPartials)
.rightOrFail { return failOut(database, room, attempt, "The signature cannot be assembled: $it") }
if (!Crypto.verifySignatureSchnorr(message, signature, held.roomKey)) {
return failOut(database, room, attempt, "The signature does not verify as the confederation's room")
}
val signed = Event(event.id, event.pubKey, event.createdAt, event.kind, event.tags, event.content, signature.toHex())
update(database, attempt) { it.copy(stage = ConfederationSigningStage.COMPLETE, signedEventJson = signed.toJson()) }
database.groupSignedEventDao().record(GroupSignedEvent.fromEvent(signed, chatRoomId = held.confederation.id))
announce(
database, attempt,
if (signed.kind == MetadataEvent.KIND) ChatMessage.TYPE_GROUP_PROFILE_SIGNED else ChatMessage.TYPE_GROUP_POST_SIGNED,
"The confederation signed ${describe(signed)}",
)
logger.i("Confederation ${held.confederation.id.take(12)} signed ${signed.id.take(8)}")
}
// ---- helpers ---------------------------------------------------------------------------
/** The roles available to sign, by role: true for a yes, false for a no. Missing for a person who has not said. */
private suspend fun availability(database: GizaDatabase, attempt: ConfederationSigningAttempt, plan: Plan): Map<ConfederationRoleId, Boolean> =
plan.people.flatMap { person ->
val said = database.confederationCeremonyDao().getSigningMessage(attempt.id, person, ConfederationSigningEvents.AVAILABILITY)
?.let { ConfederationRitualEvents.decodeByGroup(it.payload) } ?: return@flatMap emptyList()
plan.seatsOf(person).mapNotNull { seat -> said[seat.group]?.let { seat.roleId to (it == ConfederationSigningEvents.YES) } }
}.toMap()
/**
* The first `T` groups, in roster order, with at least `t_g` yeses, and in each the `t_g` lowest
* admins who said yes. Null while that many are not yet in.
*/
private fun select(held: Held, availability: Map<ConfederationRoleId, Boolean>): ConfederationSignerSelection? {
val groups = held.roster.groups.mapNotNull { group ->
val yes = group.roles.map { it.id }.filter { availability[it] == true }.map { it.adminId }.sorted()
if (yes.size >= group.threshold) group.groupId to yes.take(group.threshold).toSet() else null
}
if (groups.size < held.roster.outerThreshold) return null
return ConfederationSignerSelection(groups.take(held.roster.outerThreshold).toMap())
}
/** Whether enough roles that have not said no remain for a selection to be possible. */
private fun stillPossible(held: Held, availability: Map<ConfederationRoleId, Boolean>): Boolean =
held.roster.groups.count { group -> group.roles.count { availability[it.id] != false } >= group.threshold } >= held.roster.outerThreshold
private suspend fun <T> perRole(
database: GizaDatabase,
attempt: ConfederationSigningAttempt,
selected: List<ConfederationRosterBuilder.Seat>,
people: List<HexKey>,
kind: Kind,
read: (String) -> T,
): Map<ConfederationRoleId, T>? {
val byPerson = people.associateWith { person ->
val message = database.confederationCeremonyDao().getSigningMessage(attempt.id, person, kind) ?: return null
ConfederationRitualEvents.decodeByGroup(message.payload) ?: return null
}
return selected.associate { seat -> seat.roleId to read(byPerson.getValue(seat.admin)[seat.group] ?: return null) }
}
/** This device's share for [seat], opened from the recovery package it kept. */
private fun shareOf(held: Held, seat: ConfederationRosterBuilder.Seat, host: fr.acinq.bitcoin.PrivateKey): ConfederationShare? {
val hex = ConfederationRitualEvents.decodeByGroup(held.confederation.recoveryPackages)?.get(seat.group) ?: return null
val recovery = (ConfederationRecoveryPackage.fromData(ByteVector(hex), host) as? Either.Right)?.value ?: return null
return (recovery.open(host, held.keyState) as? Either.Right)?.value
}
private suspend fun publishAvailability(database: GizaDatabase, room: LocalChatRoom, attempt: ConfederationSigningAttempt, held: Held, available: Boolean) {
if (own(database, attempt, ConfederationSigningEvents.AVAILABILITY) != null) return
val value = if (available) ConfederationSigningEvents.YES else ConfederationSigningEvents.NO
publishOwn(
database, room, attempt, ConfederationSigningEvents.AVAILABILITY,
ConfederationRitualEvents.encodeByGroup(held.plan.seatsOf(attempt.userPublicKey).associate { it.group to value }),
)
}
private suspend fun own(database: GizaDatabase, attempt: ConfederationSigningAttempt, kind: Kind) =
database.confederationCeremonyDao().getSigningMessage(attempt.id, attempt.userPublicKey, kind)
private suspend fun publishOwn(database: GizaDatabase, room: LocalChatRoom, attempt: ConfederationSigningAttempt, kind: Kind, content: String) {
broadcast(database, room, attempt, kind, content)
database.confederationCeremonyDao().insertSigningMessage(ConfederationSigningMessage(attempt.id, attempt.userPublicKey, kind, content))
}
/** 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))
val createdAt = Clock.System.now().epochSeconds
val id = EventHasher.hashId(attempt.userPublicKey, createdAt, kind, tags, content)
database.marmotInnerEventDao().upsert(
MarmotInnerEvent(
id = id,
publicKey = attempt.userPublicKey,
kind = kind,
createdAt = Instant.fromEpochSeconds(createdAt),
tags = tags,
content = content,
chatRoomId = room.chatRoom.id,
)
)
}
private suspend fun replayStoredMessages(database: GizaDatabase, held: Held, attempt: ConfederationSigningAttempt) {
database.marmotInnerEventDao()
.getByChatRoomAndKinds(attempt.confederationId, (ConfederationSigningEvents.ALL - ConfederationSigningEvents.PROPOSAL).toList())
.filter { ConfederationSigningEvents.parseSessionId(it.tags) == attempt.id }
.forEach { stored ->
val event = Event(stored.id, stored.publicKey, stored.createdAt.epochSeconds, stored.kind, stored.tags, stored.content, "")
if (!record(database, held, database.confederationCeremonyDao().getAttempt(attempt.id) ?: return, event)) return
}
}
private inline fun <T> Either<Throwable, T>.rightOrFail(onLeft: (String) -> Nothing): T = when (this) {
is Either.Right -> value
is Either.Left -> onLeft(value.message ?: value.toString())
}
private suspend fun update(
database: GizaDatabase,
attempt: ConfederationSigningAttempt,
transform: (ConfederationSigningAttempt) -> ConfederationSigningAttempt,
): ConfederationSigningAttempt {
val current = database.confederationCeremonyDao().getAttempt(attempt.id) ?: attempt
val next = transform(current).copy(updatedAt = Clock.System.now())
database.confederationCeremonyDao().upsertAttempt(next)
return next
}
private suspend fun moveTo(database: GizaDatabase, attempt: ConfederationSigningAttempt, stage: ConfederationSigningStage) {
if (attempt.stage != stage) update(database, attempt) { it.copy(stage = stage) }
}
private suspend fun failOut(database: GizaDatabase, room: LocalChatRoom, attempt: ConfederationSigningAttempt, reason: String) {
broadcast(database, room, attempt, ConfederationSigningEvents.FAILURE, reason)
fail(database, attempt, reason)
}
private suspend fun fail(database: GizaDatabase, attempt: ConfederationSigningAttempt, reason: String) {
val current = database.confederationCeremonyDao().getAttempt(attempt.id) ?: attempt
if (!current.isRunning) return
// Whatever this device was holding for the attempt goes with it.
signers.keys.filter { it.startsWith("${current.userPublicKey}/${current.id}/") }.forEach { signers.remove(it)?.abort() }
update(database, current) { it.copy(stage = ConfederationSigningStage.FAILED, failureReason = reason) }
logger.w("Signing attempt ${attempt.id} failed: $reason")
announce(database, current, ChatMessage.TYPE_CONFEDERATION_SIGNING_FAILED, "The confederation did not sign: $reason")
}
private fun describe(event: Event): String = when (event.kind) {
MetadataEvent.KIND -> "its profile"
TextNoteEvent.KIND -> "a post"
else -> "an event of kind ${event.kind}"
}
private suspend fun announce(database: GizaDatabase, attempt: ConfederationSigningAttempt, type: String, content: String) {
database.chatMessageDao().upsert(
ChatMessage(
senderPublicKey = attempt.proposerPublicKey,
isUserMessage = false,
giftWrapPayloadId = null,
marmotGroupEventId = null,
marmotInnerEventId = null,
chatRoomId = attempt.confederationId,
content = content,
messageType = type,
)
)
}
/** For tests: forget every live signer, as a restart would. */
internal fun forgetSignersForTest() {
signers.values.forEach { it.abort() }
signers.clear()
}
}
@@ -0,0 +1,80 @@
package mobi.giza.compose.nostr.confederation
import com.vitorpamplona.quartz.nip01Core.core.Kind
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.int
import kotlinx.serialization.json.put
/**
* The confederation signing as itself, on the wire (docs/confederation.md, Phase 14): rumors in the
* confederation's own Marmot room, over upstream's Option A signing.
*
* | kind | from | carries |
* |-------|---------------|----------------------------------------------------------------------|
* | 30390 | the proposer | the unsigned event, authored by the confederation's room |
* | 30391 | each person | per role, by group: whether that role will sign ("yes" or "no") |
* | 30392 | the proposer | the selection it fixed from the yeses, and the D_sign it encodes |
* | 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 |
* | 30399 | anyone | failure, with a reason |
*
* Only the selection needs a coordinator: approvals arrive in a different order on every device,
* and somebody has to say which of them sign. Everything after it -- the nonce transcript, the
* confirmation certificate, each group's partial and the signature -- takes no secret, so every
* device computes it from the public messages it holds, and nobody can be handed a wrong one.
* Group coordinators, which the protocol leaves to the application, are therefore every device.
*/
object ConfederationSigningEvents {
const val PROPOSAL: Kind = 30390
const val AVAILABILITY: Kind = 30391
const val SESSION: Kind = 30392
const val NONCES: Kind = 30393
const val CONFIRMATIONS: Kind = 30394
const val PARTIALS: Kind = 30395
const val FAILURE: Kind = 30399
val ALL: Set<Kind> = setOf(PROPOSAL, AVAILABILITY, SESSION, NONCES, CONFIRMATIONS, PARTIALS, FAILURE)
/** Sent once per person, a value per role. */
val PER_PERSON: Set<Kind> = setOf(AVAILABILITY, NONCES, CONFIRMATIONS, PARTIALS)
fun isSigningKind(kind: Kind): Boolean = kind in ALL
const val SESSION_TAG = "confederation_signing"
const val YES = "yes"
const val NO = "no"
fun sessionTag(sessionId: String): Array<String> = arrayOf(SESSION_TAG, sessionId)
fun parseSessionId(tags: Array<Array<String>>): String? =
tags.firstOrNull { it.size >= 2 && it[0] == SESSION_TAG }?.get(1)?.takeIf(ConfederationKinds::isHex32)
private val json = Json { ignoreUnknownKeys = false }
/** The proposer's selection, by group id, and the D_sign it encodes. */
data class Session(val selection: Map<UInt, Set<UInt>>, val dSign: String) {
fun encode(): String = buildJsonObject {
put("selection", JsonObject(selection.toSortedMap().entries.associate { (g, admins) ->
g.toString() to JsonArray(admins.sorted().map { JsonPrimitive(it.toInt()) })
}))
put("dSign", dSign)
}.toString()
companion object {
fun decode(content: String): Session? = runCatching {
val obj = json.parseToJsonElement(content) as JsonObject
Session(
selection = (obj["selection"] as JsonObject).entries.associate { (g, admins) ->
g.toUInt() to (admins as JsonArray).map { (it as JsonPrimitive).int.toUInt() }.toSet()
},
dSign = (obj["dSign"] as JsonPrimitive).content,
)
}.getOrNull()
}
}
}
@@ -897,6 +897,8 @@ private fun RitualNotice(
ChatMessage.TYPE_CONFEDERATION_CEREMONY_COMPLETE -> Icons.Default.CheckCircle
ChatMessage.TYPE_CONFEDERATION_CEREMONY_FAILED -> Icons.Default.ErrorOutline
ChatMessage.TYPE_CONFEDERATION_FORMED -> Icons.Default.Hub
ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED -> Icons.Default.Draw
ChatMessage.TYPE_CONFEDERATION_SIGNING_FAILED -> Icons.Default.ErrorOutline
else -> Icons.Default.PanTool
@@ -66,10 +66,11 @@ class ShippedProfileUpgradeJvmTest {
* refresh and 40 for share repair (docs/frost-share-refresh.md, Phases 6, 7 and
* 10), 41 for governance proposals and 42 for what follows them
* (docs/member-admin-promotion.md, Phases 5, 8 and 9), 43 for the confederation
* (docs/confederation.md, Phase 4) and 44 for its key ceremony (Phase 11), so the upgrade
* crosses eight generated migrations and the file has to come out at the last.
* (docs/confederation.md, Phase 4) 44 for its key ceremony (Phase 11) and 45 for its
* signing (Phase 14), so the upgrade crosses nine generated migrations and the file has to
* come out at the last.
*/
private val current = 44
private val current = 45
private val directory: File = Files.createTempDirectory("giza-shipped-profile").toFile()
private val file: File = File(directory, "aux.db")
@@ -0,0 +1,217 @@
package mobi.giza.compose.managers
import androidx.room3.Room
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent
import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent
import fr.acinq.bitcoin.Crypto
import fr.acinq.bitcoin.PrivateKey
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlin.time.Clock
import kotlin.time.Instant
import kotlinx.coroutines.runBlocking
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.builder.getRoomDatabase
import mobi.giza.compose.database.model.ChatRoom
import mobi.giza.compose.database.model.Confederation
import mobi.giza.compose.database.model.ConfederationSigningStage
import mobi.giza.compose.database.model.MarmotInnerEvent
import mobi.giza.compose.database.model.NostrEvent
import mobi.giza.compose.database.model.Profile
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.extensions.toHex
import mobi.giza.compose.nostr.GroupNostrProfile
import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents
import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
/**
* A confederation signing as itself, one person per device (docs/confederation.md, Phase 14): a
* confederation formed across nine devices, then a proposal in its room, approvals, and Option A
* signing with every signer's nonce held in memory -- ending, on every device, in the same event,
* signed as the room's id.
*/
class ConfederationSigningJvmTest {
private fun secret(n: Int) = PrivateKey(ByteArray(32).also { it[0] = 0x71; it[31] = n.toByte() })
private fun npub(key: PrivateKey): HexKey = key.publicKey().xOnly().value.toHex()
private val groupKeys = (1..3).map { secret(it) }
private val groups = groupKeys.map(::npub)
private val people = listOf(11, 12, 13, 21, 22, 23, 31, 32, 33)
private val admins = listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33))
private inner class Device(val secret: PrivateKey, val db: GizaDatabase) {
val person = npub(secret)
lateinit var ceremonyRoom: LocalChatRoom
lateinit var room: LocalChatRoom
val received = mutableSetOf<String>()
val nsec get() = secret.value.toByteArray()
}
private val devices = linkedMapOf<HexKey, Device>()
private lateinit var confederation: Confederation
private lateinit var proposer: Device
@BeforeTest
fun formed() = runBlocking {
val coordinator = npub(secret(11))
val now = Clock.System.now().epochSeconds
val proposal = ConfederationTestGroups.proposal(groupKeys[0], groups, coordinator, createdAt = now - 10, expiresAt = now + 1000)
val acceptances = groupKeys.mapIndexed { i, key -> ConfederationTestGroups.acceptance(key, proposal, admins[i].map { npub(secret(it)) }) }
people.map(::secret).forEach { key ->
val db = getRoomDatabase(Room.inMemoryDatabaseBuilder<GizaDatabase>())
(people.map { npub(secret(it)) } + groups).forEach { member ->
val eventId = Crypto.sha256(member.encodeToByteArray()).toHex()
db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = member, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)))
db.profileDao().upsert(Profile(publicKey = member, nostrEventId = eventId, displayName = member.take(6), createdAt = Instant.fromEpochSeconds(1_790_000_000)))
}
devices[npub(key)] = Device(key, db)
}
proposer = devices.getValue(coordinator)
(listOf(proposal) + acceptances).forEach { ConfederationManager.record(proposer.db, it) }
// Part B, across the devices: the ceremony, every device joining.
val ceremony = ConfederationRitualManager.open(proposer.db, proposal.id, proposer.secret)
proposer.ceremonyRoom = proposer.db.chatRoomDao().findChatRoomById(ceremony.chatRoomId)!!
devices.values.filter { it !== proposer }.forEach { d ->
d.ceremonyRoom = d.db.nostrNip17Dao().createNip17ChatRoom(d.person, devices.keys.filter { it != d.person }, "Atlas")!!
}
pumpCeremony()
devices.values.forEach { ConfederationRitualManager.join(it.db, ceremony.id, it.nsec) }
pumpCeremony()
confederation = assertNotNull(proposer.db.confederationCeremonyDao().getConfederationForProposal(proposal.id))
// The confederation's room on every device. Its MLS state is not this test's business; a
// room with group state is what makes signing travel as a group event.
devices.values.forEach { d ->
d.db.chatRoomDao().upsert(ChatRoom(id = confederation.id, userPublicKey = d.person, subject = "#Atlas", description = null, mlsGroupState = "00"))
d.room = d.db.chatRoomDao().findChatRoomById(confederation.id)!!
}
}
@AfterTest
fun close() {
ConfederationSigningManager.forgetSignersForTest()
devices.values.forEach { it.db.close() }
}
private suspend fun pumpCeremony() {
var moved = true
while (moved) {
moved = false
for (from in devices.values) for (to in devices.values) {
if (from === to) continue
from.db.giftWrapPayloadDao().getByChatRoomAndKinds(from.ceremonyRoom.chatRoom.id, ConfederationRitualEvents.ALL.toList())
.filter { it.publicKey == from.person }.sortedBy { it.createdAt }
.forEach { q ->
if (!to.received.add(q.id)) return@forEach
moved = true
to.db.giftWrapPayloadDao().upsert(q.copy(chatRoomId = to.ceremonyRoom.chatRoom.id))
ConfederationRitualManager.process(to.db, to.ceremonyRoom, Event(q.id, q.publicKey, q.createdAt.epochSeconds, q.kind, q.tags, q.content, ""), to.person, to.nsec)
}
}
}
}
/** Ferries the room's signing messages between devices until nothing moves; [hold] keeps some back. */
private fun pump(hold: (MarmotInnerEvent) -> Boolean = { false }) = runBlocking {
var moved = true
while (moved) {
moved = false
for (from in devices.values) for (to in devices.values) {
if (from === to) continue
from.db.marmotInnerEventDao().getByChatRoomAndKinds(confederation.id, ConfederationSigningEvents.ALL.toList())
.filter { it.publicKey == from.person }.sortedWith(compareBy({ it.createdAt }, { it.kind }))
.forEach { q ->
if (hold(q) || !to.received.add(q.id)) return@forEach
moved = true
to.db.marmotInnerEventDao().upsert(q)
ConfederationSigningManager.process(to.db, to.room, Event(q.id, q.publicKey, q.createdAt.epochSeconds, q.kind, q.tags, q.content, ""), to.person, to.nsec)
}
}
}
}
private fun propose(kind: Int = MetadataEvent.KIND, content: String = """{"name":"Atlas","about":"A group of groups"}""") = runBlocking {
ConfederationSigningManager.propose(proposer.db, proposer.room, proposer.person, kind, emptyArray(), content, proposer.nsec)
}
private fun approve(attemptId: String, who: List<Int>) = runBlocking {
who.map { devices.getValue(npub(secret(it))) }.forEach { ConfederationSigningManager.approve(it.db, attemptId, it.nsec) }
}
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`() {
val attempt = propose()
pump()
approve(attempt.id, people - 11)
pump()
attempts(attempt.id).forEach { (person, a) -> assertEquals(ConfederationSigningStage.COMPLETE, a?.stage, "${person.take(6)}: ${a?.failureReason}") }
val signed = attempts(attempt.id).values.map { Event.fromJson(it!!.signedEventJson!!) }
assertEquals(1, signed.map { it.sig }.toSet().size, "the same signature on every device")
assertTrue(GroupKeyStateEvent.isSignedByRoom(signed.first(), confederation.id), "a plain nostr signature by the room's id")
runBlocking {
devices.values.forEach { d ->
val rows = d.db.groupSignedEventDao().getByChatRoomIdAndKind(confederation.id, MetadataEvent.KIND)
assertEquals("Atlas", assertNotNull(GroupNostrProfile.newestAmong(rows, confederation.id)).name())
}
}
}
@Test
fun `enough willing admins in enough groups is all it takes`() {
val attempt = propose(TextNoteEvent.KIND, "The first words of a group of groups")
pump()
// Two groups of three, two admins in each: Agora (11, 12) and Polis (21, 22). Nobody else answers.
approve(attempt.id, listOf(12, 21, 22))
pump()
listOf(11, 12, 21, 22, 33).forEach { n ->
assertEquals(ConfederationSigningStage.COMPLETE, attempts(attempt.id).getValue(npub(secret(n)))?.stage)
}
}
@Test
fun `a device that loses its nonces mid-attempt ends it for everybody`() {
val attempt = propose()
pump()
approve(attempt.id, people - 11)
pump(hold = { it.kind == ConfederationSigningEvents.NONCES })
ConfederationSigningManager.forgetSignersForTest() // every device restarts
pump()
attempts(attempt.id).values.forEach {
assertEquals(ConfederationSigningStage.FAILED, it?.stage)
assertTrue(it!!.failureReason!!.contains("restarted while signing"), it.failureReason)
}
}
@Test
fun `when too many decline, the proposer says so and it ends`() {
val attempt = propose()
pump()
runBlocking {
listOf(21, 22, 31, 32).map { devices.getValue(npub(secret(it))) }.forEach { ConfederationSigningManager.decline(it.db, attempt.id) }
}
pump()
val ended = attempts(attempt.id).getValue(proposer.person)
assertEquals(ConfederationSigningStage.FAILED, ended?.stage)
assertTrue(ended!!.failureReason!!.startsWith("Not enough admins"), ended.failureReason)
}
@Test
fun `a confederation signs only its profile and its posts`() {
assertFailsWith<IllegalArgumentException> { propose(kind = 30023, content = "long form") }
assertFailsWith<IllegalArgumentException> { propose(kind = TextNoteEvent.KIND, content = " ") }
}
}
+1
View File
@@ -92,6 +92,7 @@ the reasoning. Where the build chose differently:
| 11 | done. `ConfederationRitualManager` over upstream's `ConfederationDkg`, in a NIP-17 room the coordinator opens over every admin (with placeholder profiles for members this device has none for). Kinds 30380 (opening), 30381 (host keys), 30382 (dealings), 30383 (roster and broadcast), 30384 (authorizations), 30385 (acknowledgments), 30387 (failure). One message per person per step, one value per role, keyed by group. **No 30386:** every device assembles the certified genesis itself from evidence it already holds, so nobody can hand one over. **No investigation (30388):** a decryption fault names "a participant or the coordinator" and ends the ceremony. Before joining, a device checks the proposal and acceptances are their groups' own, every acceptance opens with its disclosed key, the room is exactly the roster's people, and each group it is in still has the admins it accepted with, compared on their own so a member without a share still checks. Joining is the only approval; dealer seeds are erased once dealt; every role derives its key state itself and the coordinator's roster must match byte for byte. Schema 44. The coordinator opens it by a button on the proposal screen rather than on its own. `ConfederationRitualScreen`, with a join, each step's named waits and abandon. `ConfederationCeremonyJvmTest` 7/7: three groups of three on nine devices reach one key that signs as the room once each recovery package is opened; one person in two groups; a holdout and abandon; a disclosed key that does not open; a substituted roster; admins changed; messages before the opening. jvmTest 1,619 |
| 12 | done. `ConfederationFormation.onComplete` files a `Confederation` (room id, X, roster, key state, genesis, the `(configSeq, rpdHash, ksdHash)` triple, this device's recovery packages) and `ConfederationMember` rows, folded into schema 44 since it has not shipped. The genesis is verified against the key state before anything is written. A line goes into each of this device's own member groups' rooms; nothing is sent to them. **No 30389 key-state event:** every founding member of the room took part and holds the record, so `ConfederationFormation.verifies` checks the stored descriptors instead; a member added later needs one, which waits for Part C's governance. A formed confederation reads "Formed" on the group's list. `ConfederationCeremonyJvmTest` now also checks every device files the same verified confederation under the room its key derives |
| 13 | done. `ConfederationFollowThrough` on the coordinator's device makes the room once every member's key package is in, retrying when one arrives, through `MarmotGroupCreation.create` rather than a new `createForConfederation`: id `marmotGroupId(02‖X)`, a random routing address, every role holder a member and an admin, `#name`, born governed with `Quorum.minimumAdmins(T)`. A record that no longer verifies, or a device holding no role, makes no room. Adoption needs no new check: every founding member holds the `Confederation` row under the room's id, and `confederationOfRoom` reads it only if it verifies. The room's screen says whose room it is and that its members are fixed until the confederation can sign. `ConfederationCeremonyJvmTest` 9/9. `./gradlew check` passes, jvmTest 1,621 |
| 14 | done. `ConfederationSigningManager` over upstream's `ConfederationSigning`, in the confederation's Marmot room. Kinds 30390 (proposal), 30391 (each person's yes or no per role), 30392 (the proposer's selection and D_sign), 30393 (nonces), 30394 (confirmations), 30395 (partials), 30399 (failure). Only the selection is coordinated: the first `T` groups in roster order with `t_g` yeses, the lowest admins first. The transcript, the certificate, every group's partial and the signature take no secret, so **every device computes them itself** and checks the signature against the room's id before keeping it: no group coordinator and no outer coordinator message. Signer state is held in memory only; a device that restarts after sending a nonce ends the attempt out loud on its next step, and `resumeRunning` does it on start. A confederation signs kinds 0 and 1 only, with Part A's statement refusals; anything else is declined out loud. A signed event lands in `GroupSignedEvent` under the room, so the existing profile, posts and broadcast screens read it. Schema 45. `ConfederationSigningJvmTest` 5/5 on nine devices: a profile signed and read back on every device; two groups of two admins enough; a restart between nonces and confirmations failing it everywhere; too many declines; refused kinds. jvmTest 1,626 |
---