diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt index f4d4e7cc..53678b41 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt @@ -658,6 +658,21 @@ object FrostSigningManager { return declined } + // A profile or a post that nothing would show once signed: a kind:0 that is + // not a profile, a kind:1 with nothing in it. Declined on arrival for the + // wallet's reason -- Giza signs only what it can check -- and filed the same + // way, so the decline goes out through [advance]. + // docs/group-nostr-profile-and-posts.md, D5. + GroupStatementRefusal.of(unsignedEvents)?.let { why -> + logger.w("Signing proposal $sessionId $why; declining") + 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)) + announceStarted(database, declined) + return declined + } + // A change to a governed room whose commit does not say what its statement // says -- or that the group's door would refuse anyway -- is declined before // anybody is asked, for the wallet's reason: a device that signs what it @@ -1008,6 +1023,15 @@ object FrostSigningManager { session.subject != FrostSigningSubject.EVENTS || items.any { item -> Event.fromJsonOrNull(item.unsignedEventJson)?.let(WalletRefusal::of) != null } + /** + * Events [GroupStatementRefusal] says nothing would show once signed: a profile + * no reader could parse, a post with nothing in it. + * docs/group-nostr-profile-and-posts.md, D5. + */ + private fun isUnshowableSession(session: FrostSigningSession, items: List): Boolean = + session.subject == FrostSigningSubject.EVENTS && + items.any { item -> Event.fromJsonOrNull(item.unsignedEventJson)?.let(GroupStatementRefusal::of) != null } + private fun isFromCoordinator( session: FrostSigningSession, innerEvent: Event @@ -2126,6 +2150,15 @@ object FrostSigningManager { return } + // The same backstop for a profile or a post nothing would show, for a + // session an older build filed before it declined those on arrival. + if (isUnshowableSession(session, items)) { + logger.w("Session $sessionId signs a profile or a post nothing could show; declining") + 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") @@ -2606,6 +2639,7 @@ object FrostSigningManager { val items = database.frostSigningSessionDao().getItems(session.id) val reason = when { isWalletSession(session, items) -> WalletRefusal.REASON + isUnshowableSession(session, items) -> GroupStatementRefusal.REASON !holdsShareFor(database, session) -> GENERATION_REFUSAL else -> "Declined to sign" } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupStatementRefusal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupStatementRefusal.kt new file mode 100644 index 00000000..0197f9e1 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupStatementRefusal.kt @@ -0,0 +1,59 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent + +/** + * A profile or a post the group is asked to sign that nothing would show once it had + * (docs/group-nostr-profile-and-posts.md, D5). + * + * The group's profile is read through `GroupNostrProfile.of` and its posts through + * `GroupPost.newestFirstAmong`, and both refuse rather than repair: a kind:0 whose + * content is not a profile, and a kind:1 with nothing in it, would each be signed, + * filed and shown nowhere, with nothing to tell the group its quorum was spent on + * nothing. Curare's editors never produce one -- they check before they propose -- but + * a proposal can come from any build, and Giza signs only what it can check. So it + * declines these the way it declines a wallet's: out loud, so the group counts it. + * + * The predicates are the ones the paste screen refuses on too + * (`GroupEventProposal.read`), so the member proposing and the member signing draw the + * same line. + */ +object GroupStatementRefusal { + /** What a decline says, on the wire and in this device's transcript. */ + const val REASON = "Giza doesn't sign a profile or a post that nothing could show" + + /** + * Whether [content] under [tags] is not a profile at all. + * + * An empty kind:0 is a profile -- the group wiping its own, which it is entitled to + * do -- and quartz reads it as the blank one it is. Only content that will not + * parse is refused, which is the same line `GroupNostrProfile.of` draws. + */ + fun isUnreadableProfile(tags: Array>, content: String): Boolean = MetadataEvent( + id = "", + pubKey = "", + createdAt = 0, + tags = tags, + content = content, + sig = "", + ).contactMetaData() == null + + /** + * Whether a kind:1 has nothing to say. A blank post cannot be told from a broken + * one, and a kind:1 is not replaceable, so it could not be taken back either. + */ + fun isBlankPost(content: String): Boolean = content.isBlank() + + /** Why [event] would be shown nowhere once signed, or null when it would be. */ + fun of(event: Event): String? = when (event.kind) { + MetadataEvent.KIND -> "is a profile no reader could parse".takeIf { + isUnreadableProfile(event.tags, event.content) + } + TextNoteEvent.KIND -> "is a post with nothing in it".takeIf { isBlankPost(event.content) } + else -> null + } + + fun of(events: List): String? = events.firstNotNullOfOrNull(::of) +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupStatementDeclineJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupStatementDeclineJvmTest.kt new file mode 100644 index 00000000..378067b5 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupStatementDeclineJvmTest.kt @@ -0,0 +1,241 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +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.assertFalse +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.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.FrostSigningItem +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.types.DkgRitualStage +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 + +/** + * Giza declines a profile or a post that nothing would show once signed, out loud + * (docs/group-nostr-profile-and-posts.md, D5). + * + * The harness is WalletDeclineJvmTest's: each proposal is a real one, made on Alice's + * device -- which stands in for a Curare member's, since proposing checks nothing -- + * and handed to Bob's through the inbound path, because the event ids are rebuilt + * there and a fabricated proposal would be dropped before the check under test ran. + */ +class GroupStatementDeclineJvmTest { + private val participants = 3 + private val threshold = 2 + + private val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( + thresholdSecretKey = PrivateKey( + ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") + ), + nParticipants = participants, + threshold = 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 alice = members[0] + private val bob = members[1] + + private lateinit var db: GizaDatabase + private lateinit var room: LocalChatRoom + + @AfterTest + fun closeDatabase() { + if (::db.isInitialized) db.close() + } + + private suspend fun openDevice(owner: HexKey) { + if (::db.isInitialized) db.close() + db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + val index = members.indexOf(owner) + val nostrEventId = "e$owner".take(64) + db.nostrEventDao().upsert( + NostrEvent(id = nostrEventId, pubKey = owner, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)) + ) + db.profileDao().upsert(Profile(publicKey = owner, nostrEventId = nostrEventId)) + + val chatRoom = ChatRoom( + id = roomId, + userPublicKey = owner, + subject = "#Ekklesia", + description = SharedKeyDerivation.describe("Admins of the group."), + mlsGroupState = null + ) + db.chatRoomDao().upsert(chatRoom) + + db.dkgSessionDao().upsert( + DkgSession( + id = ceremonyId, + chatRoomId = roomId, + coordinatorPublicKey = alice, + userPublicKey = owner, + threshold = threshold, + participantCount = participants, + 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, member -> + db.dkgSessionDao().upsert( + DkgParticipantMessage(sessionId = ceremonyId, participantPublicKey = member, kind = DkgRitualEvents.HOST_KEY, payload = hostKeys[i]) + ) + } + + room = LocalChatRoom(chatRoom = chatRoom) + } + + /** What this device has queued for the group, of one kind. The room is NIP-17 here. */ + private suspend fun queued(kind: Kind) = db.giftWrapPayloadDao() + .getByChatRoomAndKinds(roomId, listOf(kind)) + .filter { it.publicKey == room.chatRoom.userPublicKey } + + /** + * Alice's device proposes one event of [kind]; Bob's device receives the proposal. + * Returns the session id, with [db] and [room] left on Bob's device. + */ + private suspend fun proposalReachesBob(kind: Kind, tags: Array> = arrayOf(), content: String = "{}"): String { + openDevice(alice) + val session = FrostSigningManager.proposeSigning( + database = db, + localChatRoom = room, + userPublicKey = alice, + kind = kind, + tags = tags, + content = content + ) + val proposal = queued(FrostSigningEvents.PROPOSAL).single().content + + openDevice(bob) + FrostSigningManager.processSigningPayload( + database = db, + localChatRoom = room, + innerEvent = Event( + id = "proposal".padEnd(64, '0'), + pubKey = alice, + createdAt = Clock.System.now().epochSeconds, + kind = FrostSigningEvents.PROPOSAL, + tags = FrostSigningEvents.assembleTags(sessionId = session.id, dkgSessionId = ceremonyId), + content = proposal, + sig = "" + ), + userPublicKey = bob + ) + return session.id + } + + private suspend fun assertDeclinedAsUnshowable(sessionId: String) { + val session = db.frostSigningSessionDao().getSessionById(sessionId) + assertNotNull(session, "declined, not dropped: the session is filed so the decline can go out") + assertNotNull(session.signDeclinedAt) + assertNull(session.signApprovedAt) + assertFalse(FrostSigningManager.isAwaitingApproval(session, db.frostSigningSessionDao().getItems(sessionId)), "and nobody is asked") + + val declines = queued(FrostSigningEvents.DECLINE) + assertEquals(1, declines.size, "the decline is published, so the group counts it") + assertEquals(GroupStatementRefusal.REASON, declines.single().content) + assertEquals(emptyList(), queued(FrostSigningEvents.NONCE), "and nothing of the signature goes out") + } + + @Test + fun `a profile no reader could parse is declined on arrival, out loud`() = runBlocking { + assertDeclinedAsUnshowable(proposalReachesBob(kind = MetadataEvent.KIND, content = "not json")) + } + + @Test + fun `a post with nothing in it is declined on arrival`() = runBlocking { + assertDeclinedAsUnshowable(proposalReachesBob(kind = TextNoteEvent.KIND, content = " \n ")) + } + + @Test + fun `a readable profile is put to the member`() = runBlocking { + assertAsked(proposalReachesBob(kind = MetadataEvent.KIND, content = """{"name":"Translation collective"}""")) + } + + @Test + fun `an empty profile is a profile, and is put to the member`() = runBlocking { + // Wiping its profile is something a group is entitled to do. + assertAsked(proposalReachesBob(kind = MetadataEvent.KIND, content = "")) + } + + @Test + fun `a post with something to say is put to the member`() = runBlocking { + assertAsked(proposalReachesBob(kind = TextNoteEvent.KIND, content = "We meet on Thursday")) + } + + @Test + fun `approving a session an older build filed for an empty post declines it instead`() = runBlocking { + openDevice(bob) + val session = FrostSigningSession( + id = "s".repeat(64), + chatRoomId = roomId, + coordinatorPublicKey = alice, + userPublicKey = bob, + dkgSessionId = ceremonyId, + threshold = threshold, + participantCount = participants, + signerId = members.indexOf(bob), + derivationPath = SharedKeyDerivation.formatPath(SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH), + subject = FrostSigningSubject.EVENTS, + ) + val blank = Event( + id = "e".repeat(64), + pubKey = roomId, + createdAt = 1, + kind = TextNoteEvent.KIND, + tags = emptyArray(), + content = "", + sig = "", + ) + db.frostSigningSessionDao().upsert(session) + db.frostSigningSessionDao().upsertItems( + listOf(FrostSigningItem(sessionId = session.id, itemIndex = 0, unsignedEventJson = blank.toJson(), eventId = blank.id, nonceRandom = "f".repeat(64))) + ) + + FrostSigningManager.approve(db, room, session.id) + + assertDeclinedAsUnshowable(session.id) + } + + private suspend fun assertAsked(sessionId: String) { + val session = db.frostSigningSessionDao().getSessionById(sessionId) + assertNotNull(session) + assertNull(session.signDeclinedAt) + assertTrue(FrostSigningManager.isAwaitingApproval(session, db.frostSigningSessionDao().getItems(sessionId))) + assertEquals(emptyList(), queued(FrostSigningEvents.DECLINE)) + } +}