feat: a device declines a confederation event it finds wrong, out loud (confederation, Phase 3)

The refusals run where the wallet's and the statement's do: on arrival,
again at approval, as the decline's reason and in a resend. A proposal
is signed only with its proposer's own acceptance, by a coordinator who
is the proposer and an admin, and an acceptance only if its seal holds
exactly the admins and threshold this device sees in the group. The
seal's secret and the proposal being answered ride the FROST proposal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-21 21:54:30 +02:00
1 parent 24e4eec3eb
commit f7b361c95f
9 files changed
+812 -63

No files matched your search

@@ -3,15 +3,21 @@ package mobi.giza.compose.managers
import co.touchlab.kermit.Logger
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate
import com.vitorpamplona.crypto.random.RandomInstance
import kotlin.time.Clock
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.ConfederationEvent
import mobi.giza.compose.database.model.FrostSigningSession
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.extensions.toHex
import mobi.giza.compose.nostr.confederation.ConfederationAdminList
import mobi.giza.compose.nostr.confederation.ConfederationKinds
import mobi.giza.compose.nostr.confederation.ConfederationProposalAcceptanceEvent
import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent
import mobi.giza.compose.nostr.confederation.ConfederationProposalRejectionEvent
import mobi.giza.compose.nostr.confederation.ConfederationProposalWithdrawalEvent
import mobi.giza.compose.nostr.confederation.ConfederationSeal
import mobi.giza.compose.nostr.confederation.ConfederationStatus
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
@@ -102,9 +108,170 @@ object ConfederationManager {
* The same function on the proposer's device and every signer's, so the list each of them
* seals comes out the same when they see the same group (docs/confederation.md, D5).
*/
suspend fun adminListFor(database: GizaDatabase, chatRoomId: String, proposalId: HexKey): ConfederationAdminList? {
suspend fun adminListFor(database: GizaDatabase, chatRoomId: String, proposalId: HexKey): ConfederationAdminList? =
disclosureFor(database, chatRoomId)?.listFor(proposalId)
/** The admins and threshold [adminListFor] reads, before there is a proposal id to bind them to. */
class Disclosure(val group: HexKey, val admins: Set<HexKey>, val threshold: Int) {
fun listFor(proposalId: HexKey): ConfederationAdminList? = ConfederationAdminList.of(proposalId, group, threshold, admins)
}
suspend fun disclosureFor(database: GizaDatabase, chatRoomId: String): Disclosure? {
val admins = RoomAdmins.of(database, chatRoomId)?.admins ?: return null
val threshold = FrostSigningManager.completedKey(database, chatRoomId)?.threshold ?: return null
return ConfederationAdminList.of(proposalId, chatRoomId, threshold, admins)
return Disclosure(chatRoomId, admins, threshold)
}
/**
* Proposes, in [localChatRoom], that its group sign a proposal for a confederation of
* [invitees] together with its own acceptance of it, in one session (D3). [userPublicKey]
* is the coordinator, and has to be one of the group's admins (D4).
*
* The group itself is put first on the invitation if [invitees] leave it out.
*/
suspend fun proposeConfederation(
database: GizaDatabase,
localChatRoom: LocalChatRoom,
userPublicKey: HexKey,
invitees: List<ConfederationProposalEvent.Invitee>,
threshold: Int,
name: String,
expiresAt: Long,
createdAt: Long = Clock.System.now().epochSeconds,
): FrostSigningSession {
val group = localChatRoom.chatRoom.id
val admins = RoomAdmins.of(database, group)?.admins
?: throw IllegalStateException("This device cannot read the group's admins")
check(userPublicKey in admins) { "Only one of the group's admins can coordinate a confederation" }
val groups = (listOf(ConfederationProposalEvent.Invitee(group)) + invitees)
.distinctBy { it.groupPublicKey }
val tags = ConfederationProposalEvent.assembleTags(
groups = groups,
coordinator = userPublicKey,
threshold = threshold,
name = name,
nonce = RandomInstance.bytes(32).toHex(),
expiresAt = expiresAt,
)
val secret = RandomInstance.bytes(32)
val carried = ConfederationRefusal.Carried(sealSecret = secret.toHex(), proposalJson = null)
val disclosure = disclosureFor(database, group)
?: throw IllegalStateException("This device cannot read the group's admins and threshold")
val session = FrostSigningManager.proposeSigningBatch(
database = database,
localChatRoom = localChatRoom,
userPublicKey = userPublicKey,
lead = EventTemplate<Event>(createdAt, ConfederationKinds.PROPOSAL, tags, ConfederationProposalEvent.content(name, groups.size)),
dependents = { lead ->
listOf(acceptanceTemplate(disclosure, lead.id, null, group, userPublicKey, secret, createdAt))
},
proposalTags = carried.toTags(),
)
ConfederationRefusal.remember(database, session.id, carried, null)
return session
}
/** Proposes that this group accept [proposalId], disclosing its admins to the coordinator (D5). */
suspend fun proposeAcceptance(
database: GizaDatabase,
localChatRoom: LocalChatRoom,
userPublicKey: HexKey,
proposalId: HexKey,
createdAt: Long = Clock.System.now().epochSeconds,
): FrostSigningSession {
val (event, proposal) = heldProposal(database, proposalId)
val secret = RandomInstance.bytes(32)
val carried = ConfederationRefusal.Carried(sealSecret = secret.toHex(), proposalJson = event.toJson())
val disclosure = disclosureFor(database, localChatRoom.chatRoom.id)
?: throw IllegalStateException("This device cannot read the group's admins and threshold")
val template = acceptanceTemplate(
disclosure, proposal.id, proposal.relayHintFor(proposal.proposingGroup),
proposal.proposingGroup, proposal.coordinator, secret, createdAt,
)
return proposeAnswer(database, localChatRoom, userPublicKey, template, carried)
}
/** Proposes that this group reject [proposalId], saying [reason] if it gives one. */
suspend fun proposeRejection(
database: GizaDatabase,
localChatRoom: LocalChatRoom,
userPublicKey: HexKey,
proposalId: HexKey,
reason: String = "",
createdAt: Long = Clock.System.now().epochSeconds,
): FrostSigningSession {
val (event, proposal) = heldProposal(database, proposalId)
val template = EventTemplate<Event>(
createdAt, ConfederationKinds.REJECTION,
ConfederationProposalRejectionEvent.assembleTags(proposal.id, proposal.relayHintFor(proposal.proposingGroup), proposal.proposingGroup),
reason,
)
return proposeAnswer(database, localChatRoom, userPublicKey, template, ConfederationRefusal.Carried(null, event.toJson()))
}
/** Proposes that this group, which made [proposalId], take it back. */
suspend fun proposeWithdrawal(
database: GizaDatabase,
localChatRoom: LocalChatRoom,
userPublicKey: HexKey,
proposalId: HexKey,
reason: String = "",
createdAt: Long = Clock.System.now().epochSeconds,
): FrostSigningSession {
val (event, proposal) = heldProposal(database, proposalId)
val template = EventTemplate<Event>(
createdAt, ConfederationKinds.WITHDRAWAL,
ConfederationProposalWithdrawalEvent.assembleTags(proposal.id, proposal.relayHintFor(proposal.proposingGroup), proposal.groupPublicKeys),
reason,
)
return proposeAnswer(database, localChatRoom, userPublicKey, template, ConfederationRefusal.Carried(null, event.toJson()))
}
private suspend fun proposeAnswer(
database: GizaDatabase,
localChatRoom: LocalChatRoom,
userPublicKey: HexKey,
template: EventTemplate<Event>,
carried: ConfederationRefusal.Carried,
): FrostSigningSession {
val session = FrostSigningManager.proposeSigningBatch(
database = database,
localChatRoom = localChatRoom,
userPublicKey = userPublicKey,
events = listOf(template),
proposalTags = carried.toTags(),
)
ConfederationRefusal.remember(database, session.id, carried, null)
return session
}
private suspend fun heldProposal(database: GizaDatabase, proposalId: HexKey): Pair<Event, ConfederationProposalEvent.Proposal> {
val event = database.confederationDao().getEvent(proposalId)
?.takeIf { it.kind == ConfederationKinds.PROPOSAL }?.toEvent()
?: throw IllegalStateException("This device does not hold that proposal")
val proposal = ConfederationProposalEvent.parse(event)
?: throw IllegalStateException("That proposal is not well formed")
return event to proposal
}
private fun acceptanceTemplate(
disclosure: Disclosure,
proposalId: HexKey,
relayHint: String?,
proposingGroup: HexKey,
coordinator: HexKey,
secret: ByteArray,
createdAt: Long,
): EventTemplate<Event> {
val adminList = disclosure.listFor(proposalId)
?: throw IllegalStateException("This group cannot take part as it stands: it needs at least as many admins as its threshold, and a threshold of two or more")
val sealed = ConfederationSeal.seal(secret, coordinator, adminList)
return EventTemplate(
createdAt, ConfederationKinds.ACCEPTANCE,
ConfederationProposalAcceptanceEvent.assembleTags(proposalId, relayHint, proposingGroup, coordinator, sealed.ephemeralPublicKey),
sealed.content,
)
}
}
@@ -0,0 +1,211 @@
package mobi.giza.compose.managers
import co.touchlab.kermit.Logger
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
import kotlin.time.Clock
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.ConfederationSigning
import mobi.giza.compose.nostr.confederation.ConfederationKinds
import mobi.giza.compose.nostr.confederation.ConfederationProposalAcceptanceEvent
import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent
import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent.Proposal
import mobi.giza.compose.nostr.confederation.ConfederationProposalRejectionEvent
import mobi.giza.compose.nostr.confederation.ConfederationProposalState
import mobi.giza.compose.nostr.confederation.ConfederationProposalWithdrawalEvent
import mobi.giza.compose.nostr.confederation.ConfederationSeal
import mobi.giza.compose.nostr.confederation.tags.ConfederationCarriedProposalTag
import mobi.giza.compose.nostr.confederation.tags.ConfederationSealTag
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
/**
* What a member's device refuses to sign for its group about a confederation, out loud
* (docs/confederation.md, D6).
*
* Giza has no allowlist: a kind nothing refuses reaches the approval prompt. So these kinds get
* their refusals beside `WalletRefusal`, `GroupStatementRefusal` and the governance check, run
* when a proposal arrives and again when the member approves -- a group's admins can change in
* between, and the seal has to hold the admins the group has when it signs.
*
* What is refused is what is wrong: a shape this device does not sign, a coordinator who is not
* the one proposing, an admin list that is not this group's. What a device merely cannot see --
* a listed group's profile it cannot find right now -- is a warning on the approval screen, for
* the member to weigh.
*/
object ConfederationRefusal {
private val logger = Logger.withTag("ConfederationRefusal")
const val SHAPE = "Declined a confederation event in a form this device does not sign"
const val NOT_LISTED = "Declined: the proposal does not name this group"
const val COORDINATOR = "Declined: the coordinator must be the member who proposed it"
const val COORDINATOR_NOT_ADMIN = "Declined: the coordinator is not one of this group's admins"
const val EXPIRY = "Declined: the proposal has expired, or stays open longer than 30 days"
const val UNKNOWN_PROPOSAL = "Declined: this device has not seen the proposal being answered"
const val CLOSED = "Declined: the proposal is no longer open"
const val ANSWERED = "Declined: this group has already answered the proposal"
const val NO_ADMINS = "Declined: this device cannot read the group's admins to check them"
const val SEAL = "Declined: the sealed admin list is not this group's admins"
const val NOT_PROPOSER = "Declined: only the group that proposed it can withdraw it"
/** Leeway on the 30-day ceiling, for a proposer whose clock runs ahead of this one's. */
private const val CLOCK_SLACK_SECONDS = 60L * 60
/** What the FROST proposal carries beside the events: the seal's secret, and the proposal answered. */
data class Carried(val sealSecret: String?, val proposalJson: String?) {
fun toTags(): Array<Array<String>> = listOfNotNull(
sealSecret?.let(ConfederationSealTag::assemble),
proposalJson?.let(ConfederationCarriedProposalTag::assemble),
).toTypedArray()
companion object {
fun from(tags: Array<Array<String>>) = Carried(
sealSecret = ConfederationSealTag.valueIn(tags),
proposalJson = ConfederationCarriedProposalTag.valueIn(tags),
)
fun from(signing: ConfederationSigning?) = Carried(signing?.sealSecret, signing?.proposalJson)
}
}
fun involves(events: List<Event>): Boolean = events.any { ConfederationKinds.isConfederationKind(it.kind) }
/**
* Why this device declines to sign [events] for the room [chatRoomId], or null if it may be
* put to its member. [proposer] is the member who opened the signing session.
*/
suspend fun of(
database: GizaDatabase,
chatRoomId: String,
proposer: HexKey,
events: List<Event>,
carried: Carried,
now: Long = Clock.System.now().epochSeconds,
): String? {
if (!involves(events)) return null
if (!events.all { ConfederationKinds.isConfederationKind(it.kind) }) return SHAPE
val kinds = events.map { it.kind }
return when (kinds) {
listOf(ConfederationKinds.PROPOSAL, ConfederationKinds.ACCEPTANCE) -> {
val proposal = ConfederationProposalEvent.parse(events[0]) ?: return SHAPE
proposalRefusal(database, chatRoomId, proposer, proposal, now)
?: acceptanceRefusal(database, chatRoomId, proposal, events[1], carried)
}
listOf(ConfederationKinds.ACCEPTANCE) -> {
val proposal = answered(database, carried) ?: return UNKNOWN_PROPOSAL
answerRefusal(database, chatRoomId, proposal, now)
?: acceptanceRefusal(database, chatRoomId, proposal, events[0], carried)
}
listOf(ConfederationKinds.REJECTION) -> {
val proposal = answered(database, carried) ?: return UNKNOWN_PROPOSAL
val rejection = ConfederationProposalRejectionEvent.parse(events[0]) ?: return SHAPE
if (rejection.proposalId != proposal.id) return SHAPE
answerRefusal(database, chatRoomId, proposal, now)
}
listOf(ConfederationKinds.WITHDRAWAL) -> {
val proposal = answered(database, carried) ?: return UNKNOWN_PROPOSAL
val withdrawal = ConfederationProposalWithdrawalEvent.parse(events[0]) ?: return SHAPE
if (withdrawal.proposalId != proposal.id) return SHAPE
if (proposal.proposingGroup != chatRoomId) return NOT_PROPOSER
val state = ConfederationManager.status(database, proposal.id, now)?.state
if (state != null && state != ConfederationProposalState.OPEN) return CLOSED
null
}
else -> SHAPE
}
}
/** The rules for a proposal this group makes (D3, D4, D6). */
private suspend fun proposalRefusal(
database: GizaDatabase,
chatRoomId: String,
proposer: HexKey,
proposal: Proposal,
now: Long,
): String? {
if (proposal.proposingGroup != chatRoomId || !proposal.lists(chatRoomId)) return NOT_LISTED
if (proposal.coordinator != proposer) return COORDINATOR
val admins = RoomAdmins.of(database, chatRoomId)?.admins ?: return NO_ADMINS
if (proposal.coordinator !in admins) return COORDINATOR_NOT_ADMIN
if (proposal.expiresAt <= now) return EXPIRY
if (proposal.expiresAt > now + ConfederationKinds.MAX_EXPIRY_SECONDS + CLOCK_SLACK_SECONDS) return EXPIRY
return null
}
/** The rules for any answer this group gives to someone's proposal. */
private suspend fun answerRefusal(database: GizaDatabase, chatRoomId: String, proposal: Proposal, now: Long): String? {
if (!proposal.lists(chatRoomId)) return NOT_LISTED
if (proposal.isExpiredAt(now)) return EXPIRY
val status = ConfederationManager.status(database, proposal.id, now)
if (status != null) {
if (status.hasAnswered(chatRoomId)) return ANSWERED
if (status.state != ConfederationProposalState.OPEN) return CLOSED
}
return null
}
/** The seal: the acceptance has to hold, byte for byte, the admins this device sees (D5). */
private suspend fun acceptanceRefusal(
database: GizaDatabase,
chatRoomId: String,
proposal: Proposal,
event: Event,
carried: Carried,
): String? {
val acceptance = ConfederationProposalAcceptanceEvent.parse(event) ?: return SHAPE
if (acceptance.group != chatRoomId) return NOT_LISTED
if (!ConfederationProposalAcceptanceEvent.answers(acceptance, proposal)) return SHAPE
val secret = carried.sealSecret?.takeIf(ConfederationKinds::isHex32) ?: return SEAL
val expected = ConfederationManager.adminListFor(database, chatRoomId, proposal.id) ?: return NO_ADMINS
val reproduces = ConfederationSeal.reproduces(
ephemeralSecret = secret.hexToByteArray(),
coordinator = proposal.coordinator,
expected = expected,
content = acceptance.content,
ephemeralPublicKey = acceptance.ephemeralPublicKey,
)
if (!reproduces) {
logger.w("Acceptance ${event.id.take(8)} does not seal the ${expected.admins.size} admins this device sees")
return SEAL
}
return null
}
/**
* The proposal an answer answers: carried on the signing proposal and verified as its
* author's, or already on file. A carried copy that verifies is filed, as a relay's would be.
*/
private suspend fun answered(database: GizaDatabase, carried: Carried): Proposal? {
val carriedEvent = carried.proposalJson?.let { Event.fromJsonOrNull(it) }
if (carriedEvent != null && GroupKeyStateEvent.isSignedByRoom(carriedEvent, carriedEvent.pubKey)) {
ConfederationManager.record(database, carriedEvent)
return ConfederationProposalEvent.parse(carriedEvent)
}
return null
}
/** Keeps what a session over a confederation event must remember past its proposal (Phase 4's table). */
suspend fun remember(database: GizaDatabase, sessionId: String, carried: Carried, refusal: String?) {
database.confederationDao().upsertSigning(
ConfederationSigning(
sessionId = sessionId,
sealSecret = carried.sealSecret,
proposalJson = carried.proposalJson,
refusal = refusal,
)
)
}
/** The reason this device declined [sessionId], if it was a confederation refusal. */
suspend fun reasonFor(database: GizaDatabase, sessionId: String): String? =
database.confederationDao().getSigning(sessionId)?.refusal
/** The tags a resent proposal has to carry again, so a member who missed it can check it. */
suspend fun carriedTagsFor(database: GizaDatabase, sessionId: String): Array<Array<String>> =
database.confederationDao().getSigning(sessionId)?.let { Carried.from(it).toTags() } ?: emptyArray()
}
@@ -279,7 +279,8 @@ object FrostSigningManager {
localChatRoom: LocalChatRoom,
userPublicKey: HexKey,
events: List<EventTemplate<*>>,
key: DkgSession? = null
key: DkgSession? = null,
proposalTags: Array<Array<String>> = emptyArray()
): FrostSigningSession = proposeSigningBatch(
database = database,
localChatRoom = localChatRoom,
@@ -287,6 +288,7 @@ object FrostSigningManager {
lead = events.firstOrNull()
?: throw IllegalArgumentException("A signing session must be given something to sign"),
dependents = { events.drop(1) },
proposalTags = proposalTags,
key = key
)
@@ -315,7 +317,13 @@ object FrostSigningManager {
userPublicKey: HexKey,
lead: EventTemplate<*>,
dependents: (lead: Event) -> List<EventTemplate<*>>,
key: DkgSession? = null
key: DkgSession? = null,
/**
* Tags the proposal rumor carries beside the events, for what a signer needs to check
* them and the signed events must not show: a confederation acceptance's seal secret
* (docs/confederation.md, D5). Inside the group's encryption like the rest of it.
*/
proposalTags: Array<Array<String>> = emptyArray()
): FrostSigningSession {
val ceremony = key?.takeIf { it.stage == DkgRitualStage.COMPLETE && ShareGenerations.canSign(database, it) }
?: completedKey(database, localChatRoom.chatRoom.id)
@@ -381,7 +389,8 @@ object FrostSigningManager {
session = session,
kind = FrostSigningEvents.PROPOSAL,
content = FrostSigningEvents.encodeProposal(unsignedEvents),
includeKey = true
includeKey = true,
extraTags = proposalTags
)
advance(database, localChatRoom, sessionId)
@@ -689,6 +698,28 @@ object FrostSigningManager {
}
}
// A confederation event this device can check and finds wrong -- a coordinator who
// is not the proposer, a sealed admin list that is not this group's -- is declined
// before anybody is asked. What it carries to be checked with is kept either way,
// since approval checks again. docs/confederation.md, D6.
val confederation = if (ConfederationRefusal.involves(unsignedEvents)) {
ConfederationRefusal.Carried.from(innerEvent.tags)
} else {
null
}
confederation?.let { carried ->
ConfederationRefusal.of(database, localChatRoom.chatRoom.id, innerEvent.pubKey, unsignedEvents, carried)
}?.let { why ->
logger.w("Signing proposal $sessionId: $why")
val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0, participantCount = n)
.copy(signDeclinedAt = Clock.System.now())
database.frostSigningSessionDao().upsert(declined)
database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents))
ConfederationRefusal.remember(database, sessionId, confederation, why)
announceStarted(database, declined)
return declined
}
// A share of the generation the proposal names, or a refusal said out loud.
// Signing with any other generation's share would put a partial signature
// behind the wrong public share -- it cannot aggregate -- and staying
@@ -731,6 +762,7 @@ object FrostSigningManager {
val session = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0, participantCount = n)
database.frostSigningSessionDao().upsert(session)
database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents))
confederation?.let { ConfederationRefusal.remember(database, sessionId, it, null) }
announceStarted(database, session)
logger.i(
@@ -1032,6 +1064,28 @@ object FrostSigningManager {
session.subject == FrostSigningSubject.EVENTS &&
items.any { item -> Event.fromJsonOrNull(item.unsignedEventJson)?.let(GroupStatementRefusal::of) != null }
/**
* The confederation refusal that applies to [session] now, read again from what it
* carried when it arrived. docs/confederation.md, D6.
*/
private suspend fun confederationRefusalNow(
database: GizaDatabase,
localChatRoom: LocalChatRoom,
session: FrostSigningSession,
items: List<FrostSigningItem>
): String? {
if (session.subject != FrostSigningSubject.EVENTS) return null
val events = items.mapNotNull { Event.fromJsonOrNull(it.unsignedEventJson) }
if (!ConfederationRefusal.involves(events)) return null
return ConfederationRefusal.of(
database = database,
chatRoomId = localChatRoom.chatRoom.id,
proposer = session.coordinatorPublicKey,
events = events,
carried = ConfederationRefusal.Carried.from(database.confederationDao().getSigning(session.id)),
)
}
private fun isFromCoordinator(
session: FrostSigningSession,
innerEvent: Event
@@ -2159,6 +2213,19 @@ object FrostSigningManager {
return
}
// Checked again rather than trusted from arrival: the group's admins can change
// while a member decides, and the seal has to hold the ones it has when it signs.
// docs/confederation.md, D6.
confederationRefusalNow(database, localChatRoom, session, items)?.let { why ->
logger.w("Session $sessionId: $why")
database.confederationDao().getSigning(sessionId)?.let {
database.confederationDao().upsertSigning(it.copy(refusal = why))
}
update(database, session) { it.copy(signDeclinedAt = Clock.System.now()) }
advance(database, localChatRoom, sessionId)
return
}
update(database, session) { it.copy(signApprovedAt = Clock.System.now()) }
logger.i("Session $sessionId: signing approved")
@@ -2373,7 +2440,12 @@ object FrostSigningManager {
)
return false
}
Triple(FrostSigningEvents.PROPOSAL, FrostSigningEvents.encodeProposal(unsigned), emptyArray<Array<String>>())
Triple(
FrostSigningEvents.PROPOSAL,
FrostSigningEvents.encodeProposal(unsigned),
// What a confederation event is checked with goes again with it.
ConfederationRefusal.carriedTagsFor(database, sessionId)
)
}
// A Bennu peer's, declined on arrival: this device proposed none, so has
@@ -2637,7 +2709,9 @@ object FrostSigningManager {
session: FrostSigningSession
) {
val items = database.frostSigningSessionDao().getItems(session.id)
val confederationReason = ConfederationRefusal.reasonFor(database, session.id)
val reason = when {
confederationReason != null -> confederationReason
isWalletSession(session, items) -> WalletRefusal.REASON
isUnshowableSession(session, items) -> GroupStatementRefusal.REASON
!holdsShareFor(database, session) -> GENERATION_REFUSAL
@@ -0,0 +1,34 @@
package mobi.giza.compose.nostr.confederation.tags
import com.vitorpamplona.quartz.nip01Core.core.has
import com.vitorpamplona.quartz.utils.ensure
/**
* The signed proposal a group is being asked to answer, riding the FROST signing proposal for
* the answer (docs/confederation.md, Phase 3).
*
* A signer checks an answer against the proposal it answers, and could otherwise do that only
* if its relays had already delivered the proposal. Carrying it removes that dependence. It is
* a signed event, so carrying it costs no trust: the signer verifies it against its author like
* any copy from a relay, and files it as one.
*/
class ConfederationCarriedProposalTag(
val proposalJson: String,
) {
fun toTagArray() = assemble(proposalJson)
companion object {
const val TAG_NAME = "confederation_proposal"
fun parse(tag: Array<String>): ConfederationCarriedProposalTag? {
ensure(tag.has(1)) { return null }
ensure(tag[0] == TAG_NAME) { return null }
return ConfederationCarriedProposalTag(tag[1].ifBlank { return null })
}
fun assemble(proposalJson: String): Array<String> = arrayOf(TAG_NAME, proposalJson)
/** The first such tag's value among [tags], or null. */
fun valueIn(tags: Array<Array<String>>): String? = tags.firstNotNullOfOrNull(::parse)?.proposalJson
}
}
@@ -4,6 +4,8 @@ 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 mobi.giza.compose.nostr.confederation.ConfederationKinds
import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent
import mobi.giza.compose.managers.SharedKeyDerivation
import mobi.giza.compose.managers.WalletRefusal
import mobi.giza.compose.nostr.RetiredKinds
@@ -110,6 +112,27 @@ object ProposedEvent {
// they are the detail rather than a count of them.
TextNoteEvent.KIND -> Summary(label = "Post", detail = event.content)
// The confederation's (docs/confederation.md): what the group would be joining,
// with whom and on what terms, rather than a number and a ciphertext. An
// acceptance's content is sealed to the coordinator, so its summary says what
// the seal discloses instead of showing it.
ConfederationKinds.PROPOSAL -> ConfederationProposalEvent.parse(event)?.let { proposal ->
Summary(
label = "A confederation, ${proposal.name}",
detail = "Proposed with ${proposal.groups.size} groups · " +
"${proposal.threshold} of ${proposal.groups.size} groups to act",
)
} ?: Summary(label = "A confederation that cannot be read", detail = "")
ConfederationKinds.ACCEPTANCE -> Summary(
label = "Accepting a confederation",
detail = "Discloses this group's admins and threshold to the coordinator",
)
ConfederationKinds.REJECTION -> Summary(label = "Declining a confederation", detail = event.content)
ConfederationKinds.WITHDRAWAL -> Summary(label = "Withdrawing a confederation proposal", detail = event.content)
// A Bennu wallet's: declined on arrival, and said as what it is rather than
// as a number. docs/giza-wallet-removal.md.
in RetiredKinds.WALLET, in RetiredKinds.GROUP_LIGHTNING -> WALLET
@@ -0,0 +1,282 @@
package mobi.giza.compose.managers
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate
import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent
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.assertNull
import kotlin.test.assertTrue
import kotlin.time.Clock
import kotlinx.coroutines.runBlocking
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.managers.ConfederationTestGroups.key
import mobi.giza.compose.managers.ConfederationTestGroups.npub
import mobi.giza.compose.nostr.confederation.ConfederationKinds
import mobi.giza.compose.nostr.confederation.ConfederationProposalAcceptanceEvent
import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent
import mobi.giza.compose.nostr.confederation.ConfederationSeal
import mobi.giza.compose.extensions.toHex
import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent.Invitee
import mobi.giza.compose.nostr.confederation.tags.ConfederationCarriedProposalTag
import mobi.giza.compose.nostr.confederation.tags.ConfederationSealTag
import mobi.giza.compose.nostr.frost.FrostSigningEvents
import mobi.giza.compose.text.ProposedEvent
/**
* What a member's device does with a proposal to sign one of the confederation's events
* (docs/confederation.md, Phase 3): a right one is put to the member, a wrong one is declined
* out loud with its reason, and approval checks again.
*
* Each proposal is a real one, made on Alice's device and handed to Bob's through the inbound
* path. Who a device sees as the group's admins is [RoomAdmins.override], per device, since the
* harness's room has no MLS state.
*/
class ConfederationDeclineJvmTest {
private val names = listOf(npub(31), npub(32), npub(33))
private val harness = SigningProposalHarness(names = names)
private val alice = harness.members[0]
private val bob = harness.members[1]
private val carol = harness.members[2]
private val polis = key(2)
private val ekklesia = key(3)
/** Who the device being opened sees as the group's admins. */
private var admins: Set<HexKey> = harness.members.toSet()
@BeforeTest
fun seeAdmins() {
RoomAdmins.override = { id -> if (id == harness.roomId) RoomAdmins(admins, governed = false) else null }
}
@AfterTest
fun close() {
RoomAdmins.override = null
harness.close()
}
private val now get() = Clock.System.now().epochSeconds
private fun deliver(sent: SigningProposalHarness.Sent, to: HexKey, prepare: suspend (GizaDatabase) -> Unit = {}) =
runBlocking { harness.deliver(sent, to, prepare) }
private fun proposeHere(proposer: HexKey = alice, prepare: suspend (GizaDatabase) -> Unit = {}) = runBlocking {
harness.propose(proposer, prepare) { db, room ->
ConfederationManager.proposeConfederation(
db, room, proposer,
invitees = listOf(Invitee(npub(2)), Invitee(npub(3))),
threshold = 2,
name = "Atlas",
expiresAt = now + ConfederationKinds.DEFAULT_EXPIRY_SECONDS,
)
}
}
private fun session(sent: SigningProposalHarness.Sent) = runBlocking {
assertNotNull(harness.db.frostSigningSessionDao().getSessionById(sent.session.id))
}
private fun assertAsked(sent: SigningProposalHarness.Sent) = runBlocking {
val session = session(sent)
assertNull(session.signDeclinedAt, "not declined")
assertTrue(FrostSigningManager.isAwaitingApproval(session, harness.db.frostSigningSessionDao().getItems(session.id)))
assertEquals(emptyList(), harness.queued(FrostSigningEvents.DECLINE))
}
private fun assertDeclined(sent: SigningProposalHarness.Sent, reason: String) = runBlocking {
val session = session(sent)
assertNotNull(session.signDeclinedAt, "declined, and filed so the decline goes out")
assertNull(session.signApprovedAt)
assertEquals(listOf(reason), harness.queued(FrostSigningEvents.DECLINE).map { it.content }, "said out loud, with its reason")
assertEquals(emptyList(), harness.queued(FrostSigningEvents.NONCE))
}
// --- a proposal, with the proposer's own acceptance
@Test
fun `a proposal sealed with the group's own admins is put to the member`() {
val sent = proposeHere()
deliver(sent, bob)
assertAsked(sent)
val proposal = runBlocking { harness.db.frostSigningSessionDao().getItems(sent.session.id) }
.first().let { Event.fromJson(it.unsignedEventJson) }
assertEquals("A confederation, Atlas", ProposedEvent.summarize(proposal).label)
assertEquals(alice, ConfederationProposalEvent.parse(proposal)?.coordinator)
}
@Test
fun `a member who is not an admin cannot coordinate`() {
admins = setOf(bob, carol)
assertFailsWith<IllegalStateException> { proposeHere() }
}
@Test
fun `a coordinator the group does not have as an admin is declined`() {
val sent = proposeHere()
admins = setOf(bob, carol)
deliver(sent, bob)
assertDeclined(sent, ConfederationRefusal.COORDINATOR_NOT_ADMIN)
}
@Test
fun `a seal over admins this device does not see is declined`() {
admins = harness.members.toSet() + npub(40)
val sent = proposeHere()
admins = harness.members.toSet()
deliver(sent, bob)
assertDeclined(sent, ConfederationRefusal.SEAL)
}
@Test
fun `a proposal that leaves out the seal's secret is declined`() {
val sent = proposeHere().let { it.copy(tags = it.tags.filterNot { t -> t[0] == ConfederationSealTag.TAG_NAME }.toTypedArray()) }
deliver(sent, bob)
assertDeclined(sent, ConfederationRefusal.SEAL)
}
@Test
fun `admins who change before approval make approval a decline`() = runBlocking {
val sent = proposeHere()
deliver(sent, bob)
assertAsked(sent)
admins = setOf(alice, bob)
FrostSigningManager.approve(harness.db, harness.room, sent.session.id)
assertDeclined(sent, ConfederationRefusal.SEAL)
}
/** A batch built by hand, so one thing about it can be wrong: [coordinator] names someone else. */
private fun batch(coordinator: HexKey, withAcceptance: Boolean = true) = runBlocking {
harness.propose(alice) { db, room ->
val disclosure = assertNotNull(ConfederationManager.disclosureFor(db, room.chatRoom.id))
val secret = ByteArray(32) { 9 }
FrostSigningManager.proposeSigningBatch(
db, room, alice,
lead = EventTemplate<Event>(
now, ConfederationKinds.PROPOSAL,
ConfederationProposalEvent.assembleTags(
listOf(Invitee(room.chatRoom.id), Invitee(npub(2))), coordinator, 2, "Atlas", "ab".repeat(32),
now + 1000,
),
"",
),
dependents = { lead ->
if (!withAcceptance) return@proposeSigningBatch emptyList()
val sealed = ConfederationSeal.seal(secret, coordinator, disclosure.listFor(lead.id)!!)
listOf(
EventTemplate<Event>(
now, ConfederationKinds.ACCEPTANCE,
ConfederationProposalAcceptanceEvent.assembleTags(lead.id, null, room.chatRoom.id, coordinator, sealed.ephemeralPublicKey),
sealed.content,
)
)
},
proposalTags = ConfederationRefusal.Carried(secret.toHex(), null).toTags(),
)
}
}
@Test
fun `a coordinator who is not the proposer is declined`() {
val sent = batch(coordinator = carol)
deliver(sent, bob)
assertDeclined(sent, ConfederationRefusal.COORDINATOR)
}
@Test
fun `the same batch naming its proposer is put to the member`() {
val sent = batch(coordinator = alice)
deliver(sent, bob)
assertAsked(sent)
}
@Test
fun `a proposal without its proposer's acceptance is declined`() {
val sent = batch(coordinator = alice, withAcceptance = false)
deliver(sent, bob)
assertDeclined(sent, ConfederationRefusal.SHAPE)
}
@Test
fun `a confederation event batched with anything else is declined`() {
val sent = runBlocking {
harness.propose(alice) { db, room ->
FrostSigningManager.proposeSigningBatch(
db, room, alice,
events = listOf(
EventTemplate<Event>(now, TextNoteEvent.KIND, arrayOf(), "hello"),
EventTemplate<Event>(now, ConfederationKinds.REJECTION, arrayOf(arrayOf("e", "a".repeat(64))), ""),
),
)
}
}
deliver(sent, bob)
assertDeclined(sent, ConfederationRefusal.SHAPE)
}
// --- answering another group's proposal
private fun inviting(expiresAt: Long = now + 1000) = ConfederationTestGroups.proposal(
polis, listOf(npub(2), harness.roomId, npub(3)), coordinator = npub(9),
createdAt = now - 10, expiresAt = expiresAt,
)
private fun answer(proposal: Event, how: suspend (GizaDatabase, mobi.giza.compose.database.model.intermdiate.LocalChatRoom) -> mobi.giza.compose.database.model.FrostSigningSession) =
runBlocking { harness.propose(alice, prepare = { ConfederationManager.record(it, proposal) }, propose = how) }
@Test
fun `an acceptance is put to the member, with the proposal it answers carried`() {
val proposal = inviting()
val sent = answer(proposal) { db, room -> ConfederationManager.proposeAcceptance(db, room, alice, proposal.id) }
deliver(sent, bob)
assertAsked(sent)
runBlocking { assertNotNull(harness.db.confederationDao().getEvent(proposal.id), "the carried proposal is filed") }
}
@Test
fun `an answer to a proposal this device has not seen is declined`() {
val proposal = inviting()
val sent = answer(proposal) { db, room -> ConfederationManager.proposeRejection(db, room, alice, proposal.id) }
.let { it.copy(tags = it.tags.filterNot { t -> t[0] == ConfederationCarriedProposalTag.TAG_NAME }.toTypedArray()) }
deliver(sent, bob)
assertDeclined(sent, ConfederationRefusal.UNKNOWN_PROPOSAL)
}
@Test
fun `an answer to a proposal another group has rejected is declined`() {
val proposal = inviting()
val sent = answer(proposal) { db, room -> ConfederationManager.proposeAcceptance(db, room, alice, proposal.id) }
deliver(sent, bob, prepare = { ConfederationManager.record(it, ConfederationTestGroups.rejection(ekklesia, proposal)) })
assertDeclined(sent, ConfederationRefusal.CLOSED)
}
@Test
fun `an answer to an expired proposal is declined`() {
val proposal = inviting(expiresAt = now - 1)
val sent = answer(proposal) { db, room -> ConfederationManager.proposeRejection(db, room, alice, proposal.id) }
deliver(sent, bob)
assertDeclined(sent, ConfederationRefusal.EXPIRY)
}
@Test
fun `only the proposing group can withdraw`() {
val proposal = inviting()
val sent = answer(proposal) { db, room -> ConfederationManager.proposeWithdrawal(db, room, alice, proposal.id) }
deliver(sent, bob)
assertDeclined(sent, ConfederationRefusal.NOT_PROPOSER)
}
@Test
fun `a resent proposal carries its seal again`() = runBlocking {
val sent = proposeHere()
val tags = ConfederationRefusal.carriedTagsFor(harness.db, sent.session.id)
assertEquals(1, tags.count { it[0] == ConfederationSealTag.TAG_NAME })
}
}
@@ -1,52 +0,0 @@
package mobi.giza.compose.managers
import com.vitorpamplona.quartz.nip01Core.core.Event
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.runBlocking
import mobi.giza.compose.nostr.frost.FrostSigningEvents
import mobi.giza.compose.text.ProposedEvent
/**
* What a member's device does today with a proposal to sign one of the confederation's kinds
* (docs/confederation.md, Phase 1): nothing refuses it, and the member is asked to approve
* "Event of kind N". Phase 3 turns this into ConfederationDeclineJvmTest.
*/
class ConfederationKindsTodayJvmTest {
private val harness = SigningProposalHarness()
@AfterTest
fun close() = harness.close()
private fun asked(kind: Int) = runBlocking {
val (alice, bob) = harness.members
val sent = harness.propose(alice) { db, room ->
FrostSigningManager.proposeSigning(db, room, alice, kind = kind, tags = arrayOf(), content = "{}")
}
harness.deliver(sent, bob)
val db = harness.db
val session = db.frostSigningSessionDao().getSessionById(sent.session.id)
assertNotNull(session)
assertNull(session.signDeclinedAt)
val items = db.frostSigningSessionDao().getItems(session.id)
assertTrue(FrostSigningManager.isAwaitingApproval(session, items))
assertEquals(emptyList(), harness.queued(FrostSigningEvents.DECLINE))
val event = Event.fromJson(items.single().unsignedEventJson)
assertEquals("Event of kind $kind", ProposedEvent.summarize(event).label)
}
@Test
fun `a proposal is put to the member as an unknown kind`() = asked(9430)
@Test
fun `an acceptance is put to the member as an unknown kind`() = asked(9431)
@Test
fun `a rejection is put to the member as an unknown kind`() = asked(9432)
}
@@ -37,7 +37,15 @@ object ConfederationTestGroups {
return Event(id, pubKey, createdAt, kind, tags, content, sig)
}
fun proposal(by: PrivateKey, groups: List<HexKey>, coordinator: HexKey, threshold: Int = 2, name: String = "Atlas"): Event =
fun proposal(
by: PrivateKey,
groups: List<HexKey>,
coordinator: HexKey,
threshold: Int = 2,
name: String = "Atlas",
createdAt: Long = CREATED_AT,
expiresAt: Long = createdAt + ConfederationKinds.DEFAULT_EXPIRY_SECONDS,
): Event =
signed(
by, ConfederationKinds.PROPOSAL,
ConfederationProposalEvent.assembleTags(
@@ -46,9 +54,10 @@ object ConfederationTestGroups {
threshold = threshold,
name = name,
nonce = "cd".repeat(32),
expiresAt = EXPIRES_AT,
expiresAt = expiresAt,
),
ConfederationProposalEvent.content(name, groups.size),
createdAt = createdAt,
)
fun acceptance(by: PrivateKey, proposal: Event, admins: List<HexKey>, threshold: Int = 2, secret: ByteArray = ByteArray(32) { 5 }): Event {
@@ -58,19 +67,19 @@ object ConfederationTestGroups {
return signed(
by, ConfederationKinds.ACCEPTANCE,
ConfederationProposalAcceptanceEvent.assembleTags(parsed.id, null, parsed.proposingGroup, parsed.coordinator, sealed.ephemeralPublicKey),
sealed.content, createdAt = CREATED_AT + 10,
sealed.content, createdAt = proposal.createdAt + 10,
)
}
fun rejection(by: PrivateKey, proposal: Event): Event = signed(
by, ConfederationKinds.REJECTION,
ConfederationProposalRejectionEvent.assembleTags(proposal.id, null, proposal.pubKey), "Not for us",
createdAt = CREATED_AT + 10,
createdAt = proposal.createdAt + 10,
)
fun withdrawal(by: PrivateKey, proposal: Event): Event = signed(
by, ConfederationKinds.WITHDRAWAL,
ConfederationProposalWithdrawalEvent.assembleTags(proposal.id, null, ConfederationProposalEvent.parse(proposal)!!.groupPublicKeys), "",
createdAt = CREATED_AT + 20,
createdAt = proposal.createdAt + 20,
)
}
+1
View File
@@ -45,6 +45,7 @@ wait on upstream (see the next section).
| 0 | done. 9430–9433 appear in neither the NIP README's kind table (nothing between 9321 and 9734), quartz 2.20.1, Curare nor Bennu. `Nip44v2.getConversationKey` and `encryptWithNonce` are public in quartz 2.20.1. A demoted admin can still hold a share of the active generation while refresh is experimental, so `canSign` does not imply admin: D4 now checks it |
| 1 | done. `ConfederationRoomKeyJvmTest` 3/3: replaying `SharedKeyDerivation.Derived.tweaks` (new; the scalars `derive` applies) as x-only `ConfederationTweak`s signs as `marmotGroupId(02‖X)`, and the event verifies through `isSignedByRoom`, so D10 stands. `ConfederationKindsTodayJvmTest` pins 9430–9432 reaching the member as "Event of kind N". `ConfederationSealPremiseJvmTest` 3/3 against quartz's `Nip44v2`. `ConfederationFixture` and `SigningProposalHarness` lifted for the phases after |
| 2 | done. `nostr/confederation/`: `ConfederationKinds`, the proposal, acceptance, rejection and withdrawal events, `ConfederationAdminList` (decodes only its own encoding), `ConfederationSeal`, `ConfederationStatus`, five tag classes. `ConfederationEventsTest` 27/27; `RetiredKindsTest` checks the family is nobody else's and regular. An answer counts only if made by the proposal's expiry, so `ACCEPTED` does not depend on when a device heard. The seal tag rides the FROST proposal through `ConfederationSealTag` rather than `FrostSigningEvents.assembleTags` |
| 3 | done. `ConfederationRefusal` in all four places in `FrostSigningManager`: on arrival, again at approval (the admins can change while a member decides), as the decline's reason, and in the resend, which carries the seal again. Two tags ride the FROST proposal: `confederation_seal` and, for an answer, `confederation_proposal`, the signed 9430 it answers, so a signer does not depend on its relays (verified and filed like a relay's copy). `proposeSigningBatch` takes `proposalTags`. `ConfederationManager.proposeConfederation`, `proposeAcceptance`, `proposeRejection` and `proposeWithdrawal` build them. `ProposedEvent` summarises the four kinds. `ConfederationDeclineJvmTest` 16/16 replaces the Phase 1 pin. The warnings half of D6 waits for the approval screen (Phase 7). Full jvmTest 1,569, all passing once `ShippedProfileUpgradeJvmTest` was moved to 43 |
| 4 | done, before 3, because the refusals need somewhere to keep the seal and the reason past arrival. Schema 43: `ConfederationEvent` (every kind in one table, keyed by event id, indexed by the proposal it is about), `ConfederationInvitee` (which proposals name a group) and `ConfederationSigning` (per signing session: the seal secret, the carried proposal, the refusal). No `ConfederationGroup` cache: D2's lookups land in the existing `Profile` rows. `ConfederationManager.record` verifies the author's signature and files; `status` computes D8 from the rows. The repository waits for Phase 6, its first caller. `ConfederationStorageJvmTest` 5/5 |
---