diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt index 1275039a..b82033cd 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt @@ -33,20 +33,8 @@ import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent import com.machankura.bennu.compose.nostr.chronicle.ChronicleEvent import com.machankura.bennu.compose.nostr.chronicle.ChronicleRequestEvent -import com.machankura.bennu.compose.nostr.nip30303.SubmissionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionContributorListEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationContributorListEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationEvent import co.touchlab.kermit.Logger import com.vitorpamplona.quartz.nip01Core.core.firstTagValue import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent @@ -873,11 +861,10 @@ data class ChatMessage( ?: throw MarmotUnprocessableInnerEventException("Can't process ${groupEventResult.innerEventJson}") // A key ceremony's or a signing session's own message. Decided - // first, before anything that shares its kind number gets a - // look: 30310-30312 are also nip30303 kinds, and round 1 of a - // subgroup's ceremony (30312) was being read as a submission, - // failing to parse, and landing in the parent's chat as raw hex - // -- see docs/ceremony-creation.md, finding F11. Stored like + // first: 30310-30312 were nip30303 document kinds too, and round + // 1 of a subgroup's ceremony (30312) was read as a document + // submission, failed to parse, and landed in the parent's chat + // as raw hex -- see docs/ceremony-creation.md, finding F11. Stored like // every inner event, so a ceremony can replay what arrived // before its proposal; acted on by the managers // `NostrDao.fileGroupEventResult` dispatches to, which write @@ -885,25 +872,6 @@ data class ChatMessage( val isProtocolMessage = event.kind in DkgRitualEvents.ALL || event.kind in FrostSigningEvents.ALL - // A submission is an envelope: the nip30303 event it delivers - // is in its content, written by whoever wrote it. Everything - // else on the wire is the nip30303 event itself. Either way the - // row on disk is the outer event -- that is what the group sent - // and what the chat line is attributed to. - val submission = if (event.kind == SubmissionEvent.KIND && !isProtocolMessage) { - SubmissionEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig, - ) - } else { - null - } - val payload = submission?.payload() - database.marmotInnerEventDao().upsert( MarmotInnerEvent( id = event.id, @@ -913,14 +881,13 @@ data class ChatMessage( content = event.content, chatRoomId = groupEventResult.groupId, kind = event.kind, - payloadEventId = payload?.id, createdAt = Instant.fromEpochSeconds(event.createdAt) ) ) if (isProtocolMessage) return null - // A direct message is not a nip30303 payload to apply. It is + // A direct message is not a payload to apply. It is // gift wrapped for one member, and what this device does with it // depends only on whether its key opens it. A legacy room carries // the wrap itself; a current-profile room carries it inside an @@ -998,33 +965,16 @@ data class ChatMessage( return null } - // A submission whose payload will not parse, or which carries - // another submission, is kept but not applied: there is nothing - // here we can turn into a row. - if (submission != null && (payload == null || payload.kind == SubmissionEvent.KIND)) { - ChatMessage( - giftWrapPayloadId = null, - messageType = "unsupported", - marmotGroupEventId = groupEvent.id, - marmotInnerEventId = event.id, - senderPublicKey = event.pubKey, - isUserMessage = senderIdentity == activeKeyPair.pubKey.toHex(), - chatRoomId = groupEventResult.groupId, - createdAt = Instant.fromEpochSeconds(event.createdAt), - content = event.content, - ) - } else { - applyInnerEvent( - database = database, - groupId = groupEventResult.groupId, - event = payload ?: event, - marmotGroupEventId = groupEvent.id, - marmotInnerEventId = event.id, - senderPublicKey = event.pubKey, - isUserMessage = senderIdentity == activeKeyPair.pubKey.toHex(), - createdAt = Instant.fromEpochSeconds(event.createdAt), - ) - } + applyInnerEvent( + database = database, + groupId = groupEventResult.groupId, + event = event, + marmotGroupEventId = groupEvent.id, + marmotInnerEventId = event.id, + senderPublicKey = event.pubKey, + isUserMessage = senderIdentity == activeKeyPair.pubKey.toHex(), + createdAt = Instant.fromEpochSeconds(event.createdAt), + ) } is GroupEventResult.CommitPending -> { ChatMessage( @@ -1118,16 +1068,12 @@ data class ChatMessage( } /** - * Apply one nip30303 [event] the group delivered, and describe it for - * the transcript. + * Apply one [event] the group delivered, and describe it for the + * transcript. * * [event] is what is being applied; the other parameters are how it - * arrived. They come apart for submissions: the payload is written by - * whoever wrote it -- possibly nobody in this group -- while - * [marmotInnerEventId], [senderPublicKey] and [createdAt] all belong to - * the envelope a member actually sent. Entity rows take their author - * from [event], so the chat line says who added it and the row says who - * wrote it. + * arrived -- [marmotInnerEventId], [senderPublicKey] and [createdAt] + * belong to the message a member actually sent. * * [groupSignedEventId] is the third way in, and the one with no * envelope at all: a `GroupSignedEvent` the group put its own signature @@ -1166,10 +1112,9 @@ data class ChatMessage( return when (event.kind) { // First, above every content kind: protocol kinds are never - // content, whatever else shares their number, and a `when` takes - // the first arm that matches. The ceremony's 30310 and 30311 used - // to reach the nip30303 contributor-list and translation arms below - // before this one. + // content, whatever else might share their number, and a `when` + // takes the first arm that matches. The ceremony's 30310 and 30311 + // once reached document arms that sat above this one. // // A signing session's own protocol messages. FrostSigningManager // applies them and writes its own transcript lines naming who did @@ -1205,315 +1150,6 @@ data class ChatMessage( content = event.content, // TODO: Figure out what to do here... ) } - ArtifactEvent.KIND -> { - val artifactEvent = ArtifactEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig, - ) - - MantraArtifact.fromArtifactEvent( - artifactEvent = artifactEvent, - chatRoomId = groupId, - )?.let { mantraArtifact -> - database.mantraArtifactDao().upsert( - mantraArtifact.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - - // The version the artifact starts life with is its own - // event, signed in the same batch and applied after this - // one -- see AddArtifactViewModel.addArtifact. It used to - // be derived here instead; deriving it now as well would - // stand a second, unsigned version row against the same - // artifact, since the two hash differently. - - ChatMessage( - giftWrapPayloadId = null, - messageType = "artifact", - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "Added ${mantraArtifact.name} to artifacts" - ) - } - } - ArtifactVersionEvent.KIND -> { - MantraArtifactVersion.fromArtifactVersionEvent( - artifactVersionEvent = ArtifactVersionEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig - ), - chatRoomId = groupId, - )?.let { mantraArtifactVersion -> - database.mantraArtifactVersionDao().upsert( - mantraArtifactVersion.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - - // No line of its own. A version arrives as the second - // item of the batch that carries its artifact, and the - // artifact has already said so -- the same reason a - // chunk writes no line beside its chapter. While the - // version was derived here rather than signed it wrote - // none either, so this is the transcript standing still - // rather than losing something. - } - null - } - ChapterEvent.KIND -> { - // The chunks the chapter splits into are their own events, - // signed in the same session and applied after it -- see - // AddChapterViewModel.addChapter. Nothing to do here but the - // chapter itself. - MantraChapter.fromChapterEvent( - chapterEvent = ChapterEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig - ), - chatRoomId = groupId, - )?.let { mantraChapter -> - database.mantraChapterDao().upsert( - mantraChapter.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - - ChatMessage( - giftWrapPayloadId = null, - messageType = "chapter", - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "Added ${mantraChapter.name} to chapters" // TODO: Use artifact name... - ) - } - } - - ChunkEvent.KIND -> { - MantraChunk.fromChunkEvent( - chunkEvent = ChunkEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig - ), - chatRoomId = groupId, - )?.let { mantraChunk -> - database.mantraChunkDao().upsert( - mantraChunk.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - - // TODO: Chunks might be too noisy to show in chat... - } - null - } - DialectEvent.KIND -> { - MantraDialect.fromDialectEvent( - dialectEvent = DialectEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig - ), - chatRoomId = groupId, - )?.let { mantraDialect -> - database.mantraDialectDao().upsert( - mantraDialect.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - - - ChatMessage( - giftWrapPayloadId = null, - messageType = "dialect", - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "Added ${mantraDialect.name} to dialects" // TODO: Use artifact name... - ) - } - } - TranslationArtifactVersionEvent.KIND -> { - MantraTranslationArtifactVersion.fromTranslationArtifactVersionEvent( - translationArtifactVersionEvent = TranslationArtifactVersionEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig - ), - chatRoomId = groupId, - )?.let { mantraTranslationArtifactVersion -> - database.mantraTranslationArtifactVersionDao().upsert( - mantraTranslationArtifactVersion.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - - ChatMessage( - giftWrapPayloadId = null, - messageType = "translationArtifactVersion", - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "Added ${mantraTranslationArtifactVersion.name} to translation artifact versions" // TODO: Use artifact name... - ) - } - } - TranslationArtifactVersionContributorListEvent.KIND -> { - // TODO: Consume contributors... - null - } - TranslationChapterEvent.KIND -> { - MantraTranslationChapter.fromTranslationChapterEvent( - translationChapterEvent = TranslationChapterEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig - ), - chatRoomId = groupId, - )?.let { mantraTranslationChapter -> - database.mantraTranslationChapterDao().upsert( - mantraTranslationChapter.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - // TODO: translation chapter might be too noisy for chat updates - } - null - } - TranslationChunkEvent.KIND -> { - MantraTranslationChunk.fromTranslationChunkEvent( - translationChunkEvent = TranslationChunkEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig - ), - chatRoomId = groupId, - )?.let { mantraTranslationChunk -> - // One translation per source chunk. Retranslating changes - // the text and so the event's id, which makes it a new - // event rather than an edit of the old one -- so the one - // it supersedes is dropped here, or a passage would have - // two answers to what it says and the reader would be - // shown whichever the query happened to reach first. - // - // Newest wins by the timestamp the group signed at, not by - // when it arrived, with the id breaking a tie. Two devices - // catching up read the same events in whatever order the - // relay hands them over, and they have to end up holding - // the same translation either way. - val existing = database.mantraTranslationChunkDao() - .getTranslationChunksByChunkId( - translationChapterId = mantraTranslationChunk.translationChapterId, - chunkId = mantraTranslationChunk.chunkId, - ) - .filterNot { it.id == mantraTranslationChunk.id } - - val isNewest = existing.none { - it.createdAt > mantraTranslationChunk.createdAt || - (it.createdAt == mantraTranslationChunk.createdAt && - it.id > mantraTranslationChunk.id) - } - - if (isNewest) { - existing.forEach { - database.mantraTranslationChunkDao().deleteById(it.id) - } - - database.mantraTranslationChunkDao().upsert( - mantraTranslationChunk.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - } - } - null - } - TranslationContributorListEvent.KIND -> { - // TODO: Consume contributors... - null - } - TranslationEvent.KIND -> { - MantraTranslation.fromTranslationEvent( - translationEvent = TranslationEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig - ), - chatRoomId = groupId, - )?.let { mantraTranslation -> - database.mantraTranslationDao().upsert( - mantraTranslation.copy( - marmotGroupEventId = marmotGroupEventId, - groupSignedEventId = groupSignedEventId, - ) - ) - ChatMessage( - giftWrapPayloadId = null, - messageType = "translation", - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "Added ${mantraTranslation.text} to translations" // TODO: Reference original text - ) - } - } - // The group saying what key one of its rooms signs with, arriving // here the way every group-signed event does: applied by // `FrostSigningManager` once a quorum has signed the proposal it diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/ChronicleManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/ChronicleManager.kt index 3fe5838d..39cf6bfb 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/ChronicleManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/ChronicleManager.kt @@ -18,7 +18,7 @@ import kotlin.time.Instant import com.machankura.bennu.compose.nostr.chronicle.ChronicleEvent import com.machankura.bennu.compose.nostr.chronicle.ChronicleRequestEvent import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent +import com.machankura.bennu.compose.nostr.chronicle.ChronicleKinds /** * Building the group's signed record into pages a member who lacks it can apply. @@ -28,49 +28,39 @@ import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent * locally by each device that took part and never goes on the wire. This is how * it gets to them. * - * ### The events are the chronicle, and the rows are the fallback + * ### Carrying nothing, for now + * + * What a chronicle may carry is [ChronicleEvent.KINDS], and that is empty since + * the document kinds it was built for were removed (docs/ceremony-creation.md, + * Phase 7). Every entry point here takes the kinds as a parameter defaulting to + * that list, and with it empty the chronicle is quiet: [requestIfEmpty] asks for + * nothing, [sendTo] sends nothing, and a page from an older build applies + * nothing. The machinery is kept, and tested with a list of the tests' own, for + * the next kind that should join. + * + * ### The events are the chronicle * * `GroupSignedEvent` holds what the group signed, as it signed it, so - * [signedEventsOf] reads it first: no rebuild, no round-trip risk, and nothing - * that depends on a row having kept every field of the event it came from. The - * artifact's version label is the standing example -- it is not on the artifact - * row at all, and [rebuiltEventsOf] has to go and find it on the initial version - * or leave the artifact out. + * [signedEventsOf] reads it: no rebuild, no round-trip risk, and nothing that + * depends on a row having kept every field of the event it came from. * - * A room whose work predates that table has no events on file, so the rebuild - * stays as the fallback for exactly what the table is missing, keyed by id. - * Every payload it produces stands or falls on being byte-identical to what was - * signed; `ChronicleRoundTripTest` is what says it is, per kind, against a real - * quorum, and it found two faults in the artifact's rebuild the first time it - * ran -- both of which would have shipped payloads that every receiver drops as - * forgeries without a word. Both it and everything that exists only to hold it - * up are marked `@Deprecated`; the fallback can go once no install still holds - * pre-v13 work, and docs/member-chronicle.md's "Retiring the rebuild" is the list - * of what goes with it. - * - * **The allowlist does real work on the way out now.** The rebuild could only - * ever produce document kinds; the table holds everything the group has ever - * signed, `GroupKeyStateEvent` included. So [signedEventsOf] filters on - * [ChronicleEvent.isChroniclable] before anything else, which is the same rule - * [applyPage] applies on the way in. Without it `ChronicleEvent.build` would - * refuse the page and take the whole chronicle down with it. - * - * A room's own key state no longer sits in that table under the room -- it is - * signed in the NIP-17 room the ceremony ran in, before the room exists, and - * filed under that room; see `GroupKeyStateManager`. That makes the filter a - * narrower guard than it was and not a redundant one: what it is really stopping + * **The allowlist does real work on the way out.** The table holds everything + * the group has ever signed, `GroupKeyStateEvent` included. So [signedEventsOf] + * filters on the kinds before anything else, which is the same rule [applyPage] + * applies on the way in. Without it `ChronicleEvent.build` would refuse the page + * and take the whole chronicle down with it. What the filter is really stopping * is a member replaying any group-signed statement about the record as though it - * were work, and [applyPage] refuses the same kinds coming the other way. The - * two are a pair and neither is safe to drop on the strength of the other. + * were work, and [applyPage] refuses the same kinds coming the other way. The two + * are a pair and neither is safe to drop on the strength of the other. * * ### Nothing unverifiable leaves * - * Every rebuilt event is checked with [GroupKeyStateEvent.isSignedByRoom] before - * it is packed, against the same room id the recipient will check it with. That - * is not politeness towards the receiver, who checks anyway. It is what keeps an - * chronicle honest about its own size: a row that came from a member's rumor - * cannot be chronicled, and dropping it here rather than letting the recipient - * drop it means the page count says what will actually arrive. + * Every event is checked with [GroupKeyStateEvent.isSignedByRoom] before it is + * packed, against the same room id the recipient will check it with. That is not + * politeness towards the receiver, who checks anyway. It is what keeps a + * chronicle honest about its own size: dropping a payload here rather than + * letting the recipient drop it means the page count says what will actually + * arrive. */ object ChronicleManager { private const val TAG = "ChronicleManager" @@ -93,16 +83,13 @@ object ChronicleManager { recipient: HexKey, chronicleId: String = RandomInstance.bytes(32).toHex(), createdAt: Long = TimeUtils.now(), + kinds: ChronicleKinds = ChronicleEvent.KINDS, ): List> { - val held = signedEventsOf(database, chatRoomId) + val held = signedEventsOf(database, chatRoomId, kinds) - // One rule over both sources: nothing leaves that the recipient could - // not check for themselves. What a drop means depends on where it came - // from, and the two are worth telling apart when reading this log -- - // from the rebuild it is the ordinary case of a member's own rumor - // sitting in the same table as the group's work, and from the record it - // is a row that has drifted from the event it recorded, which nothing - // in this app does on purpose. + // Nothing leaves that the recipient could not check for themselves. A + // drop here is a row that has drifted from the event it recorded, which + // nothing in this app does on purpose. val verified = held.filter { GroupKeyStateEvent.isSignedByRoom(it, chatRoomId) } if (verified.size != held.size) { logger.d( @@ -111,7 +98,7 @@ object ChronicleManager { ) } - val pages = paginate(ChronicleEvent.inApplyOrder(verified)) + val pages = paginate(kinds.inApplyOrder(verified)) if (pages.isEmpty()) { logger.i("Nothing signed to chronicle for room $chatRoomId") return emptyList() @@ -130,6 +117,7 @@ object ChronicleManager { count = pages.size, recipient = recipient, createdAt = createdAt, + kinds = kinds, ) } } @@ -139,9 +127,12 @@ object ChronicleManager { /** * Ask the group for its signed history, if this device holds none of it. * - * Called on entering a room. The condition is deliberately crude -- no - * dialects and no artifacts -- because the three cases it has to catch look - * identical from inside the database and should not be told apart: + * Called on entering a room. Does nothing while [kinds] is empty, which it + * is in this app at the moment -- see the class comment. + * + * The condition is deliberately crude -- nothing of a chroniclable kind on + * file -- because the three cases it has to catch look identical from inside + * the database and should not be told apart: * * - a member added after the work was done, whose invite may be recent; * - a reinstall, whose invite is long past; @@ -162,12 +153,17 @@ object ChronicleManager { database: BennuDatabase, chatRoomId: String, userPublicKey: HexKey, + kinds: ChronicleKinds = ChronicleEvent.KINDS, ): Boolean { + // Quiet while a chronicle may carry nothing: there is no answer worth + // asking for, and asking would put a request on the wire and a line in + // the transcript on every room the member opens. + if (kinds.isEmpty()) return false + val chatRoom = database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom ?: return false if (chatRoom.chronicleRequestedAt != null) return false - val holdsWork = database.mantraDialectDao().getDialectsByChatRoomId(chatRoomId).isNotEmpty() || - database.mantraArtifactDao().getArtifactsByChatRoomId(chatRoomId).isNotEmpty() + val holdsWork = signedEventsOf(database, chatRoomId, kinds).isNotEmpty() if (holdsWork) return false @@ -217,10 +213,11 @@ object ChronicleManager { chatRoomId: String, userPublicKey: HexKey, recipient: HexKey, + kinds: ChronicleKinds = ChronicleEvent.KINDS, ): Int { if (recipient.equals(userPublicKey, ignoreCase = true)) return 0 - val pages = assemble(database, chatRoomId, recipient) + val pages = assemble(database, chatRoomId, recipient, kinds = kinds) if (pages.isEmpty()) { logger.i("Nothing signed here to send ${recipient.take(8)} for $chatRoomId") return 0 @@ -373,6 +370,7 @@ object ChronicleManager { chatRoomId: String, userPublicKey: HexKey, page: Event, + kinds: ChronicleKinds = ChronicleEvent.KINDS, ): Outcome { val recipient = ChronicleEvent( id = page.id, @@ -388,7 +386,7 @@ object ChronicleManager { return Outcome() } - return sweep(database, chatRoomId, userPublicKey) + return sweep(database, chatRoomId, userPublicKey, kinds) } /** @@ -421,6 +419,7 @@ object ChronicleManager { database: BennuDatabase, chatRoomId: String, userPublicKey: HexKey, + kinds: ChronicleKinds = ChronicleEvent.KINDS, ): Outcome { val pages = database.marmotInnerEventDao() .getByChatRoomAndKinds(chatRoomId, listOf(ChronicleEvent.KIND)) @@ -433,7 +432,7 @@ object ChronicleManager { while (true) { pass = Outcome() - pages.forEach { pass += applyPage(database, chatRoomId, it) } + pages.forEach { pass += applyPage(database, chatRoomId, it, kinds) } if (pass.failed == 0 || pass.failed >= previousFailures) { if (pass.failed > 0) { @@ -513,6 +512,7 @@ object ChronicleManager { database: BennuDatabase, chatRoomId: String, stored: MarmotInnerEvent, + kinds: ChronicleKinds, ): Outcome { val payloads = ChronicleEvent.decodePage(stored.content) if (payloads == null) { @@ -530,13 +530,13 @@ object ChronicleManager { var outcome = Outcome() - ChronicleEvent.inApplyOrder(payloads).forEach { payload -> + kinds.inApplyOrder(payloads).forEach { payload -> // The allowlist first, and it is not a formality. Verification admits // an event to the apply path on the strength of the group's // signature, which makes every kind the group has ever signed // replayable by any member at any time -- a GroupKeyStateEvent from // an earlier epoch passes the signature check perfectly. - if (!ChronicleEvent.isChroniclable(payload.kind)) { + if (!kinds.isChroniclable(payload.kind)) { logger.w( "Chronicle page ${stored.id.take(8)} carries kind ${payload.kind}, " + "which a chronicle may not deliver; dropping ${payload.id.take(8)}" @@ -605,224 +605,31 @@ object ChronicleManager { } /** - * Every chroniclable event this device holds for the room: the ones the group - * signed here or sent here, plus anything only the rows still remember. + * Every chroniclable event this device holds for the room, as the group + * signed it. * - * The record comes first because it is the event rather than a reconstruction - * of one, and the rebuild fills the gap behind it -- keyed by id, so an event - * held both ways travels once. A room that upgraded mid-life has both, and - * neither half is complete on its own. - * - * The two disagree only in one direction worth naming. An id the rebuild - * produces that the record does not hold is either work from before the - * table existed, which is the point of the fallback, or a rebuild that has - * gone wrong -- and a wrong rebuild hashes to an id whose signature does not - * verify, so the filter in [assemble] drops it either way rather than - * shipping a payload every receiver reads as a forgery. - * - * Order does not matter at this point; [ChronicleEvent.inApplyOrder] settles it - * afterwards. It is stable within a rank, so a room holding some of its work - * both ways can order two chapters differently from a member holding one way - * only. That costs nothing: pages are idempotent and applied payload by - * payload, and two members already differed by the order their rows were - * written in. + * Order does not matter at this point; [ChronicleKinds.inApplyOrder] settles + * it afterwards. */ private suspend fun signedEventsOf( database: BennuDatabase, chatRoomId: String, - ): List { - val recorded = database.groupSignedEventDao() - .getByChatRoomId(chatRoomId) - // The allowlist, applied to the source that can actually trip it -- - // see the class comment. A key state on file is the room's own, and - // sending it would be handing every member a validly signed - // statement about what the room signs with, replayable forever. - .filter { ChronicleEvent.isChroniclable(it.kind) } - .map { it.toEvent() } - - val onFile = recorded.mapTo(mutableSetOf()) { it.id } - val rebuilt = rebuiltEventsOf(database, chatRoomId).filterNot { it.id in onFile } - - if (rebuilt.isNotEmpty()) { - logger.d( - "Chronicling $chatRoomId: ${recorded.size} event(s) as the group signed them, " + - "${rebuilt.size} rebuilt from rows that predate the record" - ) - } - - return currentTranslationsOnly(recorded + rebuilt) - } - - /** - * Drops every translation of a passage but the one that stands. - * - * The record keeps every event the group ever signed, deliberately -- a - * signature is the group's statement and discarding one is not this table's - * business. The rows do not: `ChatMessage.applyInnerEvent` supersedes a - * translation chunk, deleting the one it replaces, so a passage translated - * three times leaves one row and three events. - * - * That difference reaches the chronicle the moment it is read from the record - * rather than rebuilt from rows, and it compounds: every draft a group ever - * signed would travel in every chronicle it ever sends, for as long as the room - * exists. A chronicle exists to catch a member up on where the group has got - * to, not to hand them its drafting history. - * - * **The rule is the applying arm's, restated rather than approximated**: - * newest by the timestamp the group signed at, id breaking a tie. It has to - * be, or the chronicle would ship one translation as current and the recipient - * would settle on another -- and since both are validly signed, nothing - * downstream would notice the disagreement. - * - * Dropping the drafts is safe precisely because the recipient applies the - * same rule: it is not what keeps them correct, only what stops them being - * sent work they would immediately discard. - * - * A translation naming no passage is left alone rather than grouped with - * others: it is unappliable either way, and letting one stand in for a whole - * passage would let a malformed event suppress a good one. - */ - private fun currentTranslationsOnly(events: List): List { - val translations = events.filter { it.kind == TranslationChunkEvent.KIND } - if (translations.size < 2) return events - - val current = translations - .groupBy { event -> - val translation = TranslationChunkEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig, - ) - - val chapterId = translation.translationChapterId() - val chunkId = translation.chunkId() - - if (chapterId == null || chunkId == null) event.id else "$chapterId/$chunkId" - } - .values - .mapNotNull { candidates -> - candidates.maxWithOrNull(compareBy({ it.createdAt }, { it.id })) - } - .mapTo(mutableSetOf()) { it.id } - - if (current.size != translations.size) { - logger.d( - "Leaving ${translations.size - current.size} superseded translation(s) " + - "out of the chronicle" - ) - } - - return events.filter { it.kind != TranslationChunkEvent.KIND || it.id in current } - } - - /** - * The room's rows, rebuilt into the events they came from. - * - * Walked down the tree rather than queried per kind, because only dialects - * and artifacts have a by-room query and the rest hang off a parent. The walk - * is also what makes an artifact's version label reachable: it is not on the - * artifact row -- see `MantraArtifact.toArtifactEvent` -- and the version it - * went into is one step away here. - * - * Still walked on every chronicle, and by now it contributes nothing in most - * rooms: everything signed or applied since `GroupSignedEvent` existed is on - * file as an event, and [signedEventsOf] discards whatever this rebuilds of - * it. The walk is a handful of indexed queries against a room's own rows, - * and it is what makes a half-upgraded room whole, so it runs rather than - * being skipped when the record looks complete -- there is no way to tell a - * complete record from a partial one without doing it. - * - * It returns everything it can rebuild and lets [signedEventsOf] and the - * verify filter decide what can travel. - * - * Deprecated rather than merely legacy: it is a whole mechanism kept alive - * for a shrinking set of rows, and it takes eight `toXEvent()` methods and a - * ten-case round-trip suite with it. **docs/member-chronicle.md, "Retiring the - * rebuild", is the checklist** -- what goes, what only looks like it goes, - * and the one thing that has to be true before any of it can. - */ - @Deprecated( - "Chronicle fallback for work signed before the GroupSignedEvent table. " + - "Goes when the last pre-v13 install does -- see the removal checklist " + - "in docs/member-chronicle.md." - ) - private suspend fun rebuiltEventsOf( - database: BennuDatabase, - chatRoomId: String, - ): List = buildList { - database.mantraDialectDao().getDialectsByChatRoomId(chatRoomId).forEach { - add(it.toDialectEvent()) - } - - database.mantraArtifactDao().getArtifactsByChatRoomId(chatRoomId).forEach { artifact -> - val versions = database.mantraArtifactVersionDao() - .getArtifactVersionsByArtifactId(artifact.id) - - // The version an artifact starts life with carries the label the - // artifact was signed with, and `ArtifactVersionEvent.initialVersionOf` - // gives it the artifact's own timestamp. The label is still not on the - // artifact row -- `fromArtifactEvent` drops it -- so this is where it - // comes back from. An artifact with no such version is one this device - // cannot rebuild, which is a gap in the chronicle rather than a reason to - // abandon it. - val versionLabel = versions - .firstOrNull { it.createdAt == artifact.createdAt } - ?.versionLabel - - if (versionLabel == null) { - logger.w("Artifact ${artifact.id} has no initial version; leaving it out") - } else { - add(artifact.toArtifactEvent(versionLabel = versionLabel)) - } - - versions.forEach { version -> - add(version.toArtifactVersionEvent()) - - database.mantraChapterDao() - .getChaptersByArtifactVersionId(version.id) - .forEach { chapter -> - add(chapter.toChapterEvent()) - - database.mantraChunkDao() - .getChunksByChapterId(chapter.id) - .forEach { add(it.toChunkEvent()) } - } - - database.mantraTranslationArtifactVersionDao() - .getTranslationsByArtifactVersionId(version.id) - .forEach { translationVersion -> - add(translationVersion.toTranslationArtifactVersionEvent()) - - database.mantraTranslationChapterDao() - .getTranslationChaptersByTranslationArtifactVersionId(translationVersion.id) - .forEach { translationChapter -> - add(translationChapter.toTranslationChapterEvent()) - - // Only the translation that survived supersession - // is here to be found: retranslating a passage - // changes the text and so the event id, and the - // arm that applies one drops what it replaces. So - // a chronicle carries a group's current answer to - // each passage rather than its drafts, which is - // the same thing every other member holds. - database.mantraTranslationChunkDao() - .getTranslationChunksByTranslationChapterId(translationChapter.id) - .forEach { add(it.toTranslationChunkEvent()) } - } - } - } - } - } + kinds: ChronicleKinds, + ): List = database.groupSignedEventDao() + .getByChatRoomId(chatRoomId) + // The allowlist, applied to the source that can actually trip it -- + // see the class comment. A key state on file is the room's own, and + // sending it would be handing every member a validly signed + // statement about what the room signs with, replayable forever. + .filter { kinds.isChroniclable(it.kind) } + .map { it.toEvent() } /** * [events] cut into pages that fit, keeping the order they arrive in. * * Greedy: fill a page until the next event would cross either cap. Both are - * checked because they bind different chronicles -- a room of one-line dialects - * hits the count first and a room of chapters hits the bytes. + * checked because they bind different chronicles -- a room of one-line events + * hits the count first and a room of long ones hits the bytes. * * The bytes are the page's *escaped* bytes -- what it will occupy as the * `content` of the Marmot app event that carries it, which is what a @@ -832,7 +639,7 @@ object ChronicleManager { * * An event too large to share a page with anything is given one of its own. * One too large for even that is dropped with a log rather than failing the - * chronicle: a chapter nobody can chronicle is a hole, and a member who gets + * chronicle: an event nobody can chronicle is a hole, and a member who gets * nothing at all is a bigger one. */ private fun paginate(events: List): List> { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEvent.kt index 7c4f49bc..db522049 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEvent.kt @@ -14,14 +14,6 @@ import com.machankura.bennu.compose.network.serialization.CommonJson import com.machankura.bennu.compose.nostr.chronicle.tags.ChronicleIdTag import com.machankura.bennu.compose.nostr.chronicle.tags.ChroniclePageTag import com.machankura.bennu.compose.nostr.chronicle.tags.ChronicleRecipientTag -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent /** * 30327 @@ -45,16 +37,7 @@ import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent * deliberately does not do: it never carries the chat, and it cannot make its * recipient able to *sign* anything. * - * ### Why not a [com.machankura.bennu.compose.nostr.nip30303.SubmissionEvent] each - * - * The envelope fits and the meaning does not. A submission is an *act* -- this - * member is putting this event in front of this group -- and a chronicle asserts - * nothing; it re-delivers what the group already agreed. On one kind a - * four-hundred-event backfill is indistinguishable from four hundred new - * submissions and every device has to guess which it is looking at. It would - * also be one inner event and one kind:445 per payload, where a page is one, and - * the submission arm of `ChatMessage.applyInnerEvent` files a chat line per - * payload, which a chronicle must not. + * It carries nothing in this app at the moment -- see [KINDS]. */ @Immutable class ChronicleEvent( @@ -88,18 +71,12 @@ class ChronicleEvent( companion object { /** * Sits past `GroupKeyStateEvent` at 30326, in the Marmot inner-event - * space it shares with the nip30303 document kinds and the FROST signing - * family. + * space it shares with the FROST signing family. * - * 30313 was free next to the document kinds and is not used, on - * `FrostSigningEvents`' own advice: the DKG's 30310-30316 overlap that - * range, and were told apart only by which transport carried them until a - * subgroup's ceremony moved into its parent's Marmot room and they - * collided. This family took numbers nobody else uses instead. - * - * It is also the right neighbourhood on the merits. A chronicle is not a - * document kind; it is a statement about the record, which is what a key - * state is too. + * 30313 is not used, on `FrostSigningEvents`' own advice: the DKG's + * 30310-30316 sit there, and once collided with document kinds that + * shared their numbers. This family took numbers nobody else uses + * instead. */ const val KIND: Kind = 30327 @@ -109,7 +86,7 @@ class ChronicleEvent( * The most JSON one page may carry. * * A byte cap rather than a count alone, because the payloads vary by two - * orders of magnitude -- a chunk is a paragraph, an artifact is a URL. + * orders of magnitude -- a paragraph of text against a single URL. * Sized so the finished kind:445 clears the tightest relay limits with * room for the MLS framing and the NIP-44 expansion that sit outside it; * measure it against a real one rather than trusting the arithmetic. @@ -130,8 +107,8 @@ class ChronicleEvent( * The most payloads one page may carry. * * The byte cap bounds the transport; this bounds the receiver's *work*, - * and they are not the same limit -- 64 KB of one-line dialects is a lot - * more signature verifies than 64 KB of chapters. + * and they are not the same limit -- 64 KB of one-line events is a lot + * more signature verifies than 64 KB of long ones. * * **Sized under what the byte cap allows, or it would never fire.** An * event carries a 64-character id, a 64-character pubkey and a @@ -154,82 +131,30 @@ class ChronicleEvent( const val MAX_PAGE_EVENTS = 96 /** - * The kinds a chronicle may carry, in the order they have to be applied. + * The kinds a chronicle may carry in this app: **none, at the moment.** * - * One list doing both jobs, because a separate allowlist is one more - * thing that can disagree with the order it is applied in. + * It was built to hand a late member the group's signed documents -- + * dialects, artifacts, chapters and their translations -- and those kinds + * were removed with the screens that made them (docs/ceremony-creation.md, + * Phase 7). Everything else the group signs is left out on purpose: * - * **The order is Room's, not nostr's.** Every one of these has a foreign - * key on the one before it, so a chronicle applied out of order is a - * constraint violation rather than a wrong answer. Kind order is not - * dependency order and never was -- a translation chapter (30308) hangs - * off a translation artifact version (30306) which hangs off an artifact - * version (30301) -- so this is a list rather than a `sortedBy { kind }`. + * - a `GroupKeyStateEvent` or a subgroup's birth certificate is a validly + * signed statement about the group that anyone holding a copy could + * replay -- see [ChronicleKinds]; + * - posts, profiles, relay lists and wallet statements have their own + * ways to a member who joins late, or none worth a chronicle. * - * **It is an allowlist first.** Verification admits an event to the apply - * path on the strength of the group's signature, which makes every kind - * the group has ever signed replayable by any member at any time. A - * `GroupKeyStateEvent` is group-signed and passes verification perfectly, - * so a chronicle carrying an old one is a validly signed statement about - * what the room signs with, replayed by whoever kept a copy. Nothing but - * this list stops it. - * - * ### What is missing from it, and why - * - * **Only kinds the group actually signs can be here**, because a chronicle - * that cannot be verified is one that has to be believed. Six of the - * thirteen nip30303 kinds reach a signing session; the rest travel as - * rumors -- empty signature, member author, vouched for by the MLS frame - * they arrived in and by nothing that survives leaving it. - * - * Left out for that reason: - * - * - `TranslationEvent` (30311). Nothing builds one; the inbound arm - * exists and no producer does. - * - The contributor lists (30305, 30307, 30310). `applyInnerEvent` has - * no arm that writes a row for any of them, so chronicling them would - * cost bytes and restore nothing. - * - * Two kinds were on that list and are not any more, because the app - * stopped leaving them unsigned. `ArtifactVersionEvent` (30301) used to be - * derived from the signed artifact on arrival, and is now the second item - * of the batch that carries it. `TranslationChunkEvent` (30309) -- the - * translated text itself -- used to be submitted as its author's rumor, - * and is now proposed to the group like everything else. Both are - * therefore checkable, and a chronicle that left them out would hand a new - * member the whole structure and none of the prose. + * So the machinery stays and carries nothing: with an empty list a device + * asks for no chronicle, sends none, and applies nothing from one that an + * older build sends -- see `ChronicleManager`. Adding a kind back is a + * decision that belongs here, with the reason it is safe to replay. */ - private val APPLY_ORDER: List = listOf( - DialectEvent.KIND, - ArtifactEvent.KIND, - ArtifactVersionEvent.KIND, - ChapterEvent.KIND, - ChunkEvent.KIND, - TranslationArtifactVersionEvent.KIND, - TranslationChapterEvent.KIND, - TranslationChunkEvent.KIND, - ) + val KINDS: ChronicleKinds = ChronicleKinds.NONE - /** Every kind a chronicle may carry. */ - val CHRONICLABLE_KINDS: Set = APPLY_ORDER.toSet() + /** Every kind a chronicle may carry in this app. */ + val CHRONICLABLE_KINDS: Set = KINDS.all - /** - * Where [kind] sits in dependency order, or null if a chronicle may not - * carry it at all. - */ - fun applyRank(kind: Kind): Int? = APPLY_ORDER.indexOf(kind).takeIf { it >= 0 } - - fun isChroniclable(kind: Kind): Boolean = kind in CHRONICLABLE_KINDS - - /** - * [payloads] in dependency order, so a page applies front to back. - * - * Stable within a rank: two chapters of one version have no order between - * them and keeping the caller's is one less thing that varies between two - * members assembling the same chronicle. - */ - fun inApplyOrder(payloads: List): List = - payloads.sortedBy { applyRank(it.kind) ?: Int.MAX_VALUE } + fun isChroniclable(kind: Kind): Boolean = KINDS.isChroniclable(kind) /** * The bytes [json] occupies once it is the `content` of a Marmot app event -- @@ -315,6 +240,7 @@ class ChronicleEvent( count: Int, recipient: HexKey, createdAt: Long = TimeUtils.now(), + kinds: ChronicleKinds = KINDS, initializer: TagArrayBuilder.() -> Unit = {}, ): EventTemplate { require(payloads.isNotEmpty()) { "A chronicle page carries at least one event" } @@ -322,7 +248,7 @@ class ChronicleEvent( "A chronicle page carries at most $MAX_PAGE_EVENTS events, not ${payloads.size}" } payloads.forEach { - require(isChroniclable(it.kind)) { "A chronicle may not carry kind ${it.kind}" } + require(kinds.isChroniclable(it.kind)) { "A chronicle may not carry kind ${it.kind}" } } val content = encodePage(payloads) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleKinds.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleKinds.kt new file mode 100644 index 00000000..2de65eb4 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleKinds.kt @@ -0,0 +1,51 @@ +package com.machankura.bennu.compose.nostr.chronicle + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.Kind + +/** + * The kinds a chronicle may carry, in the order they have to be applied. + * + * One list doing both jobs, because a separate allowlist is one more thing that + * can disagree with the order it is applied in. The order is the database's, not + * nostr's: where one kind's rows hang off another's, the one they hang off comes + * first, so a page applies front to back. + * + * **It is an allowlist first.** Verification admits an event to the apply path on + * the strength of the group's signature, which makes every kind the group has + * ever signed replayable by any member at any time. A `GroupKeyStateEvent` is + * group-signed and passes verification perfectly, so a chronicle carrying an old + * one is a validly signed statement about what the room signs with, replayed by + * whoever kept a copy. Nothing but this list stops it. + * + * A value rather than a constant so the machinery can be exercised without + * making anything chroniclable in the app: the app's own list is + * [ChronicleEvent.KINDS], and the tests hand in theirs. + */ +class ChronicleKinds(private val applyOrder: List) { + + /** Every kind a chronicle may carry. */ + val all: Set = applyOrder.toSet() + + /** A chronicle that may carry nothing asks for nothing and sends nothing. */ + fun isEmpty(): Boolean = applyOrder.isEmpty() + + /** Where [kind] sits in apply order, or null if a chronicle may not carry it at all. */ + fun applyRank(kind: Kind): Int? = applyOrder.indexOf(kind).takeIf { it >= 0 } + + fun isChroniclable(kind: Kind): Boolean = kind in all + + /** + * [payloads] in apply order, so a page applies front to back. + * + * Stable within a rank: two events of one kind have no order between them, + * and keeping the caller's is one less thing that varies between two members + * assembling the same chronicle. + */ + fun inApplyOrder(payloads: List): List = + payloads.sortedBy { applyRank(it.kind) ?: Int.MAX_VALUE } + + companion object { + val NONE = ChronicleKinds(emptyList()) + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt index 3bf966d2..19e2605f 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt @@ -8,19 +8,12 @@ import com.machankura.bennu.compose.nostr.GroupRelaySet import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent /** * An event a group is being asked to sign, said in words. * * Shown as the thing rather than as an event: a member deciding whether to sign - * is deciding about a dialect or an artifact, and "kind 30304" answers a + * is deciding about a profile or a relay list, and "kind 10002" answers a * question nobody asked. The raw kind stays for anything not recognised, since * refusing to describe an event is better than describing it wrongly. * @@ -36,99 +29,6 @@ object ProposedEvent { data class Summary(val label: String, val detail: String) fun summarize(event: Event): Summary = when (event.kind) { - DialectEvent.KIND -> Summary( - label = "New dialect", - detail = DialectEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ).let { dialect -> - listOfNotNull(dialect.name(), dialect.country(), dialect.language()) - .joinToString(" · ") - } - ) - - ArtifactEvent.KIND -> Summary( - label = "New artifact", - detail = ArtifactEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ).let { artifact -> - // The url is the substance of an artifact -- signing one is putting - // the group's name to what it points at -- so it goes next to the - // name rather than being left for the detail screen afterwards. - listOfNotNull(event.content, artifact.versionLabel(), artifact.url()) - .joinToString(" · ") - } - ) - - // Signed alongside the artifact it belongs to rather than on its own, - // so this is almost always read as the second line of a batch of two. - // Named after the artifact rather than the label, because the label is - // the whole of the content and would otherwise be said twice. - ArtifactVersionEvent.KIND -> Summary( - label = "Version of the artifact", - detail = event.content.ifBlank { "Unlabelled" } - ) - - ChapterEvent.KIND -> Summary( - label = "New chapter", - detail = ChapterEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ).let { chapter -> - // The text is the substance of a chapter -- signing one is putting - // the group's name to what everybody will translate from -- but it - // is a whole chapter, so its size stands in for it here. The chunk - // count says how many of the batch's other items came out of this - // text, which is the rest of what is being signed. - val chunkCount = chapter.originalText()?.let { Markdown.splitParagraphs(it).size } - - listOfNotNull( - chapter.name(), - chapter.wordCount()?.let { "$it words" }, - chunkCount?.let { "$it ${if (it == 1) "chunk" else "chunks"}" } - ).joinToString(" · ") - } - ) - - TranslationArtifactVersionEvent.KIND -> Summary( - label = "New translation", - detail = TranslationArtifactVersionEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ).let { translation -> - // Named after the dialect it is into, which is the whole of what is - // being decided: everything else in the batch follows from it. - listOfNotNull(translation.name(), translation.visibility(), translation.license()) - .joinToString(" · ") - } - ) - - TranslationChapterEvent.KIND -> Summary( - label = "Chapter of the translation", - detail = TranslationChapterEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ).let { chapter -> - // A translation chapter is a place for translated chunks to hang - // off, so there is nothing in it to read -- only where in the work - // it sits. Counted from one, the way the chapter list reads. - chapter.index()?.let { "Chapter ${it + 1}" } ?: "Position unknown" - } - ) - - TranslationChunkEvent.KIND -> Summary( - label = "Translated passage", - detail = TranslationChunkEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ).let { chunk -> - // The translation itself is the whole of what is being decided -- - // a member signing this is agreeing that these words say what the - // original said -- so it is the detail rather than a count of it. - // Where in the chapter it sits comes first, since that is what - // says which passage to read it against. - listOfNotNull( - chunk.index()?.let { "Passage ${it + 1}" }, - event.content - ).joinToString(" · ") - } - ) - // The one thing a group signs that is about the group rather than about // its work, and the only one a member sees before the room has done // anything. Shown as the path and the ceremony rather than as the key: diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/MarmotPayloadBoundsTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/MarmotPayloadBoundsTest.kt index a53528c4..39f48fa2 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/MarmotPayloadBoundsTest.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/MarmotPayloadBoundsTest.kt @@ -11,8 +11,8 @@ import com.vitorpamplona.quartz.nip01Core.tags.people.PTag import com.vitorpamplona.quartz.nip17Dm.messages.ChatMessageEvent import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler import com.machankura.bennu.compose.nostr.chronicle.ChronicleEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent +import com.machankura.bennu.compose.nostr.chronicle.TEST_KINDS +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull @@ -52,6 +52,10 @@ class MarmotPayloadBoundsTest { count = 1, recipient = recipient, createdAt = at, + // The app's own list carries nothing at the moment, so the page is + // built over the chronicle tests' list: what is under test is the + // envelope's size, not which kinds fill it. + kinds = TEST_KINDS, ) // From the template's fields, as the outbound queue assembles every rumor from // the row's: the typed template is not what goes through RumorAssembler. @@ -74,7 +78,7 @@ class MarmotPayloadBoundsTest { @Test fun `a chronicle page of the most smallest payloads is a conformant app event`() { val payloads = (0 until ChronicleEvent.MAX_PAGE_EVENTS).map { - signedPayload(DialectEvent.KIND, content = "d", id = it.toString().padStart(64, '0')) + signedPayload(TextNoteEvent.KIND, content = "d", id = it.toString().padStart(64, '0')) } assertConformant(chronicleAppEvent(payloads)) @@ -90,7 +94,7 @@ class MarmotPayloadBoundsTest { while (length < 4_096) append("{\"k\":\"v\",\"n\":[\"a\",\"b\"]}") } val payloads = (0 until ChronicleEvent.MAX_PAGE_EVENTS).map { - signedPayload(ChunkEvent.KIND, content = dense, id = it.toString().padStart(64, '0')) + signedPayload(TextNoteEvent.KIND, content = dense, id = it.toString().padStart(64, '0')) } // As many dense payloads as the byte cap admits, measured the way the packer // measures them: by the bytes the page occupies once escaped into the app diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEventTest.kt index 22542fb3..bb56ec7d 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEventTest.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEventTest.kt @@ -14,19 +14,10 @@ import com.machankura.bennu.compose.nostr.chronicle.tags.ChronicleRecipientTag import com.machankura.bennu.compose.nostr.frost.FrostSigningEvents import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.nostr.nip30303.SubmissionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionContributorListEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterContributorListEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationContributorListEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationEvent +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent /** * The envelope a chronicle travels in: what it carries, what it refuses, and the @@ -35,6 +26,10 @@ import com.machankura.bennu.compose.nostr.nip30303.TranslationEvent * Nothing here verifies a signature -- that is `GroupKeyStateTest`'s half, and * `ChronicleManager`'s at apply time. What these cover is the framing, and the two * bounds a page has to hold whoever sent it. + * + * The app's own list of kinds is empty, so what a chronicle may carry and the + * order it applies in are tested against [TEST_KINDS]; the framing and the caps + * do not care what kind a payload is. */ class ChronicleEventTest { private val recipient = "d".repeat(64) @@ -59,8 +54,8 @@ class ChronicleEventTest { @Test fun `what is encoded is what comes back whole`() { val events = listOf( - payload(DialectEvent.KIND, "isiZulu"), - payload(ArtifactEvent.KIND, "an artifact"), + payload(MetadataEvent.KIND, "{\"name\":\"Ekklesia\"}"), + payload(TextNoteEvent.KIND, "a post"), ) val decoded = ChronicleEvent.decodePage(ChronicleEvent.encodePage(events)) @@ -81,7 +76,7 @@ class ChronicleEventTest { // object for a batch of one so that builds predating batching can read // it. Both chronicle kinds are new, so there is no such build and no reason // to carry the second shape. - val encoded = ChronicleEvent.encodePage(listOf(payload(DialectEvent.KIND))) + val encoded = ChronicleEvent.encodePage(listOf(payload(TextNoteEvent.KIND))) assertTrue(encoded.startsWith("["), "a page is always an array") assertTrue(encoded.endsWith("]")) @@ -90,7 +85,7 @@ class ChronicleEventTest { @Test fun `a page that is not an array is not a page`() { - assertNull(ChronicleEvent.decodePage(payload(DialectEvent.KIND).toJson())) + assertNull(ChronicleEvent.decodePage(payload(TextNoteEvent.KIND).toJson())) assertNull(ChronicleEvent.decodePage("")) assertNull(ChronicleEvent.decodePage("not json")) assertNull(ChronicleEvent.decodePage("[unclosed")) @@ -110,7 +105,7 @@ class ChronicleEventTest { // whose signature does not verify is a well-framed page with one bad // event in it, and dropping its honest neighbours would let one forgery // deny an entire chronicle. - val good = payload(DialectEvent.KIND) + val good = payload(TextNoteEvent.KIND) assertNull(ChronicleEvent.decodePage("[${good.toJson()},\"not an event\"]")) assertNull(ChronicleEvent.decodePage("[\"not an event\",${good.toJson()}]")) @@ -121,7 +116,7 @@ class ChronicleEventTest { @Test fun `a page over the event cap is refused on the way in`() { val overCap = (0..ChronicleEvent.MAX_PAGE_EVENTS).map { - payload(DialectEvent.KIND, id = it.toString().padStart(64, '0')) + payload(TextNoteEvent.KIND, id = it.toString().padStart(64, '0')) } assertEquals(ChronicleEvent.MAX_PAGE_EVENTS + 1, overCap.size) @@ -139,7 +134,7 @@ class ChronicleEventTest { // runs, and the page-over-the-cap test above passes for the wrong reason. // Both caps have to be re-sized together; this is what says so. val atCap = (0 until ChronicleEvent.MAX_PAGE_EVENTS).map { - payload(DialectEvent.KIND, id = it.toString().padStart(64, '0')) + payload(TextNoteEvent.KIND, id = it.toString().padStart(64, '0')) } val page = ChronicleEvent.encodePage(atCap) @@ -157,7 +152,7 @@ class ChronicleEventTest { // work a remote party can ask this device to do. A chronicle is the second // place in this protocol where somebody else sets that size. val huge = ChronicleEvent.encodePage( - listOf(payload(DialectEvent.KIND, content = "x".repeat(ChronicleEvent.MAX_PAGE_BYTES))) + listOf(payload(TextNoteEvent.KIND, content = "x".repeat(ChronicleEvent.MAX_PAGE_BYTES))) ) assertTrue(huge.encodeToByteArray().size > ChronicleEvent.MAX_PAGE_BYTES) @@ -170,7 +165,7 @@ class ChronicleEventTest { // this were measured in characters the cap would let through up to four // times what it says. val wide = "世".repeat(ChronicleEvent.MAX_PAGE_BYTES / 2) - val page = ChronicleEvent.encodePage(listOf(payload(DialectEvent.KIND, content = wide))) + val page = ChronicleEvent.encodePage(listOf(payload(TextNoteEvent.KIND, content = wide))) assertTrue(page.length < ChronicleEvent.MAX_PAGE_BYTES) assertTrue(page.encodeToByteArray().size > ChronicleEvent.MAX_PAGE_BYTES) @@ -180,42 +175,24 @@ class ChronicleEventTest { // ---- What a chronicle may carry --------------------------------------- @Test - fun `the allowlist is every kind the group signs and only those`() { + fun `a kind set admits what it lists and nothing else`() { listOf( - DialectEvent.KIND, - ArtifactEvent.KIND, - ArtifactVersionEvent.KIND, - ChapterEvent.KIND, - ChunkEvent.KIND, - TranslationArtifactVersionEvent.KIND, - TranslationChapterEvent.KIND, - TranslationChunkEvent.KIND, - ).forEach { assertTrue(ChronicleEvent.isChroniclable(it), "kind $it should be chroniclable") } + AdvertisedRelayListEvent.KIND, + MetadataEvent.KIND, + TextNoteEvent.KIND, + ).forEach { assertTrue(TEST_KINDS.isChroniclable(it), "kind $it should be chroniclable") } - assertEquals(8, ChronicleEvent.CHRONICLABLE_KINDS.size) - } + assertEquals(3, TEST_KINDS.all.size) + assertFalse(TEST_KINDS.isEmpty()) - @Test - fun `the translated text is chroniclable now that the group signs it`() { - // Worth its own case because it was the feature's headline limitation for - // as long as `saveTranslation` wrote the row and queued the member's own - // rumor. A chronicle can only carry what the receiver can check, so a - // translation nobody signed could not travel, and a new member got the - // whole structure and none of the prose. - assertTrue(ChronicleEvent.isChroniclable(TranslationChunkEvent.KIND)) + // Group-signed, with an arm in applyInnerEvent, and still refused: being + // signed is not what earns a kind its place, being on the list is. + assertFalse(TEST_KINDS.isChroniclable(GroupWalletStatementEvent.KIND)) + assertNull(TEST_KINDS.applyRank(GroupWalletStatementEvent.KIND)) - // Same shape, same fix: the version an artifact starts life with used to - // be derived on arrival, so it was authored by the group with no - // signature to show for it. It is the second item of the artifact's batch - // now. - assertTrue(ChronicleEvent.isChroniclable(ArtifactVersionEvent.KIND)) - } - - @Test - fun `the kinds nobody signs are still left out`() { - // Nothing builds one of these at all; the inbound arm exists and no - // producer does. - assertFalse(ChronicleEvent.isChroniclable(TranslationEvent.KIND)) + // And the empty list admits nothing at all. + assertTrue(ChronicleKinds.NONE.isEmpty()) + assertFalse(ChronicleKinds.NONE.isChroniclable(TextNoteEvent.KIND)) } @Test @@ -226,7 +203,8 @@ class ChronicleEventTest { // validly signed statement about what the room signs with, replayed by // whoever kept a copy. Nothing but this stops it. assertFalse(ChronicleEvent.isChroniclable(GroupKeyStateEvent.KIND)) - assertNull(ChronicleEvent.applyRank(GroupKeyStateEvent.KIND)) + assertFalse(TEST_KINDS.isChroniclable(GroupKeyStateEvent.KIND)) + assertNull(TEST_KINDS.applyRank(GroupKeyStateEvent.KIND)) } @Test @@ -244,12 +222,14 @@ class ChronicleEventTest { // chronicle may carry an event its own key did not sign, which no // chroniclable kind does. See docs/subgroups.md. assertFalse(ChronicleEvent.isChroniclable(SubgroupBirthCertificateEvent.KIND)) - assertNull(ChronicleEvent.applyRank(SubgroupBirthCertificateEvent.KIND)) + assertFalse(TEST_KINDS.isChroniclable(SubgroupBirthCertificateEvent.KIND)) + assertNull(TEST_KINDS.applyRank(SubgroupBirthCertificateEvent.KIND)) } @Test - fun `a chronicle carries documents not envelopes or protocol`() { - assertFalse(ChronicleEvent.isChroniclable(SubmissionEvent.KIND)) + fun `a chronicle carries the group's work not envelopes or protocol`() { + // Against the app's own list, which is the one that will grow: the day a + // kind is added back, none of these may come with it. assertFalse(ChronicleEvent.isChroniclable(ChronicleEvent.KIND)) assertFalse(ChronicleEvent.isChroniclable(ChronicleRequestEvent.KIND)) FrostSigningEvents.ALL.forEach { @@ -257,86 +237,57 @@ class ChronicleEventTest { } } - @Test - fun `the contributor lists are left out while nothing applies them`() { - // Not an oversight. ChatMessage.applyInnerEvent has no arm that writes a - // row for any of these, so chronicling them would cost bytes and restore - // nothing. They belong in the list on the day that changes. - assertFalse(ChronicleEvent.isChroniclable(TranslationArtifactVersionContributorListEvent.KIND)) - assertFalse(ChronicleEvent.isChroniclable(TranslationChapterContributorListEvent.KIND)) - assertFalse(ChronicleEvent.isChroniclable(TranslationContributorListEvent.KIND)) - } - // ---- Dependency order ------------------------------------------------ @Test - fun `the order is the foreign keys not the kind numbers`() { - fun rank(kind: Int) = assertNotNull(ChronicleEvent.applyRank(kind), "kind $kind has no rank") + fun `the order is the list's not the kind numbers'`() { + fun rank(kind: Int) = assertNotNull(TEST_KINDS.applyRank(kind), "kind $kind has no rank") - // Every one of these is a foreign key in Room, so a chronicle applied the - // other way round is a constraint violation rather than a wrong answer. - assertTrue(rank(DialectEvent.KIND) < rank(ArtifactEvent.KIND)) - assertTrue(rank(ArtifactEvent.KIND) < rank(ArtifactVersionEvent.KIND)) - assertTrue(rank(ArtifactVersionEvent.KIND) < rank(ChapterEvent.KIND)) - assertTrue(rank(ChapterEvent.KIND) < rank(ChunkEvent.KIND)) - assertTrue(rank(ArtifactVersionEvent.KIND) < rank(TranslationArtifactVersionEvent.KIND)) - assertTrue(rank(DialectEvent.KIND) < rank(TranslationArtifactVersionEvent.KIND)) - assertTrue(rank(TranslationArtifactVersionEvent.KIND) < rank(TranslationChapterEvent.KIND)) - assertTrue(rank(ChapterEvent.KIND) < rank(TranslationChapterEvent.KIND)) - - // A translated chunk hangs off both sides at once -- the source chunk it - // translates and the translation chapter it sits in -- so it is last. - assertTrue(rank(ChunkEvent.KIND) < rank(TranslationChunkEvent.KIND)) - assertTrue(rank(TranslationChapterEvent.KIND) < rank(TranslationChunkEvent.KIND)) + // In the app the list is the database's foreign keys, so a chronicle + // applied the other way round is a constraint violation rather than a + // wrong answer. Here it is only the test's own order, which is enough to + // show the machinery follows the list. + assertTrue(rank(AdvertisedRelayListEvent.KIND) < rank(MetadataEvent.KIND)) + assertTrue(rank(MetadataEvent.KIND) < rank(TextNoteEvent.KIND)) // And the numbers really do disagree with the order, which is why this is // a list rather than a sortedBy { kind }. - assertTrue(DialectEvent.KIND > ArtifactEvent.KIND) - assertTrue(rank(DialectEvent.KIND) < rank(ArtifactEvent.KIND)) + assertTrue(AdvertisedRelayListEvent.KIND > MetadataEvent.KIND) + assertTrue(rank(AdvertisedRelayListEvent.KIND) < rank(MetadataEvent.KIND)) } @Test - fun `sorting a page puts what is referenced before what refers to it`() { + fun `sorting a page puts it in the list's order`() { val jumbled = listOf( - payload(TranslationChunkEvent.KIND), - payload(TranslationChapterEvent.KIND), - payload(ChunkEvent.KIND), - payload(DialectEvent.KIND), - payload(TranslationArtifactVersionEvent.KIND), - payload(ChapterEvent.KIND), - payload(ArtifactVersionEvent.KIND), - payload(ArtifactEvent.KIND), + payload(TextNoteEvent.KIND), + payload(MetadataEvent.KIND), + payload(AdvertisedRelayListEvent.KIND), ) assertEquals( listOf( - DialectEvent.KIND, - ArtifactEvent.KIND, - ArtifactVersionEvent.KIND, - ChapterEvent.KIND, - ChunkEvent.KIND, - TranslationArtifactVersionEvent.KIND, - TranslationChapterEvent.KIND, - TranslationChunkEvent.KIND, + AdvertisedRelayListEvent.KIND, + MetadataEvent.KIND, + TextNoteEvent.KIND, ), - ChronicleEvent.inApplyOrder(jumbled).map { it.kind } + TEST_KINDS.inApplyOrder(jumbled).map { it.kind } ) } @Test fun `two of a kind keep the order they were handed in`() { - // Nothing orders two chapters of one version, and keeping the caller's - // order is one less thing that differs between two members assembling the - // same chronicle. - val chapters = listOf( - payload(ChapterEvent.KIND, "one", id = "1".repeat(64)), - payload(ChapterEvent.KIND, "two", id = "2".repeat(64)), - payload(ChapterEvent.KIND, "three", id = "3".repeat(64)), + // Nothing orders two posts by the group, and keeping the caller's order + // is one less thing that differs between two members assembling the same + // chronicle. + val posts = listOf( + payload(TextNoteEvent.KIND, "one", id = "1".repeat(64)), + payload(TextNoteEvent.KIND, "two", id = "2".repeat(64)), + payload(TextNoteEvent.KIND, "three", id = "3".repeat(64)), ) assertEquals( listOf("one", "two", "three"), - ChronicleEvent.inApplyOrder(chapters).map { it.content } + TEST_KINDS.inApplyOrder(posts).map { it.content } ) } @@ -345,12 +296,13 @@ class ChronicleEventTest { @Test fun `a page says which chronicle it is where in it and who for`() { val template = ChronicleEvent.build( - payloads = listOf(payload(DialectEvent.KIND)), + payloads = listOf(payload(TextNoteEvent.KIND)), chronicleId = chronicleId, index = 2, count = 5, recipient = recipient, - createdAt = 1_700_000_100L + createdAt = 1_700_000_100L, + kinds = TEST_KINDS, ) val readBack = ChronicleEvent( @@ -406,17 +358,18 @@ class ChronicleEventTest { // security -- the inbound one is the boundary -- but a page nobody can // read back is better failed where it was made. assertFailsWith { - ChronicleEvent.build(emptyList(), chronicleId, 0, 1, recipient) + ChronicleEvent.build(emptyList(), chronicleId, 0, 1, recipient, kinds = TEST_KINDS) } assertFailsWith { ChronicleEvent.build( payloads = (0..ChronicleEvent.MAX_PAGE_EVENTS).map { - payload(DialectEvent.KIND, id = it.toString().padStart(64, '0')) + payload(TextNoteEvent.KIND, id = it.toString().padStart(64, '0')) }, chronicleId = chronicleId, index = 0, count = 1, - recipient = recipient + recipient = recipient, + kinds = TEST_KINDS, ) } assertFailsWith { @@ -425,18 +378,36 @@ class ChronicleEventTest { chronicleId = chronicleId, index = 0, count = 1, - recipient = recipient + recipient = recipient, + kinds = TEST_KINDS, ) } assertFailsWith { ChronicleEvent.build( payloads = listOf( - payload(DialectEvent.KIND, content = "x".repeat(ChronicleEvent.MAX_PAGE_BYTES)) + payload(TextNoteEvent.KIND, content = "x".repeat(ChronicleEvent.MAX_PAGE_BYTES)) ), chronicleId = chronicleId, index = 0, count = 1, - recipient = recipient + recipient = recipient, + kinds = TEST_KINDS, + ) + } + } + + @Test + fun `the app's own list builds no page at all`() { + // The outbound half of the app carrying nothing: a payload the test list + // admits is refused under the default, so nothing that assembles a page + // without naming its kinds can put one on the wire. + assertFailsWith { + ChronicleEvent.build( + payloads = listOf(payload(TextNoteEvent.KIND)), + chronicleId = chronicleId, + index = 0, + count = 1, + recipient = recipient, ) } } diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleRoundTripTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleRoundTripTest.kt deleted file mode 100644 index 78e88c4c..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleRoundTripTest.kt +++ /dev/null @@ -1,422 +0,0 @@ -package com.machankura.bennu.compose.nostr.chronicle - -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import fr.acinq.bitcoin.crypto.frost.TweakCache -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNotNull -import kotlin.test.assertTrue -import com.machankura.bennu.compose.database.model.MantraArtifact -import com.machankura.bennu.compose.database.model.MantraArtifactVersion -import com.machankura.bennu.compose.database.model.MantraChapter -import com.machankura.bennu.compose.database.model.MantraChunk -import com.machankura.bennu.compose.database.model.MantraDialect -import com.machankura.bennu.compose.database.model.MantraTranslationArtifactVersion -import com.machankura.bennu.compose.database.model.MantraTranslationChapter -import com.machankura.bennu.compose.database.model.MantraTranslationChunk -import com.machankura.bennu.compose.extensions.toHex -import com.machankura.bennu.compose.managers.SharedKeyDerivation -import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent - -/** - * The assumption the chronicle's *fallback* rests on: a row can be turned back - * into the event the group signed. - * - * Signed events used to be stored only as rows. `FrostSigningManager.complete` - * applied one and what survived was a `Mantra*` row, so a chronicle had to - * rebuild each payload with `toXEvent()` and hope it came out byte-identical -- - * and if it did not, the id changed, the signature no longer covered it, and - * every receiver dropped the payload as a forgery, silently, one kind at a time. - * - * That is what the round-trip note on each `toXEvent` claims and what nothing - * asserted until this ran. Every kind in `ChronicleEvent.CHRONICLABLE_KINDS` is - * checked here against a real FROST quorum, because a signature that verifies is - * the only evidence that the rebuild is faithful -- comparing fields would only - * prove the test and the code agree about which fields matter. - * - * ### Deprecated, along with what it guards - * - * `GroupSignedEvent` keeps the events now, and `ChronicleManager.assemble` reads - * them; the rebuild survives only for work signed before that table existed, and - * so does this. Nothing else covers the `toXEvent()` methods, so **this whole - * file goes when they do** -- see "Retiring the rebuild" in - * docs/member-chronicle.md. Until then a kind that fails here cannot be chronicled - * *from a row*, whatever the allowlist says, which for a pre-v13 room is the - * same thing as not at all. - */ -class ChronicleRoundTripTest { - private val participants = 3 - private val threshold = 2 - - /** Stands in for a completed ceremony; nothing here is about the DKG. */ - private val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") - ), - nParticipants = participants, - threshold = threshold - ) - - private val room: SharedKeyDerivation.Derived = SharedKeyDerivation.derive( - thresholdPublicKey = keyMaterial.thresholdPublicKey.value.toHex(), - path = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH - ) - - private val tweakCache: TweakCache = room.cache - - /** The group's identity, which is also the room's id. */ - private val chatRoomId = room.hex - - private val dialectId = "b".repeat(64) - private val artifactVersionId = "c".repeat(64) - private val chapterId = "d".repeat(64) - private val translationArtifactVersionId = "e".repeat(64) - private val translationChapterId = "f".repeat(64) - private val chunkId = "a".repeat(64) - - /** Exactly what `FrostSigningManager.unsignedEventOf` does. */ - private fun unsignedEventOf(template: EventTemplate<*>) = Event( - id = EventHasher.hashId( - pubKey = chatRoomId, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content - ), - pubKey = chatRoomId, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - sig = "" - ) - - /** A real quorum signing [eventId], in the manager's order. */ - private fun groupSignature(eventId: String): String { - val message = ByteVector(eventId.hexToByteArray()) - val signerIds = listOf(0, 1) - - val nonces = signerIds.map { signerId -> - SecretNonce.generate( - sessionRandom = ByteVector32("a".repeat(63) + "${signerId + 1}"), - secretShare = keyMaterial.secretShares[signerId], - publicShare = keyMaterial.publicShares[signerId], - tweakedThresholdPublicKey = tweakCache.tweakedPublicKey, - message = message, - extraInput = null - ) - } - - val signingSession = Session.create( - aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, - signerIds = signerIds.map { it.toUInt() }, - signerPublicShares = signerIds.map { keyMaterial.publicShares[it] }, - nParticipants = participants, - threshold = threshold, - tweakCache = tweakCache, - message = message - ) - - val partials = signerIds.mapIndexed { position, signerId -> - signingSession.sign( - nonces[position].first, - keyMaterial.secretShares[signerId], - signerId.toUInt() - ).right!! - } - - return signingSession.aggregateSigs(partials).right!!.toByteArray().toHex() - } - - /** A template, signed by the group, the way a finished session leaves one. */ - private fun signed(template: EventTemplate<*>): Event { - val unsigned = unsignedEventOf(template) - - return Event( - id = unsigned.id, - pubKey = unsigned.pubKey, - createdAt = unsigned.createdAt, - kind = unsigned.kind, - tags = unsigned.tags, - content = unsigned.content, - sig = groupSignature(unsigned.id) - ) - } - - /** - * The claim, for one kind: sign it, file it as a row, rebuild it from the - * row, and the group's signature still covers what comes out. - */ - private fun assertRoundTrips(template: EventTemplate<*>, rebuild: (Event) -> Event?) { - val signedEvent = signed(template) - assertTrue( - GroupKeyStateEvent.isSignedByRoom(signedEvent, chatRoomId), - "the harness itself must produce a verifiable event" - ) - - val rebuilt = assertNotNull( - rebuild(signedEvent), - "kind ${template.kind} did not survive being turned into a row" - ) - - // Asserted before the signature so a failure says which half broke: an id - // that moved means the tag order or a field changed in the rebuild, where - // a signature that fails on a matching id would mean something stranger. - assertEquals( - signedEvent.id, - rebuilt.id, - "kind ${template.kind} came back with a different id" - ) - assertEquals( - signedEvent.sig, - rebuilt.sig, - "kind ${template.kind} lost the group's signature" - ) - assertTrue( - GroupKeyStateEvent.isSignedByRoom(rebuilt, chatRoomId), - "kind ${template.kind} rebuilt into something the group's signature does not cover" - ) - } - - @Test - fun `a dialect survives the trip through a row`() { - assertRoundTrips( - DialectEvent.build( - name = "isiZulu", - country = "ZA", - language = "zu", - createdAt = 1_700_000_000L - ) - ) { event -> - MantraDialect.fromDialectEvent( - DialectEvent(event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig), - chatRoomId - )?.toDialectEvent() - } - } - - @Test - fun `an artifact survives the trip through a row`() { - // The one that did not, when this test was written. Two faults, and the - // second is the interesting one: `toArtifactEvent` put the alt tag last - // where `build` puts it first, and it left out the version metadata - // entirely -- because that tag is not on the row at all. It is consumed - // into the artifact's first MantraArtifactVersion and dropped. So the - // label has to come back from there, which is why it is a parameter. - assertRoundTrips( - ArtifactEvent.build( - name = "In Detention", - url = "https://example.com/in-detention", - visibility = "private", - license = "cc", - dialectId = dialectId, - versionLabel = "1.0", - createdAt = 1_700_000_000L - ) - ) { event -> - MantraArtifact.fromArtifactEvent( - ArtifactEvent(event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig), - chatRoomId - )?.toArtifactEvent(versionLabel = "1.0") - } - } - - @Test - fun `an artifact rebuilt with the wrong version label is not the one that was signed`() { - // What the parameter costs if a caller guesses. The label was part of - // what the group put its signature to, so a rebuild carrying a different - // one is a different event -- and it fails as a forgery rather than as a - // mistake, which is why the assembler reads it off the initial version - // rather than defaulting it. - val signedEvent = signed( - ArtifactEvent.build( - name = "In Detention", - url = "https://example.com/in-detention", - visibility = "private", - license = "cc", - dialectId = dialectId, - versionLabel = "1.0", - createdAt = 1_700_000_000L - ) - ) - - val rebuilt = MantraArtifact.fromArtifactEvent( - ArtifactEvent( - signedEvent.id, signedEvent.pubKey, signedEvent.createdAt, - signedEvent.tags, signedEvent.content, signedEvent.sig - ), - chatRoomId - )?.toArtifactEvent(versionLabel = "2.0") - - assertNotNull(rebuilt) - assertFalse(GroupKeyStateEvent.isSignedByRoom(rebuilt, chatRoomId)) - } - - @Test - fun `an artifact version survives the trip through a row`() { - // The second fault of the same shape, found the moment this kind became - // chroniclable: `toArtifactVersionEvent` emitted [artifactId, alt] where - // `build` emits [alt, artifactId]. It had been that way for as long as - // nothing called it, which is what makes an unused rebuild dangerous - // rather than merely dead -- the claim in its comment was never checked. - // - // Built through `initialVersionOf` rather than by hand, because that is - // what the signing batch actually proposes. - val artifact = signed( - ArtifactEvent.build( - name = "In Detention", - url = "https://example.com/in-detention", - visibility = "private", - license = "cc", - dialectId = dialectId, - versionLabel = "1.0", - createdAt = 1_700_000_000L - ) - ) - - assertRoundTrips( - ArtifactVersionEvent.initialVersionOf(artifact).single() - ) { event -> - MantraArtifactVersion.fromArtifactVersionEvent( - ArtifactVersionEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ), - chatRoomId - )?.toArtifactVersionEvent() - } - } - - @Test - fun `a translated chunk survives the trip through a row`() { - // The translated text. Chroniclable only because the app stopped saving it - // as its author's rumor and started asking the group to sign it -- until - // then a new member got the whole structure and none of the prose. - assertRoundTrips( - TranslationChunkEvent.build( - translationChapterId = translationChapterId, - chunkId = chunkId, - index = 0, - text = "Wayeyindoda enezingxenye.", - createdAt = 1_700_000_000L - ) - ) { event -> - MantraTranslationChunk.fromTranslationChunkEvent( - TranslationChunkEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ), - chatRoomId - )?.toTranslationChunkEvent() - } - } - - @Test - fun `a chapter survives the trip through a row`() { - assertRoundTrips( - ChapterEvent.build( - artifactVersionId = artifactVersionId, - name = "Chapter One", - originalText = "He was a man of parts.", - index = 0, - wordCount = 6, - characterCount = 22, - createdAt = 1_700_000_000L - ) - ) { event -> - MantraChapter.fromChapterEvent( - ChapterEvent(event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig), - chatRoomId - )?.toChapterEvent() - } - } - - @Test - fun `a chunk survives the trip through a row`() { - assertRoundTrips( - ChunkEvent.build( - chapterId = chapterId, - text = "He was a man of parts.", - index = 0, - wordCount = 6, - characterCount = 22, - createdAt = 1_700_000_000L - ) - ) { event -> - MantraChunk.fromChunkEvent( - ChunkEvent(event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig), - chatRoomId - )?.toChunkEvent() - } - } - - @Test - fun `a translation artifact version survives the trip through a row`() { - assertRoundTrips( - TranslationArtifactVersionEvent.build( - artifactVersionId = artifactVersionId, - dialectId = dialectId, - name = "isiZulu", - visibility = "private", - license = "cc", - createdAt = 1_700_000_000L - ) - ) { event -> - MantraTranslationArtifactVersion.fromTranslationArtifactVersionEvent( - TranslationArtifactVersionEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ), - chatRoomId - )?.toTranslationArtifactVersionEvent() - } - } - - @Test - fun `a translation chapter survives the trip through a row`() { - assertRoundTrips( - TranslationChapterEvent.build( - translationArtifactVersionId = translationArtifactVersionId, - chapterId = chapterId, - index = 0, - createdAt = 1_700_000_000L - ) - ) { event -> - MantraTranslationChapter.fromTranslationChapterEvent( - TranslationChapterEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ), - chatRoomId - )?.toTranslationChapterEvent() - } - } - - @Test - fun `every chroniclable kind has a round-trip test above`() { - // The list and this file have to move together. A kind added to the - // allowlist without a case here is one nobody has checked can be rebuilt, - // and the failure is silent: the receiver drops it as a forgery. - assertEquals( - 8, - ChronicleEvent.CHRONICLABLE_KINDS.size, - "a chroniclable kind was added or removed; add or remove its round-trip case" - ) - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleTestKinds.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleTestKinds.kt new file mode 100644 index 00000000..73c237ef --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleTestKinds.kt @@ -0,0 +1,35 @@ +package com.machankura.bennu.compose.nostr.chronicle + +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent + +/** + * The kinds the chronicle tests chronicle, in the order they apply. + * + * The app's own list, [ChronicleEvent.KINDS], is empty, so the machinery is + * exercised with this one instead. It is not a proposal for what the app should + * carry -- see [ChronicleEvent.KINDS] for why each of these is left out there. + * + * Chosen for three properties: + * + * - **each is a group-signed kind `ChatMessage.applyInnerEvent` has an arm + * for**, so a payload goes down the real apply path rather than falling + * through to "unsupported"; + * - **none of those arms writes a row of its own or throws** -- the group's + * profile, relay lists and posts are read straight off `GroupSignedEvent` + * -- so what a receiver holds afterwards is exactly the `GroupSignedEvent` + * rows the chronicle recorded, and comparing those is comparing the work; + * - **the order disagrees with the kind numbers** (10002 before 0 before 1), + * so a test that the order is the list's cannot pass by sorting on kind. + * + * A key state and a birth certificate are deliberately not here: they are what + * the allowlist has to refuse, so they are what the tests try to replay. + */ +internal val TEST_KINDS: ChronicleKinds = ChronicleKinds( + listOf( + AdvertisedRelayListEvent.KIND, + MetadataEvent.KIND, + TextNoteEvent.KIND, + ) +) diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/dao/GroupSignedEventDaoJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/dao/GroupSignedEventDaoJvmTest.kt index d29712a3..f60b13d2 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/dao/GroupSignedEventDaoJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/dao/GroupSignedEventDaoJvmTest.kt @@ -32,8 +32,8 @@ import com.machankura.bennu.compose.database.model.NostrEvent import com.machankura.bennu.compose.database.model.Profile import com.machankura.bennu.compose.extensions.toHex import com.machankura.bennu.compose.managers.SharedKeyDerivation -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent /** * The table that keeps what a quorum signed, checked against a real quorum. @@ -132,8 +132,8 @@ class GroupSignedEventDaoJvmTest { ) } - private val dialect = signed( - DialectEvent.build(name = "isiZulu", country = "ZA", language = "zu", createdAt = 1_700_000_000L) + private val post = signed( + TextNoteEvent.build(note = "isiZulu", createdAt = 1_700_000_000L) ) /** @@ -169,7 +169,7 @@ class GroupSignedEventDaoJvmTest { } private fun rowFor( - event: Event = dialect, + event: Event = post, path: String? = derivationPath, sessionId: String? = "session-1", ) = GroupSignedEvent.fromEvent( @@ -184,20 +184,20 @@ class GroupSignedEventDaoJvmTest { seedRoom() db.groupSignedEventDao().record(rowFor()) - val stored = db.groupSignedEventDao().getById(dialect.id) + val stored = db.groupSignedEventDao().getById(post.id) assertNotNull(stored, "the event just recorded could not be read back") - assertEquals(dialect.pubKey, stored.publicKey) - assertEquals(dialect.kind, stored.kind) - assertEquals(dialect.content, stored.content) - assertEquals(dialect.sig, stored.signature) - assertEquals(dialect.createdAt, stored.createdAt.epochSeconds) - assertContentEquals(dialect.tags.map { it.toList() }, stored.tags.map { it.toList() }) + assertEquals(post.pubKey, stored.publicKey) + assertEquals(post.kind, stored.kind) + assertEquals(post.content, stored.content) + assertEquals(post.sig, stored.signature) + assertEquals(post.createdAt, stored.createdAt.epochSeconds) + assertContentEquals(post.tags.map { it.toList() }, stored.tags.map { it.toList() }) // The claim the columns exist to support: the group's signature is still // checkable from the row, with nothing else on hand. assertTrue(stored.verifies(), "the stored row no longer verifies as the room's") - assertEquals(dialect.id, stored.toEvent().id) + assertEquals(post.id, stored.toEvent().id) } @Test @@ -205,7 +205,7 @@ class GroupSignedEventDaoJvmTest { seedRoom() db.groupSignedEventDao().record(rowFor()) - val stored = db.groupSignedEventDao().getById(dialect.id) + val stored = db.groupSignedEventDao().getById(post.id) assertNotNull(stored) assertEquals(derivationPath, stored.derivationPath) @@ -227,7 +227,7 @@ class GroupSignedEventDaoJvmTest { seedRoom() db.groupSignedEventDao().record(rowFor(path = null)) - val stored = db.groupSignedEventDao().getById(dialect.id) + val stored = db.groupSignedEventDao().getById(post.id) assertNotNull(stored) assertNull(stored.derivationPath) @@ -245,7 +245,7 @@ class GroupSignedEventDaoJvmTest { // state and never ran the session. db.groupSignedEventDao().record(rowFor(path = null, sessionId = null)) - val stored = db.groupSignedEventDao().getById(dialect.id) + val stored = db.groupSignedEventDao().getById(post.id) assertNotNull(stored) assertEquals(derivationPath, stored.derivationPath) @@ -259,7 +259,7 @@ class GroupSignedEventDaoJvmTest { db.groupSignedEventDao().record(rowFor(path = null, sessionId = null)) db.groupSignedEventDao().record(rowFor()) - val stored = db.groupSignedEventDao().getById(dialect.id) + val stored = db.groupSignedEventDao().getById(post.id) assertNotNull(stored) assertEquals(derivationPath, stored.derivationPath) @@ -270,31 +270,23 @@ class GroupSignedEventDaoJvmTest { fun `a batch is filed together and reads back oldest first`() = runBlocking { seedRoom() - val artifact = signed( - ArtifactEvent.build( - name = "In Detention", - url = "https://example.com/in-detention", - visibility = "private", - license = "cc", - dialectId = dialect.id, - versionLabel = "1.0", - createdAt = 1_700_000_010L - ) + val profile = signed( + MetadataEvent.createNew(name = "In Detention", createdAt = 1_700_000_010L) ) db.groupSignedEventDao().recordAll( - listOf(rowFor(event = artifact), rowFor(event = dialect)) + listOf(rowFor(event = profile), rowFor(event = post)) ) val dao = db.groupSignedEventDao() assertEquals( - listOf(dialect.id, artifact.id), + listOf(post.id, profile.id), dao.getByChatRoomId(chatRoomId).map { it.id }, "a room's signed work has to come back in the order it can be applied in" ) assertEquals( - listOf(dialect.id), - dao.getByChatRoomIdAndKind(chatRoomId, DialectEvent.KIND).map { it.id } + listOf(post.id), + dao.getByChatRoomIdAndKind(chatRoomId, TextNoteEvent.KIND).map { it.id } ) assertEquals(2, dao.getByFrostSigningSessionId("session-1").size) } @@ -304,38 +296,11 @@ class GroupSignedEventDaoJvmTest { seedRoom() db.groupSignedEventDao().record(rowFor().copy(content = "isiXhosa")) - val stored = db.groupSignedEventDao().getById(dialect.id) + val stored = db.groupSignedEventDao().getById(post.id) assertNotNull(stored) // The id is the hash of the fields, so an edited row is an event the // group never signed. Nothing else has to be consulted to know that. assertFalse(stored.verifies(), "an event with edited content must not verify") } - - @Test - fun `the row a signed event becomes points back at it`() = runBlocking { - seedRoom() - db.groupSignedEventDao().record(rowFor()) - - ChatMessage.applyInnerEvent( - database = db, - groupId = chatRoomId, - event = dialect, - marmotGroupEventId = null, - marmotInnerEventId = null, - senderPublicKey = chatRoomId, - isUserMessage = false, - createdAt = Instant.fromEpochSeconds(dialect.createdAt), - groupSignedEventId = dialect.id, - ) - - val row = db.mantraDialectDao().getDialectById(dialect.id) - assertNotNull(row, "the dialect the group signed was not applied") - - // Both Marmot ids are null on a group-signed event -- no group event and - // no inner event carried it -- so this column is the only provenance the - // row has. - assertNull(row.marmotGroupEventId) - assertEquals(dialect.id, row.groupSignedEventId) - } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/model/TranslationChunkApplyJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/model/TranslationChunkApplyJvmTest.kt deleted file mode 100644 index ba4d1ef4..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/model/TranslationChunkApplyJvmTest.kt +++ /dev/null @@ -1,301 +0,0 @@ -package com.machankura.bennu.compose.database.model - -import androidx.room3.Room -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import kotlinx.coroutines.runBlocking -import com.machankura.bennu.compose.database.BennuDatabase -import com.machankura.bennu.compose.database.builder.getRoomDatabase -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * What happens when a chunk is translated twice. - * - * A translation chunk is not edited. Retranslating a passage means proposing a - * new event carrying new words, and an event's id is a hash over its content -- - * so the second translation arrives as a row of its own rather than as an - * overwrite of the first. Left alone, the chapter would hold two answers to - * what one passage says, and the table pairing chunks with their translations - * would show whichever the query reached first. - * - * The rule this asserts is that the newest one wins, decided by the timestamp - * the group signed at rather than by arrival: two devices catching up read the - * same events in whatever order the relay hands them over, and they have to end - * up holding the same translation either way. - */ -class TranslationChunkApplyJvmTest { - - private val db: BennuDatabase = getRoomDatabase( - Room.inMemoryDatabaseBuilder() - ) - - @AfterTest - fun closeDb() = db.close() - - private val author = "a".repeat(64) - private val roomId = "b".repeat(64) - private val chunkId = "c".repeat(64) - private val translationChapterId = "d".repeat(64) - private val signature = "0".repeat(128) - - /** - * Everything a translation chunk hangs off, seeded as already signed: the - * room, the artifact it belongs to, the chapter and chunk it translates, and - * the translation chapter it goes into. None of it is what this test is - * about; they are the foreign keys in the way. - */ - private suspend fun seed() { - val nostrEventId = "e".repeat(64) - db.nostrEventDao().upsert( - NostrEvent( - id = nostrEventId, - pubKey = author, - kind = 0, - tags = emptyArray(), - content = "{}", - sig = signature, - ) - ) - db.profileDao().upsert(Profile(publicKey = author, nostrEventId = nostrEventId)) - db.chatRoomDao().upsert( - ChatRoom( - id = roomId, - userPublicKey = author, - subject = "a translation room", - description = null, - mlsGroupState = null, - ) - ) - - val dialectId = "1".repeat(64) - db.mantraDialectDao().upsert( - MantraDialect( - id = dialectId, - publicKey = roomId, - name = "Sesotho", - country = "ZA", - language = "st", - signature = signature, - chatRoomId = roomId, - ) - ) - - val artifactId = "2".repeat(64) - db.mantraArtifactDao().upsert( - MantraArtifact( - id = artifactId, - publicKey = roomId, - name = "To Kill a Mockingbird", - url = "https://harper.com/2-kill-Bird", - visibility = "private", - dialectId = dialectId, - license = "cc", - chatRoomId = roomId, - signature = signature, - ) - ) - - val artifactVersionId = "3".repeat(64) - db.mantraArtifactVersionDao().upsert( - MantraArtifactVersion( - id = artifactVersionId, - artifactId = artifactId, - publicKey = roomId, - versionLabel = "1.0", - signature = signature, - chatRoomId = roomId, - ) - ) - - val chapterId = "4".repeat(64) - db.mantraChapterDao().upsert( - MantraChapter( - id = chapterId, - artifactVersionId = artifactVersionId, - publicKey = roomId, - name = "Chapter 1", - originalText = "When he was nearly thirteen.", - index = 0, - wordCount = 5, - characterCount = 28, - signature = signature, - chatRoomId = roomId, - ) - ) - - db.mantraChunkDao().upsert( - MantraChunk( - id = chunkId, - chapterId = chapterId, - publicKey = roomId, - text = "When he was nearly thirteen.", - index = 0, - wordCount = 5, - characterCount = 28, - signature = signature, - chatRoomId = roomId, - ) - ) - - val translationId = "5".repeat(64) - db.mantraTranslationArtifactVersionDao().upsert( - MantraTranslationArtifactVersion( - id = translationId, - publicKey = roomId, - artifactVersionId = artifactVersionId, - dialectId = dialectId, - name = "Sesotho", - visibility = "private", - license = "cc", - signature = signature, - chatRoomId = roomId, - ) - ) - - db.mantraTranslationChapterDao().upsert( - MantraTranslationChapter( - id = translationChapterId, - publicKey = roomId, - chapterId = chapterId, - translationArtifactVersionId = translationId, - index = 0, - signature = signature, - chatRoomId = roomId, - ) - ) - } - - /** A translation of the seeded chunk, signed by the room as the group would. */ - private fun translation(text: String, createdAt: Long): Event { - val template = TranslationChunkEvent.build( - translationChapterId = translationChapterId, - chunkId = chunkId, - index = 0, - text = text, - createdAt = createdAt, - ) - - return Event( - id = EventHasher.hashId( - pubKey = roomId, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - ), - pubKey = roomId, - createdAt = template.createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - sig = signature, - ) - } - - private suspend fun apply(event: Event) = ChatMessage.applyInnerEvent( - database = db, - groupId = roomId, - event = event, - marmotGroupEventId = null, - marmotInnerEventId = null, - senderPublicKey = roomId, - isUserMessage = false, - createdAt = Instant.fromEpochSeconds(event.createdAt), - ) - - private suspend fun translations() = db.mantraTranslationChunkDao() - .getTranslationChunksByTranslationChapterId(translationChapterId) - - @Test - fun `a retranslation replaces the translation it supersedes`() = runBlocking { - seed() - - val signedAt = Clock.System.now().epochSeconds - apply(translation("Ha a le hantle lilemo li leshome le metso e meraro.", signedAt)) - apply(translation("Ha a batla ho ba lilemo li leshome le metso e meraro.", signedAt + 60)) - - // Both are valid signatures of the group's over the same passage, and - // the chapter has room for one of them. - val kept = translations().single() - assertEquals("Ha a batla ho ba lilemo li leshome le metso e meraro.", kept.text) - } - - @Test - fun `a translation arriving after the one that superseded it is dropped`() = runBlocking { - seed() - - val signedAt = Clock.System.now().epochSeconds - val first = translation("Ha a le hantle lilemo li leshome le metso e meraro.", signedAt) - val second = translation("Ha a batla ho ba lilemo li leshome le metso e meraro.", signedAt + 60) - - // The order the relay happened to hand them over in, which is not the - // order the group signed them in. A device catching up has to reach the - // same chapter as one that saw them the other way round. - apply(second) - apply(first) - - val kept = translations().single() - assertEquals(second.id, kept.id) - } - - @Test - fun `two chunks of the same chapter each keep their translation`() = runBlocking { - seed() - - // The rule is one translation per source chunk, not one per chapter. - // Matching on the chapter alone would leave a chapter that can only ever - // hold its most recently translated passage. - val otherChunkId = "f".repeat(64) - db.mantraChunkDao().upsert( - MantraChunk( - id = otherChunkId, - chapterId = "4".repeat(64), - publicKey = roomId, - text = "My brother Jem got his arm badly broken.", - index = 1, - wordCount = 8, - characterCount = 40, - signature = signature, - chatRoomId = roomId, - ) - ) - - val signedAt = Clock.System.now().epochSeconds - apply(translation("Ha a le hantle lilemo li leshome le metso e meraro.", signedAt)) - - val otherTemplate = TranslationChunkEvent.build( - translationChapterId = translationChapterId, - chunkId = otherChunkId, - index = 1, - text = "Moholoane oa ka Jem o ile a robeha letsoho.", - createdAt = signedAt + 60, - ) - apply( - Event( - id = EventHasher.hashId( - pubKey = roomId, - createdAt = otherTemplate.createdAt, - kind = otherTemplate.kind, - tags = otherTemplate.tags, - content = otherTemplate.content, - ), - pubKey = roomId, - createdAt = otherTemplate.createdAt, - kind = otherTemplate.kind, - tags = otherTemplate.tags, - content = otherTemplate.content, - sig = signature, - ) - ) - - assertEquals( - listOf(chunkId, otherChunkId), - translations().map { it.chunkId }, - ) - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChronicleApplyJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChronicleApplyJvmTest.kt index 6c1e88a2..322a4743 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChronicleApplyJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChronicleApplyJvmTest.kt @@ -4,7 +4,10 @@ import androidx.room3.Room import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent import fr.acinq.bitcoin.ByteVector import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.PrivateKey @@ -27,26 +30,21 @@ import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.database.builder.getRoomDatabase import com.machankura.bennu.compose.database.model.ChatMessage import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.GroupSignedEvent import com.machankura.bennu.compose.database.model.MarmotInnerEvent import com.machankura.bennu.compose.database.model.MarmotKeyPackage import com.machankura.bennu.compose.database.model.NostrEvent import com.machankura.bennu.compose.database.model.Profile import com.machankura.bennu.compose.extensions.toHex import com.machankura.bennu.compose.nostr.chronicle.ChronicleEvent +import com.machankura.bennu.compose.nostr.chronicle.ChronicleKinds import com.machankura.bennu.compose.nostr.chronicle.ChronicleRequestEvent +import com.machankura.bennu.compose.nostr.chronicle.TEST_KINDS import com.machankura.bennu.compose.nostr.chronicle.tags.ChronicleIdTag import com.machankura.bennu.compose.nostr.chronicle.tags.ChroniclePageTag import com.machankura.bennu.compose.nostr.chronicle.tags.ChronicleRecipientTag import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent /** * Two devices, two databases: one that did the work and one that arrived after @@ -54,14 +52,18 @@ import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent * * This is the claim the whole feature is: a member who holds no share, took part * in no signing session and cannot decrypt a word of the room's history ends up - * with the same rows as everybody else, and gets there without trusting the - * member who sent them. + * holding what the group signed, and gets there without trusting the member who + * sent it. * * The negative cases matter more than the positive one. Verification is what * makes a chronicle safe to accept from anybody, so what has to be proved is that * it refuses -- a forged payload beside honest ones, and a genuine key state * replayed out of its epoch, which passes every signature check there is and is * stopped by nothing but the allowlist. + * + * The app's own list of kinds is empty, so everything here runs on [TEST_KINDS] + * except the last section, which is about the app's list and holds it to + * carrying nothing in either direction. */ class ChronicleApplyJvmTest { /** The member who did the work. */ @@ -174,6 +176,9 @@ class ChronicleApplyJvmTest { private fun signed(template: EventTemplate<*>) = signedBy(keyMaterial, template) + private fun template(kind: Int, createdAt: Long, content: String, tags: Array> = emptyArray()) = + EventTemplate(createdAt = createdAt, kind = kind, tags = tags, content = content) + private suspend fun seedRoom(db: BennuDatabase, user: String) { val nostrEventId = "c".repeat(63) + if (user == newMember) "1" else "2" db.nostrEventDao().upsert( @@ -198,7 +203,19 @@ class ChronicleApplyJvmTest { ) } - private suspend fun apply(db: BennuDatabase, event: Event) { + /** + * What `FrostSigningManager.complete` does with a finished batch: file the + * events as the group signed them, then apply them. + */ + private suspend fun recordAndApply(db: BennuDatabase, event: Event) { + db.groupSignedEventDao().record( + GroupSignedEvent.fromEvent( + event = event, + chatRoomId = chatRoomId, + derivationPath = SharedKeyDerivation.formatPath(), + frostSigningSessionId = "session-1", + ) + ) ChatMessage.applyInnerEvent( database = db, groupId = chatRoomId, @@ -207,106 +224,24 @@ class ChronicleApplyJvmTest { marmotInnerEventId = null, senderPublicKey = chatRoomId, isUserMessage = false, - createdAt = Instant.fromEpochSeconds(event.createdAt) + createdAt = Instant.fromEpochSeconds(event.createdAt), + groupSignedEventId = event.id, ) } - /** The sender's room, with a full artifact and one translation scaffolded. */ + /** The sender's room, holding one signed event of every test kind and two of one. */ private suspend fun seedSenderWork() { seedRoom(sender, oldMember) - val dialect = signed( - DialectEvent.build(name = "isiZulu", country = "ZA", language = "zu", createdAt = 1_700_000_000L) - ).also { apply(sender, it) } - - val artifact = signed( - ArtifactEvent.build( - name = "In Detention", - url = "https://example.com/in-detention", - visibility = "private", - license = "cc", - dialectId = dialect.id, - versionLabel = "1.0", - createdAt = 1_700_000_010L - ) - ).also { apply(sender, it) } - - // The second item of the artifact's own signing batch, not a row derived - // on arrival -- which is what makes it chroniclable at all. - val version = signed(ArtifactVersionEvent.initialVersionOf(artifact).single()) - .also { apply(sender, it) } - - val chapter = signed( - ChapterEvent.build( - artifactVersionId = version.id, - name = "Chapter One", - originalText = "He was a man of parts. He had many.", - index = 0, - wordCount = 8, - characterCount = 35, - createdAt = 1_700_000_020L - ) - ).also { apply(sender, it) } - - val chunk = signed( - ChunkEvent.build( - chapterId = chapter.id, - text = "He was a man of parts.", - index = 0, - wordCount = 6, - characterCount = 22, - createdAt = 1_700_000_030L - ) - ).also { apply(sender, it) } - apply( - sender, - signed( - ChunkEvent.build( - chapterId = chapter.id, - text = "He had many.", - index = 1, - wordCount = 3, - characterCount = 12, - createdAt = 1_700_000_031L - ) - ) - ) - - val translationVersion = signed( - TranslationArtifactVersionEvent.build( - artifactVersionId = version.id, - dialectId = dialect.id, - name = "isiZulu", - visibility = "private", - license = "cc", - createdAt = 1_700_000_040L - ) - ).also { apply(sender, it) } - - val translationChapter = signed( - TranslationChapterEvent.build( - translationArtifactVersionId = translationVersion.id, - chapterId = chapter.id, - index = 0, - createdAt = 1_700_000_050L - ) - ).also { apply(sender, it) } - - // The translated text. Group-signed now, so it can travel and be checked - // -- until it was, a chronicle handed a new member the whole structure and - // none of the prose. - apply( - sender, - signed( - TranslationChunkEvent.build( - translationChapterId = translationChapter.id, - chunkId = chunk.id, - index = 0, - text = "Wayeyindoda enezingxenye.", - createdAt = 1_700_000_060L - ) - ) - ) + listOf( + template( + AdvertisedRelayListEvent.KIND, 1_700_000_000L, "", + tags = arrayOf(arrayOf("r", "wss://relay.example.com")), + ), + template(MetadataEvent.KIND, 1_700_000_010L, "{\"name\":\"Ekklesia\"}"), + template(TextNoteEvent.KIND, 1_700_000_020L, "The group says hello."), + template(TextNoteEvent.KIND, 1_700_000_021L, "And says it again."), + ).forEach { recordAndApply(sender, signed(it)) } } /** @@ -318,6 +253,7 @@ class ChronicleApplyJvmTest { template: EventTemplate, to: String = newMember, from: String = oldMember, + kinds: ChronicleKinds = TEST_KINDS, ): ChronicleManager.Outcome { val page = Event( id = EventHasher.hashId( @@ -349,79 +285,46 @@ class ChronicleApplyJvmTest { ) ) - return ChronicleManager.receive(receiver, chatRoomId, to, page) + return ChronicleManager.receive(receiver, chatRoomId, to, page, kinds) } - private suspend fun senderChronicle() = ChronicleManager.assemble(sender, chatRoomId, newMember) + private suspend fun senderChronicle() = + ChronicleManager.assemble(sender, chatRoomId, newMember, kinds = TEST_KINDS) - private suspend fun rowCounts(db: BennuDatabase): Map { - val dialects = db.mantraDialectDao().getDialectsByChatRoomId(chatRoomId) - val artifacts = db.mantraArtifactDao().getArtifactsByChatRoomId(chatRoomId) - val versions = artifacts.flatMap { - db.mantraArtifactVersionDao().getArtifactVersionsByArtifactId(it.id) - } - val chapters = versions.flatMap { db.mantraChapterDao().getChaptersByArtifactVersionId(it.id) } - val chunks = chapters.flatMap { db.mantraChunkDao().getChunksByChapterId(it.id) } - val translationVersions = versions.flatMap { - db.mantraTranslationArtifactVersionDao().getTranslationsByArtifactVersionId(it.id) - } - val translationChapters = translationVersions.flatMap { - db.mantraTranslationChapterDao() - .getTranslationChaptersByTranslationArtifactVersionId(it.id) - } - val translationChunks = translationChapters.flatMap { - db.mantraTranslationChunkDao().getTranslationChunksByTranslationChapterId(it.id) - } + /** Every payload of the sender's chronicle, one page each, numbered as [chronicleId]. */ + private suspend fun onePagePerPayload(chronicleId: String = "e".repeat(64)): List> { + val payloads = senderChronicle() + .flatMap { assertNotNull(ChronicleEvent.decodePage(it.content)) } - return mapOf( - "dialects" to dialects.size, - "artifacts" to artifacts.size, - "versions" to versions.size, - "chapters" to chapters.size, - "chunks" to chunks.size, - "translationVersions" to translationVersions.size, - "translationChapters" to translationChapters.size, - "translationChunks" to translationChunks.size, - ) + return payloads.mapIndexed { index, payload -> + ChronicleEvent.build( + payloads = listOf(payload), + chronicleId = chronicleId, + index = index, + count = payloads.size, + recipient = newMember, + createdAt = 1_700_000_100L + index, + kinds = TEST_KINDS, + ) + } } /** - * Every chronicled row as (id, author, signature), sorted. + * Every group-signed event on file as (id, author, signature), sorted. * - * Counting is not the claim. Two databases can hold the same number of - * artifacts and disagree about every one of them, and a rebuild that lost the - * group's signature -- or re-authored a row as whoever sent it -- would pass a - * count and fail the only thing the chronicle is for. + * None of the test kinds' arms writes a row of its own, so this table is the + * whole of what a chronicle restores. Compared rather than counted: two + * databases can hold the same number of events and disagree about every one, + * and a chronicle that re-authored each as whoever sent it would pass a count + * and fail the only thing it is for. */ - private suspend fun rowFingerprints(db: BennuDatabase): List> { - val artifacts = db.mantraArtifactDao().getArtifactsByChatRoomId(chatRoomId) - val versions = artifacts.flatMap { - db.mantraArtifactVersionDao().getArtifactVersionsByArtifactId(it.id) - } - val chapters = versions.flatMap { db.mantraChapterDao().getChaptersByArtifactVersionId(it.id) } - val translationVersions = versions.flatMap { - db.mantraTranslationArtifactVersionDao().getTranslationsByArtifactVersionId(it.id) - } + private suspend fun fingerprints(db: BennuDatabase): List> = + db.groupSignedEventDao().getByChatRoomId(chatRoomId) + .map { Triple(it.id, it.publicKey, it.signature) } + .sortedBy { it.first } - return buildList { - db.mantraDialectDao().getDialectsByChatRoomId(chatRoomId) - .forEach { add(Triple(it.id, it.publicKey, it.signature)) } - artifacts.forEach { add(Triple(it.id, it.publicKey, it.signature)) } - versions.forEach { add(Triple(it.id, it.publicKey, it.signature)) } - chapters.forEach { add(Triple(it.id, it.publicKey, it.signature)) } - chapters.flatMap { db.mantraChunkDao().getChunksByChapterId(it.id) } - .forEach { add(Triple(it.id, it.publicKey, it.signature)) } - translationVersions.forEach { add(Triple(it.id, it.publicKey, it.signature)) } - val translationChapters = translationVersions.flatMap { - db.mantraTranslationChapterDao() - .getTranslationChaptersByTranslationArtifactVersionId(it.id) - } - translationChapters.forEach { add(Triple(it.id, it.publicKey, it.signature)) } - translationChapters - .flatMap { db.mantraTranslationChunkDao().getTranslationChunksByTranslationChapterId(it.id) } - .forEach { add(Triple(it.id, it.publicKey, it.signature)) } - }.sortedBy { it.first } - } + private suspend fun lines(db: BennuDatabase) = + db.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId).map { it.chatMessage.messageType } @Test fun `a member who was never there ends up holding what the group signed`() = runBlocking { @@ -429,78 +332,62 @@ class ChronicleApplyJvmTest { seedRoom(receiver, newMember) assertEquals( - mapOf( - "dialects" to 0, "artifacts" to 0, "versions" to 0, "chapters" to 0, - "chunks" to 0, "translationVersions" to 0, "translationChapters" to 0, - "translationChunks" to 0, - ), - rowCounts(receiver), + emptyList(), + fingerprints(receiver), "the new member starts with nothing, which is the whole problem" ) senderChronicle().forEach { deliver(it) } - assertEquals(rowCounts(sender), rowCounts(receiver)) + val fingerprints = fingerprints(receiver) + assertTrue(fingerprints.isNotEmpty()) - // Not merely the same shape: the same rows, each with the group's own - // signature on it. A chronicle that produced look-alike rows authored by - // the member who sent them would pass a count and fail the only thing - // this is for. - val fingerprints = rowFingerprints(receiver) - assertEquals(rowFingerprints(sender), fingerprints) + // Not merely the same number: the same events, each with the group's own + // signature on it. + assertEquals(fingerprints(sender), fingerprints) - // And every one of them is the room's own work, with no exception left. - // The artifact version used to be one -- derived on arrival, so authored - // by the group and carrying no signature to show for it -- and is signed - // in the artifact's own batch now, which is what let it into the chronicle. fingerprints.forEach { (id, author, signature) -> - assertEquals(chatRoomId, author, "row $id is not authored by the room") - assertTrue(signature.isNotBlank(), "row $id came across without a signature") + assertEquals(chatRoomId, author, "event $id is not authored by the room") + assertTrue(signature.isNotBlank(), "event $id came across without a signature") } } /** * The member who was handed history can hand it on. * - * Rows are a reading of what the group signed; the events are the thing - * itself, and until they are kept the recipient of a chronicle is a dead end - * -- holding the work, unable to prove any of it, and unable to build a page - * for the next member to arrive. The path is the room's, read from the key - * state when the recipient has one. + * The events are the thing itself, and until they are kept the recipient of + * a chronicle is a dead end -- holding the work, unable to prove any of it, + * and unable to build a page for the next member to arrive. */ @Test - fun `the chronicle leaves the receiver holding the events, not only the rows`() = runBlocking { + fun `the chronicle leaves the receiver holding the events as the group signed them`() = runBlocking { seedSenderWork() seedRoom(receiver, newMember) senderChronicle().forEach { deliver(it) } - val signed = receiver.groupSignedEventDao().getByChatRoomId(chatRoomId) + val held = receiver.groupSignedEventDao().getByChatRoomId(chatRoomId) + val original = sender.groupSignedEventDao().getByChatRoomId(chatRoomId).associateBy { it.id } - assertEquals( - senderChronicle() - .flatMap { assertNotNull(ChronicleEvent.decodePage(it.content)) } - .map { it.id } - .toSet(), - signed.map { it.id }.toSet(), - "every payload that applied should be on file as the group signed it" - ) - assertTrue(signed.isNotEmpty()) + assertEquals(original.keys, held.map { it.id }.toSet()) - signed.forEach { event -> - assertEquals(chatRoomId, event.publicKey, "${event.id} is not authored by the room") + held.forEach { event -> assertTrue(event.verifies(), "${event.id} does not read back as the room's") + assertEquals( + assertNotNull(original[event.id]).toEvent().toJson(), + event.toEvent().toJson(), + "${event.id} did not arrive as the group signed it" + ) // Nothing on this device ran a session for any of it. assertNull(event.frostSigningSessionId) } - - // The rows the payloads became point back at them, which is the only - // provenance a group-signed row has: no group event, no inner event. - val dialects = receiver.mantraDialectDao().getDialectsByChatRoomId(chatRoomId) - assertTrue(dialects.isNotEmpty()) - dialects.forEach { assertEquals(it.id, it.groupSignedEventId) } } + /** + * Every test kind's arm in `applyInnerEvent` hands back a line -- "the group + * posted in its own name" and the like -- so this is a real refusal and not + * an absence. + */ @Test fun `a chronicle files no chat lines`() = runBlocking { seedSenderWork() @@ -510,9 +397,7 @@ class ChronicleApplyJvmTest { assertEquals( emptyList(), - receiver.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId) - .map { it.chatMessage.messageType } - .filterNot { it in ChatMessage.CHRONICLE_TYPES }, + lines(receiver).filterNot { it in ChatMessage.CHRONICLE_TYPES }, "the chronicle restores the work; the conversation is forward secret and stays gone" ) } @@ -522,87 +407,90 @@ class ChronicleApplyJvmTest { seedSenderWork() seedRoom(receiver, newMember) - // One page per payload, delivered backwards -- a translation chapter - // before the chapter it names, chunks before their chapter, the artifact - // last. Relays give no ordering guarantee, so this is the ordinary case - // rather than the adversarial one. - val payloads = senderChronicle() - .flatMap { assertNotNull(ChronicleEvent.decodePage(it.content)) } - val chronicleId = "e".repeat(64) + // One page per payload, delivered backwards. Relays give no ordering + // guarantee, so this is the ordinary case rather than the adversarial + // one. Nothing in the test list hangs off anything else, so no payload + // has to wait here; the retry that waiting needs is the next test's. + val outcomes = onePagePerPayload().reversed().map { deliver(it) } - val outcomes = payloads.reversed().mapIndexed { index, payload -> - deliver( - ChronicleEvent.build( - payloads = listOf(payload), - chronicleId = chronicleId, - index = index, - count = payloads.size, - recipient = newMember, - createdAt = 1_700_000_100L + index, - ) - ) - } + assertEquals(0, outcomes.sumOf { it.failed }) + assertEquals(fingerprints(sender), fingerprints(receiver)) + } - // Without this the test could pass for the wrong reason -- if nothing - // ever failed to apply, the pages were not really out of order and the - // sweep was never the thing that saved them. - assertTrue( - outcomes.any { it.failed > 0 }, - "delivering backwards should have left payloads waiting on rows they depend on" - ) - assertEquals( - 0, - outcomes.last().failed, - "the last page completes the chronicle, so the pass it triggers should leave nothing" - ) + /** + * The sweep's reason to exist: a payload that threw is run again when the + * next page arrives, because the pages are on disk and the sweep takes all of + * them. + * + * In the app the missing dependency is another payload's row; nothing in the + * test list depends on another, so here it is the room row itself, the one + * foreign key every recorded event has. What is under test is the retry, not + * the reason for it. + */ + @Test + fun `a payload that could not apply yet is retried when the next page arrives`() = runBlocking { + seedSenderWork() - assertEquals(rowCounts(sender), rowCounts(receiver)) + val pages = onePagePerPayload() + assertTrue(pages.size >= 2, "this needs a second page to arrive after the first fails") + + // No room on file yet: the first page's payload has nowhere to go. + val first = deliver(pages.first()) + assertEquals(1, first.failed, "the first payload should have been left waiting") + assertEquals(0, first.applied) + assertEquals(emptyList(), fingerprints(receiver)) + + // The room appears, and the next page's sweep takes the first one with it. + seedRoom(receiver, newMember) + val second = deliver(pages[1]) + + assertEquals(0, second.failed) + assertEquals(2, second.applied, "the waiting payload and the new one") + + pages.drop(2).forEach { deliver(it) } + assertEquals(fingerprints(sender), fingerprints(receiver)) } @Test fun `one forged payload costs itself and nothing else`() = runBlocking { - seedSenderWork() seedRoom(receiver, newMember) - val honest = signed( - DialectEvent.build(name = "isiZulu", country = "ZA", language = "zu", createdAt = 1_700_000_000L) - ) + val honest = signed(template(MetadataEvent.KIND, 1_700_000_000L, "{\"name\":\"Ekklesia\"}")) // Four ways to be a dishonest member, in one page beside one honest - // dialect. Every one of them is well-formed and would file a row without - // the check. + // profile. Every one of them is well-formed and of a kind the list admits. val forgeries = listOf( // The room's id as author -- everybody knows it -- and a made-up // signature. Event( id = EventHasher.hashId( - pubKey = chatRoomId, createdAt = 1_700_000_001L, kind = DialectEvent.KIND, - tags = honest.tags, content = "forged" + pubKey = chatRoomId, createdAt = 1_700_000_001L, kind = MetadataEvent.KIND, + tags = honest.tags, content = "{\"name\":\"forged\"}" ), - pubKey = chatRoomId, createdAt = 1_700_000_001L, kind = DialectEvent.KIND, - tags = honest.tags, content = "forged", sig = "9".repeat(128) + pubKey = chatRoomId, createdAt = 1_700_000_001L, kind = MetadataEvent.KIND, + tags = honest.tags, content = "{\"name\":\"forged\"}", sig = "9".repeat(128) ), // A real quorum, of another group. signedBy( otherKeyMaterial, - DialectEvent.build(name = "seSotho", country = "ZA", language = "st", createdAt = 1_700_000_002L) + template(MetadataEvent.KIND, 1_700_000_002L, "{\"name\":\"Elsewhere\"}") ), // Edited after the group signed it. Event( id = honest.id, pubKey = honest.pubKey, createdAt = honest.createdAt, kind = honest.kind, - tags = arrayOf(arrayOf("alt", "Dialect"), arrayOf("name", "tampered")), + tags = arrayOf(arrayOf("name", "tampered")), content = honest.content, sig = honest.sig ), // A member's own rumor, which is what everything on the wire looks // like today. Event( id = EventHasher.hashId( - pubKey = oldMember, createdAt = 1_700_000_003L, kind = DialectEvent.KIND, - tags = honest.tags, content = "unsigned" + pubKey = oldMember, createdAt = 1_700_000_003L, kind = MetadataEvent.KIND, + tags = honest.tags, content = "{\"name\":\"unsigned\"}" ), - pubKey = oldMember, createdAt = 1_700_000_003L, kind = DialectEvent.KIND, - tags = honest.tags, content = "unsigned", sig = "" + pubKey = oldMember, createdAt = 1_700_000_003L, kind = MetadataEvent.KIND, + tags = honest.tags, content = "{\"name\":\"unsigned\"}", sig = "" ), ) @@ -614,28 +502,25 @@ class ChronicleApplyJvmTest { count = 1, recipient = newMember, createdAt = 1_700_000_100L, + kinds = TEST_KINDS, ) ) assertEquals(4, outcome.skipped) assertEquals(1, outcome.applied) - val dialects = receiver.mantraDialectDao().getDialectsByChatRoomId(chatRoomId) - assertEquals(1, dialects.size, "exactly the honest one") - assertEquals(honest.id, dialects.single().id) - - // And nothing forged was kept as an event either. The record is what a - // later chronicle is built from, so a forgery filed here would be one this - // member goes on to hand to everybody else. + // Nothing forged was kept. The record is what a later chronicle is built + // from, so a forgery filed here would be one this member goes on to hand + // to everybody else. assertEquals( listOf(honest.id), - receiver.groupSignedEventDao().getByChatRoomId(chatRoomId).map { it.id } + receiver.groupSignedEventDao().getByChatRoomId(chatRoomId).map { it.id }, + "exactly the honest one" ) } @Test fun `a key state the room really signed cannot be replayed through a chronicle`() = runBlocking { - seedSenderWork() seedRoom(receiver, newMember) // Signed by the room, verifying perfectly, and refused: the allowlist is @@ -676,6 +561,7 @@ class ChronicleApplyJvmTest { assertEquals(1, outcome.skipped) assertEquals(0, outcome.applied) assertNull(receiver.groupKeyStateDao().getByChatRoomId(chatRoomId)) + assertEquals(emptyList(), fingerprints(receiver)) } @Test @@ -687,12 +573,8 @@ class ChronicleApplyJvmTest { assertEquals(0, outcome.sumOf { it.applied }) assertEquals( - mapOf( - "dialects" to 0, "artifacts" to 0, "versions" to 0, "chapters" to 0, - "chunks" to 0, "translationVersions" to 0, "translationChapters" to 0, - "translationChunks" to 0, - ), - rowCounts(receiver), + emptyList(), + fingerprints(receiver), "a bystander already holds the work; re-applying would only rewrite its provenance" ) } @@ -704,17 +586,12 @@ class ChronicleApplyJvmTest { val chronicle = senderChronicle() chronicle.forEach { deliver(it) } - val afterFirst = rowCounts(receiver) + val afterFirst = fingerprints(receiver) chronicle.forEach { deliver(it) } - assertEquals(afterFirst, rowCounts(receiver)) - assertEquals( - emptyList(), - receiver.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId) - .map { it.chatMessage.messageType } - .filterNot { it in ChatMessage.CHRONICLE_TYPES }, - ) + assertEquals(afterFirst, fingerprints(receiver)) + assertEquals(emptyList(), lines(receiver).filterNot { it in ChatMessage.CHRONICLE_TYPES }) } // ---- Asking for one -------------------------------------------------- @@ -727,7 +604,7 @@ class ChronicleApplyJvmTest { fun `a device holding none of the room's work asks for it`() = runBlocking { seedRoom(receiver, newMember) - assertTrue(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember)) + assertTrue(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember, kinds = TEST_KINDS)) // Queued with no chat line, the way a signing message travels. Broadcast // does not depend on one, and a row of envelopes in the transcript is not @@ -736,19 +613,15 @@ class ChronicleApplyJvmTest { // One line saying so, and nothing else. Asking is a thing this device did // and the room would otherwise sit empty with no explanation. - assertEquals( - listOf(ChatMessage.TYPE_CHRONICLE_REQUESTED), - receiver.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId) - .map { it.chatMessage.messageType } - ) + assertEquals(listOf(ChatMessage.TYPE_CHRONICLE_REQUESTED), lines(receiver)) } @Test fun `a device does not ask twice while an answer is in flight`() = runBlocking { seedRoom(receiver, newMember) - assertTrue(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember)) - assertFalse(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember)) + assertTrue(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember, kinds = TEST_KINDS)) + assertFalse(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember, kinds = TEST_KINDS)) assertEquals(1, queued(receiver, ChronicleRequestEvent.KIND).size) } @@ -757,16 +630,45 @@ class ChronicleApplyJvmTest { fun `a device holding the work does not ask for it`() = runBlocking { seedSenderWork() - assertFalse(ChronicleManager.requestIfEmpty(sender, chatRoomId, oldMember)) + assertFalse(ChronicleManager.requestIfEmpty(sender, chatRoomId, oldMember, kinds = TEST_KINDS)) assertEquals(0, queued(sender, ChronicleRequestEvent.KIND).size) } + /** + * "Holds the work" means holds something a chronicle would carry. A device + * whose only signed event is one the list refuses is as far behind as one + * holding nothing, and has to ask like one. + */ + @Test + fun `a device holding only signed kinds off the list still asks`() = runBlocking { + seedRoom(receiver, newMember) + + receiver.groupSignedEventDao().record( + GroupSignedEvent.fromEvent( + event = signed( + EventTemplate( + createdAt = 1_700_000_060L, + kind = GroupKeyStateEvent.KIND, + tags = GroupKeyStateEvent.assembleTags( + chatRoomId = chatRoomId, + dkgSessionId = "the-ceremony", + ), + content = keyMaterial.thresholdPublicKey.value.toHex(), + ) + ), + chatRoomId = chatRoomId, + ) + ) + + assertTrue(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember, kinds = TEST_KINDS)) + } + @Test fun `an answered request lets the room ask again`() = runBlocking { seedSenderWork() seedRoom(receiver, newMember) - ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember) + ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember, kinds = TEST_KINDS) assertNotNull(receiver.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.chronicleRequestedAt) senderChronicle().forEach { deliver(it) } @@ -782,7 +684,7 @@ class ChronicleApplyJvmTest { fun `answering a request queues the chronicle for whoever asked`() = runBlocking { seedSenderWork() - val pages = ChronicleManager.sendTo(sender, chatRoomId, oldMember, recipient = newMember) + val pages = ChronicleManager.sendTo(sender, chatRoomId, oldMember, recipient = newMember, kinds = TEST_KINDS) assertEquals(1, pages) @@ -798,21 +700,20 @@ class ChronicleApplyJvmTest { sig = "", ) assertEquals(newMember, page.recipient()) - assertEquals(ChronicleEvent.CHRONICLABLE_KINDS, page.payloads()?.map { it.kind }?.toSet()) + assertEquals(TEST_KINDS.all, page.payloads()?.map { it.kind }?.toSet()) // One line about the chronicle, and no line per page. - assertEquals( - listOf(ChatMessage.TYPE_CHRONICLE_SENT), - sender.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId) - .map { it.chatMessage.messageType } - ) + assertEquals(listOf(ChatMessage.TYPE_CHRONICLE_SENT), lines(sender)) } @Test fun `a member with nothing signed answers nothing rather than an empty chronicle`() = runBlocking { seedRoom(receiver, newMember) - assertEquals(0, ChronicleManager.sendTo(receiver, chatRoomId, newMember, recipient = oldMember)) + assertEquals( + 0, + ChronicleManager.sendTo(receiver, chatRoomId, newMember, recipient = oldMember, kinds = TEST_KINDS) + ) assertEquals(0, queued(receiver, ChronicleEvent.KIND).size) } @@ -820,7 +721,10 @@ class ChronicleApplyJvmTest { fun `a member does not answer their own request`() = runBlocking { seedSenderWork() - assertEquals(0, ChronicleManager.sendTo(sender, chatRoomId, oldMember, recipient = oldMember)) + assertEquals( + 0, + ChronicleManager.sendTo(sender, chatRoomId, oldMember, recipient = oldMember, kinds = TEST_KINDS) + ) assertEquals(0, queued(sender, ChronicleEvent.KIND).size) } @@ -830,10 +734,10 @@ class ChronicleApplyJvmTest { seedRoom(receiver, newMember) // The joiner asks. - assertTrue(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember)) + assertTrue(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember, kinds = TEST_KINDS)) // A member holding the work answers it, addressed to whoever asked. - ChronicleManager.sendTo(sender, chatRoomId, oldMember, recipient = newMember) + ChronicleManager.sendTo(sender, chatRoomId, oldMember, recipient = newMember, kinds = TEST_KINDS) // The pages reach the joiner, who applies them. queued(sender, ChronicleEvent.KIND).forEach { queuedPage -> @@ -847,7 +751,7 @@ class ChronicleApplyJvmTest { ) } - assertEquals(rowCounts(sender), rowCounts(receiver)) + assertEquals(fingerprints(sender), fingerprints(receiver)) assertNull(receiver.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.chronicleRequestedAt) } @@ -885,57 +789,30 @@ class ChronicleApplyJvmTest { return keyPackageId } - @Test - fun `inviting a member offers them the group's work alongside the welcome`() = runBlocking { - seedSenderWork() + private suspend fun invite() = sender.marmotOutboundDao().deliveryWelcome( + chatRoomId = chatRoomId, + userPublicKey = oldMember, + welcomeBytes = ByteArray(8), + peerKeyPackageEventId = seedInviteeKeyPackage(), + relays = listOf("wss://relay.example.com"), + createdAt = Clock.System.now(), + ) - sender.marmotOutboundDao().deliveryWelcome( - chatRoomId = chatRoomId, - userPublicKey = oldMember, - welcomeBytes = ByteArray(8), - peerKeyPackageEventId = seedInviteeKeyPackage(), - relays = listOf("wss://relay.example.com"), - createdAt = Clock.System.now(), - ) - - val page = queued(sender, ChronicleEvent.KIND).single() - - assertEquals( - newMember, - ChronicleEvent( - id = page.id, - pubKey = page.publicKey, - createdAt = page.createdAt.epochSeconds, - tags = page.tags, - content = page.content, - sig = "", - ).recipient() - ) - } + private suspend fun welcomesSent() = sender.giftWrapPayloadDao() + .getByChatRoomAndKinds(chatRoomId, listOf(WelcomeEvent.KIND)) + .size @Test fun `inviting into a room with nothing signed offers nothing, and still invites`() = runBlocking { seedRoom(sender, oldMember) - sender.marmotOutboundDao().deliveryWelcome( - chatRoomId = chatRoomId, - userPublicKey = oldMember, - welcomeBytes = ByteArray(8), - peerKeyPackageEventId = seedInviteeKeyPackage(), - relays = listOf("wss://relay.example.com"), - createdAt = Clock.System.now(), - ) + invite() assertEquals(0, queued(sender, ChronicleEvent.KIND).size) // The Welcome itself still went out. A push that has nothing to say is // not a failed invite, and nothing about the chronicle may report one: // the invitee asks for themselves on their first open regardless. - assertEquals( - 1, - sender.giftWrapPayloadDao() - .getByChatRoomAndKinds(chatRoomId, listOf(WelcomeEvent.KIND)) - .size - ) + assertEquals(1, welcomesSent()) } @Test @@ -943,25 +820,11 @@ class ChronicleApplyJvmTest { seedSenderWork() seedRoom(receiver, newMember) - ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember) + ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember, kinds = TEST_KINDS) // Delivered a page at a time and out of order, so the sweep runs several // times over several pages. The transcript is not a log of that. - val payloads = senderChronicle() - .flatMap { assertNotNull(ChronicleEvent.decodePage(it.content)) } - - payloads.reversed().forEachIndexed { index, payload -> - deliver( - ChronicleEvent.build( - payloads = listOf(payload), - chronicleId = "e".repeat(64), - index = index, - count = payloads.size, - recipient = newMember, - createdAt = 1_700_000_100L + index, - ) - ) - } + onePagePerPayload().reversed().forEach { deliver(it) } // Newest first, which is the transcript's order: the answer is the line above // the composer and the ask sits over it. Both land in the same second, so what @@ -969,8 +832,7 @@ class ChronicleApplyJvmTest { // without it this read whichever way SQLite happened to hand the tie back. assertEquals( listOf(ChatMessage.TYPE_CHRONICLE_RECEIVED, ChatMessage.TYPE_CHRONICLE_REQUESTED), - receiver.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId) - .map { it.chatMessage.messageType } + lines(receiver) ) } @@ -983,10 +845,93 @@ class ChronicleApplyJvmTest { // "caught up on work you have not seen yet" is a line about nothing. senderChronicle().forEach { deliver(it) } - assertEquals( - emptyList(), - receiver.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId) - .map { it.chatMessage.messageType } + assertEquals(emptyList(), lines(receiver)) + } + + // ---- The app's own list ---------------------------------------------- + // + // Everything above names its kinds. The app's call sites do not, so these hold + // the default -- ChronicleEvent.KINDS -- to what its comment promises: with + // nothing on the list, a device asks for nothing, sends nothing, and applies + // nothing an older build sends it. + + /** + * The decision itself, pinned. Adding a kind back is meant to be made on + * purpose, with the reason it is safe to replay, and this is the line that + * has to change when it is. + */ + @Test + fun `the app's own list carries nothing`() { + assertTrue(ChronicleEvent.KINDS.isEmpty()) + assertTrue(ChronicleEvent.CHRONICLABLE_KINDS.isEmpty()) + } + + /** + * Asking while nothing could answer would put a request on the wire and a + * line in the transcript on every room a member opens, for a reply that can + * only ever be silence. + */ + @Test + fun `under the app's own list a device asks for nothing`() = runBlocking { + seedRoom(receiver, newMember) + + assertFalse(ChronicleManager.requestIfEmpty(receiver, chatRoomId, newMember)) + + assertEquals(0, queued(receiver, ChronicleRequestEvent.KIND).size) + assertNull( + receiver.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.chronicleRequestedAt, + "a stamp would hold back a real request on the day the list grows" ) + assertEquals(emptyList(), lines(receiver)) + } + + /** + * Both ways a chronicle goes out -- the reply to a request and the push + * behind a Welcome -- from a room that holds plenty the group signed. The + * table holds every kind the group ever signed, so this is the filter on the + * way out doing its job, not an empty room. + */ + @Test + fun `under the app's own list a device sends nothing, even holding signed work`() = runBlocking { + seedSenderWork() + assertTrue(sender.groupSignedEventDao().getByChatRoomId(chatRoomId).isNotEmpty()) + + // Answering a request. + assertEquals(0, ChronicleManager.sendTo(sender, chatRoomId, oldMember, recipient = newMember)) + + // The push behind a Welcome, which calls the same thing with no kinds. + invite() + + assertEquals(0, queued(sender, ChronicleEvent.KIND).size) + assertEquals(emptyList(), lines(sender).filter { it in ChatMessage.CHRONICLE_TYPES }) + // And the invite itself still went out. + assertEquals(1, welcomesSent()) + } + + /** + * A member on an older build still chronicles, and its pages are genuine: + * events the room really signed, of kinds that build still lists. Arriving + * here they are refused by the list, not by the signature -- every payload + * counts as skipped, none as failed, so nothing waits to be retried. + */ + @Test + fun `under the app's own list a page from an older build applies nothing`() = runBlocking { + seedSenderWork() + seedRoom(receiver, newMember) + + val pages = senderChronicle() + val payloadCount = pages.sumOf { assertNotNull(ChronicleEvent.decodePage(it.content)).size } + + pages.forEach { deliver(it, kinds = ChronicleEvent.KINDS) } + + // And a sweep of everything stored, the way the next arrival would run it. + val outcome = ChronicleManager.sweep(receiver, chatRoomId, newMember) + + assertEquals(0, outcome.applied) + assertEquals(0, outcome.failed) + assertEquals(payloadCount, outcome.skipped) + + assertEquals(emptyList(), fingerprints(receiver)) + assertEquals(emptyList(), lines(receiver)) } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChronicleAssemblyJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChronicleAssemblyJvmTest.kt index ed613d76..4771e20c 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChronicleAssemblyJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/ChronicleAssemblyJvmTest.kt @@ -4,7 +4,10 @@ import androidx.room3.Room import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent import fr.acinq.bitcoin.ByteVector import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.PrivateKey @@ -25,30 +28,26 @@ import com.machankura.bennu.compose.database.builder.getRoomDatabase import com.machankura.bennu.compose.database.model.ChatMessage import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.MantraDialect +import com.machankura.bennu.compose.database.model.MarmotInnerEvent import com.machankura.bennu.compose.database.model.NostrEvent import com.machankura.bennu.compose.database.model.Profile import com.machankura.bennu.compose.extensions.toHex import com.machankura.bennu.compose.nostr.chronicle.ChronicleEvent +import com.machankura.bennu.compose.nostr.chronicle.TEST_KINDS import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent -import com.machankura.bennu.compose.nostr.nip30303.SubmissionEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent -import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.ChunkEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent -import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent /** - * Assembling a room's chronicle out of the rows a device actually holds. + * Assembling a room's chronicle out of what a device actually holds. * - * The seed is the real inbound path -- `ChatMessage.applyInnerEvent`, the same - * call a finished signing session makes -- so what is chronicled here is what a - * member's database really contains rather than rows built to suit the test. - * That matters because the whole risk in this direction is a rebuild that - * differs from what was signed, and rows assembled by hand would hide it. + * The seed is the real path a finished signing session takes -- the events filed + * in `GroupSignedEvent`, then handed to `ChatMessage.applyInnerEvent` -- so what is + * chronicled here is what a member's database really contains rather than rows + * built to suit the test. The record is the only source: nothing is rebuilt from + * rows, so what a chronicle carries is byte for byte what the group signed. + * + * The app's own list of kinds is empty, so these assemble with [TEST_KINDS]; the + * last case holds the default to assembling nothing. */ class ChronicleAssemblyJvmTest { private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) @@ -134,20 +133,17 @@ class ChronicleAssemblyJvmTest { ) } - /** - * Every event `apply` has been given, in the order it was given them. - * - * A test that wants the room's work on file as events too replays this - * through [record], which is the pair `FrostSigningManager.complete` writes - * in one pass. Kept here rather than returned by `seedSignedWork` so the - * seeding reads the same in both worlds. - */ - private val applied = mutableListOf() + /** Every event [seed] has been given, in the order it was given them. */ + private val seeded = mutableListOf() - /** What `FrostSigningManager.applySignedEvent` does, through the same call. */ - private suspend fun apply(template: EventTemplate<*>): Event { + /** + * What `FrostSigningManager.complete` does with a finished batch: file the + * event as the group signed it, then apply it through the same call. + */ + private suspend fun seed(template: EventTemplate<*>): Event { val event = signed(template) + record(event) ChatMessage.applyInnerEvent( database = db, groupId = chatRoomId, @@ -156,10 +152,11 @@ class ChronicleAssemblyJvmTest { marmotInnerEventId = null, senderPublicKey = chatRoomId, isUserMessage = false, - createdAt = Instant.fromEpochSeconds(event.createdAt) + createdAt = Instant.fromEpochSeconds(event.createdAt), + groupSignedEventId = event.id, ) - applied += event + seeded += event return event } @@ -178,9 +175,6 @@ class ChronicleAssemblyJvmTest { ) } - /** The whole seeded batch on file as events, as a device that signed it holds it. */ - private suspend fun recordEverythingApplied() = record(*applied.toTypedArray()) - /** ChatRoom -> Profile -> NostrEvent, the foreign key chain a room hangs off. */ private suspend fun seedRoom() { val nostrEventId = "c".repeat(64) @@ -208,105 +202,48 @@ class ChronicleAssemblyJvmTest { ) } - /** A room with one artifact, one chapter, two chunks and one translation. */ + private fun template(kind: Int, createdAt: Long, content: String, tags: Array> = emptyArray()) = + EventTemplate(createdAt = createdAt, kind = kind, tags = tags, content = content) + + /** + * A room that has signed a relay list, a profile and two posts, seeded posts + * first -- the reverse of the order they apply in, so that the chronicle being + * in order is something assembly did. + */ private suspend fun seedSignedWork() { seedRoom() - val dialect = apply( - DialectEvent.build(name = "isiZulu", country = "ZA", language = "zu", createdAt = 1_700_000_000L) - ) - - val artifact = apply( - ArtifactEvent.build( - name = "In Detention", - url = "https://example.com/in-detention", - visibility = "private", - license = "cc", - dialectId = dialect.id, - versionLabel = "1.0", - createdAt = 1_700_000_010L - ) - ) - - // The second item of the artifact's own batch, built the way the batch - // builds it. It used to be derived on arrival, which is why the chronicle - // once could not carry it: a derived row has no signature to check. - val version = apply(ArtifactVersionEvent.initialVersionOf(artifact).single()) - - val chapter = apply( - ChapterEvent.build( - artifactVersionId = version.id, - name = "Chapter One", - originalText = "He was a man of parts. He had many.", - index = 0, - wordCount = 8, - characterCount = 35, - createdAt = 1_700_000_020L - ) - ) - - val chunk = apply( - ChunkEvent.build( - chapterId = chapter.id, - text = "He was a man of parts.", - index = 0, - wordCount = 6, - characterCount = 22, - createdAt = 1_700_000_030L - ) - ) - apply( - ChunkEvent.build( - chapterId = chapter.id, - text = "He had many.", - index = 1, - wordCount = 3, - characterCount = 12, - createdAt = 1_700_000_031L - ) - ) - - val translationVersion = apply( - TranslationArtifactVersionEvent.build( - artifactVersionId = version.id, - dialectId = dialect.id, - name = "isiZulu", - visibility = "private", - license = "cc", - createdAt = 1_700_000_040L - ) - ) - - val translationChapter = apply( - TranslationChapterEvent.build( - translationArtifactVersionId = translationVersion.id, - chapterId = chapter.id, - index = 0, - createdAt = 1_700_000_050L - ) - ) - - // The translated text, which the group signs now rather than each member - // saving their own. - apply( - TranslationChunkEvent.build( - translationChapterId = translationChapter.id, - chunkId = chunk.id, - index = 0, - text = "Wayeyindoda enezingxenye.", - createdAt = 1_700_000_060L + seed(template(TextNoteEvent.KIND, 1_700_000_000L, "The group says hello.")) + seed(template(TextNoteEvent.KIND, 1_700_000_001L, "And says it again.")) + seed(template(MetadataEvent.KIND, 1_700_000_010L, "{\"name\":\"Ekklesia\"}")) + seed( + template( + AdvertisedRelayListEvent.KIND, 1_700_000_020L, "", + tags = arrayOf(arrayOf("r", "wss://relay.example.com")), ) ) } private suspend fun chronicledPayloads(): List = - ChronicleManager.assemble(db, chatRoomId, newMember) + ChronicleManager.assemble(db, chatRoomId, newMember, kinds = TEST_KINDS) .flatMap { assertNotNull(ChronicleEvent.decodePage(it.content)) } + /** + * Nothing leaves that the recipient could not check for themselves -- which + * includes a row on file whose fields have drifted from the event it + * recorded. Its id and signature are the group's; what they no longer cover + * is what it says. + */ @Test fun `every payload in a chronicle is one the room signed`() = runBlocking { seedSignedWork() + val drifted = signed(template(TextNoteEvent.KIND, 1_700_000_030L, "What the group said.")) + db.groupSignedEventDao().record( + GroupSignedEvent.fromEvent(event = drifted, chatRoomId = chatRoomId) + .copy(content = "What somebody wishes it had said.") + ) + val payloads = chronicledPayloads() assertTrue(payloads.isNotEmpty(), "a room with signed work chronicles something") @@ -316,6 +253,8 @@ class ChronicleAssemblyJvmTest { "kind ${it.kind} (${it.id.take(8)}) was chronicled without a signature the room can be checked for" ) } + assertTrue(payloads.none { it.id == drifted.id }, "the drifted row should have been left out") + assertEquals(seeded.map { it.id }.toSet(), payloads.map { it.id }.toSet()) } @Test @@ -324,71 +263,88 @@ class ChronicleAssemblyJvmTest { val byKind = chronicledPayloads().groupBy { it.kind } - assertEquals(1, byKind[DialectEvent.KIND]?.size) - assertEquals(1, byKind[ArtifactEvent.KIND]?.size) - assertEquals(1, byKind[ArtifactVersionEvent.KIND]?.size) - assertEquals(1, byKind[ChapterEvent.KIND]?.size) - assertEquals(2, byKind[ChunkEvent.KIND]?.size) - assertEquals(1, byKind[TranslationArtifactVersionEvent.KIND]?.size) - assertEquals(1, byKind[TranslationChapterEvent.KIND]?.size) - assertEquals(1, byKind[TranslationChunkEvent.KIND]?.size) + assertEquals(1, byKind[AdvertisedRelayListEvent.KIND]?.size) + assertEquals(1, byKind[MetadataEvent.KIND]?.size) + assertEquals(2, byKind[TextNoteEvent.KIND]?.size) - assertEquals(ChronicleEvent.CHRONICLABLE_KINDS, byKind.keys) + assertEquals(TEST_KINDS.all, byKind.keys) } @Test - fun `a chronicle is in dependency order across its whole length`() = runBlocking { + fun `a chronicle is in the list's order across its whole length`() = runBlocking { seedSignedWork() - val ranks = chronicledPayloads().map { assertNotNull(ChronicleEvent.applyRank(it.kind)) } + val ranks = chronicledPayloads().map { assertNotNull(TEST_KINDS.applyRank(it.kind)) } - assertEquals(ranks.sorted(), ranks, "a chronicle out of order is a foreign key violation") + // Seeded in the reverse order, so a chronicle that kept the table's order + // would fail here. In the app this is a foreign key violation on the + // receiver rather than a wrong answer. + assertEquals(ranks.sorted(), ranks, "a chronicle out of order is applied out of order") } @Test fun `a member's own rumor is not part of the group's record`() = runBlocking { seedSignedWork() - // What `MantraDao.addDialect` writes: the member's key, no signature. It - // is real work in the room and the group never signed it, so it cannot be + // A member's own kind:1, travelling through the room the way everything + // on the wire does: stored as an inner event and applied. It is real + // content in the room and the group never signed it, so it cannot be // handed to somebody who has no way to check it. - db.mantraDialectDao().upsert( - MantraDialect( - id = "f".repeat(64), - publicKey = newMember, - name = "seSotho", - country = "ZA", - language = "st", - signature = "", + val rumor = Event( + id = EventHasher.hashId( + pubKey = newMember, createdAt = 1_700_000_060L, kind = TextNoteEvent.KIND, + tags = emptyArray(), content = "My own note." + ), + pubKey = newMember, createdAt = 1_700_000_060L, kind = TextNoteEvent.KIND, + tags = emptyArray(), content = "My own note.", sig = "" + ) + db.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = rumor.id, + publicKey = rumor.pubKey, + kind = rumor.kind, + createdAt = Instant.fromEpochSeconds(rumor.createdAt), + tags = rumor.tags, + content = rumor.content, chatRoomId = chatRoomId, - createdAt = Instant.fromEpochSeconds(1_700_000_060L), ) ) + ChatMessage.applyInnerEvent( + database = db, + groupId = chatRoomId, + event = rumor, + marmotGroupEventId = null, + marmotInnerEventId = rumor.id, + senderPublicKey = newMember, + isUserMessage = true, + createdAt = Instant.fromEpochSeconds(rumor.createdAt), + ) assertEquals( - 2, - db.mantraDialectDao().getDialectsByChatRoomId(chatRoomId).size, + 1, + db.marmotInnerEventDao().getByChatRoomAndKinds(chatRoomId, listOf(TextNoteEvent.KIND)).size, "the rumor should be on disk" ) assertEquals( - 1, - chronicledPayloads().count { it.kind == DialectEvent.KIND }, - "the unsigned dialect should not have been chronicled" + 2, + chronicledPayloads().count { it.kind == TextNoteEvent.KIND }, + "only the group's two posts should have been chronicled" ) + assertTrue(chronicledPayloads().none { it.id == rumor.id }) } @Test fun `a room with nothing signed chronicles nothing, and says so rather than failing`() = runBlocking { seedRoom() - assertEquals(emptyList(), ChronicleManager.assemble(db, chatRoomId, newMember)) + assertEquals(emptyList(), ChronicleManager.assemble(db, chatRoomId, newMember, kinds = TEST_KINDS)) } @Test fun `a chronicle of one page still says it is one of one`() = runBlocking { seedSignedWork() - val pages = ChronicleManager.assemble(db, chatRoomId, newMember) + val pages = ChronicleManager.assemble(db, chatRoomId, newMember, kinds = TEST_KINDS) assertEquals(1, pages.size, "this much work fits one page") @@ -407,29 +363,25 @@ class ChronicleAssemblyJvmTest { assertNotNull(page.chronicleId()) } - // ---- Reading from the record rather than rebuilding ------------------- - /** * The events, not a reconstruction of them. * - * Byte-for-byte against what was signed, which is the assertion the whole - * rebuild machinery exists to approximate. Here it is exact by construction: - * nothing is rebuilt, so there is no tag order to get wrong and no field a - * row could have failed to keep. + * Byte-for-byte against what was signed. Exact by construction: nothing is + * rebuilt, so there is no tag order to get wrong and no field a row could + * have failed to keep. */ @Test fun `a chronicle carries the group's events as the group signed them`() = runBlocking { seedSignedWork() - recordEverythingApplied() val payloads = chronicledPayloads().associateBy { it.id } assertEquals( - applied.map { it.id }.toSet(), + seeded.map { it.id }.toSet(), payloads.keys, "everything the group signed here should be in the chronicle" ) - applied.forEach { event -> + seeded.forEach { event -> assertEquals( event.toJson(), assertNotNull(payloads[event.id]).toJson(), @@ -439,41 +391,11 @@ class ChronicleAssemblyJvmTest { } /** - * Both sources, one chronicle, and nothing counted twice. + * The failure the record makes possible, and the allowlist that stops it. * - * The state a device upgrading mid-life is in: older work only the rows - * remember, newer work on file as events. Neither half is the chronicle on its - * own, and an event held both ways is still one event. - */ - @Test - fun `work held both ways travels exactly once`() = runBlocking { - seedSignedWork() - - // Half the batch on file, the other half only as rows -- which is what - // a room that was upgraded partway through its life looks like. - record(*applied.take(applied.size / 2).toTypedArray()) - - val payloads = chronicledPayloads() - - assertEquals( - applied.map { it.id }.toSet(), - payloads.map { it.id }.toSet(), - "the two sources together should still be the whole record" - ) - assertEquals( - payloads.size, - payloads.map { it.id }.toSet().size, - "an event on file and rebuildable is one event, not two" - ) - } - - /** - * The failure this source made possible, and the allowlist that stops it. - * - * A key state is group-signed and verifies perfectly. The rebuild could not - * reach one because no `Mantra*` row holds it; the record holds every kind. - * Without the filter on the way out `ChronicleEvent.build` refuses the page - * and the room's whole chronicle fails on one event. + * A key state is group-signed and verifies perfectly, and the record holds + * every kind. Without the filter on the way out `ChronicleEvent.build` + * refuses the page and the room's whole chronicle fails on one event. * * A room no longer signs its own key state -- a group agrees that before the * room exists, in the NIP-17 room its ceremony ran in, and files it under @@ -485,7 +407,6 @@ class ChronicleAssemblyJvmTest { @Test fun `a key state the room really signed is never chronicled`() = runBlocking { seedSignedWork() - recordEverythingApplied() val keyState = signed( EventTemplate( @@ -508,88 +429,21 @@ class ChronicleAssemblyJvmTest { assertTrue(payloads.isNotEmpty(), "the rest of the room's work still chronicles") assertEquals( - ChronicleEvent.CHRONICLABLE_KINDS, + TEST_KINDS.all, payloads.map { it.kind }.toSet(), - "a chronicle carries the document kinds and nothing else" + "a chronicle carries the listed kinds and nothing else" ) assertTrue(payloads.none { it.id == keyState.id }) } /** The same rule, for a kind that is merely not on the list rather than dangerous. */ @Test - fun `a signed kind the chronicle has no arm for is left behind`() = runBlocking { + fun `a signed kind off the list is left behind`() = runBlocking { seedSignedWork() - recordEverythingApplied() - record( - signed( - EventTemplate( - createdAt = 1_700_000_080L, - kind = SubmissionEvent.KIND, - tags = emptyArray(), - content = "{}", - ) - ) - ) + record(signed(template(GroupWalletStatementEvent.KIND, 1_700_000_080L, "{}"))) - assertEquals( - ChronicleEvent.CHRONICLABLE_KINDS, - chronicledPayloads().map { it.kind }.toSet() - ) - } - - /** - * The case the rebuild cannot reach at all, which is why the record is the - * source and not merely a faster one. - * - * `MantraArtifact` does not hold the version label it was signed with -- - * `fromArtifactEvent` drops it -- so `toArtifactEvent` has to go and find it - * on the initial version, and an artifact whose version row is missing is one - * the rebuild logs and leaves out. On file as an event there is nothing to - * find: the label never left. - */ - @Test - fun `an artifact the rebuild has to leave out still chronicles from the record`() = runBlocking { - seedRoom() - - val dialect = apply( - DialectEvent.build(name = "isiZulu", country = "ZA", language = "zu", createdAt = 1_700_000_000L) - ) - - // Applied without the second item of its batch, so no version row carries - // the label back. A device that was offline for half a batch, or one that - // failed to apply the version, is in exactly this state. - val artifact = apply( - ArtifactEvent.build( - name = "In Detention", - url = "https://example.com/in-detention", - visibility = "private", - license = "cc", - dialectId = dialect.id, - versionLabel = "1.0", - createdAt = 1_700_000_010L - ) - ) - - assertEquals( - emptyList(), - db.mantraArtifactVersionDao().getArtifactVersionsByArtifactId(artifact.id), - "this test is only about an artifact whose initial version is missing" - ) - - // Rows only: the rebuild reaches the dialect and gives up on the artifact. - assertEquals( - listOf(dialect.id), - chronicledPayloads().map { it.id }, - ) - - record(dialect, artifact) - - assertEquals( - setOf(dialect.id, artifact.id), - chronicledPayloads().map { it.id }.toSet(), - "the record holds the whole event, version label and all" - ) + assertEquals(TEST_KINDS.all, chronicledPayloads().map { it.kind }.toSet()) } @Test @@ -609,144 +463,21 @@ class ChronicleAssemblyJvmTest { // counts differ whenever their databases do. Sharing an id would let one // chronicle's pages be counted towards the other's total. assertTrue( - idOf(ChronicleManager.assemble(db, chatRoomId, newMember).single()) != - idOf(ChronicleManager.assemble(db, chatRoomId, newMember).single()) + idOf(ChronicleManager.assemble(db, chatRoomId, newMember, kinds = TEST_KINDS).single()) != + idOf(ChronicleManager.assemble(db, chatRoomId, newMember, kinds = TEST_KINDS).single()) ) } - // ---- Supersession ---------------------------------------------------- - // - // The record keeps every event the group signed; the rows keep one - // translation per passage. Reading the chronicle from the record is what makes - // the difference visible, and these are what keep the two sides agreeing - // about which translation stands. - - /** The passage the seed already translated, resolved back out of the rows. */ - private suspend fun seededPassage(): Pair { - val artifactId = db.mantraArtifactDao().getArtifactsByChatRoomId(chatRoomId).single().id - val versionId = db.mantraArtifactVersionDao() - .getArtifactVersionsByArtifactId(artifactId).single().id - val chapterId = db.mantraChapterDao().getChaptersByArtifactVersionId(versionId).single().id - val chunkId = db.mantraChunkDao().getChunksByChapterId(chapterId).first().id - val translationChapterId = db.mantraTranslationChapterDao() - .getTranslationChaptersByTranslationArtifactVersionId( - db.mantraTranslationArtifactVersionDao() - .getTranslationsByArtifactVersionId(versionId).single().id - ).single().id - - return translationChapterId to chunkId - } - - private suspend fun chronicledTranslations(): List = - ChronicleManager.assemble(db, chatRoomId, newMember) - .flatMap { assertNotNull(ChronicleEvent.decodePage(it.content)) } - .filter { it.kind == TranslationChunkEvent.KIND } - + /** + * The default the app's call sites use. A room full of signed work assembles + * to nothing, because the filter on the way out is the list and the list is + * empty -- see `ChronicleApplyJvmTest` for the same from the sending side. + */ @Test - fun `a retranslated passage chronicles once, not once per draft`() = runBlocking { + fun `under the app's own list a room with signed work assembles nothing`() = runBlocking { seedSignedWork() - val (translationChapterId, chunkId) = seededPassage() + assertTrue(db.groupSignedEventDao().getByChatRoomId(chatRoomId).isNotEmpty()) - val current = apply( - TranslationChunkEvent.build( - translationChapterId = translationChapterId, - chunkId = chunkId, - index = 0, - text = "A better rendering.", - createdAt = 1_700_000_070L - ) - ) - recordEverythingApplied() - - // One row, because the applying arm superseded the first. Two events, - // because the record keeps what the group signed and does not pretend a - // signature was never made. - assertEquals( - 1, - db.mantraTranslationChunkDao() - .getTranslationChunksByTranslationChapterId(translationChapterId).size - ) - assertEquals( - 2, - db.groupSignedEventDao().getByChatRoomIdAndKind(chatRoomId, TranslationChunkEvent.KIND).size - ) - - // And one payload. Otherwise every draft a group ever signed travels in - // every chronicle it ever sends, for as long as the room exists. - assertEquals(listOf(current.id), chronicledTranslations().map { it.id }) - } - - @Test - fun `the chronicle picks the translation the recipient would keep`() = runBlocking { - seedSignedWork() - val (translationChapterId, chunkId) = seededPassage() - - // Two translations signed in the same second, which the applying arm - // settles by id. The chronicle has to settle it the same way or it ships - // one as current while the recipient keeps the other -- and both being - // validly signed, nothing downstream would notice they disagree. - val sameSecond = 1_700_000_070L - val rivals = listOf("Rendering one.", "Rendering two.", "Rendering three.") - .map { text -> - apply( - TranslationChunkEvent.build( - translationChapterId = translationChapterId, - chunkId = chunkId, - index = 0, - text = text, - createdAt = sameSecond - ) - ) - } - recordEverythingApplied() - - val kept = db.mantraTranslationChunkDao() - .getTranslationChunksByTranslationChapterId(translationChapterId).single() - - assertEquals(rivals.maxOf { it.id }, kept.id, "the row keeps the highest id of the second") - assertEquals(listOf(kept.id), chronicledTranslations().map { it.id }) - } - - @Test - fun `two passages each keep their own current translation`() = runBlocking { - seedSignedWork() - val (translationChapterId, firstChunkId) = seededPassage() - - val chapterId = db.mantraChapterDao() - .getChaptersByArtifactVersionId( - db.mantraArtifactVersionDao() - .getArtifactVersionsByArtifactId( - db.mantraArtifactDao().getArtifactsByChatRoomId(chatRoomId).single().id - ).single().id - ).single().id - val secondChunkId = db.mantraChunkDao().getChunksByChapterId(chapterId) - .first { it.id != firstChunkId }.id - - // Grouping is per passage, so retranslating one must not take the other - // with it -- the bug a naive "newest translation wins" would have. - val retranslated = apply( - TranslationChunkEvent.build( - translationChapterId = translationChapterId, - chunkId = firstChunkId, - index = 0, - text = "A better rendering.", - createdAt = 1_700_000_070L - ) - ) - val other = apply( - TranslationChunkEvent.build( - translationChapterId = translationChapterId, - chunkId = secondChunkId, - index = 1, - text = "Wayenezinye eziningi.", - createdAt = 1_700_000_065L - ) - ) - recordEverythingApplied() - - assertEquals( - setOf(retranslated.id, other.id), - chronicledTranslations().map { it.id }.toSet() - ) + assertEquals(emptyList(), ChronicleManager.assemble(db, chatRoomId, newMember)) } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SignedGroupKeyStateTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SignedGroupKeyStateTest.kt index 8bcfa422..8b8d8815 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SignedGroupKeyStateTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SignedGroupKeyStateTest.kt @@ -26,6 +26,7 @@ import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Instant import kotlinx.coroutines.flow.first +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import kotlinx.coroutines.runBlocking import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.database.model.ChatMessage @@ -47,7 +48,6 @@ import com.machankura.bennu.compose.extensions.toHex import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents import com.machankura.bennu.compose.nostr.frost.FrostSigningEvents import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent -import com.machankura.bennu.compose.nostr.nip30303.DialectEvent /** * Two devices, two databases, one real signing session, and the wire between @@ -877,7 +877,7 @@ class SignedGroupKeyStateTest { database = creator.db, localChatRoom = creator.room, userPublicKey = creator.publicKey, - events = dialects() + events = posts() ) pump(creator, other) FrostSigningManager.approve(other.db, other.room, session.id) @@ -924,7 +924,7 @@ class SignedGroupKeyStateTest { database = creator.db, localChatRoom = creator.room, userPublicKey = creator.publicKey, - events = dialects() + events = posts() ) pump(creator, other) FrostSigningManager.approve(other.db, other.room, session.id) @@ -973,7 +973,7 @@ class SignedGroupKeyStateTest { database = creator.db, localChatRoom = creator.room, userPublicKey = creator.publicKey, - events = dialects() + events = posts() ) pump(creator, other) FrostSigningManager.approve(other.db, other.room, session.id) @@ -1006,7 +1006,7 @@ class SignedGroupKeyStateTest { database = creator.db, localChatRoom = creator.room, userPublicKey = creator.publicKey, - events = dialects() + events = posts() ) pump(creator, other) FrostSigningManager.approve(other.db, other.room, session.id) @@ -1042,9 +1042,9 @@ class SignedGroupKeyStateTest { ) } - /** Every event of a batch is applied, not just the first. */ + /** Every event of a batch is recorded as signed, not just the first. */ @Test - fun `every dialect in a batch lands on every device`() = runBlocking { + fun `every post in a batch lands on every device`() = runBlocking { val creator = device(members[0], signerIndex = 0) val other = device(members[1], signerIndex = 1) @@ -1052,21 +1052,21 @@ class SignedGroupKeyStateTest { database = creator.db, localChatRoom = creator.room, userPublicKey = creator.publicKey, - events = dialects() + events = posts() ) pump(creator, other) FrostSigningManager.approve(other.db, other.room, session.id) pump(creator, other) listOf(creator, other).forEach { device -> - val names = device.items(session.id).map { item -> + val notes = device.items(session.id).map { item -> assertNotNull( - device.db.mantraDialectDao().getDialectById(item.eventId), - "item ${item.itemIndex} should have been applied" - ).name + device.db.groupSignedEventDao().getById(item.eventId), + "item ${item.itemIndex} should have been recorded as signed" + ).content } - assertEquals(listOf("Sepedi", "isiZulu", "Setswana"), names) + assertEquals(listOf("Sepedi", "isiZulu", "Setswana"), notes) } } @@ -1080,7 +1080,7 @@ class SignedGroupKeyStateTest { val creator = device(members[0], signerIndex = 0) val tooMany = (0..FrostSigningManager.MAX_BATCH_SIZE).map { index -> - DialectEvent.build(name = "d$index", country = "ZA", language = "l$index") + TextNoteEvent.build(note = "post $index") } assertFailsWith { @@ -1113,7 +1113,7 @@ class SignedGroupKeyStateTest { database = creator.db, localChatRoom = creator.room, userPublicKey = creator.publicKey, - events = dialects() + events = posts() ) pump(creator, other) @@ -1165,13 +1165,13 @@ class SignedGroupKeyStateTest { database = creator.db, localChatRoom = creator.room, userPublicKey = creator.publicKey, - events = dialects() + events = posts() ) pump(creator, other) val before = other.items(session.id) - val substitute = DialectEvent.build(name = "Xitsonga", country = "ZA", language = "tso") + val substitute = TextNoteEvent.build(note = "Xitsonga") FrostSigningManager.processSigningPayload( database = other.db, localChatRoom = other.room, @@ -1207,23 +1207,19 @@ class SignedGroupKeyStateTest { assertEquals(before.map { it.nonceRandom }, other.items(session.id).map { it.nonceRandom }) } - /** Three dialects, distinct enough that an order bug shows up as a wrong name. */ - private fun dialects() = listOf( - Triple("Sepedi", "ZA", "nso"), - Triple("isiZulu", "ZA", "zul"), - Triple("Setswana", "ZA", "tsn"), - ).map { (name, country, language) -> - DialectEvent.build(name = name, country = country, language = language) + /** Three posts, distinct enough that an order bug shows up as the wrong words. */ + private fun posts() = listOf("Sepedi", "isiZulu", "Setswana").map { note -> + TextNoteEvent.build(note = note) } // ---- What a room signs as, once it has a key state --------------------- @Test - fun `a dialect the group signs is authored by the room it was signed in`() = runBlocking { + fun `a post the group signs is authored by the room it was signed in`() = runBlocking { val creator = device(members[0], signerIndex = 0) val other = device(members[1], signerIndex = 1) - val template = DialectEvent.build(name = "Sepedi", country = "ZA", language = "nso") + val template = TextNoteEvent.build(note = "Sepedi") val session = FrostSigningManager.proposeSigning( database = creator.db, localChatRoom = creator.room, @@ -1237,19 +1233,19 @@ class SignedGroupKeyStateTest { pump(creator, other) listOf(creator, other).forEach { device -> - val dialect = device.db.mantraDialectDao().getDialectById(device.item(session.id).eventId) - assertNotNull(dialect, "a signed dialect should exist on every signer's device") - assertEquals("Sepedi", dialect.name) + val post = device.db.groupSignedEventDao().getById(device.item(session.id).eventId) + assertNotNull(post, "a signed post should exist on every signer's device") + assertEquals("Sepedi", post.content) // The ask this whole change serves: the group's work is authored by // the group's room, not by the member who typed it and not by the // bare threshold key. - assertEquals(adminRoomId, dialect.publicKey) - assertTrue(dialect.publicKey != creator.publicKey) - assertTrue(dialect.publicKey != rootPublicKey) + assertEquals(adminRoomId, post.publicKey) + assertTrue(post.publicKey != creator.publicKey) + assertTrue(post.publicKey != rootPublicKey) assertTrue( Nip01Crypto.verify( - signature = dialect.signature.hexToByteArray(), - hash = dialect.id.hexToByteArray(), + signature = post.signature.hexToByteArray(), + hash = post.id.hexToByteArray(), pubKey = adminRoomId.hexToByteArray() ) ) @@ -1402,7 +1398,7 @@ class SignedGroupKeyStateTest { description = null ) - val template = DialectEvent.build(name = "Sepedi", country = "ZA", language = "nso") + val template = TextNoteEvent.build(note = "Sepedi") val session = FrostSigningManager.proposeSigning( database = creator.db, localChatRoom = creator.room, @@ -1435,7 +1431,7 @@ class SignedGroupKeyStateTest { ) member.db.chatRoomDao().upsert(bystanderRoom) - val template = DialectEvent.build(name = "Sepedi", country = "ZA", language = "nso") + val template = TextNoteEvent.build(note = "Sepedi") assertFailsWith { FrostSigningManager.proposeSigning(