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:
1 parent
5ac4c05352
commit
e723e70a59
13 files changed
+7044
-5
No files matched your search
@@ -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)
|
||||
|
||||
+27
@@ -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(
|
||||
|
||||
+72
@@ -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(),
|
||||
)
|
||||
+4
@@ -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) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+567
@@ -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()
|
||||
}
|
||||
}
|
||||
+80
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
@@ -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
|
||||
|
||||
Reference in new issue
Block a user