frost: run re-enrollment through candidate activation
This commit is contained in:
1 parent
8a24a0607c
commit
ba42d2034d
9 files changed
+881
-16
No files matched your search
@@ -62,6 +62,7 @@ import mobi.giza.compose.exceptions.MarmotNotMemberOfChatGroupException
|
||||
import mobi.giza.compose.extensions.toHex
|
||||
import mobi.giza.compose.managers.ChillDkgRitualManager
|
||||
import mobi.giza.compose.managers.CommitOrdering
|
||||
import mobi.giza.compose.managers.FrostReEnrollmentManager
|
||||
import mobi.giza.compose.managers.FrostSigningManager
|
||||
import mobi.giza.compose.managers.GroupKeyStateManager
|
||||
import mobi.giza.compose.managers.MarmotEngine.Companion.inRoom
|
||||
@@ -77,6 +78,7 @@ import mobi.giza.compose.nostr.MarmotProfile
|
||||
import mobi.giza.compose.nostr.Relays
|
||||
import mobi.giza.compose.nostr.dkg.DkgRitualEvents
|
||||
import mobi.giza.compose.nostr.frost.FrostSigningEvents
|
||||
import mobi.giza.compose.nostr.frost.ReEnrollmentEvents
|
||||
|
||||
@Dao
|
||||
abstract class NostrDao(
|
||||
@@ -1596,6 +1598,14 @@ abstract class NostrDao(
|
||||
userPublicKey = activeKeyPair.pubKey.toHex()
|
||||
)
|
||||
|
||||
ReEnrollmentEvents.isReEnrollmentKind(innerEvent.kind) ->
|
||||
FrostReEnrollmentManager.processReEnrollmentPayload(
|
||||
database = database,
|
||||
localChatRoom = localChatRoom,
|
||||
innerEvent = innerEvent,
|
||||
userPublicKey = activeKeyPair.pubKey.toHex()
|
||||
)
|
||||
|
||||
DkgRitualEvents.isDkgRitualKind(innerEvent.kind) ->
|
||||
ChillDkgRitualManager.processRitualPayload(
|
||||
database = database,
|
||||
|
||||
@@ -32,6 +32,7 @@ import mobi.giza.compose.database.model.traits.UserViewableEntity
|
||||
import mobi.giza.compose.exceptions.MarmotUnprocessableInnerEventException
|
||||
import mobi.giza.compose.extensions.toHex
|
||||
import mobi.giza.compose.managers.ChronicleManager
|
||||
import mobi.giza.compose.managers.FrostReEnrollmentManager
|
||||
import mobi.giza.compose.managers.GroupKeyStateManager
|
||||
import mobi.giza.compose.managers.SubgroupManager
|
||||
import mobi.giza.compose.nostr.MarmotDirectMessage
|
||||
@@ -40,6 +41,7 @@ import mobi.giza.compose.nostr.chronicle.ChronicleRequestEvent
|
||||
import mobi.giza.compose.nostr.dkg.DkgRitualEvents
|
||||
import mobi.giza.compose.nostr.frost.FrostSigningEvents
|
||||
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
|
||||
import mobi.giza.compose.nostr.frost.ReEnrollmentEvents
|
||||
import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent
|
||||
|
||||
@Entity(
|
||||
@@ -731,6 +733,10 @@ data class ChatMessage(
|
||||
// Not ours to read. The group is meant to see that a private message was
|
||||
// sent and to whom, and nothing more.
|
||||
MarmotDirectMessage.Delivery.Unreadable -> {
|
||||
if (database.frostReEnrollmentDao().getRunningForRoom(chatRoomId) != null) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Relays redeliver and negentropy re-syncs; the wrap yields the same
|
||||
// id every time, so this is what keeps a second delivery from becoming
|
||||
// a second line. ChatMessage.id is autogenerated and would take a
|
||||
@@ -776,6 +782,17 @@ data class ChatMessage(
|
||||
)
|
||||
)
|
||||
|
||||
if (opened.rumor.kind in ReEnrollmentEvents.PRIVATE) {
|
||||
val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return null
|
||||
FrostReEnrollmentManager.processReEnrollmentPayload(
|
||||
database = database,
|
||||
localChatRoom = room,
|
||||
innerEvent = opened.rumor,
|
||||
userPublicKey = activeKeyPair.pubKey.toHex(),
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
ChatMessage(
|
||||
giftWrapPayloadId = null,
|
||||
messageType = TYPE_DIRECT_MESSAGE,
|
||||
@@ -843,7 +860,8 @@ data class ChatMessage(
|
||||
val isDirectMessageEnvelope = MarmotDirectMessage.wrapInside(event) != null
|
||||
val isProtocolMessage = !isDirectMessageEnvelope && (
|
||||
event.kind in DkgRitualEvents.ALL ||
|
||||
event.kind in FrostSigningEvents.ALL
|
||||
event.kind in FrostSigningEvents.ALL ||
|
||||
event.kind in ReEnrollmentEvents.ALL
|
||||
)
|
||||
|
||||
database.marmotInnerEventDao().upsert(
|
||||
|
||||
+538
@@ -0,0 +1,538 @@
|
||||
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.hexToByteArray
|
||||
import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
|
||||
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
|
||||
import com.vitorpamplona.quartz.nip01Core.tags.people.PTag
|
||||
import com.vitorpamplona.quartz.nip01Core.tags.people.taggedUsers
|
||||
import fr.acinq.bitcoin.ByteVector
|
||||
import fr.acinq.bitcoin.ByteVector32
|
||||
import fr.acinq.bitcoin.Crypto
|
||||
import fr.acinq.bitcoin.PrivateKey
|
||||
import fr.acinq.bitcoin.PublicKey
|
||||
import fr.acinq.bitcoin.crypto.frost.FrostRefresh
|
||||
import fr.acinq.bitcoin.crypto.frost.RefreshCandidate
|
||||
import fr.acinq.bitcoin.crypto.frost.RefreshDealerFault
|
||||
import fr.acinq.bitcoin.utils.Either
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Instant
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import mobi.giza.compose.database.GizaDatabase
|
||||
import mobi.giza.compose.database.model.DkgSession
|
||||
import mobi.giza.compose.database.model.FrostReEnrollmentMessage
|
||||
import mobi.giza.compose.database.model.FrostReEnrollmentSession
|
||||
import mobi.giza.compose.database.model.MarmotInnerEvent
|
||||
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
|
||||
import mobi.giza.compose.database.model.types.DkgRitualStage
|
||||
import mobi.giza.compose.database.model.types.FrostSigningStage
|
||||
import mobi.giza.compose.database.model.types.ReEnrollmentStage
|
||||
import mobi.giza.compose.extensions.toHex
|
||||
import mobi.giza.compose.nostr.dkg.DkgRitualEvents
|
||||
import mobi.giza.compose.nostr.frost.FrostSigningEvents
|
||||
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
|
||||
import mobi.giza.compose.nostr.frost.ReEnrollmentEvents
|
||||
|
||||
/** Runs a proactive FROST share refresh, from proposal through a staged activation candidate. */
|
||||
object FrostReEnrollmentManager {
|
||||
private const val TAG = "FrostReEnrollmentManager"
|
||||
private const val TRANSCRIPT_TAG = "giza/frost-refresh/transcript/v1"
|
||||
private const val PUBLIC_SHARES_TAG = "giza/frost-refresh/public-shares/v1"
|
||||
private const val MAX_ID_SEARCH = 4
|
||||
|
||||
private val logger = Logger.withTag(TAG)
|
||||
|
||||
/** Open a refresh, or return the compatible one already running for this key. */
|
||||
suspend fun proposeReEnrollment(
|
||||
database: GizaDatabase,
|
||||
localChatRoom: LocalChatRoom,
|
||||
userPublicKey: HexKey,
|
||||
): FrostReEnrollmentSession {
|
||||
database.frostReEnrollmentDao().getRunningForKey(
|
||||
completedKey(database, localChatRoom).id
|
||||
)?.let { return it }
|
||||
|
||||
val key = completedKey(database, localChatRoom)
|
||||
val state = GroupKeyStateManager.keyStateFor(database, localChatRoom.chatRoom.id)
|
||||
require(state != null && state.dkgSessionId == key.id && state.shareEpoch == key.shareEpoch) {
|
||||
"This room has no current signed key state to refresh"
|
||||
}
|
||||
require(localChatRoom.chatRoom.mlsGroupState != null) { "Re-enrollment requires a Marmot room" }
|
||||
require(key.stage == DkgRitualStage.COMPLETE && key.secretShare != null) { "This device holds no active share" }
|
||||
require(key.threshold >= 2) { "Share refresh requires a threshold of at least two" }
|
||||
require(key.shareEpoch < Long.MAX_VALUE) { "No share epoch remains" }
|
||||
|
||||
val participants = ChillDkgRitualManager.participantsOf(key, localChatRoom)
|
||||
val roomMembers = ChillDkgRitualManager.memberPublicKeys(localChatRoom) + localChatRoom.chatRoom.userPublicKey
|
||||
require(roomMembers.containsAll(participants)) { "Every share holder must be in the Marmot room" }
|
||||
require(participants.size == key.participantCount) { "The share-holder roster does not match the ceremony" }
|
||||
require(FrostSignerOrder.signerIdOf(database, key, userPublicKey) != null) { "This device is not a share holder" }
|
||||
require(key.publicShareList()?.size == key.participantCount) { "A complete public-share table is required" }
|
||||
require(
|
||||
database.frostSigningSessionDao().getSessionsForChatRoom(localChatRoom.chatRoom.id)
|
||||
.none { it.dkgSessionId == key.id && it.stage != FrostSigningStage.COMPLETE && it.stage != FrostSigningStage.FAILED }
|
||||
) { "Finish or abandon the key's open signing sessions before refreshing it" }
|
||||
|
||||
val previousState = GroupKeyStateManager.signedEventFor(database, localChatRoom.chatRoom.id)
|
||||
requireNotNull(previousState) { "The current key state has no signed event to succeed" }
|
||||
|
||||
val session = FrostReEnrollmentSession(
|
||||
id = RandomInstance.bytes(32).toHex(),
|
||||
chatRoomId = localChatRoom.chatRoom.id,
|
||||
dkgSessionId = key.id,
|
||||
coordinatorPublicKey = userPublicKey,
|
||||
userPublicKey = userPublicKey,
|
||||
currentShareEpoch = key.shareEpoch,
|
||||
nextShareEpoch = key.shareEpoch + 1,
|
||||
threshold = key.threshold,
|
||||
participantCount = key.participantCount,
|
||||
participantPublicKeys = DkgSession.formatParticipants(participants).orEmpty(),
|
||||
previousStateEventId = previousState.id,
|
||||
dealerRandom = RandomInstance.bytes(32).toHex(),
|
||||
joinApprovedAt = Clock.System.now(),
|
||||
)
|
||||
database.frostReEnrollmentDao().upsert(session)
|
||||
check(
|
||||
broadcast(
|
||||
database, localChatRoom, session, ReEnrollmentEvents.PROPOSAL, key.thresholdPublicKey.orEmpty(),
|
||||
includeProposal = true,
|
||||
)
|
||||
) { "Could not queue the refresh proposal" }
|
||||
advance(database, localChatRoom, session.id)
|
||||
return session
|
||||
}
|
||||
|
||||
/** Feed one public protocol event, or a private evaluation decrypted for this device. */
|
||||
suspend fun processReEnrollmentPayload(
|
||||
database: GizaDatabase,
|
||||
localChatRoom: LocalChatRoom,
|
||||
innerEvent: Event,
|
||||
userPublicKey: HexKey,
|
||||
) {
|
||||
val sessionId = ReEnrollmentEvents.parseSessionId(innerEvent.tags) ?: return
|
||||
val session = if (innerEvent.kind == ReEnrollmentEvents.PROPOSAL) {
|
||||
acceptProposal(database, localChatRoom, innerEvent, sessionId, userPublicKey)
|
||||
} else {
|
||||
database.frostReEnrollmentDao().getSessionById(sessionId)
|
||||
} ?: return
|
||||
|
||||
if (session.stage == ReEnrollmentStage.COMPLETE || session.stage == ReEnrollmentStage.FAILED) return
|
||||
if (!record(database, localChatRoom, session, innerEvent)) return
|
||||
advance(database, localChatRoom, session.id)
|
||||
}
|
||||
|
||||
/** Whether this device is waiting for its owner to join the refresh. */
|
||||
suspend fun pendingApproval(database: GizaDatabase, session: FrostReEnrollmentSession): Boolean =
|
||||
session.joinApprovedAt == null && session.stage != ReEnrollmentStage.COMPLETE && session.stage != ReEnrollmentStage.FAILED
|
||||
|
||||
/** Approve joining. No commitment or private evaluation is published before this call. */
|
||||
suspend fun approve(
|
||||
database: GizaDatabase,
|
||||
localChatRoom: LocalChatRoom,
|
||||
sessionId: String,
|
||||
) {
|
||||
val session = database.frostReEnrollmentDao().getSessionById(sessionId) ?: return
|
||||
if (!pendingApproval(database, session)) return
|
||||
update(database, session) { it.copy(joinApprovedAt = Clock.System.now()) }
|
||||
advance(database, localChatRoom, sessionId)
|
||||
}
|
||||
|
||||
/** Cancel before this device has committed to a candidate. The current epoch stays active. */
|
||||
suspend fun abandon(
|
||||
database: GizaDatabase,
|
||||
localChatRoom: LocalChatRoom,
|
||||
sessionId: String,
|
||||
): Boolean {
|
||||
val session = database.frostReEnrollmentDao().getSessionById(sessionId) ?: return false
|
||||
if (session.readyAt != null || session.stage == ReEnrollmentStage.COMPLETE || session.stage == ReEnrollmentStage.FAILED) {
|
||||
return false
|
||||
}
|
||||
fail(database, localChatRoom, session, "Abandoned by a participant")
|
||||
return true
|
||||
}
|
||||
|
||||
private suspend fun completedKey(database: GizaDatabase, room: LocalChatRoom): DkgSession {
|
||||
val state = GroupKeyStateManager.keyStateFor(database, room.chatRoom.id)
|
||||
val id = state?.dkgSessionId ?: throw IllegalStateException("This room has no shared key to refresh")
|
||||
return database.dkgSessionDao().getSessionById(id)
|
||||
?: throw IllegalStateException("This device does not hold the room's shared key")
|
||||
}
|
||||
|
||||
private suspend fun acceptProposal(
|
||||
database: GizaDatabase,
|
||||
localChatRoom: LocalChatRoom,
|
||||
innerEvent: Event,
|
||||
sessionId: String,
|
||||
userPublicKey: HexKey,
|
||||
): FrostReEnrollmentSession? {
|
||||
database.frostReEnrollmentDao().getSessionById(sessionId)?.let { return it }
|
||||
if (localChatRoom.chatRoom.mlsGroupState == null) return null
|
||||
|
||||
val keyId = FrostSigningEvents.parseKey(innerEvent.tags) ?: return null
|
||||
val key = database.dkgSessionDao().getSessionById(keyId) ?: return null
|
||||
val members = innerEvent.tags.taggedUsers().map { it.pubKey }.toSet() + innerEvent.pubKey
|
||||
val expectedMembers = ChillDkgRitualManager.participantsOf(key, localChatRoom)
|
||||
if (members != expectedMembers || userPublicKey !in members) return null
|
||||
|
||||
val nextEpoch = FrostSigningEvents.parseShareEpoch(innerEvent.tags) ?: return null
|
||||
val threshold = DkgRitualEvents.parseThreshold(innerEvent.tags) ?: return null
|
||||
val previousStateId = ReEnrollmentEvents.parsePreviousStateEventId(innerEvent.tags) ?: return null
|
||||
val thresholdPublicKey = GroupKeyStateEvent.parseThresholdPublicKey(innerEvent.content) ?: return null
|
||||
val state = GroupKeyStateManager.keyStateFor(database, localChatRoom.chatRoom.id) ?: return null
|
||||
val previousState = GroupKeyStateManager.signedEventFor(database, localChatRoom.chatRoom.id) ?: return null
|
||||
|
||||
if (nextEpoch != key.shareEpoch + 1 || threshold != key.threshold || members.size != key.participantCount) return null
|
||||
if (!thresholdPublicKey.equals(key.thresholdPublicKey, ignoreCase = true)) return null
|
||||
if (state.dkgSessionId != key.id || state.shareEpoch != key.shareEpoch || previousState.id != previousStateId) return null
|
||||
if (key.publicShareList()?.size != key.participantCount) return null
|
||||
|
||||
val session = FrostReEnrollmentSession(
|
||||
id = sessionId,
|
||||
chatRoomId = localChatRoom.chatRoom.id,
|
||||
dkgSessionId = key.id,
|
||||
coordinatorPublicKey = innerEvent.pubKey,
|
||||
userPublicKey = userPublicKey,
|
||||
currentShareEpoch = key.shareEpoch,
|
||||
nextShareEpoch = nextEpoch,
|
||||
threshold = threshold,
|
||||
participantCount = members.size,
|
||||
participantPublicKeys = DkgSession.formatParticipants(members).orEmpty(),
|
||||
previousStateEventId = previousStateId,
|
||||
dealerRandom = RandomInstance.bytes(32).toHex(),
|
||||
)
|
||||
database.frostReEnrollmentDao().upsert(session)
|
||||
replayStoredMessages(database, localChatRoom, session)
|
||||
return session
|
||||
}
|
||||
|
||||
private suspend fun replayStoredMessages(
|
||||
database: GizaDatabase,
|
||||
localChatRoom: LocalChatRoom,
|
||||
session: FrostReEnrollmentSession,
|
||||
) {
|
||||
val stored = database.marmotInnerEventDao()
|
||||
.getByChatRoomAndKinds(session.chatRoomId, ReEnrollmentEvents.ALL.toList())
|
||||
.filter { ReEnrollmentEvents.parseSessionId(it.tags) == session.id && it.kind != ReEnrollmentEvents.PROPOSAL }
|
||||
stored.forEach { event ->
|
||||
val inner = Event(event.id, event.publicKey, event.createdAt.epochSeconds, event.kind, event.tags, event.content, "")
|
||||
if (!record(database, localChatRoom, session, inner)) return
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun record(
|
||||
database: GizaDatabase,
|
||||
localChatRoom: LocalChatRoom,
|
||||
session: FrostReEnrollmentSession,
|
||||
innerEvent: Event,
|
||||
): Boolean {
|
||||
if (innerEvent.kind == ReEnrollmentEvents.PROPOSAL) return true
|
||||
if (innerEvent.pubKey !in session.participantPublicKeySet()) return false
|
||||
if (innerEvent.kind == ReEnrollmentEvents.FAILURE) {
|
||||
fail(database, localChatRoom, session, "Abandoned by ${innerEvent.pubKey.take(8)}: ${innerEvent.content}")
|
||||
return false
|
||||
}
|
||||
if (innerEvent.kind !in ReEnrollmentEvents.ALL || innerEvent.kind == ReEnrollmentEvents.KEY_EPOCH_STATE) return false
|
||||
|
||||
val recipient = if (innerEvent.kind in ReEnrollmentEvents.PRIVATE) session.userPublicKey else ""
|
||||
if (innerEvent.kind in ReEnrollmentEvents.PRIVATE && recipient != session.userPublicKey) return false
|
||||
if (ReEnrollmentEvents.parseParamsHash(innerEvent.tags) != expectedParamsHash(database, session)) return false
|
||||
|
||||
val known = database.frostReEnrollmentDao().getMessage(session.id, innerEvent.pubKey, recipient, innerEvent.kind)
|
||||
if (known != null) {
|
||||
if (known.payload != innerEvent.content) {
|
||||
logger.w("Refresh ${session.id}: conflicting ${innerEvent.kind} from ${innerEvent.pubKey.take(8)}; ignoring")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
database.frostReEnrollmentDao().upsert(
|
||||
FrostReEnrollmentMessage(session.id, innerEvent.pubKey, recipient, innerEvent.kind, innerEvent.content)
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
private suspend fun advance(
|
||||
database: GizaDatabase,
|
||||
localChatRoom: LocalChatRoom,
|
||||
sessionId: String,
|
||||
) {
|
||||
var session = database.frostReEnrollmentDao().getSessionById(sessionId) ?: return
|
||||
if (session.stage == ReEnrollmentStage.COMPLETE || session.stage == ReEnrollmentStage.FAILED) return
|
||||
if (session.joinApprovedAt == null) return
|
||||
|
||||
try {
|
||||
if (session.ownCommitments == null) {
|
||||
val key = activeKey(database, session)
|
||||
val ordered = orderedParticipants(database, session)
|
||||
val dealerId = FrostSignerOrder.signerIdOf(database, key, session.userPublicKey)
|
||||
?: error("This device is not a share holder")
|
||||
val shares = FrostRefresh.generateShares(
|
||||
sessionRandom = ByteVector32(session.dealerRandom ?: error("No dealer seed")),
|
||||
secretShare = PrivateKey(ByteVector32(key.secretShare ?: error("No current secret share"))),
|
||||
sessionId = ByteVector32(session.id),
|
||||
thresholdPublicKey = publicKey(key),
|
||||
currentEpoch = session.currentShareEpoch,
|
||||
nextEpoch = session.nextShareEpoch,
|
||||
participantIds = ordered.map { it.second },
|
||||
dealerId = dealerId.toUInt(),
|
||||
threshold = session.threshold,
|
||||
).orThrow("dealer generation")
|
||||
|
||||
check(
|
||||
broadcast(
|
||||
database, localChatRoom, session, ReEnrollmentEvents.COMMITMENTS,
|
||||
shares.commitments.joinToString(",") { it.value.toHex() },
|
||||
)
|
||||
) { "Could not queue the dealer commitments" }
|
||||
storeOwnMessage(
|
||||
database, session, ReEnrollmentEvents.COMMITMENTS, "",
|
||||
shares.commitments.joinToString(",") { it.value.toHex() },
|
||||
)
|
||||
shares.evaluations.forEachIndexed { index, evaluation ->
|
||||
val recipient = ordered[index].first
|
||||
val payload = evaluation.value.toHex()
|
||||
if (recipient != session.userPublicKey) {
|
||||
check(
|
||||
broadcast(database, localChatRoom, session, ReEnrollmentEvents.PRIVATE_EVALUATION, payload, recipient)
|
||||
) { "Could not queue a private evaluation for $recipient" }
|
||||
}
|
||||
storeOwnMessage(database, session, ReEnrollmentEvents.PRIVATE_EVALUATION, recipient, payload)
|
||||
}
|
||||
session = update(database, session) { it.copy(ownCommitments = shares.commitments.joinToString(",") { c -> c.value.toHex() }) }
|
||||
session = moveTo(database, session, ReEnrollmentStage.COLLECTING_EVALUATIONS)
|
||||
}
|
||||
|
||||
val ordered = orderedParticipants(database, session)
|
||||
val commitmentMessages = database.frostReEnrollmentDao()
|
||||
.getMessagesByKind(session.id, ReEnrollmentEvents.COMMITMENTS)
|
||||
if (commitmentMessages.size < session.participantCount) return
|
||||
val commitments = ordered.map { (member, _) ->
|
||||
commitmentMessages.single { it.senderPublicKey == member }.payload.split(",").map { PublicKey(ByteVector(it.hexToByteArray())) }
|
||||
}
|
||||
|
||||
val evaluationMessages = database.frostReEnrollmentDao()
|
||||
.getMessagesByKind(session.id, ReEnrollmentEvents.PRIVATE_EVALUATION)
|
||||
.filter { it.recipientPublicKey == session.userPublicKey }
|
||||
if (evaluationMessages.size < session.participantCount) return
|
||||
val evaluations = ordered.map { (member, _) ->
|
||||
PrivateKey(ByteVector32(evaluationMessages.single { it.senderPublicKey == member }.payload))
|
||||
}
|
||||
|
||||
if (session.candidateSecretShare == null) {
|
||||
val key = activeKey(database, session)
|
||||
val candidate = FrostRefresh.generateCandidate(
|
||||
oldSecretShare = PrivateKey(ByteVector32(key.secretShare ?: error("No current secret share"))),
|
||||
oldPublicShares = key.publicShareList() ?: error("No current public shares"),
|
||||
evaluations = evaluations,
|
||||
commitments = commitments,
|
||||
recipientId = (FrostSignerOrder.signerIdOf(database, key, session.userPublicKey)
|
||||
?: error("This device is not a share holder")).toUInt(),
|
||||
sessionId = ByteVector32(session.id),
|
||||
thresholdPublicKey = publicKey(key),
|
||||
currentEpoch = session.currentShareEpoch,
|
||||
nextEpoch = session.nextShareEpoch,
|
||||
participantIds = ordered.map { it.second },
|
||||
threshold = session.threshold,
|
||||
).orThrow("candidate generation")
|
||||
val transcript = transcriptHash(session, candidate, ordered, commitments)
|
||||
session = update(database, session) {
|
||||
it.copy(
|
||||
candidateSecretShare = candidate.secretShare.value.toHex(),
|
||||
candidatePublicShares = candidate.publicShares.joinToString(",") { share -> share.value.toHex() },
|
||||
transcriptHash = transcript,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (session.readyAt == null) {
|
||||
val transcript = session.transcriptHash ?: error("No candidate transcript")
|
||||
session = update(database, session) { it.copy(readyAt = Clock.System.now()) }
|
||||
check(broadcast(database, localChatRoom, session, ReEnrollmentEvents.READY, transcript)) {
|
||||
"Could not queue the candidate READY message"
|
||||
}
|
||||
storeOwnMessage(database, session, ReEnrollmentEvents.READY, "", transcript)
|
||||
session = moveTo(database, session, ReEnrollmentStage.CANDIDATE_READY)
|
||||
}
|
||||
|
||||
val ready = database.frostReEnrollmentDao().getMessagesByKind(session.id, ReEnrollmentEvents.READY)
|
||||
if (ready.size < session.participantCount || ready.any { it.payload != session.transcriptHash }) return
|
||||
moveTo(database, session, ReEnrollmentStage.ACTIVATING)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Throwable) {
|
||||
val reason = when (e) {
|
||||
is RefreshDealerFault -> "dealer ${e.dealerId} produced an invalid evaluation"
|
||||
else -> e.message ?: e::class.simpleName ?: "Unknown refresh error"
|
||||
}
|
||||
logger.e("Refresh $sessionId failed: $reason", e)
|
||||
fail(database, localChatRoom, session, reason)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun activeKey(database: GizaDatabase, session: FrostReEnrollmentSession): DkgSession =
|
||||
database.dkgSessionDao().getSessionById(session.dkgSessionId)?.takeIf {
|
||||
it.stage == DkgRitualStage.COMPLETE && it.shareEpoch == session.currentShareEpoch
|
||||
} ?: error("The active key changed while the refresh was unresolved")
|
||||
|
||||
private fun publicKey(key: DkgSession): PublicKey = PublicKey(ByteVector(key.thresholdPublicKey?.hexToByteArray() ?: error("No threshold key")))
|
||||
|
||||
private suspend fun orderedParticipants(
|
||||
database: GizaDatabase,
|
||||
session: FrostReEnrollmentSession,
|
||||
): List<Pair<HexKey, UInt>> {
|
||||
val key = activeKey(database, session)
|
||||
val ids = FrostSignerOrder.signerIds(database, key)
|
||||
val ordered = ids.entries.sortedBy { it.value }.map { it.key to it.value.toUInt() }
|
||||
require(ordered.size == session.participantCount && ordered.map { it.first }.toSet() == session.participantPublicKeySet()) {
|
||||
"The ceremony's signer order does not match the refresh roster"
|
||||
}
|
||||
require(ordered.map { it.second }.toSet() == (0 until session.participantCount).map { it.toUInt() }.toSet()) {
|
||||
"The ceremony's signer ids are not contiguous"
|
||||
}
|
||||
return ordered
|
||||
}
|
||||
|
||||
private suspend fun expectedParamsHash(database: GizaDatabase, session: FrostReEnrollmentSession): String {
|
||||
val key = activeKey(database, session)
|
||||
return FrostRefresh.paramsHash(
|
||||
ByteVector32(session.id), publicKey(key), session.currentShareEpoch, session.nextShareEpoch,
|
||||
orderedParticipants(database, session).map { it.second }, session.threshold,
|
||||
).orThrow("parameter hashing").toHex()
|
||||
}
|
||||
|
||||
private fun transcriptHash(
|
||||
session: FrostReEnrollmentSession,
|
||||
candidate: RefreshCandidate,
|
||||
ordered: List<Pair<HexKey, UInt>>,
|
||||
commitments: List<List<PublicKey>>,
|
||||
): String {
|
||||
val commitmentTranscript = ordered.mapIndexed { index, (member, _) ->
|
||||
"$member=${commitments[index].joinToString(",") { it.value.toHex() }}"
|
||||
}.joinToString(";")
|
||||
val input = listOf(
|
||||
TRANSCRIPT_TAG, session.id, session.dkgSessionId, session.previousStateEventId,
|
||||
session.currentShareEpoch.toString(), session.nextShareEpoch.toString(),
|
||||
session.threshold.toString(), session.participantCount.toString(),
|
||||
ordered.joinToString(",") { "${it.first}:${it.second}" }, commitmentTranscript,
|
||||
candidate.paramsHash.toHex(), publicSharesHash(candidate.publicShares),
|
||||
).joinToString("|")
|
||||
return Crypto.sha256(input.encodeToByteArray()).toHex()
|
||||
}
|
||||
|
||||
/** Hash a public-share table. This contains no secret material. */
|
||||
fun publicSharesHash(publicShares: List<PublicKey>): String =
|
||||
Crypto.sha256((PUBLIC_SHARES_TAG + publicShares.joinToString(",") { it.value.toHex() }).encodeToByteArray()).toHex()
|
||||
|
||||
private suspend fun storeOwnMessage(
|
||||
database: GizaDatabase,
|
||||
session: FrostReEnrollmentSession,
|
||||
kind: Int,
|
||||
recipient: HexKey,
|
||||
payload: String,
|
||||
) {
|
||||
database.frostReEnrollmentDao().upsert(FrostReEnrollmentMessage(session.id, session.userPublicKey, recipient, kind, payload))
|
||||
}
|
||||
|
||||
private suspend fun broadcast(
|
||||
database: GizaDatabase,
|
||||
localChatRoom: LocalChatRoom,
|
||||
session: FrostReEnrollmentSession,
|
||||
kind: Int,
|
||||
content: String,
|
||||
directRecipient: HexKey? = null,
|
||||
includeProposal: Boolean = false,
|
||||
): Boolean {
|
||||
val relayHints = localChatRoom.localParticipants.associate {
|
||||
it.participant.participantPublicKey to it.participant.relayHint
|
||||
}
|
||||
val recipients = if (directRecipient != null) {
|
||||
listOf(directRecipient)
|
||||
} else {
|
||||
session.participantPublicKeySet().filter { it != session.userPublicKey }.sorted()
|
||||
}
|
||||
val people = recipients.map { recipient ->
|
||||
PTag.assemble(recipient, relayHints[recipient]?.let { NormalizedRelayUrl(it) })
|
||||
}.toTypedArray()
|
||||
val tags = people + ReEnrollmentEvents.assembleTags(
|
||||
sessionId = session.id,
|
||||
dkgSessionId = if (includeProposal) session.dkgSessionId else null,
|
||||
nextShareEpoch = if (includeProposal) session.nextShareEpoch else null,
|
||||
threshold = if (includeProposal) session.threshold else null,
|
||||
paramsHash = if (kind == ReEnrollmentEvents.COMMITMENTS || kind in ReEnrollmentEvents.PRIVATE || kind == ReEnrollmentEvents.READY) {
|
||||
expectedParamsHash(database, session)
|
||||
} else null,
|
||||
transcriptHash = if (kind == ReEnrollmentEvents.READY) session.transcriptHash else null,
|
||||
previousStateEventId = if (includeProposal) session.previousStateEventId else null,
|
||||
)
|
||||
val createdAt = Clock.System.now().epochSeconds
|
||||
repeat(MAX_ID_SEARCH) { attempt ->
|
||||
val timestamp = createdAt + attempt
|
||||
val id = EventHasher.hashId(pubKey = session.userPublicKey, createdAt = timestamp, kind = kind, tags = tags, content = content)
|
||||
if (database.marmotInnerEventDao().getById(id) == null) {
|
||||
database.marmotInnerEventDao().upsert(
|
||||
MarmotInnerEvent(
|
||||
id = id,
|
||||
publicKey = session.userPublicKey,
|
||||
chatRoomId = session.chatRoomId,
|
||||
kind = kind,
|
||||
tags = tags,
|
||||
content = content,
|
||||
createdAt = Instant.fromEpochSeconds(timestamp),
|
||||
directMessageRecipientPublicKey = directRecipient,
|
||||
)
|
||||
)
|
||||
return true
|
||||
}
|
||||
}
|
||||
logger.w("Refresh ${session.id}: could not allocate an outbound id for kind $kind")
|
||||
return false
|
||||
}
|
||||
|
||||
private suspend fun fail(
|
||||
database: GizaDatabase,
|
||||
localChatRoom: LocalChatRoom,
|
||||
session: FrostReEnrollmentSession,
|
||||
reason: String,
|
||||
) {
|
||||
val current = database.frostReEnrollmentDao().getSessionById(session.id) ?: return
|
||||
if (current.stage == ReEnrollmentStage.FAILED || current.stage == ReEnrollmentStage.COMPLETE) return
|
||||
update(database, current) {
|
||||
it.copy(
|
||||
stage = ReEnrollmentStage.FAILED,
|
||||
failureReason = reason,
|
||||
dealerRandom = null,
|
||||
candidateSecretShare = null,
|
||||
)
|
||||
}
|
||||
database.frostReEnrollmentDao().scrubMessagesByKind(session.id, ReEnrollmentEvents.PRIVATE_EVALUATION)
|
||||
broadcast(database, localChatRoom, current, ReEnrollmentEvents.FAILURE, reason)
|
||||
}
|
||||
|
||||
private suspend fun update(
|
||||
database: GizaDatabase,
|
||||
session: FrostReEnrollmentSession,
|
||||
transform: (FrostReEnrollmentSession) -> FrostReEnrollmentSession,
|
||||
): FrostReEnrollmentSession {
|
||||
val current = database.frostReEnrollmentDao().getSessionById(session.id) ?: session
|
||||
val updated = transform(current)
|
||||
if (updated == current) return current
|
||||
val stamped = updated.copy(updatedAt = Clock.System.now())
|
||||
database.frostReEnrollmentDao().upsert(stamped)
|
||||
return stamped
|
||||
}
|
||||
|
||||
private suspend fun moveTo(
|
||||
database: GizaDatabase,
|
||||
session: FrostReEnrollmentSession,
|
||||
stage: ReEnrollmentStage,
|
||||
): FrostReEnrollmentSession = update(database, session) { current ->
|
||||
val settled = current.stage == ReEnrollmentStage.COMPLETE || current.stage == ReEnrollmentStage.FAILED
|
||||
if (settled || current.stage.ordinal >= stage.ordinal) current else current.copy(stage = stage)
|
||||
}
|
||||
|
||||
private fun <T> Either<Throwable, T>.orThrow(step: String): T =
|
||||
right ?: throw IllegalStateException("FROST refresh $step failed: ${left?.message}")
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package mobi.giza.compose.managers
|
||||
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import mobi.giza.compose.database.GizaDatabase
|
||||
import mobi.giza.compose.database.model.DkgSession
|
||||
import mobi.giza.compose.nostr.dkg.DkgRitualEvents
|
||||
|
||||
/** The FROST signer ids fixed by a ChillDKG ceremony's host-key ordering. */
|
||||
object FrostSignerOrder {
|
||||
suspend fun signerIds(database: GizaDatabase, key: DkgSession): Map<HexKey, Int> {
|
||||
val hostKeys = database.dkgSessionDao()
|
||||
.getMessagesByKind(key.id, DkgRitualEvents.HOST_KEY)
|
||||
.associate { it.participantPublicKey to it.payload.lowercase() }
|
||||
val order = hostKeys.values.sorted()
|
||||
return hostKeys.mapNotNull { (member, hostKey) ->
|
||||
order.indexOf(hostKey).takeIf { it >= 0 }?.let { member to it }
|
||||
}.toMap()
|
||||
}
|
||||
|
||||
suspend fun signerIdOf(database: GizaDatabase, key: DkgSession, member: HexKey): Int? =
|
||||
signerIds(database, key)[member]
|
||||
}
|
||||
@@ -42,7 +42,6 @@ import mobi.giza.compose.database.model.types.DkgRitualStage
|
||||
import mobi.giza.compose.database.model.types.FrostSigningStage
|
||||
import mobi.giza.compose.database.model.types.FrostSigningSubject
|
||||
import mobi.giza.compose.extensions.toHex
|
||||
import mobi.giza.compose.nostr.dkg.DkgRitualEvents
|
||||
import mobi.giza.compose.nostr.frost.FrostSigningEvents
|
||||
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
|
||||
|
||||
@@ -1602,23 +1601,13 @@ object FrostSigningManager {
|
||||
private suspend fun signerIds(
|
||||
database: GizaDatabase,
|
||||
key: DkgSession
|
||||
): Map<HexKey, Int> {
|
||||
val hostKeys = database.dkgSessionDao()
|
||||
.getMessagesByKind(key.id, DkgRitualEvents.HOST_KEY)
|
||||
.associate { it.participantPublicKey to it.payload.lowercase() }
|
||||
|
||||
val order = hostKeys.values.sorted()
|
||||
|
||||
return hostKeys.mapNotNull { (member, hostKey) ->
|
||||
order.indexOf(hostKey).takeIf { it >= 0 }?.let { member to it }
|
||||
}.toMap()
|
||||
}
|
||||
): Map<HexKey, Int> = FrostSignerOrder.signerIds(database, key)
|
||||
|
||||
private suspend fun signerIdOf(
|
||||
database: GizaDatabase,
|
||||
key: DkgSession,
|
||||
member: HexKey
|
||||
): Int? = signerIds(database, key)[member]
|
||||
): Int? = FrostSignerOrder.signerIdOf(database, key, member)
|
||||
|
||||
/**
|
||||
* The key a room signs with, or null when it has none.
|
||||
|
||||
@@ -16,6 +16,7 @@ import com.vitorpamplona.quartz.nip44Encryption.Nip44
|
||||
import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler
|
||||
import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent
|
||||
import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
|
||||
import mobi.giza.compose.nostr.frost.ReEnrollmentEvents
|
||||
|
||||
/**
|
||||
* A one-to-one message carried inside a Marmot group, as the application payload of a
|
||||
@@ -143,7 +144,7 @@ object MarmotDirectMessage {
|
||||
)
|
||||
}
|
||||
|
||||
if (opened.rumor.kind != ChatMessageEvent.KIND) {
|
||||
if (opened.rumor.kind != ChatMessageEvent.KIND && opened.rumor.kind !in ReEnrollmentEvents.PRIVATE) {
|
||||
return Delivery.Rejected("unsupported rumor kind ${opened.rumor.kind}")
|
||||
}
|
||||
|
||||
|
||||
+30
@@ -25,6 +25,8 @@ import mobi.giza.compose.database.builder.getRoomDatabase
|
||||
import mobi.giza.compose.nostr.MarmotDirectMessage
|
||||
import mobi.giza.compose.nostr.dkg.DkgRitualEvents
|
||||
import mobi.giza.compose.nostr.frost.FrostSigningEvents
|
||||
import mobi.giza.compose.nostr.frost.ReEnrollmentEvents
|
||||
import mobi.giza.compose.nostr.frost.tags.ReEnrollmentSessionIdTag
|
||||
|
||||
/**
|
||||
* A key ceremony's or a signing session's message, arriving in a Marmot room,
|
||||
@@ -180,6 +182,34 @@ class ProtocolKindDispatchJvmTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a refresh protocol message writes no chat line`(): Unit = runBlocking {
|
||||
ReEnrollmentEvents.ALL.forEach { kind ->
|
||||
val (_, line) = arrive(kind, content = round1Content)
|
||||
assertNull(line, "kind $kind is a share refresh's")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a private refresh evaluation is opened without a chat line`(): Unit = runBlocking {
|
||||
val wrap = MarmotDirectMessage.wrap(
|
||||
signer = senderSigner,
|
||||
recipientPublicKey = self.pubKey.toHexKey(),
|
||||
kind = ReEnrollmentEvents.PRIVATE_EVALUATION,
|
||||
createdAt = 1,
|
||||
tags = arrayOf(
|
||||
PTag.assemble(self.pubKey.toHexKey(), null),
|
||||
ReEnrollmentSessionIdTag.assemble("5e55".repeat(16)),
|
||||
),
|
||||
content = "01".repeat(32),
|
||||
)
|
||||
val envelope = MarmotDirectMessage.envelope(sender, self.pubKey.toHexKey(), wrap, createdAt = 1)
|
||||
|
||||
val (_, line) = arrive(Event.fromJson(envelope.toJson()))
|
||||
|
||||
assertNull(line, "the evaluation is protocol input, not a direct-message bubble")
|
||||
}
|
||||
|
||||
/**
|
||||
* Bennu's wallets reach a room Giza shares with Bennu members, and Giza takes no part
|
||||
* in them (docs/giza-wallet-removal.md, Phase 1). None of their kinds is ever a
|
||||
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
package mobi.giza.compose.managers
|
||||
|
||||
import androidx.room3.Room
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Event
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import fr.acinq.bitcoin.ByteVector32
|
||||
import fr.acinq.bitcoin.PrivateKey
|
||||
import fr.acinq.bitcoin.crypto.frost.Frost
|
||||
import fr.acinq.bitcoin.crypto.frost.KeyMaterial
|
||||
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.database.GizaDatabase
|
||||
import mobi.giza.compose.database.builder.getRoomDatabase
|
||||
import mobi.giza.compose.database.model.ChatRoom
|
||||
import mobi.giza.compose.database.model.DkgParticipantMessage
|
||||
import mobi.giza.compose.database.model.DkgSession
|
||||
import mobi.giza.compose.database.model.GroupKeyState
|
||||
import mobi.giza.compose.database.model.GroupSignedEvent
|
||||
import mobi.giza.compose.database.model.MarmotInnerEvent
|
||||
import mobi.giza.compose.database.model.Participant
|
||||
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
|
||||
import mobi.giza.compose.database.model.types.DkgRitualStage
|
||||
import mobi.giza.compose.database.model.types.ReEnrollmentStage
|
||||
import mobi.giza.compose.extensions.toHex
|
||||
import mobi.giza.compose.nostr.dkg.DkgRitualEvents
|
||||
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
|
||||
import mobi.giza.compose.nostr.frost.ReEnrollmentEvents
|
||||
|
||||
class FrostReEnrollmentManagerJvmTest {
|
||||
private val participants = 3
|
||||
private val threshold = 2
|
||||
private val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen(
|
||||
PrivateKey(ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1")),
|
||||
participants,
|
||||
threshold,
|
||||
)
|
||||
private val thresholdPublicKey = keyMaterial.thresholdPublicKey.value.toHex()
|
||||
private val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey)
|
||||
private val ceremonyId = "ceremony".padEnd(64, '0')
|
||||
private val members = listOf("a", "b", "c").map { it.repeat(64) }
|
||||
private val hostKeys = listOf("2a", "2b", "2c").map { it.padEnd(66, '0') }
|
||||
private val devices = mutableListOf<Device>()
|
||||
private val delivered = mutableSetOf<String>()
|
||||
|
||||
@AfterTest
|
||||
fun closeDatabases() {
|
||||
devices.forEach { it.db.close() }
|
||||
devices.clear()
|
||||
delivered.clear()
|
||||
}
|
||||
|
||||
private inner class Device(val index: Int) {
|
||||
val member: HexKey = members[index]
|
||||
val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder<GizaDatabase>())
|
||||
lateinit var room: LocalChatRoom
|
||||
|
||||
suspend fun open() {
|
||||
members.forEach { GroupFixtures.seedProfile(db, it) }
|
||||
db.chatRoomDao().upsert(
|
||||
ChatRoom(id = roomId, userPublicKey = member, subject = null, description = null, mlsGroupState = "state")
|
||||
)
|
||||
db.participantDao().upsert(members.map { Participant(participantPublicKey = it, chatRoomId = roomId, relayHint = null) })
|
||||
room = requireNotNull(db.chatRoomDao().findChatRoomById(roomId))
|
||||
db.dkgSessionDao().upsert(
|
||||
DkgSession(
|
||||
id = ceremonyId,
|
||||
chatRoomId = roomId,
|
||||
coordinatorPublicKey = members[0],
|
||||
userPublicKey = member,
|
||||
threshold = threshold,
|
||||
participantCount = participants,
|
||||
participantPublicKeys = DkgSession.formatParticipants(members.toSet()),
|
||||
stage = DkgRitualStage.COMPLETE,
|
||||
hostPublicKey = hostKeys[index],
|
||||
round1Random = "1".repeat(64),
|
||||
round2AuxRandom = "2".repeat(64),
|
||||
thresholdPublicKey = thresholdPublicKey,
|
||||
secretShare = keyMaterial.secretShares[index].value.toHex(),
|
||||
publicShares = keyMaterial.publicShares.joinToString(",") { it.value.toHex() },
|
||||
)
|
||||
)
|
||||
members.forEachIndexed { i, participant ->
|
||||
db.dkgSessionDao().upsert(
|
||||
DkgParticipantMessage(ceremonyId, participant, DkgRitualEvents.HOST_KEY, hostKeys[i])
|
||||
)
|
||||
}
|
||||
db.groupKeyStateDao().upsert(
|
||||
GroupKeyState(
|
||||
chatRoomId = roomId,
|
||||
dkgSessionId = ceremonyId,
|
||||
thresholdPublicKey = thresholdPublicKey,
|
||||
derivationPath = SharedKeyDerivation.formatPath(SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH),
|
||||
announcedBy = roomId,
|
||||
announcedAt = kotlin.time.Instant.fromEpochSeconds(1_700_000_000),
|
||||
)
|
||||
)
|
||||
val signed = GroupFixtures.signedAsRoom(
|
||||
keyMaterial,
|
||||
GroupKeyStateEvent.KIND,
|
||||
GroupKeyStateEvent.assembleTags(roomId, ceremonyId),
|
||||
thresholdPublicKey,
|
||||
)
|
||||
db.groupSignedEventDao().upsert(
|
||||
GroupSignedEvent.fromEvent(
|
||||
signed,
|
||||
roomId,
|
||||
SharedKeyDerivation.formatPath(SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH),
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun session() = db.frostReEnrollmentDao().getRunningForKey(ceremonyId)
|
||||
?: db.frostReEnrollmentDao().getLatestForKey(ceremonyId)
|
||||
|
||||
suspend fun receive(queued: MarmotInnerEvent) {
|
||||
db.marmotInnerEventDao().upsert(queued.copy(directMessageRecipientPublicKey = null))
|
||||
FrostReEnrollmentManager.processReEnrollmentPayload(
|
||||
db,
|
||||
room,
|
||||
Event(
|
||||
id = queued.id,
|
||||
pubKey = queued.publicKey,
|
||||
createdAt = queued.createdAt.epochSeconds,
|
||||
kind = queued.kind,
|
||||
tags = queued.tags,
|
||||
content = queued.content,
|
||||
sig = "",
|
||||
),
|
||||
member,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun openDevices() {
|
||||
devices += List(participants) { index -> Device(index).apply { open() } }
|
||||
}
|
||||
|
||||
private suspend fun pump(
|
||||
maxRounds: Int = 30,
|
||||
predicate: (MarmotInnerEvent) -> Boolean = { true },
|
||||
) {
|
||||
repeat(maxRounds) {
|
||||
var moved = false
|
||||
devices.forEach { sender ->
|
||||
val queued = sender.db.marmotInnerEventDao()
|
||||
.getByChatRoomAndKinds(roomId, ReEnrollmentEvents.ALL.toList())
|
||||
.filter { it.id !in delivered && predicate(it) }
|
||||
queued.forEach { event ->
|
||||
devices.forEach { recipient ->
|
||||
if (recipient.member == event.publicKey) return@forEach
|
||||
val direct = event.directMessageRecipientPublicKey
|
||||
if (direct != null && recipient.member != direct) return@forEach
|
||||
recipient.receive(event)
|
||||
moved = true
|
||||
}
|
||||
delivered += event.id
|
||||
}
|
||||
}
|
||||
if (!moved) return
|
||||
}
|
||||
error("The refresh did not settle after $maxRounds delivery rounds")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a proposal publishes nothing until each member approves`() = runBlocking {
|
||||
openDevices()
|
||||
val proposal = devices[0].let { sender ->
|
||||
FrostReEnrollmentManager.proposeReEnrollment(sender.db, sender.room, sender.member)
|
||||
}
|
||||
pump { it.kind == ReEnrollmentEvents.PROPOSAL }
|
||||
|
||||
devices.drop(1).forEach { device ->
|
||||
val session = device.session()!!
|
||||
assertEquals(proposal.id, session.id)
|
||||
assertNull(session.joinApprovedAt)
|
||||
assertNull(session.ownCommitments)
|
||||
assertTrue(FrostReEnrollmentManager.pendingApproval(device.db, session))
|
||||
assertTrue(device.db.frostReEnrollmentDao().getMessagesByKind(session.id, ReEnrollmentEvents.COMMITMENTS).isEmpty())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `all members reach activation with the same verified candidate`() = runBlocking {
|
||||
openDevices()
|
||||
devices[0].let { FrostReEnrollmentManager.proposeReEnrollment(it.db, it.room, it.member) }
|
||||
pump { it.kind == ReEnrollmentEvents.PROPOSAL }
|
||||
devices.drop(1).forEach { device ->
|
||||
FrostReEnrollmentManager.approve(device.db, device.room, device.session()!!.id)
|
||||
}
|
||||
pump()
|
||||
|
||||
val sessions = devices.map { it.session()!! }
|
||||
assertEquals(List(participants) { ReEnrollmentStage.ACTIVATING }, sessions.map { it.stage })
|
||||
assertEquals(1, sessions.map { it.transcriptHash }.toSet().size)
|
||||
assertEquals(1, sessions.map { it.candidatePublicShares }.toSet().size)
|
||||
|
||||
val updatedSecrets = sessions.map { PrivateKey(ByteVector32(it.candidateSecretShare!!)) }
|
||||
val updatedPublic = sessions.first().candidatePublicShareList()!!
|
||||
assertTrue(KeyMaterial(keyMaterial.thresholdPublicKey, updatedSecrets, updatedPublic, threshold).isValid())
|
||||
assertTrue(updatedSecrets.zip(keyMaterial.secretShares).all { (new, old) -> new != old })
|
||||
|
||||
devices.forEachIndexed { index, device ->
|
||||
val key = device.db.dkgSessionDao().getSessionById(ceremonyId)!!
|
||||
assertEquals(0, key.shareEpoch)
|
||||
assertEquals(keyMaterial.secretShares[index].value.toHex(), key.secretShare)
|
||||
}
|
||||
|
||||
val direct = devices.flatMap { sender ->
|
||||
sender.db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(ReEnrollmentEvents.PRIVATE_EVALUATION))
|
||||
.filter { it.directMessageRecipientPublicKey != null }
|
||||
}
|
||||
assertEquals(participants * (participants - 1), direct.distinctBy { it.id }.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a corrupt private evaluation fails before activation and leaves the old share active`() = runBlocking {
|
||||
openDevices()
|
||||
devices[0].let { FrostReEnrollmentManager.proposeReEnrollment(it.db, it.room, it.member) }
|
||||
pump { it.kind == ReEnrollmentEvents.PROPOSAL }
|
||||
devices.drop(1).forEach { device ->
|
||||
FrostReEnrollmentManager.approve(device.db, device.room, device.session()!!.id)
|
||||
}
|
||||
pump { it.kind == ReEnrollmentEvents.COMMITMENTS }
|
||||
pump { event -> event.kind == ReEnrollmentEvents.PRIVATE_EVALUATION && event.directMessageRecipientPublicKey != members[1] }
|
||||
pump { event ->
|
||||
event.kind == ReEnrollmentEvents.PRIVATE_EVALUATION &&
|
||||
event.publicKey == members[0] && event.directMessageRecipientPublicKey == members[1]
|
||||
}
|
||||
|
||||
val target = devices[1]
|
||||
val corrupt = devices[2].db.marmotInnerEventDao()
|
||||
.getByChatRoomAndKinds(roomId, listOf(ReEnrollmentEvents.PRIVATE_EVALUATION))
|
||||
.single { it.directMessageRecipientPublicKey == target.member }
|
||||
target.receive(corrupt.copy(content = "01".repeat(32)))
|
||||
|
||||
val failed = target.session()!!
|
||||
val evaluations = target.db.frostReEnrollmentDao().getMessagesByKind(failed.id, ReEnrollmentEvents.PRIVATE_EVALUATION)
|
||||
assertEquals(
|
||||
ReEnrollmentStage.FAILED,
|
||||
failed.stage,
|
||||
"reason=${failed.failureReason}; evaluations=${evaluations.map { "${it.senderPublicKey.take(1)}:${it.recipientPublicKey.take(1)}:${it.payload.take(4)}" }}",
|
||||
)
|
||||
assertNotNull(failed.failureReason)
|
||||
assertNull(failed.candidateSecretShare)
|
||||
assertEquals(keyMaterial.secretShares[1].value.toHex(), target.db.dkgSessionDao().getSessionById(ceremonyId)?.secretShare)
|
||||
assertEquals(0, target.db.dkgSessionDao().getSessionById(ceremonyId)?.shareEpoch)
|
||||
assertTrue(
|
||||
target.db.frostReEnrollmentDao().getMessagesByKind(failed.id, ReEnrollmentEvents.PRIVATE_EVALUATION)
|
||||
.all { it.payload.isEmpty() }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
# FROST re-enrollment
|
||||
|
||||
**Status: Phase 1 implemented and tested on JVM and Linux x64; app integration in progress.**
|
||||
**Status: Phases 1–4 implemented and tested through candidate READY and ACTIVATING; candidate-signed activation and UI in progress.**
|
||||
|
||||
The implementation keeps one cryptographic implementation rather than adding a parallel C
|
||||
module and binding stack. `FrostRefresh` lives in bitcoin-kmp beside `FrostEnrollment` and
|
||||
|
||||
Reference in new issue
Block a user