frost: fence signing sessions by share epoch

This commit is contained in:
Kgothatso Ngako committed 2026-11-19 23:24:01 +02:00
1 parent 947685a914
commit aaa68a3dbd
14 files changed
+4845 -24

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -153,7 +153,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
UnsignedNostrEvent::class,
Zap::class
],
version = 37,
version = 38,
autoMigrations = [
// v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can
// generate the migration itself — nothing existing changes shape.
@@ -396,6 +396,11 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
// not sent since its last full save" -- true of every one of them at the moment of the
// upgrade, because the build before this one saved the whole state on every send.
AutoMigration(from = 36, to = 37),
// v38 adds application-level FROST share epochs. Existing keys, key states and
// signing sessions read back as epoch zero, which is what they were. The nullable
// refresh identifiers and transcript link read as "not a refresh". New columns
// only: no ceremony runs and no share material moves during the upgrade.
AutoMigration(from = 37, to = 38),
]
)
@ConstructedBy(GizaDatabaseConstructor::class)
@@ -62,7 +62,12 @@ abstract class GroupKeyStateDao {
open suspend fun replace(groupKeyState: GroupKeyState): GroupKeyState {
val known = getByChatRoomId(groupKeyState.chatRoomId)
if (known != null && known.announcedAt >= groupKeyState.announcedAt) return known
if (known != null) {
if (known.shareEpoch > groupKeyState.shareEpoch) return known
if (known.shareEpoch == groupKeyState.shareEpoch && known.announcedAt >= groupKeyState.announcedAt) {
return known
}
}
val stamped = groupKeyState.copy(
createdAt = known?.createdAt ?: groupKeyState.createdAt,
@@ -137,6 +137,9 @@ data class ChatMessage(
*/
val dkgSessionId: String? = null,
/** The re-enrollment a refresh transcript line belongs to, or null for anything else. */
val reEnrollmentSessionId: String? = null,
override val createdAt: Instant = Clock.System.now(),
override val updatedAt: Instant = createdAt,
override val savedAt: Instant = Clock.System.now(),
@@ -1,5 +1,6 @@
package mobi.giza.compose.database.model
import androidx.room3.ColumnInfo
import androidx.room3.Entity
import androidx.room3.ForeignKey
import androidx.room3.Index
@@ -62,6 +63,10 @@ data class DkgSession(
/** The `n`: how many members have to show up before params can be built. */
val participantCount: Int,
/** Zero for the original ChillDKG output, incremented for each activated share refresh. */
@ColumnInfo(defaultValue = "0")
val shareEpoch: Long = 0,
/**
* Everyone the ceremony is being run with, comma-separated hex, sorted --
* or null on a row written before this column existed.
@@ -128,7 +133,7 @@ data class DkgSession(
/** Result: the group's FROST threshold public key, hex. */
val thresholdPublicKey: HexKey? = null,
/** Result, secret: this device's FROST secret share, hex. */
/** This device's FROST secret share at [shareEpoch], hex. */
val secretShare: HexKey? = null,
/**
@@ -145,6 +150,9 @@ data class DkgSession(
/** Result: recovery data, to be backed up alongside the host key. */
val recoveryData: HexKey? = null,
/** When the previous share and its ChillDKG recovery inputs were retired, if a refresh has activated. */
val previousShareScrubbedAt: Instant? = null,
val failureReason: String? = null,
/**
@@ -88,6 +88,13 @@ data class FrostSigningSession(
/** The ceremony whose key this signs with — a group may hold more than one. */
val dkgSessionId: String,
/** The share generation this session may use. Written at proposal and never changed. */
@ColumnInfo(defaultValue = "0")
val shareEpoch: Long = 0,
/** The re-enrollment whose candidate this activation signs with, or null for an ordinary session. */
val refreshSessionId: String? = null,
/** The `t` of the t-of-n: how many partial signatures make a signature. */
val threshold: Int,
@@ -1,5 +1,6 @@
package mobi.giza.compose.database.model
import androidx.room3.ColumnInfo
import androidx.room3.Entity
import androidx.room3.ForeignKey
import androidx.room3.Index
@@ -45,8 +46,8 @@ import mobi.giza.compose.managers.SharedKeyDerivation
* behind it, and [dkgSessionId] is a pointer. The share itself never leaves
* `DkgSession.secretShare` on the device that generated it.
*
* One row per room: a room is derived from one key, and a group that re-runs
* its ceremony derives a different room rather than re-keying this one.
* One row per room: a room is derived from one key. A fresh DKG derives a different
* room; a proactive share refresh keeps the key and room and advances [shareEpoch].
*/
@Entity(
foreignKeys = [
@@ -83,6 +84,22 @@ data class GroupKeyState(
/** The path [chatRoomId] was derived at, `m/9420/0/0` style. */
val derivationPath: String,
/** Zero for the original key state, incremented for each activated share refresh. */
@ColumnInfo(defaultValue = "0")
val shareEpoch: Long = 0,
/** The re-enrollment that produced this state, or null for the original key state. */
val refreshSessionId: String? = null,
/** The canonical refresh transcript this state commits to, or null at epoch zero. */
val refreshTranscriptHash: HexKey? = null,
/** The signed key-state event immediately before this one, or null at epoch zero. */
val previousStateEventId: HexKey? = null,
/** Hash of the candidate public-share table, or null at epoch zero. */
val publicSharesHash: HexKey? = null,
/**
* Who said it: the group's own nostr identity, since only a quorum can put
* a state on the record. Kept for the transcript -- the derivation below and
@@ -342,6 +342,7 @@ object FrostSigningManager {
coordinatorPublicKey = userPublicKey,
userPublicKey = userPublicKey,
dkgSessionId = ceremony.id,
shareEpoch = ceremony.shareEpoch,
threshold = ceremony.threshold,
participantCount = ceremony.participantCount,
signerId = signerId,
@@ -362,7 +363,7 @@ object FrostSigningManager {
database = database,
localChatRoom = localChatRoom,
session = session,
kind = FrostSigningEvents.PROPOSAL,
kind = if (ceremony.shareEpoch == 0L) FrostSigningEvents.PROPOSAL else FrostSigningEvents.PROPOSAL_V2,
content = FrostSigningEvents.encodeProposal(unsignedEvents),
includeKey = true
)
@@ -389,7 +390,9 @@ object FrostSigningManager {
return
}
val session = if (innerEvent.kind == FrostSigningEvents.PROPOSAL) {
val session = if (innerEvent.kind == FrostSigningEvents.PROPOSAL ||
innerEvent.kind == FrostSigningEvents.PROPOSAL_V2
) {
acceptProposal(
database = database,
localChatRoom = localChatRoom,
@@ -500,6 +503,7 @@ object FrostSigningManager {
coordinatorPublicKey = innerEvent.pubKey,
userPublicKey = userPublicKey,
dkgSessionId = key.id,
shareEpoch = key.shareEpoch,
threshold = key.threshold,
participantCount = key.participantCount,
signerId = signerId,
@@ -550,6 +554,20 @@ object FrostSigningManager {
return null
}
val proposalEpoch = FrostSigningEvents.parseShareEpoch(innerEvent.tags) ?: 0
val versionMatches = if (innerEvent.kind == FrostSigningEvents.PROPOSAL_V2) {
proposalEpoch > 0
} else {
proposalEpoch == 0L
}
if (!versionMatches || key.shareEpoch != proposalEpoch) {
logger.w(
"Signing proposal $sessionId is for share epoch $proposalEpoch, " +
"but this device's active epoch is ${key.shareEpoch}; dropping"
)
return null
}
val signerId = signerIdOf(database, key, userPublicKey)
if (signerId == null) {
logger.w("Signing proposal $sessionId is for a ceremony this device did not take part in; dropping")
@@ -943,6 +961,13 @@ object FrostSigningManager {
if (session.stage == FrostSigningStage.COMPLETE || session.stage == FrostSigningStage.FAILED) return
val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return
if (key.shareEpoch != session.shareEpoch) {
logger.i(
"Session $sessionId belongs to share epoch ${session.shareEpoch}, " +
"but the active epoch is ${key.shareEpoch}; leaving it superseded"
)
return
}
val secretShare = key.secretShare?.let { PrivateKey(ByteVector32(it)) } ?: return
val thresholdPublicKey = key.thresholdPublicKey ?: return
@@ -1640,10 +1665,18 @@ object FrostSigningManager {
*/
suspend fun completedKey(database: GizaDatabase, chatRoomId: String): DkgSession? {
GroupKeyStateManager.keyStateFor(database, chatRoomId)?.let { state ->
database.dkgSessionDao().getSessionById(state.dkgSessionId)?.takeIf { key ->
key.stage == DkgRitualStage.COMPLETE &&
key.secretShare != null &&
key.thresholdPublicKey == state.thresholdPublicKey
val key = database.dkgSessionDao().getSessionById(state.dkgSessionId)
if (key != null && key.shareEpoch != state.shareEpoch) {
logger.w(
"Room $chatRoomId expects share epoch ${state.shareEpoch}, " +
"but its key is at ${key.shareEpoch}; signing is blocked pending refresh recovery"
)
return null
}
key?.takeIf {
it.stage == DkgRitualStage.COMPLETE &&
it.secretShare != null &&
it.thresholdPublicKey == state.thresholdPublicKey
}?.let { return it }
}
@@ -2132,6 +2165,12 @@ object FrostSigningManager {
return false
}
val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return false
if (key.shareEpoch != session.shareEpoch) {
logger.i("Session $sessionId belongs to a superseded share epoch; nothing to resend")
return false
}
val items = database.frostSigningSessionDao().getItems(sessionId)
if (items.isEmpty()) {
logger.w("Session $sessionId holds no items; nothing to resend")
@@ -2166,7 +2205,11 @@ object FrostSigningManager {
)
return false
}
Triple(FrostSigningEvents.PROPOSAL, FrostSigningEvents.encodeProposal(unsigned), emptyArray<Array<String>>())
Triple(
if (session.shareEpoch == 0L) FrostSigningEvents.PROPOSAL else FrostSigningEvents.PROPOSAL_V2,
FrostSigningEvents.encodeProposal(unsigned),
emptyArray<Array<String>>()
)
}
// A Bennu peer's, declined on arrival: this device proposed none, so has
@@ -2690,7 +2733,8 @@ object FrostSigningManager {
sessionId = session.id,
dkgSessionId = if (includeKey) session.dkgSessionId else null,
signerIds = signerIds,
silentMembers = silentMembers
silentMembers = silentMembers,
shareEpoch = if (includeKey && session.shareEpoch > 0) session.shareEpoch else null
) + extraTags
// No MLS state is what marks a room NIP-17 -- the same reading
@@ -9,6 +9,7 @@ import kotlinx.serialization.json.jsonArray
import mobi.giza.compose.network.serialization.CommonJson
import mobi.giza.compose.nostr.frost.tags.FrostKeyTag
import mobi.giza.compose.nostr.frost.tags.FrostSessionIdTag
import mobi.giza.compose.nostr.frost.tags.FrostShareEpochTag
import mobi.giza.compose.nostr.frost.tags.FrostSignerIdsTag
import mobi.giza.compose.nostr.frost.tags.FrostSilentMembersTag
@@ -73,6 +74,9 @@ object FrostSigningEvents {
*/
val PROPOSAL: Kind = 30320
/** An epoch-aware proposal. Older builds do not route it and cannot answer with stale shares. */
val PROPOSAL_V2: Kind = 30345
/** A signer's `IndividualNonce`, hex encoded. */
val NONCE: Kind = 30321
@@ -115,6 +119,7 @@ object FrostSigningEvents {
/** Every kind above, for filtering inbound payloads in one check. */
val ALL: Set<Kind> = setOf(
PROPOSAL,
PROPOSAL_V2,
TRANSACTION_PROPOSAL,
NONCE,
SIGNER_SET,
@@ -139,16 +144,18 @@ object FrostSigningEvents {
sessionId: String,
dkgSessionId: String? = null,
signerIds: List<Int>? = null,
silentMembers: List<HexKey>? = null
silentMembers: List<HexKey>? = null,
shareEpoch: Long? = null
): Array<Array<String>> = buildList {
add(FrostSessionIdTag.assemble(sessionId))
dkgSessionId?.let { add(FrostKeyTag.assemble(it)) }
signerIds?.let { add(FrostSignerIdsTag.assemble(it)) }
silentMembers?.takeIf { it.isNotEmpty() }?.let { add(FrostSilentMembersTag.assemble(it)) }
shareEpoch?.let { add(FrostShareEpochTag.assemble(it)) }
}.toTypedArray()
/** Whether [kind] opens a session: over events, or a Bennu peer's over a transaction. */
fun isProposal(kind: Kind): Boolean = kind == PROPOSAL || kind == TRANSACTION_PROPOSAL
fun isProposal(kind: Kind): Boolean = kind == PROPOSAL || kind == PROPOSAL_V2 || kind == TRANSACTION_PROPOSAL
/** Whether a [TRANSACTION_PROPOSAL] is a sweep from a Lightning wallet, by its `sweep` tag. */
fun isSweep(tags: Array<Array<String>>): Boolean = tags.any { it.size >= 2 && it[0] == "sweep" }
@@ -162,6 +169,9 @@ object FrostSigningEvents {
fun parseSignerIds(tags: Array<Array<String>>): List<Int>? =
tags.firstNotNullOfOrNull(FrostSignerIdsTag::parse)?.signerIds
fun parseShareEpoch(tags: Array<Array<String>>): Long? =
tags.firstNotNullOfOrNull(FrostShareEpochTag::parse)?.shareEpoch
/**
* Who the coordinator says it has not heard from, or null on any proposal
* that is not a resend.
@@ -0,0 +1,29 @@
package mobi.giza.compose.nostr.frost.tags
import com.vitorpamplona.quartz.nip01Core.core.has
import com.vitorpamplona.quartz.utils.ensure
/** The application-level FROST share generation a signing session is bound to. */
class FrostShareEpochTag(
val shareEpoch: Long,
) {
fun toTagArray() = assemble(shareEpoch)
companion object {
const val TAG_NAME = "frost_share_epoch"
fun parse(tag: Array<String>): FrostShareEpochTag? {
ensure(tag.has(1)) { return null }
ensure(tag[0] == TAG_NAME) { return null }
val epoch = tag[1].toLongOrNull()?.takeIf { it >= 0 } ?: return null
return FrostShareEpochTag(epoch)
}
fun assemble(shareEpoch: Long): Array<String> {
require(shareEpoch >= 0) { "share epoch must not be negative" }
return arrayOf(TAG_NAME, shareEpoch.toString())
}
fun assemble(frostShareEpochTag: FrostShareEpochTag) = assemble(frostShareEpochTag.shareEpoch)
}
}
@@ -0,0 +1,22 @@
package mobi.giza.compose.nostr.frost
import mobi.giza.compose.nostr.frost.tags.FrostShareEpochTag
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
class FrostShareEpochTagTest {
@Test
fun `an epoch round trips`() {
val tag = FrostShareEpochTag.assemble(42)
assertEquals(42, FrostShareEpochTag.parse(tag)?.shareEpoch)
}
@Test
fun `a malformed or negative epoch is refused`() {
assertNull(FrostShareEpochTag.parse(arrayOf("frost_share_epoch", "not-a-number")))
assertNull(FrostShareEpochTag.parse(arrayOf("frost_share_epoch", "-1")))
assertFailsWith<IllegalArgumentException> { FrostShareEpochTag.assemble(-1) }
}
}
@@ -0,0 +1,70 @@
package mobi.giza.compose.database.dao
import androidx.room3.Room
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.time.Instant
import kotlinx.coroutines.runBlocking
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.builder.getRoomDatabase
import mobi.giza.compose.database.model.GroupKeyState
import mobi.giza.compose.managers.GroupFixtures
class GroupKeyStateDaoJvmTest {
private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder<GizaDatabase>())
private val roomId = "42".repeat(32)
@AfterTest
fun closeDb() = db.close()
private fun state(epoch: Long, seconds: Long) = GroupKeyState(
chatRoomId = roomId,
dkgSessionId = "ceremony",
thresholdPublicKey = "02" + "42".repeat(32),
derivationPath = "m/9420/0/0",
shareEpoch = epoch,
announcedBy = roomId,
announcedAt = Instant.fromEpochSeconds(seconds),
)
@Test
fun `an older key state cannot replace a newer share epoch`() = runBlocking {
GroupFixtures.seedRoom(db, roomId)
db.groupKeyStateDao().replace(state(epoch = 1, seconds = 100))
val regressed = db.groupKeyStateDao().replace(state(epoch = 0, seconds = 200))
assertEquals(1, regressed.shareEpoch)
assertEquals(100, regressed.announcedAt.epochSeconds)
}
@Test
fun `a later state at the same epoch is still idempotent`() = runBlocking {
GroupFixtures.seedRoom(db, roomId)
db.groupKeyStateDao().replace(state(epoch = 1, seconds = 100))
db.groupKeyStateDao().replace(state(epoch = 1, seconds = 200))
val settled = db.groupKeyStateDao().replace(state(epoch = 1, seconds = 150))
assertEquals(200, settled.announcedAt.epochSeconds)
}
@Test
fun `a key state starts at epoch zero by default`() = runBlocking {
GroupFixtures.seedRoom(db, roomId)
val settled = db.groupKeyStateDao().replace(
GroupKeyState(
chatRoomId = roomId,
dkgSessionId = "ceremony",
thresholdPublicKey = "02" + "42".repeat(32),
derivationPath = "m/9420/0/0",
announcedBy = roomId,
announcedAt = Instant.fromEpochSeconds(100),
)
)
assertEquals(0, settled.shareEpoch)
}
}
@@ -37,13 +37,13 @@ import mobi.giza.compose.managers.OldEngineBlob
* uses, rather than a decoder in a test. Phase 8 added a table, so this branch is the
* first in a while whose upgrade can fail for a reason that has nothing to do with MLS.
*
* It is named for what it opens rather than for a migration, because 36 -> 37 is an
* `AutoMigration` and there is no `MIGRATION_36_37` to call: Room generates it, and
* It is named for what it opens rather than for a migration, because 36 -> 38 consists of
* `AutoMigration`s and there is no `MIGRATION_36_38` to call: Room generates them, and
* the only way to run the generated one is to let Room decide it is needed. That is
* also the failure this catches. An entity added to the `@Database` list without an
* `AutoMigration` beside it builds, passes every test over an in-memory database, and
* installs perfectly on a phone that has never had the app -- and throws
* `IllegalStateException: A migration from 36 to 37 was required but not found` on
* `IllegalStateException: A migration from 36 to 38 was required but not found` on
* every phone that has.
*
* The v36 database is built from the exported schema rather than from copied SQL, so
@@ -62,7 +62,7 @@ class ShippedProfileUpgradeJvmTest {
private val shipped = 36
/** The schema version this branch builds. */
private val current = 37
private val current = 38
private val directory: File = Files.createTempDirectory("giza-shipped-profile").toFile()
private val file: File = File(directory, "aux.db")
@@ -225,13 +225,13 @@ class ShippedProfileUpgradeJvmTest {
// -- what it has to prove --------------------------------------------------------
/**
* Room finds the way from 36 to 37, runs it, and stamps the file with the hash the
* Room finds the way from 36 to 38, runs it, and stamps the file with the hash the
* generated code expects. The hash is the assertion that matters: Room writes it
* only after `validateMigration` has compared every table it was handed against the
* schema the entities declare.
*/
@Test
fun `a v36 profile opens at v37, with the table this branch adds`(): Unit = runBlocking {
fun `a v36 profile opens at v38, with the table this branch adds`(): Unit = runBlocking {
writeShippedProfile()
onDisk { connection ->
assertEquals(shipped.toLong(), connection.userVersion(), "the fixture is not at the shipped version")
@@ -247,7 +247,7 @@ class ShippedProfileUpgradeJvmTest {
assertEquals(
schema(current)["identityHash"]!!.jsonPrimitive.content,
connection.identityHash(),
"Room did not stamp the v37 identity hash, so it did not validate the migrated schema",
"Room did not stamp the v38 identity hash, so it did not validate the migrated schema",
)
val expected = entities(current).associateBy { it.tableName() }
assertEquals(expected.keys, connection.tables(), "the migrated file has a different set of tables")
@@ -248,7 +248,8 @@ class FrostSigningResendJvmTest {
member: HexKey,
content: String = "",
silent: List<HexKey>? = null,
includeKey: Boolean = false
includeKey: Boolean = false,
shareEpoch: Long? = null
) {
FrostSigningManager.processSigningPayload(
database = db,
@@ -261,7 +262,8 @@ class FrostSigningResendJvmTest {
tags = FrostSigningEvents.assembleTags(
sessionId = sessionId,
dkgSessionId = if (includeKey) ceremonyId else null,
silentMembers = silent
silentMembers = silent,
shareEpoch = shareEpoch
),
content = content,
sig = ""
@@ -1331,4 +1333,51 @@ class FrostSigningResendJvmTest {
assertEquals(0, resendAll())
assertEquals(1, queued(FrostSigningEvents.PROPOSAL).size)
}
// --- share epochs -------------------------------------------------------
@Test
fun `a post-genesis proposal carries its share epoch on the v2 kind`() = runBlocking {
openDevice(marmot = true)
val key = db.dkgSessionDao().getSessionById(ceremonyId)!!
db.dkgSessionDao().upsert(key.copy(shareEpoch = 1))
val session = propose()
assertEquals(1, session.shareEpoch)
val proposal = queuedInner(FrostSigningEvents.PROPOSAL_V2).single()
assertEquals(1, FrostSigningEvents.parseShareEpoch(proposal.tags))
assertTrue(queuedInner(FrostSigningEvents.PROPOSAL).isEmpty())
}
@Test
fun `a proposal for another share epoch is dropped`() = runBlocking {
openDevice()
val sessionId = "d".repeat(64)
receive(
sessionId = sessionId,
kind = FrostSigningEvents.PROPOSAL_V2,
member = alice,
content = unsignedEvent().toJson(),
includeKey = true,
shareEpoch = 1,
)
assertNull(db.frostSigningSessionDao().getSessionById(sessionId))
}
@Test
fun `a superseded session is not resent`() = runBlocking {
openDevice()
val session = propose()
val key = db.dkgSessionDao().getSessionById(ceremonyId)!!
db.dkgSessionDao().upsert(key.copy(shareEpoch = session.shareEpoch + 1))
val before = queued(FrostSigningEvents.PROPOSAL).size
assertFalse(resend(session.id))
assertEquals(before, queued(FrostSigningEvents.PROPOSAL).size)
assertNull(session(session.id).resentAt)
}
}