From e723e70a59317ba1cd41b729acc7a5fa996445ff Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 01:00:30 +0200 Subject: [PATCH 01/16] feat: a confederation signs as itself, one person per device (confederation, Phase 14) Every role holder is asked; the proposer fixes the selection from the first yeses, and each selected role makes a nonce held in memory only, confirms and gives its partial. The transcript, the certificate, each group's partial and the signature need no secret, so every device computes them and checks the signature against the room's id before keeping it. A device that restarts mid-attempt ends it out loud. Co-Authored-By: Claude Opus 5.5 --- .../45.json | 6037 +++++++++++++++++ .../giza/compose/database/GizaDatabase.kt | 9 +- .../database/dao/ConfederationCeremonyDao.kt | 27 + .../giza/compose/database/dao/NostrDao.kt | 16 + .../compose/database/model/ChatMessage.kt | 10 +- .../model/ConfederationSigningAttempt.kt | 72 + .../repository/DatabaseChatRepository.kt | 4 + .../managers/ConfederationSigningManager.kt | 567 ++ .../ConfederationSigningEvents.kt | 80 + .../composable/widgets/chat/ChatTranscript.kt | 2 + .../ShippedProfileUpgradeJvmTest.kt | 7 +- .../managers/ConfederationSigningJvmTest.kt | 217 + docs/confederation.md | 1 + 13 files changed, 7044 insertions(+), 5 deletions(-) create mode 100644 composeApp/schemas/mobi.giza.compose.database.GizaDatabase/45.json create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ConfederationSigningAttempt.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationSigningEvents.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt diff --git a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/45.json b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/45.json new file mode 100644 index 00000000..5fb7cdb8 --- /dev/null +++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/45.json @@ -0,0 +1,6037 @@ +{ + "formatVersion": 1, + "database": { + "version": 45, + "identityHash": "4097e68a695ef0410fb2c8968c8fb2f3", + "entities": [ + { + "tableName": "BroadcastNostrEventReceipt", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `nostrEventId` TEXT NOT NULL, `unsignedNostrEventId` INTEGER, `isAccepted` INTEGER NOT NULL, `isSync` INTEGER NOT NULL, `relayURL` TEXT NOT NULL, `messages` TEXT, FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "isAccepted", + "columnName": "isAccepted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isSync", + "columnName": "isSync", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messages", + "columnName": "messages", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_BroadcastNostrEventReceipt_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventReceipt_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_BroadcastNostrEventReceipt_isAccepted", + "unique": false, + "columnNames": [ + "isAccepted" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventReceipt_isAccepted` ON `${TABLE_NAME}` (`isAccepted`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "BroadcastNostrEventRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `nostrEventId` TEXT NOT NULL, `unsignedNostrEventId` INTEGER, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_BroadcastNostrEventRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_BroadcastNostrEventRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Connection", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sourcePublicKey` TEXT NOT NULL, `destinationPublicKey` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`sourcePublicKey`, `destinationPublicKey`), FOREIGN KEY(`sourcePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`destinationPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sourcePublicKey", + "columnName": "sourcePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "destinationPublicKey", + "columnName": "destinationPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sourcePublicKey", + "destinationPublicKey" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sourcePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "destinationPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + } + ] + }, + { + "tableName": "ChatMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `senderPublicKey` TEXT NOT NULL, `isUserMessage` INTEGER NOT NULL, `giftWrapPayloadId` TEXT, `marmotGroupEventId` TEXT, `marmotInnerEventId` TEXT, `chatRoomId` TEXT NOT NULL, `replyToMessageId` INTEGER, `quotedMessageId` INTEGER, `content` TEXT NOT NULL, `messageType` TEXT NOT NULL, `directMessageRecipientPublicKey` TEXT, `frostSigningSessionId` TEXT, `dkgSessionId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`giftWrapPayloadId`) REFERENCES `GiftWrapPayload`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`marmotGroupEventId`) REFERENCES `MarmotGroupEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`marmotInnerEventId`) REFERENCES `MarmotInnerEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isUserMessage", + "columnName": "isUserMessage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "giftWrapPayloadId", + "columnName": "giftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotInnerEventId", + "columnName": "marmotInnerEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToMessageId", + "columnName": "replyToMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "quotedMessageId", + "columnName": "quotedMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messageType", + "columnName": "messageType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "directMessageRecipientPublicKey", + "columnName": "directMessageRecipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ChatMessage_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ChatMessage_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "GiftWrapPayload", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapPayloadId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MarmotGroupEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotGroupEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MarmotInnerEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotInnerEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageBroadcastNostrEventRequestRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `broadcastNostrEventRequestId` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`broadcastNostrEventRequestId`) REFERENCES `BroadcastNostrEventRequest`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "broadcastNostrEventRequestId", + "columnName": "broadcastNostrEventRequestId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "BroadcastNostrEventRequest", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "broadcastNostrEventRequestId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageBroadcastNostrEventReceiptRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `broadcastNostrEventReceiptId` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`broadcastNostrEventReceiptId`) REFERENCES `BroadcastNostrEventReceipt`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "broadcastNostrEventReceiptId", + "columnName": "broadcastNostrEventReceiptId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "BroadcastNostrEventReceipt", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "broadcastNostrEventReceiptId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageNostrEventRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatRoom", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `subject` TEXT, `description` TEXT, `mlsGroupState` TEXT, `initialGiftWrapPayloadId` TEXT, `leftGroupAt` INTEGER, `joinedGroupAt` INTEGER, `chronicleRequestedAt` INTEGER, `parentChatRoomId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`userPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`initialGiftWrapPayloadId`) REFERENCES `GiftWrapPayload`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT" + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT" + }, + { + "fieldPath": "mlsGroupState", + "columnName": "mlsGroupState", + "affinity": "TEXT" + }, + { + "fieldPath": "initialGiftWrapPayloadId", + "columnName": "initialGiftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "leftGroupAt", + "columnName": "leftGroupAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "joinedGroupAt", + "columnName": "joinedGroupAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "chronicleRequestedAt", + "columnName": "chronicleRequestedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "userPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "GiftWrapPayload", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "initialGiftWrapPayloadId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Confederation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `ceremonyId` TEXT NOT NULL, `name` TEXT NOT NULL, `roster` TEXT NOT NULL, `keyState` TEXT NOT NULL, `genesis` TEXT NOT NULL, `configSeq` INTEGER NOT NULL, `rosterHash` TEXT NOT NULL, `keyStateHash` TEXT NOT NULL, `recoveryPackages` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ceremonyId", + "columnName": "ceremonyId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roster", + "columnName": "roster", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyState", + "columnName": "keyState", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "genesis", + "columnName": "genesis", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "configSeq", + "columnName": "configSeq", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rosterHash", + "columnName": "rosterHash", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyStateHash", + "columnName": "keyStateHash", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "recoveryPackages", + "columnName": "recoveryPackages", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Confederation_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Confederation_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + } + ] + }, + { + "tableName": "ConfederationCeremony", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `openingJson` TEXT NOT NULL, `stage` TEXT NOT NULL, `approvedAt` INTEGER, `dealerSeeds` TEXT, `recoveryNonces` TEXT, `keyState` TEXT, `transitionHash` TEXT, `genesis` TEXT, `recoveryPackages` TEXT, `confederationPublicKey` TEXT, `failureReason` TEXT, `culprit` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "openingJson", + "columnName": "openingJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "approvedAt", + "columnName": "approvedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "dealerSeeds", + "columnName": "dealerSeeds", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryNonces", + "columnName": "recoveryNonces", + "affinity": "TEXT" + }, + { + "fieldPath": "keyState", + "columnName": "keyState", + "affinity": "TEXT" + }, + { + "fieldPath": "transitionHash", + "columnName": "transitionHash", + "affinity": "TEXT" + }, + { + "fieldPath": "genesis", + "columnName": "genesis", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryPackages", + "columnName": "recoveryPackages", + "affinity": "TEXT" + }, + { + "fieldPath": "confederationPublicKey", + "columnName": "confederationPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "culprit", + "columnName": "culprit", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ConfederationCeremony_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationCeremony_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_ConfederationCeremony_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationCeremony_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationMember", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`confederationId` TEXT NOT NULL, `groupPublicKey` TEXT NOT NULL, PRIMARY KEY(`confederationId`, `groupPublicKey`))", + "fields": [ + { + "fieldPath": "confederationId", + "columnName": "confederationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "groupPublicKey", + "columnName": "groupPublicKey", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "confederationId", + "groupPublicKey" + ] + }, + "indices": [ + { + "name": "index_ConfederationMember_groupPublicKey", + "unique": false, + "columnNames": [ + "groupPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationMember_groupPublicKey` ON `${TABLE_NAME}` (`groupPublicKey`)" + } + ] + }, + { + "tableName": "ConfederationSigningAttempt", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `confederationId` TEXT NOT NULL, `proposerPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `eventJson` TEXT NOT NULL, `stage` TEXT NOT NULL, `approvedAt` INTEGER, `declinedAt` INTEGER, `signedEventJson` TEXT, `failureReason` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`confederationId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "confederationId", + "columnName": "confederationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposerPublicKey", + "columnName": "proposerPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventJson", + "columnName": "eventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "approvedAt", + "columnName": "approvedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "declinedAt", + "columnName": "declinedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "signedEventJson", + "columnName": "signedEventJson", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ConfederationSigningAttempt_confederationId", + "unique": false, + "columnNames": [ + "confederationId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationSigningAttempt_confederationId` ON `${TABLE_NAME}` (`confederationId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "confederationId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationSigningMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`attemptId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`attemptId`, `senderPublicKey`, `kind`), FOREIGN KEY(`attemptId`) REFERENCES `ConfederationSigningAttempt`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "attemptId", + "columnName": "attemptId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "attemptId", + "senderPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "ConfederationSigningAttempt", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "attemptId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationCeremonyMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `senderPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `ConfederationCeremony`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "senderPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "ConfederationCeremony", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `kind` INTEGER NOT NULL, `pubKey` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `eventCreatedAt` INTEGER NOT NULL, `eventJson` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, `ownSessionId` TEXT, `publishedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventCreatedAt", + "columnName": "eventCreatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "eventJson", + "columnName": "eventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "ownSessionId", + "columnName": "ownSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "publishedAt", + "columnName": "publishedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ConfederationEvent_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + }, + { + "name": "index_ConfederationEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_ConfederationEvent_publishedAt", + "unique": false, + "columnNames": [ + "publishedAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_publishedAt` ON `${TABLE_NAME}` (`publishedAt`)" + } + ] + }, + { + "tableName": "ConfederationInvitee", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`proposalId` TEXT NOT NULL, `groupPublicKey` TEXT NOT NULL, PRIMARY KEY(`proposalId`, `groupPublicKey`))", + "fields": [ + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "groupPublicKey", + "columnName": "groupPublicKey", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "proposalId", + "groupPublicKey" + ] + }, + "indices": [ + { + "name": "index_ConfederationInvitee_groupPublicKey", + "unique": false, + "columnNames": [ + "groupPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationInvitee_groupPublicKey` ON `${TABLE_NAME}` (`groupPublicKey`)" + } + ] + }, + { + "tableName": "ConfederationSigning", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `sealSecret` TEXT, `proposalJson` TEXT, `refusal` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sealSecret", + "columnName": "sealSecret", + "affinity": "TEXT" + }, + { + "fieldPath": "proposalJson", + "columnName": "proposalJson", + "affinity": "TEXT" + }, + { + "fieldPath": "refusal", + "columnName": "refusal", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId" + ] + }, + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "DkgParticipantMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `participantPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `participantPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "participantPublicKey", + "kind" + ] + }, + "indices": [ + { + "name": "index_DkgParticipantMessage_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_DkgParticipantMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "DkgSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "DkgSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `threshold` INTEGER NOT NULL, `participantCount` INTEGER NOT NULL, `participantPublicKeys` TEXT, `subject` TEXT, `walletPolicy` TEXT, `stage` TEXT NOT NULL, `hostPublicKey` TEXT NOT NULL, `round1Random` TEXT NOT NULL, `round2AuxRandom` TEXT NOT NULL, `coordinatorRound1` TEXT, `certificate` TEXT, `thresholdPublicKey` TEXT, `secretShare` TEXT, `publicShares` TEXT, `recoveryData` TEXT, `failureReason` TEXT, `hostKeyApprovedAt` INTEGER, `round1ApprovedAt` INTEGER, `round2ApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `parentChatRoomId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "threshold", + "columnName": "threshold", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantCount", + "columnName": "participantCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantPublicKeys", + "columnName": "participantPublicKeys", + "affinity": "TEXT" + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT" + }, + { + "fieldPath": "walletPolicy", + "columnName": "walletPolicy", + "affinity": "TEXT" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "hostPublicKey", + "columnName": "hostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round1Random", + "columnName": "round1Random", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round2AuxRandom", + "columnName": "round2AuxRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorRound1", + "columnName": "coordinatorRound1", + "affinity": "TEXT" + }, + { + "fieldPath": "certificate", + "columnName": "certificate", + "affinity": "TEXT" + }, + { + "fieldPath": "thresholdPublicKey", + "columnName": "thresholdPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "secretShare", + "columnName": "secretShare", + "affinity": "TEXT" + }, + { + "fieldPath": "publicShares", + "columnName": "publicShares", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "hostKeyApprovedAt", + "columnName": "hostKeyApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "round1ApprovedAt", + "columnName": "round1ApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "round2ApprovedAt", + "columnName": "round2ApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedThrough", + "columnName": "approvalRequestedThrough", + "affinity": "TEXT" + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_DkgSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_DkgSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSignerMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `signerPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `signerPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signerPublicKey", + "columnName": "signerPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "signerPublicKey", + "kind" + ] + }, + "indices": [ + { + "name": "index_FrostSignerMessage_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSignerMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSigningItem", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `itemIndex` INTEGER NOT NULL, `unsignedEventJson` TEXT NOT NULL, `eventId` TEXT NOT NULL, `nonceRandom` TEXT NOT NULL, `aggregatedNonce` TEXT, `signature` TEXT, PRIMARY KEY(`sessionId`, `itemIndex`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "itemIndex", + "columnName": "itemIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "unsignedEventJson", + "columnName": "unsignedEventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventId", + "columnName": "eventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nonceRandom", + "columnName": "nonceRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "aggregatedNonce", + "columnName": "aggregatedNonce", + "affinity": "TEXT" + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "itemIndex" + ] + }, + "indices": [ + { + "name": "index_FrostSigningItem_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningItem_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSigningSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `threshold` INTEGER NOT NULL, `participantCount` INTEGER NOT NULL, `signerId` INTEGER NOT NULL, `derivationPath` TEXT, `generation` INTEGER, `stage` TEXT NOT NULL, `signerIds` TEXT, `failureReason` TEXT, `signApprovedAt` INTEGER, `signDeclinedAt` INTEGER, `approvalRequestedAt` INTEGER, `resentAt` INTEGER, `subject` TEXT NOT NULL DEFAULT 'EVENTS', `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "threshold", + "columnName": "threshold", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantCount", + "columnName": "participantCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "signerId", + "columnName": "signerId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT" + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signerIds", + "columnName": "signerIds", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "signApprovedAt", + "columnName": "signApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "signDeclinedAt", + "columnName": "signDeclinedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedAt", + "columnName": "approvalRequestedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "resentAt", + "columnName": "resentAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'EVENTS'" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_FrostSigningSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_FrostSigningSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `receiverPublicKey` TEXT NOT NULL, `receiverRelayHit` TEXT, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "receiverPublicKey", + "columnName": "receiverPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receiverRelayHit", + "columnName": "receiverRelayHit", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapSeal", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `giftWrapMessageId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapMessageId`) REFERENCES `GiftWrapMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "giftWrapMessageId", + "columnName": "giftWrapMessageId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "GiftWrapMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapMessageId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapPayload", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `quotedEventId` TEXT, `giftWrapSealId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapSealId`) REFERENCES `GiftWrapSeal`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedEventId", + "columnName": "quotedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "giftWrapSealId", + "columnName": "giftWrapSealId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "GiftWrapSeal", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapSealId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupKeyState", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `thresholdPublicKey` TEXT NOT NULL, `derivationPath` TEXT NOT NULL, `announcedBy` TEXT NOT NULL, `announcedAt` INTEGER NOT NULL, `parentChatRoomId` TEXT, `birthCertificateJson` TEXT, `generation` INTEGER, `publicSharesHash` TEXT, `memberBindings` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thresholdPublicKey", + "columnName": "thresholdPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcedBy", + "columnName": "announcedBy", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcedAt", + "columnName": "announcedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "birthCertificateJson", + "columnName": "birthCertificateJson", + "affinity": "TEXT" + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER" + }, + { + "fieldPath": "publicSharesHash", + "columnName": "publicSharesHash", + "affinity": "TEXT" + }, + { + "fieldPath": "memberBindings", + "columnName": "memberBindings", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId" + ] + }, + "indices": [ + { + "name": "index_GroupKeyState_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupKeyState_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupSignedEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `derivationPath` TEXT, `frostSigningSessionId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT" + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GroupSignedEvent_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupSignedEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_GroupSignedEvent_frostSigningSessionId", + "unique": false, + "columnNames": [ + "frostSigningSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_frostSigningSessionId` ON `${TABLE_NAME}` (`frostSigningSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "KeyShareGeneration", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `secretShare` TEXT, `publicShares` TEXT NOT NULL, `state` TEXT NOT NULL, `refreshSessionId` TEXT, `recoveryData` TEXT, `activatedAt` INTEGER, `wipedAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `generation`), FOREIGN KEY(`dkgSessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "secretShare", + "columnName": "secretShare", + "affinity": "TEXT" + }, + { + "fieldPath": "publicShares", + "columnName": "publicShares", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "refreshSessionId", + "columnName": "refreshSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "activatedAt", + "columnName": "activatedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "wipedAt", + "columnName": "wipedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "dkgSessionId", + "generation" + ] + }, + "indices": [ + { + "name": "index_KeyShareGeneration_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_KeyShareGeneration_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "DkgSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dkgSessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "KeyShareMember", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `participantId` INTEGER NOT NULL, `memberPublicKey` TEXT NOT NULL, `hostPublicKey` TEXT NOT NULL, `standing` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `generation`, `participantId`), FOREIGN KEY(`dkgSessionId`, `generation`) REFERENCES `KeyShareGeneration`(`dkgSessionId`, `generation`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantId", + "columnName": "participantId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "memberPublicKey", + "columnName": "memberPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "hostPublicKey", + "columnName": "hostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "standing", + "columnName": "standing", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "dkgSessionId", + "generation", + "participantId" + ] + }, + "indices": [ + { + "name": "index_KeyShareMember_dkgSessionId_generation", + "unique": false, + "columnNames": [ + "dkgSessionId", + "generation" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_KeyShareMember_dkgSessionId_generation` ON `${TABLE_NAME}` (`dkgSessionId`, `generation`)" + } + ], + "foreignKeys": [ + { + "table": "KeyShareGeneration", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dkgSessionId", + "generation" + ], + "referencedColumns": [ + "dkgSessionId", + "generation" + ] + } + ] + }, + { + "tableName": "ShareRefreshConfirmation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `baseGeneration` INTEGER NOT NULL, `refreshSessionId` TEXT NOT NULL, `confirmedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `baseGeneration`))", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "baseGeneration", + "columnName": "baseGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "refreshSessionId", + "columnName": "refreshSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "confirmedAt", + "columnName": "confirmedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "dkgSessionId", + "baseGeneration" + ] + } + }, + { + "tableName": "ShareRefreshMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `participantPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `participantPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `ShareRefreshSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "participantPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "ShareRefreshSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ShareRefreshSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `baseGeneration` INTEGER NOT NULL, `recipientIds` TEXT NOT NULL, `withheld` TEXT, `stage` TEXT NOT NULL, `round1Random` TEXT NOT NULL, `auxRandom` TEXT NOT NULL, `dealApprovedAt` INTEGER, `confirmApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `coordinatorRound1` TEXT, `certificate` TEXT, `failureReason` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "baseGeneration", + "columnName": "baseGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recipientIds", + "columnName": "recipientIds", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "withheld", + "columnName": "withheld", + "affinity": "TEXT" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round1Random", + "columnName": "round1Random", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "auxRandom", + "columnName": "auxRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dealApprovedAt", + "columnName": "dealApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "confirmApprovedAt", + "columnName": "confirmApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedThrough", + "columnName": "approvalRequestedThrough", + "affinity": "TEXT" + }, + { + "fieldPath": "coordinatorRound1", + "columnName": "coordinatorRound1", + "affinity": "TEXT" + }, + { + "fieldPath": "certificate", + "columnName": "certificate", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ShareRefreshSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRefreshSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_ShareRefreshSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRefreshSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ShareRepairMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `recipientPublicKey` TEXT NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `senderPublicKey`, `kind`, `recipientPublicKey`), FOREIGN KEY(`sessionId`) REFERENCES `ShareRepairSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recipientPublicKey", + "columnName": "recipientPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "senderPublicKey", + "kind", + "recipientPublicKey" + ] + }, + "foreignKeys": [ + { + "table": "ShareRepairSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ShareRepairSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `targetId` INTEGER NOT NULL, `targetPublicKey` TEXT NOT NULL, `targetHostPublicKey` TEXT NOT NULL, `helperIds` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `stage` TEXT NOT NULL, `sessionRandom` TEXT NOT NULL, `helpApprovedAt` INTEGER, `approvalRequested` INTEGER NOT NULL, `failureReason` TEXT, `nParticipants` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "targetId", + "columnName": "targetId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "targetPublicKey", + "columnName": "targetPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "targetHostPublicKey", + "columnName": "targetHostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "helperIds", + "columnName": "helperIds", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sessionRandom", + "columnName": "sessionRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "helpApprovedAt", + "columnName": "helpApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequested", + "columnName": "approvalRequested", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "nParticipants", + "columnName": "nParticipants", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ShareRepairSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRepairSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_ShareRepairSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRepairSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GovernanceProposal", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `routingId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `frostSigningSessionId` TEXT NOT NULL, `commitEventId` TEXT NOT NULL, `commitEventJson` TEXT NOT NULL, `peerKeyPackageEventId` TEXT, `priorStateHex` TEXT NOT NULL, `pendingStateHex` TEXT NOT NULL, `stage` TEXT NOT NULL, `thenRotateWithout` TEXT, `promotionOfferId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "routingId", + "columnName": "routingId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "epoch", + "columnName": "epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "commitEventId", + "columnName": "commitEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "commitEventJson", + "columnName": "commitEventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "peerKeyPackageEventId", + "columnName": "peerKeyPackageEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "priorStateHex", + "columnName": "priorStateHex", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "pendingStateHex", + "columnName": "pendingStateHex", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thenRotateWithout", + "columnName": "thenRotateWithout", + "affinity": "TEXT" + }, + { + "fieldPath": "promotionOfferId", + "columnName": "promotionOfferId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GovernanceProposal_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GovernanceProposal_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GovernanceProposal_frostSigningSessionId", + "unique": false, + "columnNames": [ + "frostSigningSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GovernanceProposal_frostSigningSessionId` ON `${TABLE_NAME}` (`frostSigningSessionId`)" + }, + { + "name": "index_GovernanceProposal_commitEventId", + "unique": false, + "columnNames": [ + "commitEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GovernanceProposal_commitEventId` ON `${TABLE_NAME}` (`commitEventId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InReplyToRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`replyingNostrEventId` TEXT NOT NULL, `inReplyToNostrEventId` TEXT NOT NULL, `inReplyToProfilePublicKey` TEXT, `inReplyToRootNostrEventId` TEXT, `inReplyToRootProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`replyingNostrEventId`, `inReplyToNostrEventId`), FOREIGN KEY(`inReplyToProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`inReplyToRootProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`inReplyToNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`inReplyToRootNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "replyingNostrEventId", + "columnName": "replyingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "inReplyToNostrEventId", + "columnName": "inReplyToNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "inReplyToProfilePublicKey", + "columnName": "inReplyToProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootNostrEventId", + "columnName": "inReplyToRootNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootProfilePublicKey", + "columnName": "inReplyToRootProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "replyingNostrEventId", + "inReplyToNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToRootProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToRootNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotCommitResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `peerKeyPackageEventId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `isOneMemberInitialGroupCreation` INTEGER NOT NULL, `commitBytes` BLOB NOT NULL, `welcomeBytes` BLOB, `groupInfoBytes` BLOB, `framedCommitBytes` BLOB NOT NULL, `preCommitExporterSecret` BLOB NOT NULL, `obligationId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "peerKeyPackageEventId", + "columnName": "peerKeyPackageEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isOneMemberInitialGroupCreation", + "columnName": "isOneMemberInitialGroupCreation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "commitBytes", + "columnName": "commitBytes", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "welcomeBytes", + "columnName": "welcomeBytes", + "affinity": "BLOB" + }, + { + "fieldPath": "groupInfoBytes", + "columnName": "groupInfoBytes", + "affinity": "BLOB" + }, + { + "fieldPath": "framedCommitBytes", + "columnName": "framedCommitBytes", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "preCommitExporterSecret", + "columnName": "preCommitExporterSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "obligationId", + "columnName": "obligationId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "MarmotGroupEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `signature` TEXT NOT NULL, `encryptedContent` TEXT NOT NULL, `expiresAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`id`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "encryptedContent", + "columnName": "encryptedContent", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "expiresAt", + "columnName": "expiresAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "id" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotInnerEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `quotedEventId` TEXT, `marmotGroupEventId` TEXT, `directMessageRecipientPublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`marmotGroupEventId`) REFERENCES `MarmotGroupEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedEventId", + "columnName": "quotedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "directMessageRecipientPublicKey", + "columnName": "directMessageRecipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "MarmotGroupEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotGroupEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotKeyPackage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `tlsEncodedMarmotKeyPackage` BLOB NOT NULL, `profile` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`publicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "tlsEncodedMarmotKeyPackage", + "columnName": "tlsEncodedMarmotKeyPackage", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "profile", + "columnName": "profile", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "publicKey" + ], + "referencedColumns": [ + "publicKey" + ] + } + ] + }, + { + "tableName": "MarmotKeyPackageBundle", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `tlsEncodedMarmotKeyPackage` BLOB NOT NULL, `ncryptsecInitPrivateKey` TEXT NOT NULL, `ncryptsecEncryptionPrivateKey` TEXT NOT NULL, `ncryptsecSignaturePrivateKey` TEXT NOT NULL, `consumed` INTEGER NOT NULL, `rotated` INTEGER NOT NULL, `profile` TEXT, `dTag` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "tlsEncodedMarmotKeyPackage", + "columnName": "tlsEncodedMarmotKeyPackage", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "ncryptsecInitPrivateKey", + "columnName": "ncryptsecInitPrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ncryptsecEncryptionPrivateKey", + "columnName": "ncryptsecEncryptionPrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ncryptsecSignaturePrivateKey", + "columnName": "ncryptsecSignaturePrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "consumed", + "columnName": "consumed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rotated", + "columnName": "rotated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "profile", + "columnName": "profile", + "affinity": "TEXT" + }, + { + "fieldPath": "dTag", + "columnName": "dTag", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_MarmotKeyPackageBundle_publicKey", + "unique": false, + "columnNames": [ + "publicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MarmotKeyPackageBundle_publicKey` ON `${TABLE_NAME}` (`publicKey`)" + } + ] + }, + { + "tableName": "MarmotRouting", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`routingId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `activeFromEpoch` INTEGER NOT NULL, `retiredAtEpoch` INTEGER, PRIMARY KEY(`routingId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "routingId", + "columnName": "routingId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "activeFromEpoch", + "columnName": "activeFromEpoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "retiredAtEpoch", + "columnName": "retiredAtEpoch", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "routingId" + ] + }, + "indices": [ + { + "name": "index_MarmotRouting_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MarmotRouting_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotPublishObligation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`obligationId` TEXT NOT NULL, `bytes` BLOB NOT NULL, PRIMARY KEY(`obligationId`))", + "fields": [ + { + "fieldPath": "obligationId", + "columnName": "obligationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "bytes", + "columnName": "bytes", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "obligationId" + ] + } + }, + { + "tableName": "MarmotOutboundGate", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`groupId` TEXT NOT NULL, `gate` TEXT NOT NULL, PRIMARY KEY(`groupId`))", + "fields": [ + { + "fieldPath": "groupId", + "columnName": "groupId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "gate", + "columnName": "gate", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "groupId" + ] + } + }, + { + "tableName": "MarmotRetainedEpochSecret", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `senderDataSecret` BLOB NOT NULL, `encryptionSecret` BLOB NOT NULL, `leafCount` INTEGER NOT NULL, `exporterSecret` BLOB NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`, `epoch`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "epoch", + "columnName": "epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderDataSecret", + "columnName": "senderDataSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "encryptionSecret", + "columnName": "encryptionSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "leafCount", + "columnName": "leafCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "exporterSecret", + "columnName": "exporterSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "epoch" + ] + }, + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotSenderRatchet", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `leafIndex` INTEGER NOT NULL, `applicationGeneration` INTEGER NOT NULL, `record` BLOB NOT NULL, PRIMARY KEY(`chatRoomId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "epoch", + "columnName": "epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "leafIndex", + "columnName": "leafIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "applicationGeneration", + "columnName": "applicationGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "record", + "columnName": "record", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId" + ] + }, + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Mention", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `mentionedPublicKey` TEXT NOT NULL, `mentioningNostrEventId` TEXT, `relayUrl` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, FOREIGN KEY(`mentionedPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`mentioningNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mentionedPublicKey", + "columnName": "mentionedPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "mentioningNostrEventId", + "columnName": "mentioningNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "relayUrl", + "columnName": "relayUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "mentionedPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "mentioningNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NegentropySynchronizeRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `uuid` TEXT NOT NULL, `purpose` TEXT NOT NULL, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `isRecommendedRelay` INTEGER NOT NULL, `level` INTEGER NOT NULL, `synchronizationFilter` TEXT NOT NULL, `ownerPublicKey` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "uuid", + "columnName": "uuid", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isRecommendedRelay", + "columnName": "isRecommendedRelay", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "level", + "columnName": "level", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "synchronizationFilter", + "columnName": "synchronizationFilter", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerPublicKey", + "columnName": "ownerPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_NegentropySynchronizeRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NegentropySynchronizeRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_NegentropySynchronizeRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NegentropySynchronizeRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NegentropySynchronizeResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `status` TEXT NOT NULL, `negentropySynchronizeRequestId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`negentropySynchronizeRequestId`) REFERENCES `SynchronizeNostrEventResult`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "negentropySynchronizeRequestId", + "columnName": "negentropySynchronizeRequestId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "SynchronizeNostrEventResult", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "negentropySynchronizeRequestId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NostrEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `pubKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `sig` TEXT NOT NULL, `relayUrl` TEXT, `quotedNostrEventId` TEXT, `quotedAuthorPublicKey` TEXT, `inReplyToNostrEventId` TEXT, `inReplyToAuthorPublicKey` TEXT, `inReplyToRootNostrEventId` TEXT, `inReplyToRootAuthorPublicKey` TEXT, `repostedNostrEventId` TEXT, `repostedAuthorPublicKey` TEXT, `unsignedNostrEventId` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sig", + "columnName": "sig", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayUrl", + "columnName": "relayUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "quotedNostrEventId", + "columnName": "quotedNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "quotedAuthorPublicKey", + "columnName": "quotedAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToNostrEventId", + "columnName": "inReplyToNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToAuthorPublicKey", + "columnName": "inReplyToAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootNostrEventId", + "columnName": "inReplyToRootNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootAuthorPublicKey", + "columnName": "inReplyToRootAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "repostedNostrEventId", + "columnName": "repostedNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "repostedAuthorPublicKey", + "columnName": "repostedAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_NostrEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_NostrEvent_pubKey", + "unique": false, + "columnNames": [ + "pubKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_pubKey` ON `${TABLE_NAME}` (`pubKey`)" + }, + { + "name": "index_NostrEvent_quotedNostrEventId", + "unique": false, + "columnNames": [ + "quotedNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_quotedNostrEventId` ON `${TABLE_NAME}` (`quotedNostrEventId`)" + }, + { + "name": "index_NostrEvent_inReplyToNostrEventId", + "unique": false, + "columnNames": [ + "inReplyToNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_inReplyToNostrEventId` ON `${TABLE_NAME}` (`inReplyToNostrEventId`)" + }, + { + "name": "index_NostrEvent_inReplyToRootNostrEventId", + "unique": false, + "columnNames": [ + "inReplyToRootNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_inReplyToRootNostrEventId` ON `${TABLE_NAME}` (`inReplyToRootNostrEventId`)" + } + ] + }, + { + "tableName": "NostrEventRelay", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`relayURL` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`nostrEventId`, `relayURL`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "nostrEventId", + "relayURL" + ] + }, + "indices": [ + { + "name": "index_NostrEventRelay_relayURL", + "unique": false, + "columnNames": [ + "relayURL" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEventRelay_relayURL` ON `${TABLE_NAME}` (`relayURL`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Participant", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `participantPublicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `adminAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, FOREIGN KEY(`participantPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "adminAt", + "columnName": "adminAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "participantPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Post", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `repostId` TEXT, `quote` TEXT, `content` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `replyToId` TEXT, `profilePublicKey` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`profilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyToId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostId", + "columnName": "repostId", + "affinity": "TEXT" + }, + { + "fieldPath": "quote", + "columnName": "quote", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToId", + "columnName": "replyToId", + "affinity": "TEXT" + }, + { + "fieldPath": "profilePublicKey", + "columnName": "profilePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Post_profilePublicKey", + "unique": false, + "columnNames": [ + "profilePublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_profilePublicKey` ON `${TABLE_NAME}` (`profilePublicKey`)" + }, + { + "name": "index_Post_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Post_replyToId", + "unique": false, + "columnNames": [ + "replyToId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_replyToId` ON `${TABLE_NAME}` (`replyToId`)" + }, + { + "name": "index_Post_repostId", + "unique": false, + "columnNames": [ + "repostId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_repostId` ON `${TABLE_NAME}` (`repostId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "profilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyToId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Profile", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`publicKey` TEXT NOT NULL, `userName` TEXT, `displayName` TEXT, `picture` TEXT, `banner` TEXT, `website` TEXT, `about` TEXT, `bot` INTEGER, `pronouns` TEXT, `nip05` TEXT, `domain` TEXT, `lud06` TEXT, `lud16` TEXT, `twitter` TEXT, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`publicKey`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userName", + "columnName": "userName", + "affinity": "TEXT" + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT" + }, + { + "fieldPath": "picture", + "columnName": "picture", + "affinity": "TEXT" + }, + { + "fieldPath": "banner", + "columnName": "banner", + "affinity": "TEXT" + }, + { + "fieldPath": "website", + "columnName": "website", + "affinity": "TEXT" + }, + { + "fieldPath": "about", + "columnName": "about", + "affinity": "TEXT" + }, + { + "fieldPath": "bot", + "columnName": "bot", + "affinity": "INTEGER" + }, + { + "fieldPath": "pronouns", + "columnName": "pronouns", + "affinity": "TEXT" + }, + { + "fieldPath": "nip05", + "columnName": "nip05", + "affinity": "TEXT" + }, + { + "fieldPath": "domain", + "columnName": "domain", + "affinity": "TEXT" + }, + { + "fieldPath": "lud06", + "columnName": "lud06", + "affinity": "TEXT" + }, + { + "fieldPath": "lud16", + "columnName": "lud16", + "affinity": "TEXT" + }, + { + "fieldPath": "twitter", + "columnName": "twitter", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "publicKey" + ] + }, + "indices": [ + { + "name": "index_Profile_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Profile_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "QuotedRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`quotingNostrEventId` TEXT NOT NULL, `quotedNostrEventId` TEXT NOT NULL, `quotedProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`quotingNostrEventId`, `quotedNostrEventId`), FOREIGN KEY(`quotedProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`quotingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`quotedNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "quotingNostrEventId", + "columnName": "quotingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedNostrEventId", + "columnName": "quotedNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedProfilePublicKey", + "columnName": "quotedProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "quotingNostrEventId", + "quotedNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotedProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Reaction", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `content` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `replyToId` TEXT NOT NULL, `profilePublicKey` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`profilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyToId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToId", + "columnName": "replyToId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "profilePublicKey", + "columnName": "profilePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Reaction_profilePublicKey", + "unique": false, + "columnNames": [ + "profilePublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_profilePublicKey` ON `${TABLE_NAME}` (`profilePublicKey`)" + }, + { + "name": "index_Reaction_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Reaction_replyToId", + "unique": false, + "columnNames": [ + "replyToId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_replyToId` ON `${TABLE_NAME}` (`replyToId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "profilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyToId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "RecentSearch", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`query` TEXT NOT NULL, `synchronizationFilters` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`query`))", + "fields": [ + { + "fieldPath": "query", + "columnName": "query", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "synchronizationFilters", + "columnName": "synchronizationFilters", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "query" + ] + } + }, + { + "tableName": "Relay", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`publicKey` TEXT NOT NULL, `type` TEXT NOT NULL, `url` TEXT NOT NULL, `read` INTEGER NOT NULL, `write` INTEGER NOT NULL, PRIMARY KEY(`publicKey`, `type`, `url`))", + "fields": [ + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "read", + "columnName": "read", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "write", + "columnName": "write", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "publicKey", + "type", + "url" + ] + } + }, + { + "tableName": "RepostedRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`repostingNostrEventId` TEXT NOT NULL, `repostedNostrEventId` TEXT NOT NULL, `repostedProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`repostingNostrEventId`, `repostedNostrEventId`), FOREIGN KEY(`repostedProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostedNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "repostingNostrEventId", + "columnName": "repostingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostedNostrEventId", + "columnName": "repostedNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostedProfilePublicKey", + "columnName": "repostedProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "repostingNostrEventId", + "repostedNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostedProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "SynchronizeNostrEventRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `purpose` TEXT NOT NULL, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `isRecommendedRelay` INTEGER NOT NULL, `level` INTEGER NOT NULL, `synchronizationFilters` TEXT NOT NULL, `ownerPublicKey` TEXT, `nostrEventId` TEXT, `unsignedNostrEventId` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isRecommendedRelay", + "columnName": "isRecommendedRelay", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "level", + "columnName": "level", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "synchronizationFilters", + "columnName": "synchronizationFilters", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerPublicKey", + "columnName": "ownerPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_SynchronizeNostrEventRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_SynchronizeNostrEventRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "SynchronizeNostrEventResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_SynchronizeNostrEventResult_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventResult_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "UnsignedNostrEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `pubKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `privateTags` TEXT, `content` TEXT NOT NULL, `signedAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "privateTags", + "columnName": "privateTags", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signedAt", + "columnName": "signedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_UnsignedNostrEvent_pubKey", + "unique": false, + "columnNames": [ + "pubKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_UnsignedNostrEvent_pubKey` ON `${TABLE_NAME}` (`pubKey`)" + }, + { + "name": "index_UnsignedNostrEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_UnsignedNostrEvent_kind` ON `${TABLE_NAME}` (`kind`)" + } + ] + }, + { + "tableName": "Zap", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `postId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `receiverPublicKey` TEXT NOT NULL, `message` TEXT, `invoice` TEXT, `amountInMillisatoshis` INTEGER, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`senderPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`receiverPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`postId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "postId", + "columnName": "postId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receiverPublicKey", + "columnName": "receiverPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "message", + "columnName": "message", + "affinity": "TEXT" + }, + { + "fieldPath": "invoice", + "columnName": "invoice", + "affinity": "TEXT" + }, + { + "fieldPath": "amountInMillisatoshis", + "columnName": "amountInMillisatoshis", + "affinity": "INTEGER" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Zap_senderPublicKey", + "unique": false, + "columnNames": [ + "senderPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_senderPublicKey` ON `${TABLE_NAME}` (`senderPublicKey`)" + }, + { + "name": "index_Zap_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Zap_postId", + "unique": false, + "columnNames": [ + "postId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_postId` ON `${TABLE_NAME}` (`postId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "senderPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "receiverPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "postId" + ], + "referencedColumns": [ + "id" + ] + } + ] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '4097e68a695ef0410fb2c8968c8fb2f3')" + ] + } +} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt index baf26602..d19c0727 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt @@ -69,6 +69,8 @@ import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.Confederation import mobi.giza.compose.database.model.ConfederationCeremony import mobi.giza.compose.database.model.ConfederationMember +import mobi.giza.compose.database.model.ConfederationSigningAttempt +import mobi.giza.compose.database.model.ConfederationSigningMessage import mobi.giza.compose.database.model.ConfederationCeremonyMessage import mobi.giza.compose.database.model.ConfederationEvent import mobi.giza.compose.database.model.ConfederationInvitee @@ -138,6 +140,8 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) Confederation::class, ConfederationCeremony::class, ConfederationMember::class, + ConfederationSigningAttempt::class, + ConfederationSigningMessage::class, ConfederationCeremonyMessage::class, ConfederationEvent::class, ConfederationInvitee::class, @@ -189,7 +193,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) UnsignedNostrEvent::class, Zap::class ], - version = 44, + version = 45, autoMigrations = [ // v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can // generate the migration itself — nothing existing changes shape. @@ -461,6 +465,9 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) // Phases 11 and 12): ConfederationCeremony, ConfederationCeremonyMessage, Confederation // and ConfederationMember. New tables only, so Room generates it. AutoMigration(from = 43, to = 44), + // v45 adds the confederation signing as itself (docs/confederation.md, Phase 14): + // ConfederationSigningAttempt and ConfederationSigningMessage. New tables only. + AutoMigration(from = 44, to = 45), ] ) @ConstructedBy(GizaDatabaseConstructor::class) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationCeremonyDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationCeremonyDao.kt index 31ac7f8a..f2466cec 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationCeremonyDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationCeremonyDao.kt @@ -62,4 +62,31 @@ interface ConfederationCeremonyDao { @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertMembers(members: List) + + @Query("SELECT * FROM ConfederationSigningAttempt WHERE id = :id") + suspend fun getAttempt(id: String): mobi.giza.compose.database.model.ConfederationSigningAttempt? + + @Query("SELECT * FROM ConfederationSigningAttempt WHERE id = :id") + fun observeAttempt(id: String): Flow + + @Query("SELECT * FROM ConfederationSigningAttempt WHERE confederationId = :confederationId ORDER BY createdAt DESC") + fun observeAttempts(confederationId: HexKey): Flow> + + @Query("SELECT * FROM ConfederationSigningAttempt WHERE userPublicKey = :userPublicKey AND stage NOT IN ('COMPLETE', 'FAILED')") + suspend fun getRunningAttempts(userPublicKey: HexKey): List + + @Upsert + suspend fun upsertAttempt(attempt: mobi.giza.compose.database.model.ConfederationSigningAttempt) + + @Query("SELECT * FROM ConfederationSigningMessage WHERE attemptId = :attemptId AND senderPublicKey = :sender AND kind = :kind") + suspend fun getSigningMessage(attemptId: String, sender: HexKey, kind: Kind): mobi.giza.compose.database.model.ConfederationSigningMessage? + + @Query("SELECT * FROM ConfederationSigningMessage WHERE attemptId = :attemptId") + suspend fun getSigningMessages(attemptId: String): List + + @Query("SELECT * FROM ConfederationSigningMessage WHERE attemptId = :attemptId") + fun observeSigningMessages(attemptId: String): Flow> + + @Insert(onConflict = OnConflictStrategy.IGNORE) + suspend fun insertSigningMessage(message: mobi.giza.compose.database.model.ConfederationSigningMessage): Long } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt index aefdadb5..5efef2e6 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt @@ -88,6 +88,8 @@ import mobi.giza.compose.nostr.Relays import mobi.giza.compose.nostr.dkg.DkgRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.managers.ConfederationRitualManager +import mobi.giza.compose.managers.ConfederationSigningManager +import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.nostr.frost.ShareRefreshEvents import mobi.giza.compose.nostr.frost.ShareRepairEvents @@ -1675,6 +1677,20 @@ abstract class NostrDao( Event.fromJsonOrNull(groupEventResult.innerEventJson) ?.let { innerEvent -> when { + // The confederation signing as itself, in its own room. + // docs/confederation.md, Phase 14. + ConfederationSigningEvents.isSigningKind(innerEvent.kind) -> { + if (ExperimentalFeatures.confederation) { + ConfederationSigningManager.process( + database = database, + localChatRoom = localChatRoom, + innerEvent = innerEvent, + userPublicKey = activeKeyPair.pubKey.toHex(), + nostrPrivateKey = activeKeyPair.privKey!!, + ) + } + } + FrostSigningEvents.isFrostSigningKind(innerEvent.kind) -> FrostSigningManager.processSigningPayload( database = database, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt index 16f51b26..f16b8a35 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt @@ -4,6 +4,7 @@ import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import mobi.giza.compose.nostr.GroupNostrProfile import mobi.giza.compose.nostr.RetiredKinds import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents import androidx.room3.Entity import androidx.room3.ForeignKey @@ -544,6 +545,10 @@ data class ChatMessage( /** A group's room, on its admins' devices: the group is now part of a formed confederation (Phase 12). */ const val TYPE_CONFEDERATION_FORMED = "confederationFormed" + /** The confederation's room: a proposal for it to sign, and one that did not finish (Phase 14). */ + const val TYPE_CONFEDERATION_SIGNING_PROPOSED = "confederationSigningProposed" + const val TYPE_CONFEDERATION_SIGNING_FAILED = "confederationSigningFailed" + val CONFEDERATION_TYPES = setOf( TYPE_CONFEDERATION_PROPOSED, TYPE_CONFEDERATION_ACCEPTED, @@ -553,6 +558,8 @@ data class ChatMessage( TYPE_CONFEDERATION_CEREMONY_COMPLETE, TYPE_CONFEDERATION_CEREMONY_FAILED, TYPE_CONFEDERATION_FORMED, + TYPE_CONFEDERATION_SIGNING_PROPOSED, + TYPE_CONFEDERATION_SIGNING_FAILED, ) val GROUP_IDENTITY_TYPES = setOf( @@ -994,7 +1001,8 @@ data class ChatMessage( event.kind in FrostSigningEvents.ALL || event.kind in ShareRefreshEvents.ALL || event.kind in ShareRepairEvents.ALL || - event.kind in GovernanceEvents.ALL + event.kind in GovernanceEvents.ALL || + event.kind in ConfederationSigningEvents.ALL ) database.marmotInnerEventDao().upsert( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ConfederationSigningAttempt.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ConfederationSigningAttempt.kt new file mode 100644 index 00000000..305c5235 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ConfederationSigningAttempt.kt @@ -0,0 +1,72 @@ +package mobi.giza.compose.database.model + +import androidx.room3.Entity +import androidx.room3.ForeignKey +import androidx.room3.Index +import androidx.room3.PrimaryKey +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import kotlin.time.Clock +import kotlin.time.Instant + +/** + * One attempt by a confederation to sign one event (docs/confederation.md, Phase 14). + * + * Unlike a FROST signing session, an attempt cannot outlive a restart once its nonces are out: + * upstream's signer state lives in memory only and must never be persisted, because a restored + * nonce can reveal the share. So this row holds what the attempt is about and what this device has + * said, and a device that comes back to an attempt it was signing in ends it, out loud; the + * proposer starts a new one under a new session id. + */ +@Entity( + foreignKeys = [ + ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["confederationId"], onDelete = ForeignKey.CASCADE) + ], + indices = [Index("confederationId")], +) +data class ConfederationSigningAttempt( + /** The signing session id, 32 bytes of hex: hashed into D_sign. */ + @PrimaryKey + val id: String, + /** The confederation's room, whose id is also the confederation's. */ + val confederationId: HexKey, + val proposerPublicKey: HexKey, + val userPublicKey: HexKey, + /** The unsigned event, authored by the room, with its id. */ + val eventJson: String, + val stage: ConfederationSigningStage = ConfederationSigningStage.AWAITING_APPROVAL, + val approvedAt: Instant? = null, + val declinedAt: Instant? = null, + /** The event, signed, once it is. */ + val signedEventJson: String? = null, + val failureReason: String? = null, + val createdAt: Instant = Clock.System.now(), + val updatedAt: Instant = createdAt, +) { + val isRunning: Boolean + get() = stage != ConfederationSigningStage.COMPLETE && stage != ConfederationSigningStage.FAILED +} + +enum class ConfederationSigningStage { + AWAITING_APPROVAL, + SELECTING, + NONCES, + CONFIRMING, + SIGNING, + COMPLETE, + FAILED, +} + +@Entity( + primaryKeys = ["attemptId", "senderPublicKey", "kind"], + foreignKeys = [ + ForeignKey(entity = ConfederationSigningAttempt::class, parentColumns = ["id"], childColumns = ["attemptId"], onDelete = ForeignKey.CASCADE) + ], +) +data class ConfederationSigningMessage( + val attemptId: String, + val senderPublicKey: HexKey, + val kind: Kind, + val payload: String, + val receivedAt: Instant = Clock.System.now(), +) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 016b4102..0923f292 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -81,6 +81,7 @@ import mobi.giza.compose.managers.ChronicleManager import mobi.giza.compose.managers.FrostSigningManager import mobi.giza.compose.extensions.toHex import mobi.giza.compose.managers.ConfederationRitualManager +import mobi.giza.compose.managers.ConfederationSigningManager import mobi.giza.compose.managers.ConfederationFormation import mobi.giza.compose.managers.ConfederationFollowThrough import mobi.giza.compose.managers.GroupKeyStateManager @@ -173,6 +174,9 @@ class DatabaseChatRepository( launch { runCatching { ConfederationRitualManager.resumeRunning(database, keyPair.pubKey.toHex(), secret) } .onFailure { logger.e("Could not resume confederation ceremonies", it) } + // An attempt this device was signing in cannot survive a restart: ended out loud. + runCatching { ConfederationSigningManager.resumeRunning(database, keyPair.pubKey.toHex(), secret) } + .onFailure { logger.e("Could not resume confederation signing", it) } } } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt new file mode 100644 index 00000000..2e1f1619 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt @@ -0,0 +1,567 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.crypto.random.RandomInstance +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.ByteVector64 +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.XonlyPublicKey +import fr.acinq.bitcoin.crypto.confederation.ConfederationConfirmationCertificate +import fr.acinq.bitcoin.crypto.confederation.ConfederationKeyState +import fr.acinq.bitcoin.crypto.confederation.ConfederationRecoveryPackage +import fr.acinq.bitcoin.crypto.confederation.ConfederationRoleId +import fr.acinq.bitcoin.crypto.confederation.ConfederationRoster +import fr.acinq.bitcoin.crypto.confederation.ConfederationShare +import fr.acinq.bitcoin.crypto.confederation.ConfederationSigner +import fr.acinq.bitcoin.crypto.confederation.ConfederationSignerSelection +import fr.acinq.bitcoin.crypto.confederation.ConfederationSigning +import fr.acinq.bitcoin.crypto.confederation.ConfederationSigningSession +import fr.acinq.bitcoin.crypto.confederation.ConfederationTweak +import fr.acinq.bitcoin.utils.Either +import kotlin.time.Clock +import kotlin.time.Instant +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.Confederation +import mobi.giza.compose.database.model.ConfederationSigningAttempt +import mobi.giza.compose.database.model.ConfederationSigningMessage +import mobi.giza.compose.database.model.ConfederationSigningStage +import mobi.giza.compose.database.model.GroupSignedEvent +import mobi.giza.compose.database.model.MarmotInnerEvent +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents +import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder +import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder.Plan +import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents + +/** + * A confederation signing an event as itself, one person per device (docs/confederation.md, + * Phase 14), over upstream's Option A signing, in the confederation's own Marmot room. + * + * Every role holder is asked, as a FROST member is: approving says this person's roles will sign. + * The proposer, who coordinates, fixes the selection from the first yeses -- at least `T` groups, + * at least `t_g` admins in each -- and then each selected role makes a nonce, confirms the + * transcript and the event, and gives its partial. Everything that takes no secret is computed on + * every device from the public messages, so each device builds the signature itself and checks it + * against the room's id before it keeps it. + * + * **A signer lives in memory only.** Upstream's state holds a secret nonce that must never be + * stored, restored or used twice, so [signers] is this process's and nothing else's. A device that + * restarts after sending a nonce can no longer confirm or sign; it ends the attempt, out loud, and + * the proposer starts a fresh one under a new session id. That is the opposite of + * `FrostSigningManager`, which stores its nonce randomness, and it is upstream's rule (F-24). + * + * The room signs as its own id: the key's tweaks are `SharedKeyDerivation`'s, as for every keyed + * room (D10). + * + * WARNING: upstream's confederation module is experimental and unaudited. This runs behind + * `ExperimentalFeatures.confederation`, off in release. + */ +object ConfederationSigningManager { + private val logger = Logger.withTag("ConfederationSigningManager") + private val mutex = Mutex() + + /** Live signer states, by user, attempt and role. In memory only, by design. */ + private val signers = mutableMapOf() + + private fun signerKey(user: HexKey, attemptId: String, role: ConfederationRoleId) = "$user/$attemptId/${role.groupId}:${role.adminId}" + + /** The kinds a confederation signs here: its profile and its posts (Phase 15). */ + val SIGNABLE_KINDS: Set = setOf(MetadataEvent.KIND, TextNoteEvent.KIND) + + const val RESTARTED = "A device restarted while signing, so this attempt cannot finish. Propose it again" + + // ---- what a confederation is on this device ------------------------------------------------ + + /** Everything this device holds about one confederation, read back from storage. */ + internal class Held( + val confederation: Confederation, + val plan: Plan, + val roster: ConfederationRoster, + val keyState: ConfederationKeyState, + val tweaks: List, + val roomKey: XonlyPublicKey, + ) + + internal suspend fun held(database: GizaDatabase, confederationId: HexKey): Held? { + val confederation = database.confederationCeremonyDao().getConfederation(confederationId) + ?.takeIf(ConfederationFormation::verifies) ?: return null + val ceremony = database.confederationCeremonyDao().getCeremony(confederation.ceremonyId) ?: return null + val plan = ConfederationRitualEvents.Opening.decode(ceremony.openingJson) + ?.let { ConfederationRitualManager.planFrom(it) as? Either.Right }?.value ?: return null + val roster = (ConfederationRoster.fromData(ByteVector(confederation.roster)) as? Either.Right)?.value ?: return null + val keyState = (ConfederationKeyState.fromData(ByteVector(confederation.keyState), roster) as? Either.Right)?.value ?: return null + val derived = SharedKeyDerivation.derive("02${confederation.publicKey}") + if (derived.hex != confederationId) return null + return Held(confederation, plan, roster, keyState, derived.tweaks.map { ConfederationTweak(it, isXonly = true) }, derived.publicKey) + } + + /** Whether this device holds a role in [confederationId], and so can propose and sign for it. */ + suspend fun canSign(database: GizaDatabase, confederationId: HexKey, userPublicKey: HexKey): Boolean = + held(database, confederationId)?.plan?.seatsOf(userPublicKey)?.isNotEmpty() == true + + /** Why this device would not sign [event] for [held]'s confederation, or null. */ + private fun refusalOf(held: Held, event: Event): String? = when { + event.pubKey != held.confederation.id -> "The event is not authored by the confederation" + event.kind !in SIGNABLE_KINDS -> "A confederation signs only its profile and its posts here" + event.kind == MetadataEvent.KIND && GroupStatementRefusal.isUnreadableProfile(event.tags, event.content) -> GroupStatementRefusal.REASON + event.kind == TextNoteEvent.KIND && GroupStatementRefusal.isBlankPost(event.content) -> GroupStatementRefusal.REASON + EventHasher.hashId(event.pubKey, event.createdAt, event.kind, event.tags, event.content) != event.id -> "The event's id is not the hash of its fields" + else -> null + } + + // ---- proposing ------------------------------------------------------------------------- + + /** Proposes that the confederation whose room is [localChatRoom] sign one event. Proposing is the proposer's approval. */ + suspend fun propose( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + kind: Kind, + tags: Array>, + content: String, + nostrPrivateKey: ByteArray, + createdAt: Long = Clock.System.now().epochSeconds, + ): ConfederationSigningAttempt = mutex.withLock { + val roomId = localChatRoom.chatRoom.id + val held = held(database, roomId) ?: throw IllegalStateException("This device holds no confederation for this room") + check(held.plan.seatsOf(userPublicKey).isNotEmpty()) { "Only someone who holds a role in the confederation can propose for it" } + val id = EventHasher.hashId(roomId, createdAt, kind, tags, content) + val event = Event(id, roomId, createdAt, kind, tags, content, "") + refusalOf(held, event)?.let { throw IllegalArgumentException(it) } + + val attempt = ConfederationSigningAttempt( + id = RandomInstance.bytes(32).toHex(), + confederationId = roomId, + proposerPublicKey = userPublicKey, + userPublicKey = userPublicKey, + eventJson = event.toJson(), + approvedAt = Clock.System.now(), + stage = ConfederationSigningStage.SELECTING, + ) + database.confederationCeremonyDao().upsertAttempt(attempt) + announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED, "A proposal for the confederation to sign: ${describe(event)}") + broadcast(database, localChatRoom, attempt, ConfederationSigningEvents.PROPOSAL, event.toJson()) + publishAvailability(database, localChatRoom, attempt, held, available = true) + advance(database, localChatRoom, attempt.id, nostrPrivateKey) + database.confederationCeremonyDao().getAttempt(attempt.id)!! + } + + // ---- inbound --------------------------------------------------------------------------- + + suspend fun process( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + innerEvent: Event, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + ) = mutex.withLock { + val attemptId = ConfederationSigningEvents.parseSessionId(innerEvent.tags) ?: return@withLock + val held = held(database, localChatRoom.chatRoom.id) ?: run { + logger.i("Signing message for ${localChatRoom.chatRoom.id.take(12)}, which is no confederation here; leaving it stored") + return@withLock + } + val attempt = if (innerEvent.kind == ConfederationSigningEvents.PROPOSAL) { + acceptProposal(database, localChatRoom, held, innerEvent, attemptId, userPublicKey) + } else { + database.confederationCeremonyDao().getAttempt(attemptId) + } ?: return@withLock + if (!attempt.isRunning) return@withLock + if (!record(database, held, attempt, innerEvent)) return@withLock + advance(database, localChatRoom, attempt.id, nostrPrivateKey) + } + + private suspend fun acceptProposal( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + held: Held, + innerEvent: Event, + attemptId: String, + userPublicKey: HexKey, + ): ConfederationSigningAttempt? { + database.confederationCeremonyDao().getAttempt(attemptId)?.let { return it } + if (held.plan.seatsOf(innerEvent.pubKey).isEmpty()) { + logger.w("Signing proposal $attemptId from ${innerEvent.pubKey.take(8)}, who holds no role; dropping") + return null + } + if (held.plan.seatsOf(userPublicKey).isEmpty()) return null + val event = Event.fromJsonOrNull(innerEvent.content) ?: return null + val attempt = ConfederationSigningAttempt( + id = attemptId, + confederationId = held.confederation.id, + proposerPublicKey = innerEvent.pubKey, + userPublicKey = userPublicKey, + eventJson = event.toJson(), + ) + val refusal = refusalOf(held, event) + if (refusal != null) { + // Declined out loud, as a FROST member declines what it cannot check: this person's + // roles will not sign, and the group can tell that from a phone in a pocket. + logger.w("Signing proposal $attemptId refused: $refusal") + database.confederationCeremonyDao().upsertAttempt(attempt.copy(declinedAt = Clock.System.now(), failureReason = refusal)) + publishAvailability(database, localChatRoom, attempt, held, available = false) + return database.confederationCeremonyDao().getAttempt(attemptId) + } + database.confederationCeremonyDao().upsertAttempt(attempt) + announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED, "A proposal for the confederation to sign: ${describe(event)}") + replayStoredMessages(database, held, attempt) + return database.confederationCeremonyDao().getAttempt(attemptId) + } + + /** + * Files one message. Per-person messages only from a person holding a role, with a value for + * exactly their roles; the session only from the proposer; a failure from anyone with a role. + * Returns false when it ended the attempt. + */ + private suspend fun record(database: GizaDatabase, held: Held, attempt: ConfederationSigningAttempt, innerEvent: Event): Boolean { + val sender = innerEvent.pubKey + val groups = held.plan.seatsOf(sender).map { it.group }.toSet() + when (innerEvent.kind) { + in ConfederationSigningEvents.PER_PERSON -> { + if (groups.isEmpty()) return true + if (ConfederationRitualEvents.decodeByGroup(innerEvent.content)?.keys != groups) return true + database.confederationCeremonyDao().insertSigningMessage(ConfederationSigningMessage(attempt.id, sender, innerEvent.kind, innerEvent.content)) + } + ConfederationSigningEvents.SESSION -> { + if (sender != attempt.proposerPublicKey) return true + database.confederationCeremonyDao().insertSigningMessage(ConfederationSigningMessage(attempt.id, sender, innerEvent.kind, innerEvent.content)) + } + ConfederationSigningEvents.FAILURE -> { + if (groups.isEmpty()) return true + fail(database, attempt, "Ended by ${ConfederationManager.nameOf(database, sender)}: ${innerEvent.content}") + return false + } + } + return true + } + + // ---- the member's say -------------------------------------------------------------------- + + fun isAwaitingApproval(attempt: ConfederationSigningAttempt): Boolean = + attempt.isRunning && attempt.approvedAt == null && attempt.declinedAt == null + + suspend fun approve(database: GizaDatabase, attemptId: String, nostrPrivateKey: ByteArray) = mutex.withLock { + val attempt = database.confederationCeremonyDao().getAttempt(attemptId)?.takeIf(::isAwaitingApproval) ?: return@withLock + val room = database.chatRoomDao().findChatRoomById(attempt.confederationId) ?: return@withLock + val held = held(database, attempt.confederationId) ?: return@withLock + // Checked again: what is signed has to be what this device would sign now. + refusalOf(held, Event.fromJson(attempt.eventJson))?.let { why -> + update(database, attempt) { it.copy(declinedAt = Clock.System.now(), failureReason = why) } + publishAvailability(database, room, attempt, held, available = false) + return@withLock + } + update(database, attempt) { it.copy(approvedAt = Clock.System.now()) } + publishAvailability(database, room, attempt, held, available = true) + advance(database, room, attemptId, nostrPrivateKey) + } + + suspend fun decline(database: GizaDatabase, attemptId: String) = mutex.withLock { + val attempt = database.confederationCeremonyDao().getAttempt(attemptId)?.takeIf(::isAwaitingApproval) ?: return@withLock + val room = database.chatRoomDao().findChatRoomById(attempt.confederationId) ?: return@withLock + val held = held(database, attempt.confederationId) ?: return@withLock + update(database, attempt) { it.copy(declinedAt = Clock.System.now()) } + publishAvailability(database, room, attempt, held, available = false) + advance(database, room, attemptId, ByteArray(0)) + } + + /** + * After a restart: an attempt this device sent nonces in and has not finished cannot finish + * now, since the nonces went with the process. Ends each out loud. Others are moved on. + */ + suspend fun resumeRunning(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray): Int = mutex.withLock { + val running = database.confederationCeremonyDao().getRunningAttempts(userPublicKey) + running.forEach { attempt -> + val room = database.chatRoomDao().findChatRoomById(attempt.confederationId) ?: return@forEach + runCatching { advance(database, room, attempt.id, nostrPrivateKey) } + .onFailure { logger.e("Could not resume signing attempt ${attempt.id}", it) } + } + running.size + } + + // ---- the rounds ---------------------------------------------------------------------------- + + private suspend fun advance(database: GizaDatabase, room: LocalChatRoom, attemptId: String, nostrPrivateKey: ByteArray) { + val attempt = database.confederationCeremonyDao().getAttempt(attemptId)?.takeIf { it.isRunning } ?: return + val held = held(database, attempt.confederationId) ?: return + val me = attempt.userPublicKey + val plan = held.plan + val event = Event.fromJson(attempt.eventJson) + val message = ByteVector32(event.id) + + // 1. The proposer fixes the selection from the yeses, once there are enough. + if (me == attempt.proposerPublicKey && own(database, attempt, ConfederationSigningEvents.SESSION) == null) { + val availability = availability(database, attempt, plan) + val selection = select(held, availability) + if (selection == null) { + if (!stillPossible(held, availability)) { + return failOut(database, room, attempt, "Not enough admins of enough groups are willing to sign") + } + return moveTo(database, attempt, ConfederationSigningStage.SELECTING) + } + val session = ConfederationSigningSession.create(held.keyState, ByteVector32(attempt.id), selection, held.tweaks) + .rightOrFail { return failOut(database, room, attempt, "The signing session cannot be made: $it") } + publishOwn(database, room, attempt, ConfederationSigningEvents.SESSION, + ConfederationSigningEvents.Session(selection.groups, session.dSign.toHex()).encode()) + } + val sent = database.confederationCeremonyDao().getSigningMessage(attempt.id, attempt.proposerPublicKey, ConfederationSigningEvents.SESSION) + ?.let { ConfederationSigningEvents.Session.decode(it.payload) } + ?: return moveTo(database, attempt, ConfederationSigningStage.SELECTING) + val selection = ConfederationSignerSelection(sent.selection) + val session = ConfederationSigningSession.create(held.keyState, ByteVector32(attempt.id), selection, held.tweaks) + .rightOrFail { return failOut(database, room, attempt, "The proposer's selection is not one this confederation can sign with: $it") } + if (!session.check(ByteVector(sent.dSign))) { + return failOut(database, room, attempt, "The proposer's signing session is not the one this device derives") + } + val selected = session.signers.mapNotNull { plan.seatOf(it) } + val people = selected.map { it.admin }.distinct() + val mine = selected.filter { it.admin == me } + val host = { seat: ConfederationRosterBuilder.Seat -> ConfederationRosterBuilder.hostSecretKey(nostrPrivateKey, seat.group, plan.proposal.id) } + + // 2. Each selected role's nonce, made now and held in memory only. + if (mine.isNotEmpty() && own(database, attempt, ConfederationSigningEvents.NONCES) == null) { + val nonces = mine.associate { seat -> + val share = shareOf(held, seat, host(seat)) ?: return failOut(database, room, attempt, "This device's share no longer opens") + val signer = ConfederationSigning.generateNonce(session, seat.roleId, share, ByteVector32(RandomInstance.bytes(32))) + .rightOrFail { return failOut(database, room, attempt, "A nonce could not be made: $it") } + signers[signerKey(me, attempt.id, seat.roleId)] = signer + seat.group to signer.publicNonce.toHex() + } + publishOwn(database, room, attempt, ConfederationSigningEvents.NONCES, ConfederationRitualEvents.encodeByGroup(nonces)) + } + val nonces = perRole(database, attempt, selected, people, ConfederationSigningEvents.NONCES) { ByteVector(it) } + ?: return moveTo(database, attempt, ConfederationSigningStage.NONCES) + val transcript = ConfederationSigning.transcript(session, nonces) + .rightOrFail { return failOut(database, room, attempt, "The nonce transcript cannot be built: $it") } + + // 3. Each selected role confirms the transcript and the event. + if (mine.isNotEmpty() && own(database, attempt, ConfederationSigningEvents.CONFIRMATIONS) == null) { + val confirmations = mine.associate { seat -> + val signer = signers[signerKey(me, attempt.id, seat.roleId)] ?: return failOut(database, room, attempt, RESTARTED) + seat.group to ConfederationSigning.confirm(signer, transcript, message, host(seat)) + .rightOrFail { return failOut(database, room, attempt, "Confirming failed: $it") }.toHex() + } + publishOwn(database, room, attempt, ConfederationSigningEvents.CONFIRMATIONS, ConfederationRitualEvents.encodeByGroup(confirmations)) + } + val confirmations = perRole(database, attempt, selected, people, ConfederationSigningEvents.CONFIRMATIONS) { ByteVector64(it) } + ?: return moveTo(database, attempt, ConfederationSigningStage.CONFIRMING) + val certificate = ConfederationSigning.certificate(session, transcript, message, confirmations) + .rightOrFail { return failOut(database, room, attempt, "The confirmations cannot be certified: $it") } + if (!ConfederationSigning.verifyCertificate(session, transcript, message, certificate)) { + return failOut(database, room, attempt, "A confirmation does not verify") + } + + // 4. Each selected role's partial: the signer is spent here, whatever happens. + if (mine.isNotEmpty() && own(database, attempt, ConfederationSigningEvents.PARTIALS) == null) { + val partials = mine.associate { seat -> + val signer = signers.remove(signerKey(me, attempt.id, seat.roleId)) ?: return failOut(database, room, attempt, RESTARTED) + val share = shareOf(held, seat, host(seat)) ?: return failOut(database, room, attempt, "This device's share no longer opens") + seat.group to ConfederationSigning.sign(signer, share, transcript, message, certificate) + .rightOrFail { return failOut(database, room, attempt, "Signing failed: $it") }.toHex() + } + publishOwn(database, room, attempt, ConfederationSigningEvents.PARTIALS, ConfederationRitualEvents.encodeByGroup(partials)) + } + val partials = perRole(database, attempt, selected, people, ConfederationSigningEvents.PARTIALS) { ByteVector32(it) } + ?: return moveTo(database, attempt, ConfederationSigningStage.SIGNING) + + // 5. Every group's partial and the signature, on every device. + complete(database, room, attempt, held, session, transcript, certificate, message, event, partials) + } + + private suspend fun complete( + database: GizaDatabase, + room: LocalChatRoom, + attempt: ConfederationSigningAttempt, + held: Held, + session: ConfederationSigningSession, + transcript: fr.acinq.bitcoin.crypto.confederation.ConfederationNonceTranscript, + certificate: ConfederationConfirmationCertificate, + message: ByteVector32, + event: Event, + partials: Map, + ) { + val groupPartials = session.groups.associateWith { groupId -> + ConfederationSigning.aggregateGroup(session, transcript, message, certificate, groupId, partials.filterKeys { it.groupId == groupId }) + .rightOrFail { culprit -> return failOut(database, room, attempt, "Group ${held.plan.groups.getOrNull(groupId.toInt())?.let { ConfederationManager.nameOf(database, it) }}'s partial does not add up: $culprit") } + } + val signature = ConfederationSigning.aggregate(session, transcript, message, certificate, groupPartials) + .rightOrFail { return failOut(database, room, attempt, "The signature cannot be assembled: $it") } + if (!Crypto.verifySignatureSchnorr(message, signature, held.roomKey)) { + return failOut(database, room, attempt, "The signature does not verify as the confederation's room") + } + val signed = Event(event.id, event.pubKey, event.createdAt, event.kind, event.tags, event.content, signature.toHex()) + update(database, attempt) { it.copy(stage = ConfederationSigningStage.COMPLETE, signedEventJson = signed.toJson()) } + database.groupSignedEventDao().record(GroupSignedEvent.fromEvent(signed, chatRoomId = held.confederation.id)) + announce( + database, attempt, + if (signed.kind == MetadataEvent.KIND) ChatMessage.TYPE_GROUP_PROFILE_SIGNED else ChatMessage.TYPE_GROUP_POST_SIGNED, + "The confederation signed ${describe(signed)}", + ) + logger.i("Confederation ${held.confederation.id.take(12)} signed ${signed.id.take(8)}") + } + + // ---- helpers --------------------------------------------------------------------------- + + /** The roles available to sign, by role: true for a yes, false for a no. Missing for a person who has not said. */ + private suspend fun availability(database: GizaDatabase, attempt: ConfederationSigningAttempt, plan: Plan): Map = + plan.people.flatMap { person -> + val said = database.confederationCeremonyDao().getSigningMessage(attempt.id, person, ConfederationSigningEvents.AVAILABILITY) + ?.let { ConfederationRitualEvents.decodeByGroup(it.payload) } ?: return@flatMap emptyList() + plan.seatsOf(person).mapNotNull { seat -> said[seat.group]?.let { seat.roleId to (it == ConfederationSigningEvents.YES) } } + }.toMap() + + /** + * The first `T` groups, in roster order, with at least `t_g` yeses, and in each the `t_g` lowest + * admins who said yes. Null while that many are not yet in. + */ + private fun select(held: Held, availability: Map): ConfederationSignerSelection? { + val groups = held.roster.groups.mapNotNull { group -> + val yes = group.roles.map { it.id }.filter { availability[it] == true }.map { it.adminId }.sorted() + if (yes.size >= group.threshold) group.groupId to yes.take(group.threshold).toSet() else null + } + if (groups.size < held.roster.outerThreshold) return null + return ConfederationSignerSelection(groups.take(held.roster.outerThreshold).toMap()) + } + + /** Whether enough roles that have not said no remain for a selection to be possible. */ + private fun stillPossible(held: Held, availability: Map): Boolean = + held.roster.groups.count { group -> group.roles.count { availability[it.id] != false } >= group.threshold } >= held.roster.outerThreshold + + private suspend fun perRole( + database: GizaDatabase, + attempt: ConfederationSigningAttempt, + selected: List, + people: List, + kind: Kind, + read: (String) -> T, + ): Map? { + val byPerson = people.associateWith { person -> + val message = database.confederationCeremonyDao().getSigningMessage(attempt.id, person, kind) ?: return null + ConfederationRitualEvents.decodeByGroup(message.payload) ?: return null + } + return selected.associate { seat -> seat.roleId to read(byPerson.getValue(seat.admin)[seat.group] ?: return null) } + } + + /** This device's share for [seat], opened from the recovery package it kept. */ + private fun shareOf(held: Held, seat: ConfederationRosterBuilder.Seat, host: fr.acinq.bitcoin.PrivateKey): ConfederationShare? { + val hex = ConfederationRitualEvents.decodeByGroup(held.confederation.recoveryPackages)?.get(seat.group) ?: return null + val recovery = (ConfederationRecoveryPackage.fromData(ByteVector(hex), host) as? Either.Right)?.value ?: return null + return (recovery.open(host, held.keyState) as? Either.Right)?.value + } + + private suspend fun publishAvailability(database: GizaDatabase, room: LocalChatRoom, attempt: ConfederationSigningAttempt, held: Held, available: Boolean) { + if (own(database, attempt, ConfederationSigningEvents.AVAILABILITY) != null) return + val value = if (available) ConfederationSigningEvents.YES else ConfederationSigningEvents.NO + publishOwn( + database, room, attempt, ConfederationSigningEvents.AVAILABILITY, + ConfederationRitualEvents.encodeByGroup(held.plan.seatsOf(attempt.userPublicKey).associate { it.group to value }), + ) + } + + private suspend fun own(database: GizaDatabase, attempt: ConfederationSigningAttempt, kind: Kind) = + database.confederationCeremonyDao().getSigningMessage(attempt.id, attempt.userPublicKey, kind) + + private suspend fun publishOwn(database: GizaDatabase, room: LocalChatRoom, attempt: ConfederationSigningAttempt, kind: Kind, content: String) { + broadcast(database, room, attempt, kind, content) + database.confederationCeremonyDao().insertSigningMessage(ConfederationSigningMessage(attempt.id, attempt.userPublicKey, kind, content)) + } + + /** Queues a rumor for the confederation's Marmot room, encrypted to the room as a group event. */ + private suspend fun broadcast(database: GizaDatabase, room: LocalChatRoom, attempt: ConfederationSigningAttempt, kind: Kind, content: String) { + val tags = arrayOf(ConfederationSigningEvents.sessionTag(attempt.id)) + val createdAt = Clock.System.now().epochSeconds + val id = EventHasher.hashId(attempt.userPublicKey, createdAt, kind, tags, content) + database.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = id, + publicKey = attempt.userPublicKey, + kind = kind, + createdAt = Instant.fromEpochSeconds(createdAt), + tags = tags, + content = content, + chatRoomId = room.chatRoom.id, + ) + ) + } + + private suspend fun replayStoredMessages(database: GizaDatabase, held: Held, attempt: ConfederationSigningAttempt) { + database.marmotInnerEventDao() + .getByChatRoomAndKinds(attempt.confederationId, (ConfederationSigningEvents.ALL - ConfederationSigningEvents.PROPOSAL).toList()) + .filter { ConfederationSigningEvents.parseSessionId(it.tags) == attempt.id } + .forEach { stored -> + val event = Event(stored.id, stored.publicKey, stored.createdAt.epochSeconds, stored.kind, stored.tags, stored.content, "") + if (!record(database, held, database.confederationCeremonyDao().getAttempt(attempt.id) ?: return, event)) return + } + } + + private inline fun Either.rightOrFail(onLeft: (String) -> Nothing): T = when (this) { + is Either.Right -> value + is Either.Left -> onLeft(value.message ?: value.toString()) + } + + private suspend fun update( + database: GizaDatabase, + attempt: ConfederationSigningAttempt, + transform: (ConfederationSigningAttempt) -> ConfederationSigningAttempt, + ): ConfederationSigningAttempt { + val current = database.confederationCeremonyDao().getAttempt(attempt.id) ?: attempt + val next = transform(current).copy(updatedAt = Clock.System.now()) + database.confederationCeremonyDao().upsertAttempt(next) + return next + } + + private suspend fun moveTo(database: GizaDatabase, attempt: ConfederationSigningAttempt, stage: ConfederationSigningStage) { + if (attempt.stage != stage) update(database, attempt) { it.copy(stage = stage) } + } + + private suspend fun failOut(database: GizaDatabase, room: LocalChatRoom, attempt: ConfederationSigningAttempt, reason: String) { + broadcast(database, room, attempt, ConfederationSigningEvents.FAILURE, reason) + fail(database, attempt, reason) + } + + private suspend fun fail(database: GizaDatabase, attempt: ConfederationSigningAttempt, reason: String) { + val current = database.confederationCeremonyDao().getAttempt(attempt.id) ?: attempt + if (!current.isRunning) return + // Whatever this device was holding for the attempt goes with it. + signers.keys.filter { it.startsWith("${current.userPublicKey}/${current.id}/") }.forEach { signers.remove(it)?.abort() } + update(database, current) { it.copy(stage = ConfederationSigningStage.FAILED, failureReason = reason) } + logger.w("Signing attempt ${attempt.id} failed: $reason") + announce(database, current, ChatMessage.TYPE_CONFEDERATION_SIGNING_FAILED, "The confederation did not sign: $reason") + } + + private fun describe(event: Event): String = when (event.kind) { + MetadataEvent.KIND -> "its profile" + TextNoteEvent.KIND -> "a post" + else -> "an event of kind ${event.kind}" + } + + private suspend fun announce(database: GizaDatabase, attempt: ConfederationSigningAttempt, type: String, content: String) { + database.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = attempt.proposerPublicKey, + isUserMessage = false, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = attempt.confederationId, + content = content, + messageType = type, + ) + ) + } + + /** For tests: forget every live signer, as a restart would. */ + internal fun forgetSignersForTest() { + signers.values.forEach { it.abort() } + signers.clear() + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationSigningEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationSigningEvents.kt new file mode 100644 index 00000000..e1ef3989 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationSigningEvents.kt @@ -0,0 +1,80 @@ +package mobi.giza.compose.nostr.confederation + +import com.vitorpamplona.quartz.nip01Core.core.Kind +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.int +import kotlinx.serialization.json.put + +/** + * The confederation signing as itself, on the wire (docs/confederation.md, Phase 14): rumors in the + * confederation's own Marmot room, over upstream's Option A signing. + * + * | kind | from | carries | + * |-------|---------------|----------------------------------------------------------------------| + * | 30390 | the proposer | the unsigned event, authored by the confederation's room | + * | 30391 | each person | per role, by group: whether that role will sign ("yes" or "no") | + * | 30392 | the proposer | the selection it fixed from the yeses, and the D_sign it encodes | + * | 30393 | each selected | per role: its public nonce | + * | 30394 | each selected | per role: its confirmation of the transcript and the event | + * | 30395 | each selected | per role: its member partial | + * | 30399 | anyone | failure, with a reason | + * + * Only the selection needs a coordinator: approvals arrive in a different order on every device, + * and somebody has to say which of them sign. Everything after it -- the nonce transcript, the + * confirmation certificate, each group's partial and the signature -- takes no secret, so every + * device computes it from the public messages it holds, and nobody can be handed a wrong one. + * Group coordinators, which the protocol leaves to the application, are therefore every device. + */ +object ConfederationSigningEvents { + const val PROPOSAL: Kind = 30390 + const val AVAILABILITY: Kind = 30391 + const val SESSION: Kind = 30392 + const val NONCES: Kind = 30393 + const val CONFIRMATIONS: Kind = 30394 + const val PARTIALS: Kind = 30395 + const val FAILURE: Kind = 30399 + + val ALL: Set = setOf(PROPOSAL, AVAILABILITY, SESSION, NONCES, CONFIRMATIONS, PARTIALS, FAILURE) + + /** Sent once per person, a value per role. */ + val PER_PERSON: Set = setOf(AVAILABILITY, NONCES, CONFIRMATIONS, PARTIALS) + + fun isSigningKind(kind: Kind): Boolean = kind in ALL + + const val SESSION_TAG = "confederation_signing" + const val YES = "yes" + const val NO = "no" + + fun sessionTag(sessionId: String): Array = arrayOf(SESSION_TAG, sessionId) + + fun parseSessionId(tags: Array>): String? = + tags.firstOrNull { it.size >= 2 && it[0] == SESSION_TAG }?.get(1)?.takeIf(ConfederationKinds::isHex32) + + private val json = Json { ignoreUnknownKeys = false } + + /** The proposer's selection, by group id, and the D_sign it encodes. */ + data class Session(val selection: Map>, val dSign: String) { + fun encode(): String = buildJsonObject { + put("selection", JsonObject(selection.toSortedMap().entries.associate { (g, admins) -> + g.toString() to JsonArray(admins.sorted().map { JsonPrimitive(it.toInt()) }) + })) + put("dSign", dSign) + }.toString() + + companion object { + fun decode(content: String): Session? = runCatching { + val obj = json.parseToJsonElement(content) as JsonObject + Session( + selection = (obj["selection"] as JsonObject).entries.associate { (g, admins) -> + g.toUInt() to (admins as JsonArray).map { (it as JsonPrimitive).int.toUInt() }.toSet() + }, + dSign = (obj["dSign"] as JsonPrimitive).content, + ) + }.getOrNull() + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt index a0f3aa52..62321c23 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt @@ -897,6 +897,8 @@ private fun RitualNotice( ChatMessage.TYPE_CONFEDERATION_CEREMONY_COMPLETE -> Icons.Default.CheckCircle ChatMessage.TYPE_CONFEDERATION_CEREMONY_FAILED -> Icons.Default.ErrorOutline ChatMessage.TYPE_CONFEDERATION_FORMED -> Icons.Default.Hub + ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED -> Icons.Default.Draw + ChatMessage.TYPE_CONFEDERATION_SIGNING_FAILED -> Icons.Default.ErrorOutline else -> Icons.Default.PanTool diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt index c76db20d..8af95b73 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt @@ -66,10 +66,11 @@ class ShippedProfileUpgradeJvmTest { * refresh and 40 for share repair (docs/frost-share-refresh.md, Phases 6, 7 and * 10), 41 for governance proposals and 42 for what follows them * (docs/member-admin-promotion.md, Phases 5, 8 and 9), 43 for the confederation - * (docs/confederation.md, Phase 4) and 44 for its key ceremony (Phase 11), so the upgrade - * crosses eight generated migrations and the file has to come out at the last. + * (docs/confederation.md, Phase 4) 44 for its key ceremony (Phase 11) and 45 for its + * signing (Phase 14), so the upgrade crosses nine generated migrations and the file has to + * come out at the last. */ - private val current = 44 + private val current = 45 private val directory: File = Files.createTempDirectory("giza-shipped-profile").toFile() private val file: File = File(directory, "aux.db") diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt new file mode 100644 index 00000000..17cbf424 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt @@ -0,0 +1,217 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PrivateKey +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Instant +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.Confederation +import mobi.giza.compose.database.model.ConfederationSigningStage +import mobi.giza.compose.database.model.MarmotInnerEvent +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents +import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents +import mobi.giza.compose.nostr.frost.GroupKeyStateEvent + +/** + * A confederation signing as itself, one person per device (docs/confederation.md, Phase 14): a + * confederation formed across nine devices, then a proposal in its room, approvals, and Option A + * signing with every signer's nonce held in memory -- ending, on every device, in the same event, + * signed as the room's id. + */ +class ConfederationSigningJvmTest { + private fun secret(n: Int) = PrivateKey(ByteArray(32).also { it[0] = 0x71; it[31] = n.toByte() }) + private fun npub(key: PrivateKey): HexKey = key.publicKey().xOnly().value.toHex() + + private val groupKeys = (1..3).map { secret(it) } + private val groups = groupKeys.map(::npub) + private val people = listOf(11, 12, 13, 21, 22, 23, 31, 32, 33) + private val admins = listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33)) + + private inner class Device(val secret: PrivateKey, val db: GizaDatabase) { + val person = npub(secret) + lateinit var ceremonyRoom: LocalChatRoom + lateinit var room: LocalChatRoom + val received = mutableSetOf() + val nsec get() = secret.value.toByteArray() + } + + private val devices = linkedMapOf() + private lateinit var confederation: Confederation + private lateinit var proposer: Device + + @BeforeTest + fun formed() = runBlocking { + val coordinator = npub(secret(11)) + val now = Clock.System.now().epochSeconds + val proposal = ConfederationTestGroups.proposal(groupKeys[0], groups, coordinator, createdAt = now - 10, expiresAt = now + 1000) + val acceptances = groupKeys.mapIndexed { i, key -> ConfederationTestGroups.acceptance(key, proposal, admins[i].map { npub(secret(it)) }) } + + people.map(::secret).forEach { key -> + val db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + (people.map { npub(secret(it)) } + groups).forEach { member -> + val eventId = Crypto.sha256(member.encodeToByteArray()).toHex() + db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = member, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = member, nostrEventId = eventId, displayName = member.take(6), createdAt = Instant.fromEpochSeconds(1_790_000_000))) + } + devices[npub(key)] = Device(key, db) + } + proposer = devices.getValue(coordinator) + (listOf(proposal) + acceptances).forEach { ConfederationManager.record(proposer.db, it) } + + // Part B, across the devices: the ceremony, every device joining. + val ceremony = ConfederationRitualManager.open(proposer.db, proposal.id, proposer.secret) + proposer.ceremonyRoom = proposer.db.chatRoomDao().findChatRoomById(ceremony.chatRoomId)!! + devices.values.filter { it !== proposer }.forEach { d -> + d.ceremonyRoom = d.db.nostrNip17Dao().createNip17ChatRoom(d.person, devices.keys.filter { it != d.person }, "Atlas")!! + } + pumpCeremony() + devices.values.forEach { ConfederationRitualManager.join(it.db, ceremony.id, it.nsec) } + pumpCeremony() + confederation = assertNotNull(proposer.db.confederationCeremonyDao().getConfederationForProposal(proposal.id)) + + // The confederation's room on every device. Its MLS state is not this test's business; a + // room with group state is what makes signing travel as a group event. + devices.values.forEach { d -> + d.db.chatRoomDao().upsert(ChatRoom(id = confederation.id, userPublicKey = d.person, subject = "#Atlas", description = null, mlsGroupState = "00")) + d.room = d.db.chatRoomDao().findChatRoomById(confederation.id)!! + } + } + + @AfterTest + fun close() { + ConfederationSigningManager.forgetSignersForTest() + devices.values.forEach { it.db.close() } + } + + private suspend fun pumpCeremony() { + var moved = true + while (moved) { + moved = false + for (from in devices.values) for (to in devices.values) { + if (from === to) continue + from.db.giftWrapPayloadDao().getByChatRoomAndKinds(from.ceremonyRoom.chatRoom.id, ConfederationRitualEvents.ALL.toList()) + .filter { it.publicKey == from.person }.sortedBy { it.createdAt } + .forEach { q -> + if (!to.received.add(q.id)) return@forEach + moved = true + to.db.giftWrapPayloadDao().upsert(q.copy(chatRoomId = to.ceremonyRoom.chatRoom.id)) + ConfederationRitualManager.process(to.db, to.ceremonyRoom, Event(q.id, q.publicKey, q.createdAt.epochSeconds, q.kind, q.tags, q.content, ""), to.person, to.nsec) + } + } + } + } + + /** Ferries the room's signing messages between devices until nothing moves; [hold] keeps some back. */ + private fun pump(hold: (MarmotInnerEvent) -> Boolean = { false }) = runBlocking { + var moved = true + while (moved) { + moved = false + for (from in devices.values) for (to in devices.values) { + if (from === to) continue + from.db.marmotInnerEventDao().getByChatRoomAndKinds(confederation.id, ConfederationSigningEvents.ALL.toList()) + .filter { it.publicKey == from.person }.sortedWith(compareBy({ it.createdAt }, { it.kind })) + .forEach { q -> + if (hold(q) || !to.received.add(q.id)) return@forEach + moved = true + to.db.marmotInnerEventDao().upsert(q) + ConfederationSigningManager.process(to.db, to.room, Event(q.id, q.publicKey, q.createdAt.epochSeconds, q.kind, q.tags, q.content, ""), to.person, to.nsec) + } + } + } + } + + private fun propose(kind: Int = MetadataEvent.KIND, content: String = """{"name":"Atlas","about":"A group of groups"}""") = runBlocking { + ConfederationSigningManager.propose(proposer.db, proposer.room, proposer.person, kind, emptyArray(), content, proposer.nsec) + } + + private fun approve(attemptId: String, who: List) = runBlocking { + who.map { devices.getValue(npub(secret(it))) }.forEach { ConfederationSigningManager.approve(it.db, attemptId, it.nsec) } + } + + private fun attempts(attemptId: String) = runBlocking { devices.values.associate { it.person to it.db.confederationCeremonyDao().getAttempt(attemptId) } } + + @Test + fun `the confederation signs its profile, and every device holds it signed as the room`() { + val attempt = propose() + pump() + approve(attempt.id, people - 11) + pump() + + attempts(attempt.id).forEach { (person, a) -> assertEquals(ConfederationSigningStage.COMPLETE, a?.stage, "${person.take(6)}: ${a?.failureReason}") } + val signed = attempts(attempt.id).values.map { Event.fromJson(it!!.signedEventJson!!) } + assertEquals(1, signed.map { it.sig }.toSet().size, "the same signature on every device") + assertTrue(GroupKeyStateEvent.isSignedByRoom(signed.first(), confederation.id), "a plain nostr signature by the room's id") + + runBlocking { + devices.values.forEach { d -> + val rows = d.db.groupSignedEventDao().getByChatRoomIdAndKind(confederation.id, MetadataEvent.KIND) + assertEquals("Atlas", assertNotNull(GroupNostrProfile.newestAmong(rows, confederation.id)).name()) + } + } + } + + @Test + fun `enough willing admins in enough groups is all it takes`() { + val attempt = propose(TextNoteEvent.KIND, "The first words of a group of groups") + pump() + // Two groups of three, two admins in each: Agora (11, 12) and Polis (21, 22). Nobody else answers. + approve(attempt.id, listOf(12, 21, 22)) + pump() + listOf(11, 12, 21, 22, 33).forEach { n -> + assertEquals(ConfederationSigningStage.COMPLETE, attempts(attempt.id).getValue(npub(secret(n)))?.stage) + } + } + + @Test + fun `a device that loses its nonces mid-attempt ends it for everybody`() { + val attempt = propose() + pump() + approve(attempt.id, people - 11) + pump(hold = { it.kind == ConfederationSigningEvents.NONCES }) + ConfederationSigningManager.forgetSignersForTest() // every device restarts + pump() + attempts(attempt.id).values.forEach { + assertEquals(ConfederationSigningStage.FAILED, it?.stage) + assertTrue(it!!.failureReason!!.contains("restarted while signing"), it.failureReason) + } + } + + @Test + fun `when too many decline, the proposer says so and it ends`() { + val attempt = propose() + pump() + runBlocking { + listOf(21, 22, 31, 32).map { devices.getValue(npub(secret(it))) }.forEach { ConfederationSigningManager.decline(it.db, attempt.id) } + } + pump() + val ended = attempts(attempt.id).getValue(proposer.person) + assertEquals(ConfederationSigningStage.FAILED, ended?.stage) + assertTrue(ended!!.failureReason!!.startsWith("Not enough admins"), ended.failureReason) + } + + @Test + fun `a confederation signs only its profile and its posts`() { + assertFailsWith { propose(kind = 30023, content = "long form") } + assertFailsWith { propose(kind = TextNoteEvent.KIND, content = " ") } + } +} diff --git a/docs/confederation.md b/docs/confederation.md index 7f740e09..2944baef 100644 --- a/docs/confederation.md +++ b/docs/confederation.md @@ -92,6 +92,7 @@ the reasoning. Where the build chose differently: | 11 | done. `ConfederationRitualManager` over upstream's `ConfederationDkg`, in a NIP-17 room the coordinator opens over every admin (with placeholder profiles for members this device has none for). Kinds 30380 (opening), 30381 (host keys), 30382 (dealings), 30383 (roster and broadcast), 30384 (authorizations), 30385 (acknowledgments), 30387 (failure). One message per person per step, one value per role, keyed by group. **No 30386:** every device assembles the certified genesis itself from evidence it already holds, so nobody can hand one over. **No investigation (30388):** a decryption fault names "a participant or the coordinator" and ends the ceremony. Before joining, a device checks the proposal and acceptances are their groups' own, every acceptance opens with its disclosed key, the room is exactly the roster's people, and each group it is in still has the admins it accepted with, compared on their own so a member without a share still checks. Joining is the only approval; dealer seeds are erased once dealt; every role derives its key state itself and the coordinator's roster must match byte for byte. Schema 44. The coordinator opens it by a button on the proposal screen rather than on its own. `ConfederationRitualScreen`, with a join, each step's named waits and abandon. `ConfederationCeremonyJvmTest` 7/7: three groups of three on nine devices reach one key that signs as the room once each recovery package is opened; one person in two groups; a holdout and abandon; a disclosed key that does not open; a substituted roster; admins changed; messages before the opening. jvmTest 1,619 | | 12 | done. `ConfederationFormation.onComplete` files a `Confederation` (room id, X, roster, key state, genesis, the `(configSeq, rpdHash, ksdHash)` triple, this device's recovery packages) and `ConfederationMember` rows, folded into schema 44 since it has not shipped. The genesis is verified against the key state before anything is written. A line goes into each of this device's own member groups' rooms; nothing is sent to them. **No 30389 key-state event:** every founding member of the room took part and holds the record, so `ConfederationFormation.verifies` checks the stored descriptors instead; a member added later needs one, which waits for Part C's governance. A formed confederation reads "Formed" on the group's list. `ConfederationCeremonyJvmTest` now also checks every device files the same verified confederation under the room its key derives | | 13 | done. `ConfederationFollowThrough` on the coordinator's device makes the room once every member's key package is in, retrying when one arrives, through `MarmotGroupCreation.create` rather than a new `createForConfederation`: id `marmotGroupId(02‖X)`, a random routing address, every role holder a member and an admin, `#name`, born governed with `Quorum.minimumAdmins(T)`. A record that no longer verifies, or a device holding no role, makes no room. Adoption needs no new check: every founding member holds the `Confederation` row under the room's id, and `confederationOfRoom` reads it only if it verifies. The room's screen says whose room it is and that its members are fixed until the confederation can sign. `ConfederationCeremonyJvmTest` 9/9. `./gradlew check` passes, jvmTest 1,621 | +| 14 | done. `ConfederationSigningManager` over upstream's `ConfederationSigning`, in the confederation's Marmot room. Kinds 30390 (proposal), 30391 (each person's yes or no per role), 30392 (the proposer's selection and D_sign), 30393 (nonces), 30394 (confirmations), 30395 (partials), 30399 (failure). Only the selection is coordinated: the first `T` groups in roster order with `t_g` yeses, the lowest admins first. The transcript, the certificate, every group's partial and the signature take no secret, so **every device computes them itself** and checks the signature against the room's id before keeping it: no group coordinator and no outer coordinator message. Signer state is held in memory only; a device that restarts after sending a nonce ends the attempt out loud on its next step, and `resumeRunning` does it on start. A confederation signs kinds 0 and 1 only, with Part A's statement refusals; anything else is declined out loud. A signed event lands in `GroupSignedEvent` under the room, so the existing profile, posts and broadcast screens read it. Schema 45. `ConfederationSigningJvmTest` 5/5 on nine devices: a profile signed and read back on every device; two groups of two admins enough; a restart between nonces and confirmations failing it everywhere; too many declines; refused kinds. jvmTest 1,626 | --- From bacd53a1ae9ce876ed15c435b6f9bb38ecb49550 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 01:10:30 +0200 Subject: [PATCH 02/16] feat: what a confederation signs: its profile, its posts and its charter (confederation, Phase 15) The profile and post editors work in a confederation's room, proposing through the confederation instead of a FROST key, and the signed event lands where the existing screens read it. A charter names exactly the confederation's groups under its name; once signed it goes to relays, and every member group's room hears of it, which is how members who are not admins learn the confederation exists. A request to sign opens from its line in the room for each member to approve or decline. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 12 ++ .../repository/DatabaseChatRepository.kt | 25 +++ .../DatabaseConfederationRepository.kt | 19 ++ .../compose/managers/ConfederationManager.kt | 30 ++++ .../managers/ConfederationSigningManager.kt | 41 ++++- .../ConfederationCharterEvent.kt | 51 ++++++ .../nostr/confederation/ConfederationKinds.kt | 5 +- .../giza/compose/repository/ChatRepository.kt | 11 ++ .../repository/ConfederationRepository.kt | 19 ++ .../mobi/giza/compose/text/ProposedEvent.kt | 5 + .../ui/composable/AddGroupPostScreen.kt | 18 +- .../ui/composable/ChatRoomDetailScreen.kt | 35 +++- .../ui/composable/ChatRoomMessagingScreen.kt | 6 + .../composable/ConfederationSigningScreen.kt | 169 ++++++++++++++++++ .../composable/EditGroupNostrProfileScreen.kt | 18 +- .../ui/composable/navigation/GizaNavHost.kt | 11 ++ .../routes/ConfederationSigningRoute.kt | 10 ++ .../composable/widgets/chat/ChatTranscript.kt | 17 ++ .../ui/view/model/AddGroupPostViewModel.kt | 29 ++- .../ui/view/model/ChatRoomDetailViewModel.kt | 12 ++ .../model/ConfederationSigningViewModel.kt | 85 +++++++++ .../model/EditGroupNostrProfileViewModel.kt | 29 ++- .../view/model/GroupNostrProfileViewModel.kt | 2 +- .../ui/view/model/GroupPostsViewModel.kt | 2 +- .../ui/view/state/ChatRoomDetailUIState.kt | 2 + .../view/state/ConfederationSigningUIState.kt | 21 +++ .../managers/ConfederationSigningJvmTest.kt | 42 +++++ .../composable/ConfederationScreensJvmTest.kt | 51 ++++++ docs/confederation.md | 1 + 29 files changed, 739 insertions(+), 39 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationCharterEvent.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationSigningScreen.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationSigningRoute.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationSigningViewModel.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationSigningUIState.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index b9b806df..03441aa7 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -740,4 +740,16 @@ %1$s: %2$d of %3$d admins to sign Formed This is the room of the confederation %1$s. Its key is held by the admins of its groups together. Until the confederation can sign, who is in this room cannot change. + The confederation's signature + Approve + Decline + Signed by %1$d admins of %2$d groups together, once enough of them approve. You approve for every group you are an admin of. + The confederation signed it + The confederation did not sign it: %1$s + You declined this + Approved + Declined + This device holds no such request for the confederation to sign + Propose the charter + The charter is the confederation's public statement of the groups it is made of, signed with its own key. It is how members who are not admins hear of it. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 0923f292..2bf6a1b1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -270,6 +270,31 @@ class DatabaseChatRepository( override suspend fun confederationProposalCount(chatRoomId: String): Int = database.confederationDao().getProposalsNaming(chatRoomId).size + override suspend fun canSignAsConfederation(chatRoomId: String): Boolean { + if (!ExperimentalFeatures.confederation) return false + val me = activeIdentity.value?.takeIf { it.canSign }?.nostrPublicKey ?: return false + return ConfederationSigningManager.canSign(database, chatRoomId, me) + } + + override suspend fun proposeAsConfederation( + localChatRoom: LocalChatRoom, + kind: Kind, + tags: Array>, + content: String, + ): String { + val identity = activeIdentity.value ?: throw IllegalStateException("No identity is signed in") + val secret = identity.nostrPrivateKey ?: throw IllegalStateException("This identity cannot sign") + return ConfederationSigningManager.propose( + database, localChatRoom, identity.nostrPublicKey, kind, tags, content, secret.value.toByteArray(), + ).id + } + + override suspend fun proposeCharter(localChatRoom: LocalChatRoom): String { + val (kind, tags, content) = ConfederationSigningManager.charterTemplate(database, localChatRoom.chatRoom.id) + ?: throw IllegalStateException("This device holds no confederation for this room") + return proposeAsConfederation(localChatRoom, kind, tags, content) + } + override suspend fun confederationOfRoom(chatRoomId: String): String? = database.confederationCeremonyDao().getConfederation(chatRoomId) ?.takeIf { ConfederationFormation.verifies(it) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt index 3e857c81..e188f111 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt @@ -16,6 +16,9 @@ import mobi.giza.compose.database.model.Confederation import mobi.giza.compose.database.model.ConfederationCeremony import mobi.giza.compose.database.model.ConfederationCeremonyMessage import mobi.giza.compose.database.model.ConfederationEvent +import mobi.giza.compose.database.model.ConfederationSigningAttempt +import mobi.giza.compose.database.model.ConfederationSigningMessage +import mobi.giza.compose.managers.ConfederationSigningManager import mobi.giza.compose.managers.ConfederationRitualManager import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder @@ -59,6 +62,22 @@ class DatabaseConfederationRepository( override suspend fun abandonCeremony(sessionId: String) = ConfederationRitualManager.abandon(database, sessionId) + override fun observeSigningAttempt(attemptId: String): Flow = + database.confederationCeremonyDao().observeAttempt(attemptId) + + override fun observeSigningMessages(attemptId: String): Flow> = + database.confederationCeremonyDao().observeSigningMessages(attemptId) + + override suspend fun confederationPlan(confederationId: HexKey): ConfederationRosterBuilder.Plan? = + ConfederationSigningManager.held(database, confederationId)?.plan + + override suspend fun approveSigning(attemptId: String) { + val secret = activeIdentity.value?.nostrPrivateKey ?: return + ConfederationSigningManager.approve(database, attemptId, secret.value.toByteArray()) + } + + override suspend fun declineSigning(attemptId: String) = ConfederationSigningManager.decline(database, attemptId) + override fun observeConfederationsOf(groupPublicKey: HexKey): Flow> = database.confederationCeremonyDao().observeConfederationsOf(groupPublicKey) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt index 62a6b66c..8ff6ad23 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt @@ -16,6 +16,7 @@ import mobi.giza.compose.database.model.FrostSigningSession import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.confederation.ConfederationAdminList +import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent import mobi.giza.compose.nostr.confederation.ConfederationKinds import mobi.giza.compose.nostr.confederation.ConfederationProposalAcceptanceEvent import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent @@ -58,6 +59,9 @@ object ConfederationManager { ?.let { it.proposalId to emptyList() } ConfederationKinds.WITHDRAWAL -> ConfederationProposalWithdrawalEvent.parse(event) ?.let { it.proposalId to emptyList() } + // Filed under its own id, and under every group it names, so each member group finds it. + ConfederationKinds.CHARTER -> ConfederationCharterEvent.parse(event) + ?.let { it.id to it.groups } else -> null } ?: run { logger.w("Confederation event ${event.id.take(8)} of kind ${event.kind} is not well formed; dropping") @@ -96,6 +100,7 @@ object ConfederationManager { * not hold yet gets its line when the proposal is filed. */ private suspend fun announce(database: GizaDatabase, event: Event, proposalId: HexKey) { + if (event.kind == ConfederationKinds.CHARTER) return announceCharter(database, event) val proposal = proposal(database, proposalId) ?: return val rooms = proposal.groupPublicKeys.mapNotNull { database.chatRoomDao().findChatRoomById(it) } if (rooms.isEmpty()) return @@ -134,6 +139,31 @@ object ConfederationManager { } } + /** + * A line in each member group's room this device holds: the one way a group's members who are + * not admins hear that their group is part of a confederation. A claim by the confederation's + * key, which the line says. + */ + private suspend fun announceCharter(database: GizaDatabase, event: Event) { + val charter = ConfederationCharterEvent.parse(event) ?: return + charter.groups.forEach { group -> + if (database.chatRoomDao().findChatRoomById(group) == null) return@forEach + database.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = event.pubKey, + isUserMessage = false, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = group, + content = "The confederation ${charter.name} signed its charter, naming this group among its ${charter.groups.size}", + messageType = ChatMessage.TYPE_CONFEDERATION_FORMED, + createdAt = Instant.fromEpochSeconds(event.createdAt), + ) + ) + } + } + /** How a line names a group: "This group" in its own room, else its profile's name or its npub. */ suspend fun nameOf(database: GizaDatabase, group: HexKey, inRoom: String? = null): String { if (group == inRoom) return "This group" diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt index 2e1f1619..8ce1580a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt @@ -39,6 +39,7 @@ import mobi.giza.compose.database.model.GroupSignedEvent import mobi.giza.compose.database.model.MarmotInnerEvent import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder.Plan @@ -76,8 +77,8 @@ object ConfederationSigningManager { private fun signerKey(user: HexKey, attemptId: String, role: ConfederationRoleId) = "$user/$attemptId/${role.groupId}:${role.adminId}" - /** The kinds a confederation signs here: its profile and its posts (Phase 15). */ - val SIGNABLE_KINDS: Set = setOf(MetadataEvent.KIND, TextNoteEvent.KIND) + /** The kinds a confederation signs here: its profile, its posts and its charter (Phase 15). */ + val SIGNABLE_KINDS: Set = setOf(MetadataEvent.KIND, TextNoteEvent.KIND, ConfederationCharterEvent.KIND) const val RESTARTED = "A device restarted while signing, so this attempt cannot finish. Propose it again" @@ -113,13 +114,31 @@ object ConfederationSigningManager { /** Why this device would not sign [event] for [held]'s confederation, or null. */ private fun refusalOf(held: Held, event: Event): String? = when { event.pubKey != held.confederation.id -> "The event is not authored by the confederation" - event.kind !in SIGNABLE_KINDS -> "A confederation signs only its profile and its posts here" + event.kind !in SIGNABLE_KINDS -> "A confederation signs only its profile, its posts and its charter here" + event.kind == ConfederationCharterEvent.KIND && !isTrueCharter(held, event) -> + "The charter does not name exactly this confederation's groups, under its name" event.kind == MetadataEvent.KIND && GroupStatementRefusal.isUnreadableProfile(event.tags, event.content) -> GroupStatementRefusal.REASON event.kind == TextNoteEvent.KIND && GroupStatementRefusal.isBlankPost(event.content) -> GroupStatementRefusal.REASON EventHasher.hashId(event.pubKey, event.createdAt, event.kind, event.tags, event.content) != event.id -> "The event's id is not the hash of its fields" else -> null } + /** A charter names exactly the groups the confederation was formed from, under its name. */ + private fun isTrueCharter(held: Held, event: Event): Boolean { + val charter = ConfederationCharterEvent.parse(event) ?: return false + return charter.groups.toSet() == held.plan.groups.toSet() && charter.name == held.confederation.name + } + + /** The charter [held]'s confederation would sign: its groups, under its name. */ + suspend fun charterTemplate(database: GizaDatabase, confederationId: HexKey): Triple>, String>? { + val held = held(database, confederationId) ?: return null + return Triple( + ConfederationCharterEvent.KIND, + ConfederationCharterEvent.assembleTags(held.confederation.name, held.plan.groups), + ConfederationCharterEvent.content(held.confederation.name, held.plan.groups.size), + ) + } + // ---- proposing ------------------------------------------------------------------------- /** Proposes that the confederation whose room is [localChatRoom] sign one event. Proposing is the proposer's approval. */ @@ -403,9 +422,19 @@ object ConfederationSigningManager { database.groupSignedEventDao().record(GroupSignedEvent.fromEvent(signed, chatRoomId = held.confederation.id)) announce( database, attempt, - if (signed.kind == MetadataEvent.KIND) ChatMessage.TYPE_GROUP_PROFILE_SIGNED else ChatMessage.TYPE_GROUP_POST_SIGNED, + when (signed.kind) { + MetadataEvent.KIND -> ChatMessage.TYPE_GROUP_PROFILE_SIGNED + ConfederationCharterEvent.KIND -> ChatMessage.TYPE_CONFEDERATION_FORMED + else -> ChatMessage.TYPE_GROUP_POST_SIGNED + }, "The confederation signed ${describe(signed)}", ) + // The charter is the confederation's public statement: filed as Part A's events are, and + // owed to relays by the device that proposed it (D9), where the member groups' devices hear it. + if (signed.kind == ConfederationCharterEvent.KIND) { + ConfederationManager.record(database, signed) + if (attempt.proposerPublicKey == attempt.userPublicKey) database.confederationDao().markOwn(signed.id, attempt.id) + } logger.i("Confederation ${held.confederation.id.take(12)} signed ${signed.id.take(8)}") } @@ -541,12 +570,16 @@ object ConfederationSigningManager { private fun describe(event: Event): String = when (event.kind) { MetadataEvent.KIND -> "its profile" TextNoteEvent.KIND -> "a post" + ConfederationCharterEvent.KIND -> "its charter" else -> "an event of kind ${event.kind}" } private suspend fun announce(database: GizaDatabase, attempt: ConfederationSigningAttempt, type: String, content: String) { database.chatMessageDao().upsert( ChatMessage( + // The attempt, so the line opens it. Not a FROST session: the column has no key + // onto one, and the transcript reads it by the line's type. + frostSigningSessionId = attempt.id, senderPublicKey = attempt.proposerPublicKey, isUserMessage = false, giftWrapPayloadId = null, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationCharterEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationCharterEvent.kt new file mode 100644 index 00000000..ee5fc770 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationCharterEvent.kt @@ -0,0 +1,51 @@ +package mobi.giza.compose.nostr.confederation + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import mobi.giza.compose.nostr.confederation.tags.ConfederationGroupTag + +/** + * A confederation saying, with its own key, which groups it is made of (docs/confederation.md, + * Phase 15). + * + * ``` + * kind: 9434 + * pubkey: set by the signing attempt + * content: a sentence for clients that know nothing of this kind + * tags: + * ["p", , "", "group"] one per member group + * ["name", ] + * ["alt", ...] + * ``` + * + * The one public statement that the confederation exists, and the only way a group's members + * who are not its admins hear of it: the `p` tags reach every member group's devices through the + * same relay filter that brings them proposals. What it proves is that whoever holds the + * confederation's key named these groups -- a reader cannot check the roster behind the key, any + * more than it can tell a group's key from a person's. + */ +object ConfederationCharterEvent { + val KIND: Kind = ConfederationKinds.CHARTER + const val ALT = "A confederation of nostr groups, naming its member groups" + + data class Charter(val id: HexKey, val confederation: HexKey, val name: String, val groups: List) + + fun assembleTags(name: String, groups: List): Array> = ( + groups.sorted().map { ConfederationGroupTag.assemble(it, null) } + listOf( + arrayOf(ConfederationProposalEvent.NAME_TAG, name), + arrayOf(ConfederationProposalEvent.ALT_TAG, ALT), + ) + ).toTypedArray() + + fun content(name: String, groupCount: Int): String = "$name, a confederation of $groupCount groups" + + fun parse(event: Event): Charter? = runCatching { + if (event.kind != KIND || !ConfederationKinds.isPublicKey(event.pubKey)) return null + val groups = event.tags.mapNotNull(ConfederationGroupTag::parse).map { it.groupPublicKey } + if (groups.size !in ConfederationKinds.MIN_GROUPS..ConfederationKinds.MAX_GROUPS) return null + if (groups.any { !ConfederationKinds.isPublicKey(it) } || groups.toSet().size != groups.size) return null + val name = ConfederationProposalEvent.single(event.tags, ConfederationProposalEvent.NAME_TAG)?.takeIf { it.isNotBlank() } ?: return null + Charter(event.id, event.pubKey, name, groups) + }.getOrNull() +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationKinds.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationKinds.kt index 01df2e11..9d8127c5 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationKinds.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationKinds.kt @@ -20,7 +20,10 @@ object ConfederationKinds { const val REJECTION: Kind = 9432 const val WITHDRAWAL: Kind = 9433 - val ALL: Set = setOf(PROPOSAL, ACCEPTANCE, REJECTION, WITHDRAWAL) + /** The confederation's own public statement of which groups it is made of (Phase 15). Signed by the confederation. */ + const val CHARTER: Kind = 9434 + + val ALL: Set = setOf(PROPOSAL, ACCEPTANCE, REJECTION, WITHDRAWAL, CHARTER) /** The answers a group can give, and the one a proposing group can take back. */ val ANSWERS: Set = setOf(ACCEPTANCE, REJECTION, WITHDRAWAL) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index a43e518e..5330b466 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -138,6 +138,17 @@ interface ChatRepository { /** The confederation whose room [chatRoomId] is, by name, if its record verifies here. docs/confederation.md, Phase 13. */ suspend fun confederationOfRoom(chatRoomId: String): String? = null + /** Whether this device holds a role in the confederation whose room [chatRoomId] is. docs/confederation.md, Phase 15. */ + suspend fun canSignAsConfederation(chatRoomId: String): Boolean = false + + /** Proposes that the confederation whose room [localChatRoom] is sign one event. The attempt's id. */ + suspend fun proposeAsConfederation(localChatRoom: LocalChatRoom, kind: Kind, tags: Array>, content: String): String = + throw UnsupportedOperationException("No confederation here") + + /** Proposes that the confederation sign its charter: its groups, under its name. The attempt's id. */ + suspend fun proposeCharter(localChatRoom: LocalChatRoom): String = + throw UnsupportedOperationException("No confederation here") + /** * Why these members cannot hold a subgroup ceremony together, or null when * they can. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt index 9e25b3a9..b7abbc20 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt @@ -9,6 +9,8 @@ import mobi.giza.compose.database.model.Confederation import mobi.giza.compose.database.model.ConfederationCeremony import mobi.giza.compose.database.model.ConfederationCeremonyMessage import mobi.giza.compose.database.model.ConfederationEvent +import mobi.giza.compose.database.model.ConfederationSigningAttempt +import mobi.giza.compose.database.model.ConfederationSigningMessage import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder import mobi.giza.compose.database.model.FrostSigningSession import mobi.giza.compose.database.model.intermdiate.LocalChatRoom @@ -86,6 +88,18 @@ interface ConfederationRepository { suspend fun abandonCeremony(sessionId: String) + /** One attempt by a confederation to sign an event, as it changes. docs/confederation.md, Phase 14. */ + fun observeSigningAttempt(attemptId: String): Flow + + fun observeSigningMessages(attemptId: String): Flow> + + /** The roster's plan for the confederation whose room [confederationId] is, if this device holds it. */ + suspend fun confederationPlan(confederationId: HexKey): ConfederationRosterBuilder.Plan? + + suspend fun approveSigning(attemptId: String) + + suspend fun declineSigning(attemptId: String) + /** The confederations [groupPublicKey] is part of, on this device. docs/confederation.md, Phase 12. */ fun observeConfederationsOf(groupPublicKey: HexKey): Flow> @@ -126,6 +140,11 @@ interface ConfederationRepository { override suspend fun joinCeremony(sessionId: String) = Unit override suspend fun abandonCeremony(sessionId: String) = Unit override fun observeConfederationsOf(groupPublicKey: HexKey): Flow> = flowOf(emptyList()) + override fun observeSigningAttempt(attemptId: String): Flow = flowOf(null) + override fun observeSigningMessages(attemptId: String): Flow> = flowOf(emptyList()) + override suspend fun confederationPlan(confederationId: HexKey): ConfederationRosterBuilder.Plan? = null + override suspend fun approveSigning(attemptId: String) = Unit + override suspend fun declineSigning(attemptId: String) = Unit } } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt index 4fb9f820..84a3d385 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt @@ -4,6 +4,7 @@ import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent import mobi.giza.compose.nostr.confederation.ConfederationKinds import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent import mobi.giza.compose.managers.SharedKeyDerivation @@ -124,6 +125,10 @@ object ProposedEvent { ) } ?: Summary(label = "A confederation that cannot be read", detail = "") + ConfederationKinds.CHARTER -> ConfederationCharterEvent.parse(event)?.let { charter -> + Summary(label = "The confederation's charter", detail = "${charter.name}, naming its ${charter.groups.size} groups") + } ?: Summary(label = "A charter that cannot be read", detail = "") + ConfederationKinds.ACCEPTANCE -> Summary( label = "Accepting a confederation", detail = "Discloses this group's admins and threshold to the coordinator", diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/AddGroupPostScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/AddGroupPostScreen.kt index d6877905..ec70d970 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/AddGroupPostScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/AddGroupPostScreen.kt @@ -41,6 +41,7 @@ import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.FrostSigningRepository +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationSigningRoute import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute import mobi.giza.compose.ui.composable.navigation.routes.Route import mobi.giza.compose.ui.composable.widgets.ErrorState @@ -158,11 +159,18 @@ fun AddGroupPostScreen( // on the list it is not in would // read as a failure. onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) + if (addGroupPostViewModel.isConfederation) { + ConfederationSigningRoute( + activeUserPublicKey = activeUserPublicKey, + attemptId = sessionId + ) + } else { + FrostSigningRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + sessionId = sessionId + ) + } ) }, // Both stay on the draft. One is an diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 79fb2290..add4cb6d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -17,6 +17,9 @@ import mobi.giza.compose.resources.no_confederations_yet import mobi.giza.compose.resources.one_confederation_proposal import mobi.giza.compose.resources.n_confederation_proposals import mobi.giza.compose.resources.this_is_the_confederations_room +import mobi.giza.compose.resources.propose_the_charter +import mobi.giza.compose.resources.the_charter_names_the_groups +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationSigningRoute import androidx.compose.material.icons.filled.Campaign import mobi.giza.compose.resources.not_described_yet import mobi.giza.compose.resources.no_name_on_this_profile @@ -721,11 +724,35 @@ fun ChatRoomDetailScreen( chatRoomDetailUIState.confederationName?.let { name -> item { Card(modifier = Modifier.fillMaxWidth()) { - Text( + Column( modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), - text = stringResource(Res.string.this_is_the_confederations_room, name), - style = MaterialTheme.typography.bodyMedium, - ) + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + Text( + text = stringResource(Res.string.this_is_the_confederations_room, name), + style = MaterialTheme.typography.bodyMedium, + ) + // Its charter, which it signs itself (Phase 15). + if (chatRoomDetailUIState.canSignAsConfederation && identityCanSign) { + Text( + text = stringResource(Res.string.the_charter_names_the_groups), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + TextButton(onClick = { + chatRoomDetailViewModel.proposeCharter( + onSuccess = { attemptId -> + onNavigateToRoute.invoke( + ConfederationSigningRoute(activeUserPublicKey = activeUserPublicKey, attemptId = attemptId) + ) + }, + onFailure = {}, + ) + }) { + Text(stringResource(Res.string.propose_the_charter)) + } + } + } } } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt index 45ac06e2..39b9166a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt @@ -46,6 +46,7 @@ import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.DkgRepository import mobi.giza.compose.repository.FrostSigningRepository import mobi.giza.compose.repository.NostrRepository +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationSigningRoute import mobi.giza.compose.ui.composable.navigation.routes.ChatRoomDetailRoute import mobi.giza.compose.ui.composable.navigation.routes.DkgRitualRoute import mobi.giza.compose.ui.composable.navigation.routes.ProposalListRoute @@ -185,6 +186,11 @@ fun ChatRoomMessagingScreen( ) ) }, + onOpenConfederationSigning = { attemptId -> + onNavigateToRoute.invoke( + ConfederationSigningRoute(activeUserPublicKey = activeUserPublicKey, attemptId = attemptId) + ) + }, onOpenSigning = { sessionId -> onNavigateToRoute.invoke( proposalDestination( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationSigningScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationSigningScreen.kt new file mode 100644 index 00000000..1c8d49ec --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationSigningScreen.kt @@ -0,0 +1,169 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Block +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material.icons.filled.HourglassEmpty +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import mobi.giza.compose.database.model.ConfederationSigningStage +import mobi.giza.compose.managers.ConfederationSigningManager +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.answer_no +import mobi.giza.compose.resources.answer_waiting +import mobi.giza.compose.resources.answer_yes +import mobi.giza.compose.resources.approve_for_the_confederation +import mobi.giza.compose.resources.confederation_signing +import mobi.giza.compose.resources.decline_for_the_confederation +import mobi.giza.compose.resources.signed_by_admins_of_groups +import mobi.giza.compose.resources.the_confederation_did_not_sign_it +import mobi.giza.compose.resources.the_confederation_signed_it +import mobi.giza.compose.resources.this_device_holds_no_such_request +import mobi.giza.compose.resources.you_declined_this +import mobi.giza.compose.text.ProposedEvent +import mobi.giza.compose.ui.composable.widgets.Decorative +import mobi.giza.compose.ui.composable.widgets.EmptyState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.ConfederationSigningViewModel +import mobi.giza.compose.ui.view.state.ConfederationSigningUIState +import org.jetbrains.compose.resources.stringResource + +/** + * A confederation's request to sign one event (docs/confederation.md, Phase 15): what it would + * sign, said the way a group's signing screen says it, who has approved, and -- for a member not + * yet asked -- approve or decline, which counts for every group they are an admin of. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ConfederationSigningScreen( + attemptId: String, + initialConfederationSigningUIState: ConfederationSigningUIState = ConfederationSigningUIState.Loading, + confederationRepository: ConfederationRepository, + onNavigateBack: () -> Unit, +) { + val viewModel: ConfederationSigningViewModel = viewModel( + factory = ConfederationSigningViewModel.factory(attemptId, initialConfederationSigningUIState, confederationRepository) + ) + LaunchedEffect(true) { + if (initialConfederationSigningUIState == ConfederationSigningUIState.Loading) viewModel.initiate() + } + val state by viewModel.uiState.collectAsState() + val identityCanSign = LocalCanSign.current + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(text = stringResource(Res.string.confederation_signing), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + ) { padding -> + ScreenStateTransition(state) { uiState -> + when (val current = uiState) { + ConfederationSigningUIState.Loading -> LoadingDataIndicator(modifier = Modifier.padding(padding)) + + ConfederationSigningUIState.NotHeld -> EmptyState( + modifier = Modifier.padding(padding), + message = stringResource(Res.string.this_device_holds_no_such_request), + ) + + is ConfederationSigningUIState.Loaded -> Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + val attempt = current.attempt + val summary = ProposedEvent.summarize(current.event) + Text(text = summary.label, style = MaterialTheme.typography.labelMedium) + Text(text = summary.detail, style = MaterialTheme.typography.titleMedium) + Text( + text = stringResource(Res.string.signed_by_admins_of_groups, current.roleCount, current.groupCount), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + when { + attempt.stage == ConfederationSigningStage.COMPLETE -> + Text(text = stringResource(Res.string.the_confederation_signed_it), style = MaterialTheme.typography.titleSmall) + attempt.stage == ConfederationSigningStage.FAILED -> + Text( + text = stringResource(Res.string.the_confederation_did_not_sign_it, attempt.failureReason.orEmpty()), + color = MaterialTheme.colorScheme.error, + ) + attempt.declinedAt != null -> + Text(text = stringResource(Res.string.you_declined_this)) + } + + if (ConfederationSigningManager.isAwaitingApproval(attempt) && identityCanSign) { + Button(modifier = Modifier.fillMaxWidth(), enabled = !current.isActing, onClick = viewModel::approve) { + Text(stringResource(Res.string.approve_for_the_confederation)) + } + OutlinedButton(modifier = Modifier.fillMaxWidth(), enabled = !current.isActing, onClick = viewModel::decline) { + Text(stringResource(Res.string.decline_for_the_confederation)) + } + } + + HorizontalDivider() + current.answers.forEach { (name, answer) -> + ListItem( + leadingContent = { + Icon( + imageVector = when (answer) { + true -> Icons.Default.CheckCircle + false -> Icons.Default.Block + null -> Icons.Default.HourglassEmpty + }, + contentDescription = Decorative, + ) + }, + headlineContent = { Text(name, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + supportingContent = { + Text( + stringResource( + when (answer) { + true -> Res.string.answer_yes + false -> Res.string.answer_no + null -> Res.string.answer_waiting + } + ) + ) + }, + ) + } + } + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditGroupNostrProfileScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditGroupNostrProfileScreen.kt index 00211c4c..d59a79c1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditGroupNostrProfileScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditGroupNostrProfileScreen.kt @@ -47,6 +47,7 @@ import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.FrostSigningRepository +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationSigningRoute import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute import mobi.giza.compose.ui.composable.navigation.routes.Route import mobi.giza.compose.ui.composable.widgets.ErrorState @@ -198,11 +199,18 @@ fun EditGroupNostrProfileScreen( // group still showing the old one // would read as a failure. onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) + if (editGroupNostrProfileViewModel.isConfederation) { + ConfederationSigningRoute( + activeUserPublicKey = activeUserPublicKey, + attemptId = sessionId + ) + } else { + FrostSigningRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + sessionId = sessionId + ) + } ) }, // Stay on the form with what was typed diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index 66e2df5b..feee98a7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -8,6 +8,8 @@ import mobi.giza.compose.ui.composable.navigation.routes.AddGroupPostRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationsRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProposalRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRitualRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationSigningRoute +import mobi.giza.compose.ui.composable.ConfederationSigningScreen import mobi.giza.compose.ui.composable.ConfederationRitualScreen import mobi.giza.compose.ui.composable.ConfederationProposalScreen import mobi.giza.compose.ui.composable.navigation.routes.ProposeConfederationRoute @@ -1319,6 +1321,15 @@ fun GizaNavHost( onNavigateBack = { navController.popBackStack() } ) } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + ConfederationSigningScreen( + attemptId = route.attemptId, + confederationRepository = databaseConfederationRepository, + onNavigateBack = { navController.popBackStack() } + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationSigningRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationSigningRoute.kt new file mode 100644 index 00000000..82b3c028 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationSigningRoute.kt @@ -0,0 +1,10 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** One attempt by a confederation to sign an event. docs/confederation.md, Phase 15. */ +@Serializable +data class ConfederationSigningRoute( + val activeUserPublicKey: String, + val attemptId: String, +): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt index 62321c23..3bdbb693 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt @@ -123,6 +123,8 @@ fun ChatTranscript( * and cannot say which one it meant. */ onOpenSigning: (sessionId: String?) -> Unit, + /** Opens a confederation's request to sign: docs/confederation.md, Phase 15. */ + onOpenConfederationSigning: (attemptId: String) -> Unit = {}, /** Opens the room's proposals, all of them, whatever their state. */ onOpenProposals: () -> Unit, ) { @@ -375,6 +377,21 @@ fun ChatTranscript( // settled because it reports rather than asks -- a // quorum has already signed by the time this line // exists. It leads nowhere. + // A request for the confederation to sign: it opens, since a + // member answers it there. docs/confederation.md, Phase 15. + if (localChatMessage.chatMessage.messageType == ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED) { + RitualNotice( + localChatMessage = localChatMessage, + isAnswered = false, + isSettled = true, + onClick = { + localChatMessage.chatMessage.frostSigningSessionId?.let(onOpenConfederationSigning) + }, + opens = null, + ) + return@items + } + if (localChatMessage.chatMessage.messageType in ChatMessage.GROUP_IDENTITY_TYPES) { RitualNotice( localChatMessage = localChatMessage, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/AddGroupPostViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/AddGroupPostViewModel.kt index a696c125..7ae9b3fd 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/AddGroupPostViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/AddGroupPostViewModel.kt @@ -51,6 +51,10 @@ class AddGroupPostViewModel( val isActionPending: MutableState = mutableStateOf(false) + /** Whether this room is a confederation's, whose statements the confederation signs. Read at load. */ + var isConfederation: Boolean = false + private set + fun initiateAddGroupPost() { viewModelScope.launch(Dispatchers.IO) { val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) @@ -64,7 +68,8 @@ class AddGroupPostViewModel( // The same condition the group detail screen gates the entry // point on. canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && - frostSigningRepository.canSign(chatRoomId), + (frostSigningRepository.canSign(chatRoomId) || + chatRepository.canSignAsConfederation(chatRoomId).also { isConfederation = it }), ) } } @@ -107,20 +112,26 @@ class AddGroupPostViewModel( viewModelScope.launch(Dispatchers.IO) { val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - kind = template.kind, - tags = template.tags, - content = template.content, - ) + // A confederation's room signs through the confederation, not a FROST + // key: docs/confederation.md, Phase 15. + if (isConfederation) { + chatRepository.proposeAsConfederation(localChatRoom, template.kind, template.tags, template.content) + } else { + frostSigningRepository.proposeSigning( + localChatRoom = localChatRoom, + userPublicKey = activeUserPublicKey, + kind = template.kind, + tags = template.tags, + content = template.content, + )?.id + } }.onFailure { error -> logger.e("Failed to propose a post for $chatRoomId", error) }.getOrNull() viewModelScope.launch(Dispatchers.Main) { if (session != null) { - onSuccess.invoke(session.id) + onSuccess.invoke(session) } else { onFailure.invoke() } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index d048388b..4777c5dd 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -134,6 +134,7 @@ class ChatRoomDetailViewModel( groupPosts = chatRepository.groupPosts(chatRoomId), confederationProposalCount = chatRepository.confederationProposalCount(chatRoomId), confederationName = chatRepository.confederationOfRoom(chatRoomId), + canSignAsConfederation = chatRepository.canSignAsConfederation(chatRoomId), canProposeAsGroup = canSign && roomIsOpen, subgroupsNeedAWallet = canSign && subgroupsNeedAWallet, canGovern = canGovern, @@ -510,6 +511,17 @@ class ChatRoomDetailViewModel( } + /** Proposes the confederation's charter, in its own room. docs/confederation.md, Phase 15. */ + fun proposeCharter(onSuccess: (attemptId: String) -> Unit, onFailure: () -> Unit) { + val loaded = chatRoomDetailUIState as? ChatRoomDetailUIState.Loaded ?: return + viewModelScope.launch(Dispatchers.IO) { + val attemptId = runCatching { chatRepository.proposeCharter(loaded.localChatRoom) } + .onFailure { logger.e("Could not propose the charter for $chatRoomId", it) } + .getOrNull() + viewModelScope.launch(Dispatchers.Main) { if (attemptId != null) onSuccess(attemptId) else onFailure() } + } + } + companion object { private const val TAG = "ChatRoomDetailViewModel" diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationSigningViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationSigningViewModel.kt new file mode 100644 index 00000000..d299ac6e --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationSigningViewModel.kt @@ -0,0 +1,85 @@ +package mobi.giza.compose.ui.view.model + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.Event +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents +import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.ui.view.state.ConfederationSigningUIState + +/** One attempt by a confederation to sign an event, watched as answers arrive (docs/confederation.md, Phase 15). */ +class ConfederationSigningViewModel( + val attemptId: String, + initialConfederationSigningUIState: ConfederationSigningUIState, + val confederationRepository: ConfederationRepository, +) : ViewModel() { + private val logger = Logger.withTag("ConfederationSigningViewModel") + private val state = MutableStateFlow(initialConfederationSigningUIState) + val uiState: StateFlow = state.asStateFlow() + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + combine( + confederationRepository.observeSigningAttempt(attemptId), + confederationRepository.observeSigningMessages(attemptId), + ) { attempt, messages -> attempt to messages }.collect { (attempt, messages) -> + if (attempt == null) { + state.value = ConfederationSigningUIState.NotHeld + return@collect + } + val plan = confederationRepository.confederationPlan(attempt.confederationId) + val event = Event.fromJsonOrNull(attempt.signedEventJson ?: attempt.eventJson) ?: return@collect + val said = messages.filter { it.kind == ConfederationSigningEvents.AVAILABILITY }.associate { message -> + message.senderPublicKey to (ConfederationRitualEvents.decodeByGroup(message.payload)?.values?.all { it == ConfederationSigningEvents.YES } == true) + } + val answers = plan?.people.orEmpty().map { person -> confederationRepository.nameOf(person) to said[person] } + val acting = (state.value as? ConfederationSigningUIState.Loaded)?.isActing == true + state.value = ConfederationSigningUIState.Loaded( + attempt = attempt, + event = event, + answers = answers, + roleCount = plan?.seats?.size ?: 0, + groupCount = plan?.groups?.size ?: 0, + isActing = acting, + ) + } + } + } + + fun approve() = act { confederationRepository.approveSigning(attemptId) } + + fun decline() = act { confederationRepository.declineSigning(attemptId) } + + private fun act(action: suspend () -> Unit) { + val loaded = state.value as? ConfederationSigningUIState.Loaded ?: return + if (loaded.isActing) return + state.update { (it as? ConfederationSigningUIState.Loaded)?.copy(isActing = true) ?: it } + viewModelScope.launch(Dispatchers.IO) { + runCatching { action() }.onFailure { logger.e("Signing action failed", it) } + state.update { (it as? ConfederationSigningUIState.Loaded)?.copy(isActing = false) ?: it } + } + } + + companion object { + fun factory( + attemptId: String, + initialConfederationSigningUIState: ConfederationSigningUIState = ConfederationSigningUIState.Loading, + confederationRepository: ConfederationRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { ConfederationSigningViewModel(attemptId, initialConfederationSigningUIState, confederationRepository) } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModel.kt index fef838bc..15395d18 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModel.kt @@ -48,6 +48,10 @@ class EditGroupNostrProfileViewModel( val isActionPending: MutableState = mutableStateOf(false) + /** Whether this room is a confederation's, whose statements the confederation signs. Read at load. */ + var isConfederation: Boolean = false + private set + fun initiateEditGroupNostrProfile() { viewModelScope.launch(Dispatchers.IO) { val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) @@ -61,7 +65,8 @@ class EditGroupNostrProfileViewModel( // The same condition the group detail screen gates the entry // point on. canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && - frostSigningRepository.canSign(chatRoomId), + (frostSigningRepository.canSign(chatRoomId) || + chatRepository.canSignAsConfederation(chatRoomId).also { isConfederation = it }), ) } } @@ -108,20 +113,26 @@ class EditGroupNostrProfileViewModel( viewModelScope.launch(Dispatchers.IO) { val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - kind = template.kind, - tags = template.tags, - content = template.content, - ) + // A confederation's room signs through the confederation, not a FROST + // key: docs/confederation.md, Phase 15. + if (isConfederation) { + chatRepository.proposeAsConfederation(localChatRoom, template.kind, template.tags, template.content) + } else { + frostSigningRepository.proposeSigning( + localChatRoom = localChatRoom, + userPublicKey = activeUserPublicKey, + kind = template.kind, + tags = template.tags, + content = template.content, + )?.id + } }.onFailure { error -> logger.e("Failed to propose a nostr profile for $chatRoomId", error) }.getOrNull() viewModelScope.launch(Dispatchers.Main) { if (session != null) { - onSuccess.invoke(session.id) + onSuccess.invoke(session) } else { onFailure.invoke() } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupNostrProfileViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupNostrProfileViewModel.kt index b7a0ed79..f23b1e7e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupNostrProfileViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupNostrProfileViewModel.kt @@ -44,7 +44,7 @@ class GroupNostrProfileViewModel( localChatRoom = localChatRoom, groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && - chatRepository.canSign(chatRoomId), + (chatRepository.canSign(chatRoomId) || chatRepository.canSignAsConfederation(chatRoomId)), ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupPostsViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupPostsViewModel.kt index 7e7a9c29..164582a7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupPostsViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupPostsViewModel.kt @@ -40,7 +40,7 @@ class GroupPostsViewModel( groupPosts = chatRepository.groupPosts(chatRoomId), groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && - chatRepository.canSign(chatRoomId), + (chatRepository.canSign(chatRoomId) || chatRepository.canSignAsConfederation(chatRoomId)), ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt index 03a951bd..600d2db3 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -76,6 +76,8 @@ sealed interface ChatRoomDetailUIState { val confederationProposalCount: Int = 0, /** The confederation whose room this is, by name: its membership is fixed until it can sign. */ val confederationName: String? = null, + /** Whether this device holds a role in that confederation, and so can propose what it signs. */ + val canSignAsConfederation: Boolean = false, /** * Whether this device could put a profile or a post to the group's quorum: * a Marmot room it has not left, not disbanded, where it holds a share of diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationSigningUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationSigningUIState.kt new file mode 100644 index 00000000..cdc890ba --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationSigningUIState.kt @@ -0,0 +1,21 @@ +package mobi.giza.compose.ui.view.state + +import com.vitorpamplona.quartz.nip01Core.core.Event +import mobi.giza.compose.database.model.ConfederationSigningAttempt + +/** One attempt by a confederation to sign an event (docs/confederation.md, Phase 15). */ +sealed interface ConfederationSigningUIState { + data class Loaded( + val attempt: ConfederationSigningAttempt, + val event: Event, + /** Every role holder by name, with their answer: true, false, or null while they have not said. */ + val answers: List>, + val roleCount: Int, + val groupCount: Int, + val isActing: Boolean = false, + ) : ConfederationSigningUIState + + data object NotHeld : ConfederationSigningUIState + + data object Loading : ConfederationSigningUIState +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt index 17cbf424..85d50e9a 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt @@ -16,6 +16,7 @@ import kotlin.test.assertNotNull import kotlin.test.assertTrue import kotlin.time.Clock import kotlin.time.Instant +import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.builder.getRoomDatabase @@ -28,6 +29,7 @@ import mobi.giza.compose.database.model.Profile import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents import mobi.giza.compose.nostr.frost.GroupKeyStateEvent @@ -214,4 +216,44 @@ class ConfederationSigningJvmTest { assertFailsWith { propose(kind = 30023, content = "long form") } assertFailsWith { propose(kind = TextNoteEvent.KIND, content = " ") } } + + // ---- Phase 15: the charter ------------------------------------------------------------ + + @Test + fun `a charter naming exactly its groups is signed, filed and owed to relays`() { + val polisMember = devices.getValue(npub(secret(22))) + runBlocking { + polisMember.db.chatRoomDao().upsert(ChatRoom(id = groups[1], userPublicKey = polisMember.person, subject = "#Polis", description = null, mlsGroupState = "00")) + } + val (kind, tags, content) = runBlocking { assertNotNull(ConfederationSigningManager.charterTemplate(proposer.db, confederation.id)) } + val attempt = runBlocking { ConfederationSigningManager.propose(proposer.db, proposer.room, proposer.person, kind, tags, content, proposer.nsec) } + pump() + approve(attempt.id, people - 11) + pump() + + attempts(attempt.id).values.forEach { assertEquals(ConfederationSigningStage.COMPLETE, it?.stage, it?.failureReason) } + val signed = Event.fromJson(attempts(attempt.id).getValue(proposer.person)!!.signedEventJson!!) + runBlocking { + val owed = proposer.db.confederationDao().observeUnpublished().first() + assertEquals(listOf(signed.id), owed.map { it.id }, "the proposer's device owes it to relays") + assertEquals(groups.toSet(), proposer.db.confederationDao().getEvent(signed.id)?.let { listOf(it) }?.let { + ConfederationCharterEvent.parse(it.single().toEvent())?.groups?.toSet() + }) + assertTrue( + polisMember.db.chatMessageDao().getChatMessagesByChatRoomId(groups[1]) + .any { it.chatMessage.content.contains("signed its charter") }, + "Polis's room hears of it", + ) + } + } + + @Test + fun `a charter that leaves out a group is refused`() { + val wrong = ConfederationCharterEvent.assembleTags(confederation.name, groups.take(2)) + assertFailsWith { + runBlocking { + ConfederationSigningManager.propose(proposer.db, proposer.room, proposer.person, ConfederationCharterEvent.KIND, wrong, "x", proposer.nsec) + } + } + } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt index 60474fb1..93b244b6 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt @@ -23,6 +23,9 @@ import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost import mobi.giza.compose.ui.theme.GizaTheme import mobi.giza.compose.ui.view.state.ConfederationProposalUIState import mobi.giza.compose.ui.view.state.ConfederationRitualUIState +import mobi.giza.compose.ui.view.state.ConfederationSigningUIState +import mobi.giza.compose.database.model.ConfederationSigningAttempt +import mobi.giza.compose.database.model.ConfederationSigningStage import mobi.giza.compose.database.model.ConfederationCeremony import mobi.giza.compose.database.model.ConfederationCeremonyStage import mobi.giza.compose.ui.view.state.ConfederationsUIState @@ -267,4 +270,52 @@ class ConfederationScreensJvmTest { } assertions() } + + private fun signing(stage: ConfederationSigningStage, approved: Boolean, failure: String? = null) = ConfederationSigningUIState.Loaded( + attempt = ConfederationSigningAttempt( + id = "s".repeat(64), confederationId = roomId, proposerPublicKey = polis, userPublicKey = "a".repeat(64), + eventJson = "{}", stage = stage, approvedAt = if (approved) kotlin.time.Instant.fromEpochSeconds(1) else null, failureReason = failure, + ), + event = com.vitorpamplona.quartz.nip01Core.core.Event("e".repeat(64), roomId, 1, 1, emptyArray(), "The first words of a group of groups", ""), + answers = listOf("Ana" to true, "Bo" to null, "Cy" to false), + roleCount = 9, + groupCount = 3, + ) + + @Test + fun `a member is asked to approve what the confederation would sign, and sees who has answered`() = + renderSigning(signing(ConfederationSigningStage.SELECTING, approved = false)) { + onNodeWithText("The first words of a group of groups").assertIsDisplayed() + onNodeWithText("Approve").assertIsDisplayed() + onNodeWithText("Decline").assertIsDisplayed() + onNodeWithText("Signed by 9 admins of 3 groups together", substring = true).assertIsDisplayed() + onNodeWithText("Ana").assertIsDisplayed() + onNodeWithText("Approved").assertIsDisplayed() + } + + @Test + fun `an attempt that did not finish says why, and asks nothing`() = + renderSigning(signing(ConfederationSigningStage.FAILED, approved = true, failure = "A device restarted while signing")) { + onNodeWithText("The confederation did not sign it: A device restarted while signing").assertIsDisplayed() + onAllNodesWithText("Approve").assertCountEquals(0) + } + + private fun renderSigning(state: ConfederationSigningUIState, assertions: ComposeUiTest.() -> Unit) = + runDesktopComposeUiTest(width = 400, height = 3000) { + setContent { + GizaTheme { + ProvideSnackbarHost { + Box(modifier = Modifier.fillMaxSize()) { + ConfederationSigningScreen( + attemptId = "s".repeat(64), + initialConfederationSigningUIState = state, + confederationRepository = ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY, + onNavigateBack = {}, + ) + } + } + } + } + assertions() + } } diff --git a/docs/confederation.md b/docs/confederation.md index 2944baef..0c96c012 100644 --- a/docs/confederation.md +++ b/docs/confederation.md @@ -93,6 +93,7 @@ the reasoning. Where the build chose differently: | 12 | done. `ConfederationFormation.onComplete` files a `Confederation` (room id, X, roster, key state, genesis, the `(configSeq, rpdHash, ksdHash)` triple, this device's recovery packages) and `ConfederationMember` rows, folded into schema 44 since it has not shipped. The genesis is verified against the key state before anything is written. A line goes into each of this device's own member groups' rooms; nothing is sent to them. **No 30389 key-state event:** every founding member of the room took part and holds the record, so `ConfederationFormation.verifies` checks the stored descriptors instead; a member added later needs one, which waits for Part C's governance. A formed confederation reads "Formed" on the group's list. `ConfederationCeremonyJvmTest` now also checks every device files the same verified confederation under the room its key derives | | 13 | done. `ConfederationFollowThrough` on the coordinator's device makes the room once every member's key package is in, retrying when one arrives, through `MarmotGroupCreation.create` rather than a new `createForConfederation`: id `marmotGroupId(02‖X)`, a random routing address, every role holder a member and an admin, `#name`, born governed with `Quorum.minimumAdmins(T)`. A record that no longer verifies, or a device holding no role, makes no room. Adoption needs no new check: every founding member holds the `Confederation` row under the room's id, and `confederationOfRoom` reads it only if it verifies. The room's screen says whose room it is and that its members are fixed until the confederation can sign. `ConfederationCeremonyJvmTest` 9/9. `./gradlew check` passes, jvmTest 1,621 | | 14 | done. `ConfederationSigningManager` over upstream's `ConfederationSigning`, in the confederation's Marmot room. Kinds 30390 (proposal), 30391 (each person's yes or no per role), 30392 (the proposer's selection and D_sign), 30393 (nonces), 30394 (confirmations), 30395 (partials), 30399 (failure). Only the selection is coordinated: the first `T` groups in roster order with `t_g` yeses, the lowest admins first. The transcript, the certificate, every group's partial and the signature take no secret, so **every device computes them itself** and checks the signature against the room's id before keeping it: no group coordinator and no outer coordinator message. Signer state is held in memory only; a device that restarts after sending a nonce ends the attempt out loud on its next step, and `resumeRunning` does it on start. A confederation signs kinds 0 and 1 only, with Part A's statement refusals; anything else is declined out loud. A signed event lands in `GroupSignedEvent` under the room, so the existing profile, posts and broadcast screens read it. Schema 45. `ConfederationSigningJvmTest` 5/5 on nine devices: a profile signed and read back on every device; two groups of two admins enough; a restart between nonces and confirmations failing it everywhere; too many declines; refused kinds. jvmTest 1,626 | +| 15 | done but for governance. **Profile and posts:** the existing editors work in a confederation's room. `ChatRepository.canSignAsConfederation` opens them to a role holder, and `proposeAsConfederation` sends the proposal through `ConfederationSigningManager` instead of FROST; the signed event lands where the profile and posts screens and the broadcast screen already read. **Charter (9434):** the confederation's own public statement naming its groups, proposed from its room's card. A device signs only a charter naming exactly the confederation's groups under its name. Once signed it is filed as Part A's events are and owed to relays by the proposer's device, and every member group's devices hear it through the existing `#p` filter and write a line in the group's room. That is how members who are not admins learn of it. `ConfederationSigningScreen` approves or declines for every role a person holds and lists who has answered, opened from the line in the room's transcript (the line carries the attempt id) or after proposing. **Not done:** admin changes in the confederation's room signed by the confederation; the room stays fixed at its founders. `ConfederationSigningJvmTest` 7/7, `ConfederationScreensJvmTest` 12/12. `./gradlew check` passes, jvmTest 1,630 | --- From e909313c765e4dabf52054dc751d14912585682b Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 01:10:46 +0200 Subject: [PATCH 03/16] docs: Part C is built, and what it chose differently (confederation, Phase 16) Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 2 +- docs/confederation.md | 25 +++++++++++++++++-------- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/docs/README.md b/docs/README.md index c43b1cac..18b980fa 100644 --- a/docs/README.md +++ b/docs/README.md @@ -15,7 +15,7 @@ the [retired](./retired/) notes now. | [shared-key-ceremony.md](./shared-key-ceremony.md) | ChillDKG over NIP-17: the rounds, the approval gates, the chat transcript, participant ordering | | [shared-key-derivation.md](./shared-key-derivation.md) | deriving further keys from the group's threshold key with FROST tweaks — why not BIP32, why no chain code, and the one rule that must not be broken | | [subgroups.md](./subgroups.md) | a group making another group — the four ceremonies, what the parent's signature actually covers, and why the child's key is fresh rather than derived | -| [confederation.md](./confederation.md) | a group made of groups: a phased plan, Parts A and B (phases 0-13) built behind a flag that is off in release, Part C (signing as the confederation) next. Groups with a public nostr profile propose, accept or reject a confederation in public, an acceptance carries the group's admins sealed to the coordinator in a way every signer recomputes, and the confederation's DKG and Marmot room follow. Covers why the public events are regular kinds, why nothing can be encrypted from or to a group's npub, how the coordinator is kept from substituting a roster, and why everything after the agreement waits on upstream publishing the distributed rounds | +| [confederation.md](./confederation.md) | a group made of groups: a phased plan, built behind a flag that is off in release but for its device run and the room's governance. Agreeing to form (Part A), the key ceremony and room (Part B), and the confederation signing its profile, posts and charter (Part C). Groups with a public nostr profile propose, accept or reject a confederation in public, an acceptance carries the group's admins sealed to the coordinator in a way every signer recomputes, and the confederation's DKG and Marmot room follow. Covers why the public events are regular kinds, why nothing can be encrypted from or to a group's npub, how the coordinator is kept from substituting a roster, and why everything after the agreement waits on upstream publishing the distributed rounds | | [confederation-upstream.md](./confederation-upstream.md) | the work below Giza that unblocks the confederation's Parts B and C: a phased plan, not built, across secp256k1-zkp, secp256k1-kmp and bitcoin-kmp. Covers why the one-process DKG and signing cannot simply be exposed step by step (the coordinator derives everyone's key state, acknowledgment is signed before the share is stored, nonce randomness is derived from the session id), why every DKG step can stay stateless, the storage contract a device follows, and Prefractal as an all-groups-must-sign path that needs no upstream work | | [automatic-key-ceremony.md](./automatic-key-ceremony.md) | joining is the only approval: a phased plan, built but for its device session, that makes a key ceremony run by itself after a member joins. Covers why contributing and confirming were never decisions a person could add to, the resume sweep that replaces the tap, the coordinator's follow-up steps and the one key state a device can sign without asking, and why abandon stays | | [ceremony-creation.md](./ceremony-creation.md) | one place to start a key ceremony — how joining a subgroup's ceremony opened a second one for the parent room, the screen that showed a ceremony and offered to start one in the same button, and the removal of the nip30303 documents, whose kinds collided with the ceremony's, leaving the member chronicle with nothing to carry and nothing to say | diff --git a/docs/confederation.md b/docs/confederation.md index 0c96c012..e7aad740 100644 --- a/docs/confederation.md +++ b/docs/confederation.md @@ -35,17 +35,19 @@ Read these first: the cryptography this plan ends on, and why that cryptography cannot run across devices yet. -Written against `c9e6f07c` on 2026-11-21. **Parts A and B are built**, behind +Written against `c9e6f07c` on 2026-11-21. **Parts A, B and C are built**, behind `ExperimentalFeatures.confederation`, one commit per phase: Part A (phases 0 to 8) on `claude/confederation-implementation-plan-a24dc6`, Phase 9 upstream -([confederation-upstream.md](./confederation-upstream.md)), and Part B (phases 10 to 13) on -`claude/confederation-part-b` from `ba3800e1`. Part C (phases 14 to 16) is next; nothing upstream -blocks it now. jvmTest went from 1,569 to 1,621, all passing, and `./gradlew check` passes: -`m3Audit`, `brandAudit` and `walletAudit` are at their budgets, and `compileDebugKotlinAndroid` -builds. +([confederation-upstream.md](./confederation-upstream.md)), Part B (phases 10 to 13) on +`claude/confederation-part-b` and Part C (phases 14 and 15) on `claude/confederation-part-c`. +Phase 16's device run is what is left. jvmTest went from 1,569 to 1,630, all passing, and +`./gradlew check` passes: `m3Audit`, `brandAudit` and `walletAudit` are at their budgets, and +`compileDebugKotlinAndroid` builds. **Not done:** nothing here has run on a device. No proposal has crossed real relays between -real groups, no ceremony has run on more than one real device, and no iOS build has been made. +real groups, no ceremony or signing attempt has run on more than one real device, and no iOS +build has been made. The confederation's room cannot yet change its members: admin changes +signed by the confederation are not built. Upstream's independent review of the step interface is still pending (`doc/confederation-review.md` section 21), which is why the flag stays off in release. The phases are kept as written, because they are the reasoning. Where the build chose differently: @@ -74,6 +76,12 @@ the reasoning. Where the build chose differently: | Phase 12: `ConfederationKeyStateEvent` (30389) | not built. Every founding member holds the record; `ConfederationFormation.verifies` checks it. A member added later needs one, and that waits for Part C's governance | | Phase 12: a line posted into each group's room by the coordinator | a line each admin's own device writes in its own group rooms, sending nothing | | Phase 13: `MarmotGroupCreation.createForConfederation` | `ConfederationFollowThrough` calling `MarmotGroupCreation.create` directly, as subgroups do | +| Phase 14: a group coordinator per group, the outer coordinator aggregating | only the selection is coordinated. The transcript, the certificate, every group's partial and the signature take no secret, so every device computes them and checks the signature against the room's id | +| Phase 14: kinds 30390 to 30399 | 30390 to 30395 and 30399; the rest unused | +| Phase 14: the selection "in the order approvals arrive" | the first `T` groups in roster order with `t_g` yeses, the lowest admins first, so the selection does not depend on delivery order once enough have said yes | +| Phase 15: the confederation's kind:0 and kind:1 through `GroupNostrProfile` and `GroupPost` | the same editors and readers, with `ChatRepository.canSignAsConfederation` and `proposeAsConfederation` deciding which signer a room's statements go to | +| Phase 15: a charter that each group's members find on relays | as planned, kind 9434, carried by Part A's publisher and subscription; a device signs only one naming exactly the confederation's groups | +| Phase 15: governance of the room through `GovernanceManager` | not built: the room stays fixed at its founding members | ## Progress @@ -94,6 +102,7 @@ the reasoning. Where the build chose differently: | 13 | done. `ConfederationFollowThrough` on the coordinator's device makes the room once every member's key package is in, retrying when one arrives, through `MarmotGroupCreation.create` rather than a new `createForConfederation`: id `marmotGroupId(02‖X)`, a random routing address, every role holder a member and an admin, `#name`, born governed with `Quorum.minimumAdmins(T)`. A record that no longer verifies, or a device holding no role, makes no room. Adoption needs no new check: every founding member holds the `Confederation` row under the room's id, and `confederationOfRoom` reads it only if it verifies. The room's screen says whose room it is and that its members are fixed until the confederation can sign. `ConfederationCeremonyJvmTest` 9/9. `./gradlew check` passes, jvmTest 1,621 | | 14 | done. `ConfederationSigningManager` over upstream's `ConfederationSigning`, in the confederation's Marmot room. Kinds 30390 (proposal), 30391 (each person's yes or no per role), 30392 (the proposer's selection and D_sign), 30393 (nonces), 30394 (confirmations), 30395 (partials), 30399 (failure). Only the selection is coordinated: the first `T` groups in roster order with `t_g` yeses, the lowest admins first. The transcript, the certificate, every group's partial and the signature take no secret, so **every device computes them itself** and checks the signature against the room's id before keeping it: no group coordinator and no outer coordinator message. Signer state is held in memory only; a device that restarts after sending a nonce ends the attempt out loud on its next step, and `resumeRunning` does it on start. A confederation signs kinds 0 and 1 only, with Part A's statement refusals; anything else is declined out loud. A signed event lands in `GroupSignedEvent` under the room, so the existing profile, posts and broadcast screens read it. Schema 45. `ConfederationSigningJvmTest` 5/5 on nine devices: a profile signed and read back on every device; two groups of two admins enough; a restart between nonces and confirmations failing it everywhere; too many declines; refused kinds. jvmTest 1,626 | | 15 | done but for governance. **Profile and posts:** the existing editors work in a confederation's room. `ChatRepository.canSignAsConfederation` opens them to a role holder, and `proposeAsConfederation` sends the proposal through `ConfederationSigningManager` instead of FROST; the signed event lands where the profile and posts screens and the broadcast screen already read. **Charter (9434):** the confederation's own public statement naming its groups, proposed from its room's card. A device signs only a charter naming exactly the confederation's groups under its name. Once signed it is filed as Part A's events are and owed to relays by the proposer's device, and every member group's devices hear it through the existing `#p` filter and write a line in the group's room. That is how members who are not admins learn of it. `ConfederationSigningScreen` approves or declines for every role a person holds and lists who has answered, opened from the line in the room's transcript (the line carries the attempt id) or after proposing. **Not done:** admin changes in the confederation's room signed by the confederation; the room stays fixed at its founders. `ConfederationSigningJvmTest` 7/7, `ConfederationScreensJvmTest` 12/12. `./gradlew check` passes, jvmTest 1,630 | +| 16 | the record done; the device run not. No ceremony or signing attempt has run across real devices, relays or an iOS build | --- @@ -859,7 +868,7 @@ group, rather than "17 of 21". --- -# Part C: acting (blocked on upstream) +# Part C: acting ## Phase 14: nested signing across devices From ccc439b2db885dcff062a3d788f9202b38b3b259 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 01:24:34 +0200 Subject: [PATCH 04/16] docs: the group's inbox, planned as NIP-4E on a group's npub (group-inbox, Phase 0) Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 1 + docs/group-inbox.md | 804 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 805 insertions(+) create mode 100644 docs/group-inbox.md diff --git a/docs/README.md b/docs/README.md index c43b1cac..e9037d6d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -41,6 +41,7 @@ the [retired](./retired/) notes now. | [dependency-update.md](./dependency-update.md) | moving everything else in the catalogue to its newest stable release, phased and built but for a mac, devices and pushing the submodule branches — why the libraries go first and need no newer Kotlin, why AGP and Kotlin can only move down the whole submodule chain at once, the material3 alpha that was built for an older Compose than the app's, and what has to keep opening on a device afterwards | | [giza-wallet-removal.md](./giza-wallet-removal.md) | taking every wallet out of Giza, phased and built but for moving off the wallet library (7b). Covers why a Giza member declines a Bennu peer's wallet proposal instead of ignoring or signing it, why the wallet's kinds are retired rather than freed, why a recovery phrase stays as a key backup that has to derive the same npub and id byte for byte, and why the threshold crypto keeps the build tied to the wallet library until the last phase | | [group-nostr-profile-and-posts.md](./group-nostr-profile-and-posts.md) | bringing back the group's nostr profile and its posts, ported from Curare, phased and built but for its device run: why it is a port and not a revert of `b21f4c4d`, what Giza does today with a peer's kind:0 or kind:1, why relay lists stay out, why the group's lightning address is kept but never offered, why a broadcast never writes a `NostrEvent` row and sends nothing but those two kinds, and declining what no reader would show | +| [group-inbox.md](./group-inbox.md) | a group that can be written to privately: a phased plan, not built, for NIP-4E on a group's npub. A ChillDKG ceremony at threshold 1 leaves every admin holding the same inbox key, the group announces it in a signed 10044, admins read the NIP-17 messages sent to it, and a reply is a batch of seals the quorum signs before the proposer's device wraps and sends them. Covers why the key is its own ceremony and never a signing key, why the proposal hides the reply from members who are not admins, what every signer checks before signing a seal, and the rotation on every admin change with what it cannot undo | | [giza-app-icon.md](./giza-app-icon.md) | the sphinx icon on iOS, desktop and in the app, phased and built but for the checks on a mac, a phone and Windows — one master SVG and one generator for every raster, why the iOS light icon must carry no alpha channel, why its dark icon is transparent and its tinted one grayscale, the desktop installers and window that show Java's icon today, and why the mark's cutouts need no fill rule | | [member-admin-promotion.md](./member-admin-promotion.md) | making a member an admin and back, phased and built, promotion with a share and demotion with a refresh under the experimental enrollment, under three rules: every admin holds a share, every commit in a keyed room is a proposal until the group's threshold signature is on it, and a robust group keeps at least three admins. Covers why the commit rides inside the group's signature and the rule inside the group's state, which lets every device refuse an unsigned commit with the libraries as they are, why a member's own leave stays exempt, and why a removed admin comes back as an admin when re-invited today | | [admin-change-rotation.md](./admin-change-rotation.md) | an admin change carries its rotation with it: a phased plan, built but for its device session, in which the rotation that follows removing an admin, and the one before a first promotion, asks nobody, because the group's signature on the change already decided who is withheld, and in which admin changes and rotations take turns. Covers the five ways the two overlap today, a removed admin who keeps a live share among them, and the one check a device makes to take part unasked | diff --git a/docs/group-inbox.md b/docs/group-inbox.md new file mode 100644 index 00000000..3c484e05 --- /dev/null +++ b/docs/group-inbox.md @@ -0,0 +1,804 @@ +# The group's inbox: NIP-4E for a group's npub + +A plan for four things a group cannot do today: + +1. **Be written to privately.** Anyone on nostr can send the group a NIP-17 direct + message, addressed to the group's npub, the way they would write to a person. +2. **Have its admins read what it is sent.** Every current admin's device opens those + messages, and nobody else's does: not the group's other members, and not a relay. +3. **Answer as itself.** An admin drafts a reply; it reaches the person only once the + group's quorum has signed it, so the reply is the group's word and not the drafter's. +4. **Change the lock when the admins change.** The key that opens the inbox is + regenerated, by a new ceremony, whenever an admin leaves or joins, and whenever an admin + asks for it. + +None of this is possible with the group's own key. Nobody holds a group's secret key, so +nothing can be NIP-44-encrypted *to* its npub or *from* it +([confederation.md](./confederation.md#d5-encrypting-the-admin-list-a-seal-every-signer-can-recompute) +says so and builds around it). NIP-4E is the way out: a nostr identity may announce a +*separate* encryption key, and senders encrypt to that instead. This plan gives the group +such a key, generated by a ChillDKG ceremony among its admins and held in full by each of +them. The group's npub still signs, through FROST, and only through FROST. + +Read [shared-key-ceremony.md](./shared-key-ceremony.md) and +[shared-key-derivation.md](./shared-key-derivation.md) first: the ceremony is the one this +plan runs again, and the derivation note's one rule (never reconstruct a derived key in +the clear) is the rule D2 explains this plan does not break. Then +[group-nostr-profile-and-posts.md](./group-nostr-profile-and-posts.md), for how a group +proposes, signs and broadcasts an event in its own name; +[admin-change-rotation.md](./admin-change-rotation.md), for the follow-through an admin +change already runs, which D14 adds to; and +[marmot-direct-messages.md](./marmot-direct-messages.md), for the last time this app built +a gift wrap by hand. + +**Planned, not built.** Written against `5ac4c053`, on 2026-11-22. Paths starting `K/` are +under `composeApp/src/commonMain/kotlin/mobi/giza/compose/`. + +--- + +## The specification, as it stands + +NIP-4E is a draft. Two open pull requests carry it, and this plan follows both, as they +read on 2026-11-22: + +| where | what it defines | what this plan takes | +|---|---|---| +| [nostr-protocol/nips#1647](https://github.com/nostr-protocol/nips/pull/1647) (`4e.md` on `per-device-keys`) | kind **10044**, a replaceable announcement `{"kind":10044,"tags":[["n",""]]}` signed by the identity; kinds **4454** and **4455**, a client asking for the encryption secret and another client handing it over | 10044, exactly. Not 4454 or 4455: see D1 | +| [nostr-protocol/nips#2361](https://github.com/nostr-protocol/nips/pull/2361) (`17.md` on `nip17-key`, head `bee7463`) | how NIP-17's layers change when either side has an encryption key | all of it | + +#2361's layers, in its own pseudo-code's terms: + +``` +gift wrap (1059) pubkey = a fresh random key, per message + tags = [["p", receiverIdentityKey, relay]] the identity, not E + content = nip44(seal, conv(wrapper secret, receiverEncryptionKey)) + +seal (13) pubkey = senderIdentityKey signed by the identity + tags = [["n", senderEncryptionKey]] when it differs from the identity + content = nip44(rumor, conv(senderEncryptionKey secret, receiverEncryptionKey)) + +rumor (14) unchanged; its pubkey must equal the seal's +``` + +Two consequences shape everything below: + +- **The seal is signed by the identity, but encrypted with the encryption key.** For a + group, that splits cleanly: the admins hold the encryption key and can build the seal's + content; only the quorum can sign the seal. That is the user's requirement — any admin + can read, a reply needs the group's signature — and it falls out of the spec rather than + being built on top of it. +- **The gift wrap names the identity, not the key.** A recipient with several keys (the + current one and the ones before it) cannot tell from the outside which one a wrap was + encrypted to, and tries them. #2361's review says so as an objection. For a group that + rotates on every admin change, it is a cost this plan pays on purpose (D14). + +quartz 2.20.1 already ships the announcement side, under +`com.vitorpamplona.quartz.experimental.decoupling`: `EncryptionKeyListEvent` (kind 10044, +`encryptionKey()`, `keys()`, `build`), `KeyTag` (the `n` tag), `DecoupledCipher`, and the +4454/4455 exchange. The app uses none of it today. quartz's `GiftWrapEvent.create` and +`SealEvent.create` encrypt to the key they address and sign with the signer they are +given, so neither can build #2361's layers for a group; both are built by hand here, as +`MarmotDirectMessage.wrap` already does for its own reasons. quartz's `DecoupledCipher` +reads a sender's key from their 10044 and has no seal `n` tag; D8 reads both. + +The spec is open, and the main objection to #2361 (that a decoupled sender writing to an +app that does not follow it fails silently) is a live one. So every wire decision lives in +one package, `K/nostr/inbox/`, with tests that pin the bytes, and Phase 0 records the +commits read. + +--- + +## What Giza does today + +Traced through the code at `5ac4c053`. Phase 1 pins them as tests before anything changes. + +| event | where it lands | what happens | +|---|---|---| +| a kind 1059 `#p`-tagged to a group's npub | nowhere: `LiveSubscriptionManager` asks only for `#p` = the active identity, on `Relays.DefaultDMRelayList` | never fetched. If it arrived another way, `NostrDao.indexNostrEvent` stores a `GiftWrapMessage` and never opens it: only the active identity's key is tried | +| a peer proposes a kind 10044 for the group to sign | `FrostSigningManager.acceptProposal` | no refusal fires (the signer has no allowlist), so it is asked as "Event of kind 10044" and can be signed | +| a peer proposes a kind 13 | same | "Event of kind 13", signable. A member asked to sign a sealed ciphertext it cannot read is a rubber stamp, which is the thing [giza-wallet-removal.md](./giza-wallet-removal.md) says a Giza device must not be | +| either completes | `complete` → `applySignedEvent` → `ChatMessage.applyInnerEvent` | falls to `unsupported()`: a raw-JSON bubble on every device | +| a ChillDKG ceremony in a Marmot room | `ChillDkgRitualManager.proposeRitual` | allowed only as a subgroup's (`require` at `:267`); every completed `DkgSession` is a key `completedKey` and `getKeyHoldingSessions` may sign with | +| the user's own NIP-17 send | `NostrNip17Dao.persistAndBroadcastGiftWrap` | goes to `DefaultDMRelayList` only; the recipient's 10050 is looked up and the block that would use it is commented out (`:186-218`) | + +Four things already exist and are reused unchanged: + +- **ChillDKG accepts `t = 1`**, and with it every participant's share is the whole secret + ([subgroups.md](./subgroups.md) notes that it "will happily generate one", which is + why `acceptProposal` refuses one for a signing key). That is D2. +- **`proposeSigningBatch` with `proposalTags`** carries hidden tags inside the MLS-encrypted + proposal, as the confederation's seal does. That is D11. +- **`approveIfVouched`** signs a key state a device can check for itself without asking its + owner. D5 uses the same door for a rotated key's announcement. +- **`ConfederationPublisher`**'s owed-event pattern (`ownSessionId`, `publishedAt`, backoff + from a minute to half an hour) is how a signed event reaches relays without a person + pressing Broadcast. D7 and D10 reuse it. + +--- + +## Decisions + +### D1. 10044 from #1647, the layers from #2361, and no 4454 or 4455 + +The announcement and the layers are what a sender's app reads, so they follow the drafts +to the byte. + +4454 and 4455 are how one person's clients pass the secret between themselves: a new +client asks in public, an old one answers in public, both signed by the identity. A group +has no use for them. The admins are not one person's clients, the identity cannot sign a +4455 without a quorum, and the ceremony (D2) already leaves the secret on every device that +should have it. Publishing either would announce, under the group's name, which devices +hold its inbox. + +### D2. The inbox key is a ChillDKG ceremony with threshold 1, over the admins + +A ChillDKG ceremony among the current admins, with `t = 1`. In ChillDKG every participant's +share is the sum of every participant's polynomial evaluated at its index; at `t = 1` each +polynomial is a constant, so every share is the same number: the sum of everyone's +contributions. Every admin ends the ceremony holding the same secret `e`, the ceremony's +threshold public key is `E = e·G`, and nobody had to send anybody a secret outside the +protocol. + +What the ceremony buys over one admin picking `e` and sending it round (which is how +Bennu's lightning wallet shared its node seed, D4 of +[retired/group-lightning-wallet.md](./retired/group-lightning-wallet.md)): + +- **Nobody chooses the key.** Every admin contributes. An admin whose device is compromised + cannot steer the group onto a key the attacker picked in advance, and an admin who knows + the dealer's habits learns nothing about the next key. +- **Everybody agrees on it, provably.** ChillDKG's CertEq round fails the ceremony unless + every participant saw the same result, so no admin can be left holding a different `E` + from the one the group announces. +- **Blame is built in.** A participant who sends a bad contribution is named, as for any + ceremony. +- **It is the ceremony the app already runs**: the rounds, the resume sweep, the transcript + lines and the waiting-on screen. + +Why not a `t`-of-`n` ceremony whose shares are then revealed to everyone: it needs a fourth +round and a pairwise channel, and ends in the same place. `t = 1` gets there in the rounds +that exist. + +This does not break the derivation note's rule. That rule is about the *signing* key: a +derived signing key reconstructed in the clear leaks the group key. The inbox key is a +different key, from a different ceremony, related to the signing key by nothing. Its +secret being whole on every admin's device is the point of it. + +Phase 0 checks the premise in bitcoin-kmp before anything is built: a three-participant +`t = 1` ChillDKG leaves three identical `secretShare`s, each times `G` equal to the +threshold public key. + +### D3. Its own kinds, its own tables, its own manager. Never a `DkgSession` + +A `t = 1` key in `DkgSession` would be worse than misfiled. `getKeyHoldingSessions` and +`FrostSigningManager.completedKey` scan that table for keys to sign with, and a key any +one admin can sign with alone would be found there. So the inbox ceremony is kept apart +the way the confederation's is: + +- **Kinds:** a family of seven, the same shape as 30310–30316 (proposal, host key, round 1, + coordinator round 1, round 2, certificate, failure). Candidate numbers are 30390–30396. + Phase 0 checks them against the NIP kind table, quartz, Curare, Bennu and `RetiredKinds`, + as confederation Phase 0 did for 9430–9433. New kinds also keep a Bennu admin's device + from mistaking the ceremony for a subgroup's, which a 30310 with a subset of `p` tags in + a Marmot room would be to it. +- **Tables:** `InboxKeyCeremony` and `InboxKeyCeremonyMessage` (the ceremony's inputs and + received messages, as `DkgSession` and `DkgParticipantMessage` keep them), and `InboxKey` + (the output). Phase 3. +- **Manager:** `K/managers/InboxKeyRitualManager.kt`, on the same + `fr.acinq.bitcoin.crypto.dkg.chill.ChillDKG` calls as `ChillDkgRitualManager`, with the + same discipline: every step a pure function of stored inputs, faults as values. +- **Transport:** MLS inner events in the group's own Marmot room, `p`-tagging the admins. + Every member of the room receives them, which is fine: ChillDKG encrypts each + contribution to its recipients' host keys, so a member who is not an admin learns `E` + and nothing else. +- **Host key:** `sha256("mantra/inbox-key/host-key/v1" || nsec || room id)`, so the inbox + ceremony's host key is not the one the group's signing ceremony used, and an inbox key + in one group is unlinkable to another's. The tag is a hash input and is spelled with + `mantra/`, as every protocol tag in the app is ([giza-rebrand.md](./giza-rebrand.md)). +- **Recovery:** the host secret comes from the nsec, and `InboxKey` keeps ChillDKG's + recovery data, so a recovery phrase restores the inbox key as it restores a share. + +A test pins that no `InboxKeyCeremony` is ever returned by `getKeyHoldingSessions`, +`completedKey` or `ShareGenerations`. + +### D4. Who takes part: exactly the admins, and nobody is asked + +The participants are `RoomAdmins.of(room)` when the ceremony is proposed, and every +device checks the proposal's `p` tags against its own reading of the policy. A mismatch +fails the ceremony out loud, with the difference named, through the family's failure kind. +A member who is not an admin files the transcript lines and takes no part. + +An admin's device takes part **without asking**. The decision to hold the key was made +when the group made them an admin, and the decision to *have* an inbox is the group's +signature on its announcement (D5), not the ceremony. Joining a key ceremony is asked today +([shared-key-ceremony.md](./shared-key-ceremony.md#joining-is-the-only-approval)) because +it enrols someone in a permanent signing quorum; this ceremony enrols nobody in anything, +and an admin who could decline it would only be holding the group's inbox shut. + +Every admin has to take part, as in every ChillDKG. A device that never answers is named on +the ceremony's screen after a day, with **Abandon** beside it, as today. A Bennu admin +cannot take part at all, so a group with one cannot open an inbox until that admin runs +Giza or stops being an admin. The screen says that rather than "waiting". + +The ceremony refuses to start while a rotation or an admin change is in flight +(`RotationHold`), for the same reason rotations and admin changes take turns +([admin-change-rotation.md](./admin-change-rotation.md)): the admin set it is run over +would be stale before it finished. + +### D5. The group decides to have an inbox by signing its announcement + +Nothing is public until the group signs a kind 10044 naming `E`. That signature is the +decision, and it is asked: the approval screen says, in plain words, that anyone on nostr +will be able to send the group private messages, that every admin will be able to read +them, and which relays they will arrive on (D6). + +Later announcements, for a rotated key, are not asked again. The group already decided to +have an inbox, and a rotation is what keeping it means. They go through `approveIfVouched`, +the door key states use, when this device can vouch for all of: + +- the group has signed a 10044 before; +- `E` is the output of a completed inbox ceremony in this room, which this device took part + in and holds `e` for; +- that ceremony's participants are the room's current admins. + +A device that cannot vouch is asked, as for an unvouchable key state. + +`InboxKeyRefusal` declines, out loud, in the four places every refusal sits +(`acceptProposal`, the `approve` backstop, `publishDecline`'s reason, the unshowable-session +check), any 10044 that: + +- names a key which is not the output of a completed inbox ceremony in this room; +- names more than one `n`, or has content; +- is proposed in a room that is not a keyed Marmot room. + +### D6. The group's DM relays are a group-signed 10050, proposed with the first 10044 + +A sender's app sends a NIP-17 message to the recipient's 10050 relays, and many send +nothing when there are none. So the first announcement is a **batch** of two events, the +10044 and a 10050, signed in one session +([frost-batch-signing.md](./frost-batch-signing.md)). The setup screen fills the 10050 with +`Relays.DefaultDMRelayList` and the member can edit it before proposing. Changing it later +is its own proposal from the inbox's settings. + +This brings back one of the four relay lists +[group-nostr-profile-and-posts.md](./group-nostr-profile-and-posts.md#d1-profile-and-posts-only-relay-lists-stay-out) +left out, and only that one: an inbox nobody can deliver to is not an inbox. `InboxKeyRefusal` +declines a 10050 whose relays are not all `wss://` and public (the profile plan's +`relayUrlOrNull`). + +### D7. The announcement is published by the device that proposed it + +A 10044 that is signed but not on relays is an inbox no sender can find. So the signed +10044 and 10050 are filed as owed on the proposer's device and sent by an +`InboxAnnouncementPublisher` (the `ConfederationPublisher` pattern) to the publish set and +the group's own 10050 relays, with backoff until a relay takes each. They are also added to +`BROADCASTABLE_KINDS`, so any member can send them again by hand from the broadcast screen. +Neither writes a `NostrEvent` row (D7 of the profile plan, for the same reasons). + +### D8. Reading: a pipeline of its own, beside the personal one and never inside it + +The personal DM path is built around one identity: it subscribes to `#p` = me, tries only +the active key, and files what it opens into chat rooms keyed by participants. Putting the +group's mail through it would mix the group's correspondents into the admin's own DM list, +and give every wrap two keys to be tried against for no reason. So the group's inbox has +its own path, and writes no `GiftWrapMessage`, `GiftWrapPayload` or `NostrEvent` row: + +1. **Subscription.** `LiveSubscriptionManager` holds `live-group-inbox` while the flag is on: + kind 1059 with `#p` = the npub of every room where this device holds an inbox key, on + the union of those groups' 10050 relays and the app's DM relays, re-sent when the set + changes (the `followConfederations` shape). Catch-up uses `since` = the newest wrap seen + minus two days, since NIP-59 back-dates wraps by up to that much. +2. **Opening the wrap.** Try each `InboxKey` this device holds for the room, newest first. + Every wrap goes into a ledger, `GroupInboxWrap`, keyed by its id, as opened or not, so + redelivery is a no-op and a key that arrives later (a restore) can reopen what is there. +3. **Opening the seal.** Verify its signature. The sender's key for the conversation key is + the seal's `n` tag if it has one, else the `n` of the sender's own 10044 if this device + has it (quartz's model), else the sender's identity. The rumor's pubkey must equal the + seal's, as for any NIP-17 message. +4. **Filing.** A kind 14 rumor becomes a `GroupInboxMessage`: room, rumor id (unique, so two + wraps of one rumor are one message), wrap id, sender, the rumor's JSON, its time, which + key generation opened it, and a conversation id: the sorted set of the sender and the + rumor's `p` tags, without the group, as NIP-17 defines a chat. A rumor of any other kind + is filed as a message this screen cannot show yet, not dropped. + +A wrap no held key opens is **counted, not hidden**. The inbox says how many messages this +device cannot open, and why that happens: a sender's app that does not follow NIP-4E +encrypted to the group's npub, which nobody can open (see *Out of scope* for the only fix), +or the message was sent to a key from before this admin's time. + +### D9. Only the admins who hold the key see anything of the inbox + +The inbox screen, its row on the group's screen and its count are shown only on a device +that holds an `InboxKey` for the room. A member who is not an admin sees that the group has +an inbox (the 10044 is public) and nothing in it. D11 keeps the same true of replies, which +otherwise would travel through the room in a form every member can read. + +### D10. A reply is a batch of seals, signed by the group and wrapped by the proposer + +An admin replying to a conversation builds: + +``` +rumor kind 14, pubkey = the group's npub (the room id), unsigned + tags: ["p", ] … , ["e", , , "reply"] + content: the reply + +for each recipient r, and once for the group itself: + seal kind 13, pubkey = the group's npub + tags: [["n", E]] the current generation's key + content: nip44(rumor, conv(e, encryption key of r)) + created_at: now minus up to two days, at random (NIP-59) +``` + +`r`'s encryption key is the `n` of `r`'s 10044 when this device has one, otherwise `r`'s +identity. For the group's own copy it is `E`. + +The seals go to the quorum as one batch through `proposeSigningBatch`. Proposing is the +proposer's approval, as for every proposal. Once the session completes, the proposer's +device wraps each signed seal under a fresh random key (`p` = the recipient's identity, +content encrypted to the recipient's encryption key, #2361's wrap) and publishes it to that +recipient's 10050 relays, falling back to the publish set. The group's own copy goes to the +group's 10050. This is filed as owed and sent with backoff by an `InboxReplyPublisher`, the +same pattern as D7. + +The group's own copy is how every admin sees the reply: it arrives through D8 like any +other message, on every admin's device, as an outgoing line in the conversation. The +proposer's device files it at once too, without waiting for the round trip. + +If the proposer's device is gone, any admin can **Send again** from the conversation: the +signed seals are on every signer's device as `GroupSignedEvent` rows, and wrapping needs no +key but a random one. A second send makes second wraps of the same rumor, which D8's +rumor-id key collapses on the group's side; a recipient's app may show it twice. + +Why one seal per recipient: NIP-17's seal is encrypted to its one recipient. A reply to a +conversation of three people is four seals, and four signatures in one session. + +### D11. The proposal hides the reply from members who are not admins + +A FROST proposal travels as an MLS inner event and reaches every member of the room. Its +content is the unsigned events to sign, which here are seals: ciphertext. What the signers +also need — which seal is for whom, and on what evidence — rides as a proposal tag, +encrypted to the inbox key: + +``` +["inbox_manifest", nip44(manifest, conv(e, E))] + +manifest: +{"v":1,"generation":, + "seals":[{"recipient":"","key":"", + "announcement":}, …], + "group_copy":} +``` + +A member without the key sees that the group is signing so many seals, which is the number +of recipients plus one, and nothing else. That leak is stated in *Risks*. + +### D12. Every signer reads the reply before signing it, and declines what does not add up + +`InboxReplyRefusal` joins the others in the same four places. A signer: + +1. decrypts the manifest with a key of the generation it names. A signer that holds no such + key **declines**, out loud: "This device holds no inbox key for this group". That is a + share-holder who is not a current admin (possible while share refresh is experimental), + or an admin whose device missed the ceremony. Signing a ciphertext it cannot read is the + rubber stamp Giza does not do; +2. checks the generation is one this device holds and the batch's every `n` tag is that + generation's `E`; +3. checks every `announcement` it is given: a valid 10044, authored by that seal's + recipient, whose `n` is that seal's `key`. A `null` announcement means the key must be + the recipient's identity; +4. opens every seal with `conv(e, key)` and checks they all hold the **same** rumor, byte + for byte; +5. checks that rumor: kind 14, pubkey the room id, no signature, non-blank content, and its + `p` tags exactly the manifest's recipients other than the group; +6. checks exactly one seal is the group's own copy, to `E`, and each `created_at` is within + two days before now and not in the future. + +A proposer who wrote one thing to the group's copy and another to a recipient, sealed to a +key that is not the recipient's, or added a recipient the rumor does not name, is declined +by every honest signer. What a signer *cannot* check — that a recipient without a 10044 +has not published one since, or that their app reads #2361's `n` tag — is a warning, not a +refusal, per the line [automatic-key-ceremony.md](./automatic-key-ceremony.md) drew. + +The approval screen shows what the signer is agreeing to: the reply's text, the message it +answers, its recipients by name, and any warning. + +### D13. A recipient without a 10044 gets the reply, with a warning + +A seal encrypted from the inbox key opens only in an app that reads #2361's `n` tag. An app +that does not computes the conversation key from the group's npub, and fails. Giza cannot +tell which a recipient uses: a 10044 shows they do, its absence shows nothing. + +So the composer and the approval screen warn when a recipient has no 10044 ("Their app may +not be able to open a message from a group"), and the reply goes anyway. Refusing would +refuse every recipient whose app reads the tag without announcing a key of its own, which +is every #2361 app whose user has not decoupled. + +### D14. Rotation is a new ceremony, and old keys are kept for reading only + +`InboxKey` has a generation. A rotation runs D2 again over the current admins, and once +its 10044 is signed (D5, unasked) and sent (D7), the new generation is the one replies are +sealed from. Until then the announced one stays in use, so there is never a moment where +the group seals from a key senders have not been told about. A reply proposed under one +generation and completed after a rotation is still valid: its seals' `n` names the key they +used. + +What starts a rotation: + +| trigger | how | asked? | +|---|---|---| +| an admin is removed, demoted or steps down | `GovernanceFollowThrough` owes one once the change has landed, as it owes a share rotation today, and runs it after that rotation (D4's `RotationHold`) | no. The group's signature on the change was the decision | +| an admin is promoted | the same, after the enrollment | no. The new admin needs a key | +| an admin asks for one | **Rotate the inbox key** in the inbox's settings, for a lost phone or a suspicion | no further approval: proposing is the proposer's, and nobody else is asked anything until the announcement, which is vouched | +| a rotation failed or was abandoned | the same button, offered on the failed ceremony's screen | as above | + +Old keys are kept, marked retired, and used only to open: a sender may hold a 10044 from +before the rotation for a while, and messages from before are in the ledger to be reopened. +D8 tries the newest first. + +What a rotation **cannot** do, and the screen does not pretend otherwise: + +- A removed admin keeps every message they already read, and the keys they held. Their + Giza device wipes its inbox keys and inbox messages for the room when it sees itself + removed (as a share is wiped), but that is cooperation, not enforcement. +- A sender who has not refreshed the group's 10044 still encrypts to the old key, which the + removed admin also holds, until their app looks again. Nothing the group does reaches + that cache. + +### D15. A promoted admin starts with an empty inbox + +The rotation a promotion triggers gives the new admin the new key and none of the old ones, +so they read what arrives from then on. Handing a new admin the group's whole correspondence +is a different decision from making them an admin, and it is the quorum's to make, not a +side effect of a rotation. This plan does not make it (*Out of scope*). The inbox screen +says why a new admin sees nothing earlier. + +### D16. Behind a flag + +`ExperimentalFeatures.groupInbox`, `groupInboxOverride ?: isDevelopmentBuild()`, as +`confederation` is. Off in release until the device run (Phase 10) has passed and the two +pull requests have settled. The refusals (D5, D12) and the declines run whatever the flag +says, as every refusal does: a release build declines a peer's inbox proposal out loud +rather than signing it blind. + +--- + +## Who is asked what + +| step | who | asked? | +|---|---|---| +| set up an inbox (propose the first ceremony) | any admin | the button | +| take part in the ceremony | every admin | no (D4) | +| propose the first 10044 + 10050 | the ceremony's coordinator, on completion | no (it is the coordinator's follow-through) | +| sign the first 10044 + 10050 | `t` holders | **yes: the group's decision to have an inbox** (D5) | +| publish them | the proposer's device | no (D7) | +| read a message | every admin's device | no | +| propose a reply | any admin | the Send button | +| sign a reply | `t` holders | **yes: each reply** (D12) | +| wrap and send it | the proposer's device | no (D10) | +| a rotation's ceremony and its 10044 | every admin, `t` holders | no (D14, D5) | + +--- + +## Phases + +One commit per phase, in the repository's style (`feat: … (group-inbox, Phase n)`). Every +phase leaves `./gradlew :composeApp:jvmTest` and `:composeApp:m3Audit` green, and +`check`'s brand and wallet audits at budget. + +### Phase 0: this document, and five checks + +This document and its row in [README.md](./README.md). Then, before any code: + +1. **`t = 1` ChillDKG** (D2). In bitcoin-kmp's tests or a scratch jvmTest: three + participants, `t = 1`; every `secretShare` is equal, and equals the threshold public + key's discrete log (`secretShare·G == thresholdPublicKey`). If the library refuses + `t = 1` or the shares differ, stop: the fallback is a `t = n` ceremony followed by a + reveal round to host keys, checked against `publicShares`, and D2 and Phase 4 change. +2. **Kinds** (D3). 30390–30396 against the NIP README's table, quartz 2.20.1, Curare, + Bennu and `RetiredKinds`. Record the result here. +3. **quartz.** That `Nip44.v2.computeConversationKey` / `encrypt` / `decrypt` take an + arbitrary secret and public key; that `EncryptionKeyListEvent` parses #1647's form; + that an event template of kind 13 can be built unsigned and handed to the signing + session as `FrostSigningManager.unsignedEventOf` expects. +4. **The premise.** In `SignedGroupKeyStateTest`'s harness, a batch of two kind 13 events + signed in a keyed room verifies as the room's id. If it fails, no recipient would accept + the group's seal, and the plan stops. +5. **The spec.** Re-read #1647 and #2361 at their heads and record the commits in + *The specification, as it stands*. If #2361 has moved the `n` tag or added a second + `p`, the wire phase follows it. + +### Phase 1: pin today + +Tests of *What Giza does today*, written to pass now and flipped on purpose later: + +- `ProposedEventTest`: a kind 10044, 10050 and 13 summarise as "Event of kind N". Phase 5 + and Phase 8 flip them. +- `GroupInboxTodayJvmTest`: + - a kind 1059 `p`-tagged to a group's npub, fed to `storeNostrEvent`, is stored and never + opened. Phase 6 makes it never stored by that path at all; + - a peer's kind 10044 and kind 13 proposals reach the owner's approval prompt (Phase 5 + and Phase 8 turn them into declines unless they check out); + - `live-group-inbox` does not exist. + +### Phase 2: the wire, in one package + +No database, no UI. `K/nostr/inbox/`: + +- `InboxKeyRitualEvents` and its tags: the seven kinds, each with the `inbox_key_session` + and generation tags, and the proposal's `p` tags. +- `InboxAnnouncement`: builds and reads the group's 10044 through quartz's + `EncryptionKeyListEvent`, and the 10050 through `DmRelayListEvent`. +- `InboxSeal`: builds the unsigned seal of D10; opens a seal by D8's rule (the `n` tag, then + the sender's 10044, then the identity). +- `InboxWrap`: wraps a signed seal by #2361 (`p` = identity, encrypted to the encryption + key, fresh key, back-dated `created_at`); opens a wrap by trying keys. +- `InboxReplyManifest`: D11's JSON, encrypted to `conv(e, E)`, with a decoder that accepts + only its own encoding. +- `InboxConversation.idOf(rumor)`: D8's conversation id. + +Tests (`InboxWireTest`, pure): every layer round-trips; a seal opens with the `n` tag, with +a 10044 and with neither; a wrap built here opens with quartz's own +`unwrapAndUnsealOrNull` when both sides use identity keys (so the hand-built wrap is +still a NIP-59 wrap); a manifest with a stray field is refused; the conversation id is the +same whatever order the `p` tags are in. + +### Phase 3: storage, schema 44 → 45 + +Additive, so an `AutoMigration(44, 45)` with its comment, the exported +`composeApp/schemas/…/45.json`, and `ShippedProfileUpgradeJvmTest`'s `current` moved to 45. + +| table | key | holds | +|---|---|---| +| `InboxKeyCeremony` | session id | room, generation, participants, coordinator, the ChillDKG inputs (randomness, host secret's tag), stage, the waiting-since time | +| `InboxKeyCeremonyMessage` | `(session, participant, kind)` | each received message, as `DkgParticipantMessage` | +| `InboxKey` | `(room, generation)` | `E`, `e`, recovery data, ceremony id, state (`HELD`, `ANNOUNCED`, `RETIRED`, `WIPED`), the signed 10044's id | +| `GroupInboxWrap` | wrap id | room, received at, opened by which generation or not yet | +| `GroupInboxMessage` | rumor id | room, wrap id, conversation id, sender, rumor JSON, created at, generation, outgoing or not | +| `GroupInboxOutbound` | `(signing session, seal id)` | recipient, the relays, the wrap once built, `publishedAt`, the backoff | + +`e` is stored as a share is stored, and wiped as a share is wiped. DAOs beside them, and +`InboxStorageJvmTest`: redelivery of a wrap or a rumor is a no-op, wiping a generation +removes `e` and keeps `E`, and no `InboxKey` is visible to `getKeyHoldingSessions`, +`completedKey` or `ShareGenerations` (D3). + +### Phase 4: the ceremony (D2, D3, D4) + +- `InboxKeyRitualManager`: `propose` (refused unless the proposer is a current admin, the + room is a keyed Marmot room, the flag is on and `RotationHold` is clear), `process` + (store, then ask whether it can move), `advance` (the ChillDKG steps at `t = 1`), + `abandon`, `resumeRunning`. On completion, check `e·G == E` and write `InboxKey` at the + next generation. +- Inbound: an arm in `NostrDao.fileGroupEventResult`'s dispatch for the seven kinds, ahead + of content kinds as the ceremony's are. +- The sweep: `NostrRepository.resumeRunningCeremonies` resumes inbox ceremonies too. +- The transcript: `INBOX_KEY_TYPES`, rendered as `RitualNotice`s that open the ceremony's + screen. Wording says what a step does: "set up the group's inbox", "added their part to + the inbox key", "the group's inbox key is ready". +- `InboxKeyRitualScreen`: the ceremony's state, who it waits on and since when, + **Abandon**. M3 rules as in `CLAUDE.md`, and a back button. +- Tests, in the ritual harness that `CeremonyAcrossDevicesJvmTest` uses, three admins and + a member: + - every admin's device ends with the same `e`, and `e·G` is the announced `E`; + - the member's device files the lines and holds no `InboxKey`; + - a proposal naming a non-admin, or leaving an admin out, fails out loud on every admin's + device; + - a ceremony survives a restart mid-round (stored inputs, as `DkgSession`); + - a faulty contribution names its sender. + +### Phase 5: announcing (D5, D6, D7) + +- `InboxKeyRefusal`, in the four places. +- `ProposedEvent` arms: a 10044 is "The group's inbox key", with the key's fingerprint and + whether this device holds it; a 10050 is "Where the group receives messages", with the + relays. +- The follow-through: on the coordinator's device, a completed first-generation ceremony + proposes the 10044 and 10050 batch. A later generation proposes the 10044 alone, and + `approveIfVouched` signs it where D5's three conditions hold. +- `ChatMessage.applyInnerEvent` arms: a room-signed 10044 is "The group has an inbox" the + first time and "The group changed its inbox key" after; a 10050 is "The group changed + where it receives messages". Types in `GROUP_IDENTITY_TYPES`. +- On a signed 10044, `InboxKey.state` moves to `ANNOUNCED` for its generation and the + previous one to `RETIRED`. +- `InboxAnnouncementPublisher`, started by `SynchronizationViewModel` beside + `ConfederationPublisher`. `BROADCASTABLE_KINDS` gains 10044 and 10050. +- Tests: `InboxAnnouncementJvmTest` — the first batch is asked, a rotation's is not, a + 10044 naming a stranger's key is declined with its reason and the proposer's device shows + the decline, the published event is identical to the signed one and writes no + `NostrEvent` or `Profile` row. Phase 1's 10044/10050 pins flip. + +### Phase 6: reading (D8, D9) + +- `live-group-inbox` in `LiveSubscriptionManager`, and catch-up with the two-day margin. +- `GroupInboxManager.receive(wrap)`: ledger, open, verify, file. Never through + `storeNostrEvent`: the subscription hands wraps straight to it, and + `indexNostrEvent` skips a wrap `p`-tagged to a room this device keeps an inbox for. +- `GroupInboxManager.reopen(room)`, run when a key arrives. +- `DirectMessagePeerSync.KINDS` gains 10044, so a correspondent's encryption key is known + when the group replies, and D8 can use a sender's 10044 for a seal with no `n` tag. +- Repository flows: conversations for a room (newest first, unread count), messages of a + conversation, the count of wraps no key opens. +- The wipe: a device that sees itself no longer an admin of a room wipes that room's + `InboxKey`s and `GroupInboxMessage`s, and writes a transcript line saying so. +- Tests: `GroupInboxReadJvmTest` — a stock NIP-17 message from an identity-only sender to a + group with a 10044, built with quartz's own `GiftWrapEvent.create` around a seal made to + `E`, opens on every admin's device and on no member's; a #2361 sender with an `n` tag + opens; a wrap to the group's npub is counted unopenable; the same rumor in two wraps is + one message; a wrap to a retired key still opens; the wipe. Phase 1's wrap pin flips. + +### Phase 7: the inbox, seen + +- Routes and screens, each with a back button, `readableContent()`, the four states and + `ScreenStateTransition`: + - `GroupInboxScreen`: conversations, each with its people by name, the last line and an + unread mark; the empty state says nobody has written yet, or for a new admin that + earlier messages were sent before they held the key (D15); the count of messages this + device cannot open, with a line on why. + - `GroupInboxConversationScreen`: the messages, incoming and outgoing, with outgoing ones + marked by state (being signed, sent, signed but not sent). + - `GroupInboxSettingsScreen`: the current key's generation and fingerprint, whether it is + announced, the 10050's relays with **Change**, **Rotate the inbox key**, and the + ceremony's state while one runs. +- The group's screen: an "Inbox" row with the unread count, shown only where this device + holds a key (D9). Where the group has no inbox and this device's identity is an admin, a + "Set up an inbox" row instead, which explains the decision and opens a setup screen with + the 10050 relays to edit before the ceremony is proposed. +- Strings in sentence case from the catalogue; nothing says Bennu, and nothing says + "NIP-4E" to a person. +- Tests: `GroupInboxScreenJvmTest` — the row is absent for a member and present for an + admin with a key; the empty states; the unopenable count. + +### Phase 8: replying (D10, D11, D12, D13) + +- `InboxReply.build(room, conversation, text, replyTo)`: the rumor, the seals and the + manifest, from the current announced generation and each recipient's latest 10044. +- The composer under `GroupInboxConversationScreen`: proposes through `proposeSigningBatch` + with the manifest tag, warns per D13, and says above the button that the group's quorum + has to sign it before it is sent. +- `InboxReplyRefusal`, in the four places, with D12's checks. +- `ProposedEvent` for a batch of seals: on a device with the key, "A reply from the group's + inbox" with the text and recipients; on one without, "A private reply from the group's + inbox". `FrostSigningScreen` shows the decrypted reply, what it answers, and the warnings. +- `ChatMessage.applyInnerEvent`: a room-signed kind 13 draws nothing in the room's + transcript. The signing session's own lines already say the group signed something, and + a line naming the reply would reach members who are not admins. +- `InboxReplyPublisher`: on completion, on the proposer's device, wrap each seal and send + it with backoff (D10); file the group's copy as an outgoing message at once. **Send + again** in the conversation, for any admin, on a reply whose session completed. +- Recipient relays: the recipient's 10050 if known, else the publish set. This is new code + rather than reuse: the personal path's equivalent is commented out, and fixing that is + not this plan's. +- Tests: `InboxReplyJvmTest`, three admins with threshold 2 and an outside recipient — + - a reply proposed by A and signed by B reaches the recipient's relays as #2361 wraps, + and opens with the recipient's encryption key, and with their identity key when they + have no 10044; + - the group's copy opens on C's device as an outgoing message; + - each D12 refusal on its own: a mismatched group copy, a seal to a key that is not the + recipient's, an extra recipient, a forged 10044, a blank reply, a manifest for a + generation the signer does not hold. Each is declined with its reason, and the + proposer's device shows it; + - a member's device without the key reads the proposal as "A private reply" and learns + no text and no recipient. + Phase 1's kind 13 pin flips. + +### Phase 9: rotation (D14, D15) + +- `GovernanceFollowThrough` owes an inbox rotation after a removal, demotion, step-down or + promotion has landed, and starts it once `RotationHold` is clear, after any share + rotation the same change owes. +- **Rotate the inbox key** in the settings screen, and on a failed ceremony's screen. +- `InboxReply.build` reads the announced generation, never the newest held one. +- Tests: `InboxRotationJvmTest` — + - removing an admin rotates the key with nobody asked, the new 10044 is vouched and + signed unasked, the removed admin's device wipes its keys, and a message sent to the + new key does not open on it; + - a message to the old key still opens on the remaining admins' devices; + - a promoted admin holds only the new generation and sees an empty inbox with D15's + explanation; + - a reply proposed before the rotation and completed after it still verifies and opens; + - an inbox ceremony does not start while a share rotation is pending. + +### Phase 10: the record, and devices + +- Mark this plan built, with a *what the plan said / what it turned out to be* table, and + update the README row. +- A *since* note on [confederation.md](./confederation.md) D5: something *can* now be + encrypted to a group, through its inbox key, for a group that has one. D5's seal stays as + it is; whether a confederation should use the inbox is its own question. +- Device run, three desktop clients or emulators in one keyed group with threshold 2, a + fourth member who is not an admin, and an outside identity on a NIP-17 client that + supports #2361 (and, separately, one that does not): + 1. A sets up the inbox; the ceremony runs with nobody tapping; A and B sign the 10044 and + 10050; a public client shows the group's 10044. + 2. The outside identity writes to the group. A, B and C see it; D sees an inbox row + nowhere. + 3. B replies; A signs; the outside identity's client shows the reply as from the group. + 4. The same with the client that does not support #2361: confirm the warning was shown, + and record what that client does with the reply. + 5. Remove C as admin; the rotation runs unasked; C's device wipes; a new message opens on + A and B and not on C. + 6. Write to the group from an app with no NIP-4E at all; confirm the inbox counts it as + unopenable. + +--- + +## Risks + +| risk | what to do | +|---|---| +| #1647 or #2361 changes, or is not merged. #2361's main reviewer opposes it in base NIP-17 | the wire is one package with pinned tests (Phase 2); Phase 0 records the commits read. The flag stays off in release until they settle | +| a recipient's app does not read the seal's `n` tag, and the group's reply fails to open with nothing said on either side | D13's warning; the device run records what real clients do. The only fix that needs nobody else's cooperation is threshold ECDH (*Out of scope*) | +| senders whose apps ignore 10044 write to the group's npub, which nobody can open | counted and explained (D8), never hidden | +| every admin's device holds `e` in full: one compromised admin device reads the whole inbox, past and future, until the next rotation | inherent to "every admin can read". The rotation on every admin change, and **Rotate the inbox key**, are the mitigations, and D14 says what they cannot undo. It cannot sign a reply: that still takes `t` | +| members who are not admins see how many seals a reply has, so how many people it goes to | stated in D11. Padding the batch with decoy seals would hide it at the cost of signatures; not planned | +| ChillDKG at `t = 1` is refused by a future bitcoin-kmp, or behaves differently | Phase 0's check, kept as a test in `InboxKeyRitualJvmTest`, fails first | +| a `t = 1` key is mistaken for a signing key | D3: its own tables, and a test that no signing path can see it | +| trial decryption against every retired key, for every wrap | a NIP-44 decryption per key per wrap; a group that rotated twenty times tries twenty. Measure in Phase 6; retire keys past a horizon only if it shows | +| two admin devices both send a reply's wraps | only the proposer's sends unprompted (D10); **Send again** is a person's choice. The group's side collapses duplicates by rumor id | +| a group with a Bennu admin can never open an inbox | the ceremony's screen says why (D4) | +| the group's 10050 lists relays that drop gift wraps | the setup screen fills in the app's own DM relays, which take them | + +--- + +## Out of scope + +- **Threshold ECDH.** The one way to read mail sent to the group's *npub*, and to reply to + someone whose app ignores the `n` tag, with no help from anyone else: each share-holder + multiplies the sender's key by its share, and `t` of the results combine, by the same + Lagrange weights as a signature, into the conversation key nobody holds the secret for. + It needs the share scalars out of the signing library, the derivation's tweaks applied + to them, an interactive round per message, and its own plan. +- **The group starting a conversation.** A reply needs a conversation to answer. Writing + first is the same machinery with a recipient picker and is the natural next plan. +- **Handing a promoted admin the inbox's history** (D15). A group-signed decision to send + retired keys to a named admin, sealed to their host key. +- **Kind 15 (files) and reactions.** Filed and shown as "a message this screen cannot show + yet". +- **4454 and 4455** (D1), and a NIP-4E key for a person's own identity. +- **Notifications** for new inbox messages. +- **Chronicling** inbox announcements to late members: `ChronicleKinds` stays `NONE`. +- **The confederation's seal** moving onto inbox keys. +- **The personal path's ignored 10050** (`NostrNip17Dao.kt:186-218`). Noticed, not fixed + here. + +--- + +## Order and size + +| phase | rough size | depends on | +|---|---|---| +| 0 checks | a scratch test or two, this document | — | +| 1 pin | ~150 lines of test | 0 | +| 2 wire | ~600 main, ~500 test | 0 | +| 3 storage | ~400 main, ~200 test | 2 | +| 4 ceremony | ~1,200 main, ~600 test | 3 | +| 5 announcing | ~600 main, ~400 test | 4 | +| 6 reading | ~700 main, ~500 test | 3 and 5 (a key to subscribe with) | +| 7 inbox UI | ~1,300 main, ~300 test | 6 | +| 8 replying | ~1,100 main, ~700 test | 6 and 7 | +| 9 rotation | ~400 main, ~400 test | 5 and 8 | +| 10 record | docs and a device session | all | + +Phase 2 can be written beside Phase 1. Phases 6 and 7 can overlap once 6's repository flows +exist. Everything else is in order: the ceremony before anything it produces, the reading +before the replying, and rotation last, because it is the only phase that needs everything +else to rotate. + +--- + +## Checking the work + +```bash +./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest +``` + +```bash +./gradlew :composeApp:m3Audit +``` + +```bash +./gradlew check +``` + +`wallet-audit.sh` greps for retired kinds and sats: none of 10044, 10050, 13, 14, 1059 or +30390–30396 is retired. `brand-audit.sh` fails on a Bennu name outside a comment, which the +D4 explanation for a Bennu admin has to put in a comment or say without naming it ("an admin +whose app cannot take part"). From 877f5bbe587a24ee9b5d9633968336e0b3cf037d Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 01:27:02 +0200 Subject: [PATCH 05/16] test: a threshold-1 ceremony leaves every admin one secret, and a group-signed seal verifies (group-inbox, Phase 0) The five checks before any code. ChillDKG at t = 1 gives every participant the same secret, whose public key is the ceremony's; a batch of kind 13 events the quorum signs verifies as the room. The plan's kinds 30390-30396 collide with quartz's trusted lists, so the ceremony takes 30410-30416, which nothing else uses. Co-Authored-By: Claude Opus 5.5 --- .../compose/managers/InboxKeyPremiseTest.kt | 111 ++++++++++++++++++ .../managers/SignedGroupKeyStateTest.kt | 44 +++++++ docs/group-inbox.md | 20 +++- 3 files changed, 170 insertions(+), 5 deletions(-) create mode 100644 composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/InboxKeyPremiseTest.kt diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/InboxKeyPremiseTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/InboxKeyPremiseTest.kt new file mode 100644 index 00000000..c278b4a2 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/InboxKeyPremiseTest.kt @@ -0,0 +1,111 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip44Encryption.Nip44v2 +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.ByteVector64 +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import fr.acinq.bitcoin.crypto.dkg.chill.ChillDKG +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * The premise docs/group-inbox.md (D2) rests on, run against real ChillDKG: a ceremony at + * threshold 1 leaves every participant holding the *same* secret, and that secret is the + * discrete log of the ceremony's threshold public key. + * + * At `t = 1` every participant's polynomial is a constant, so every share is the sum of + * everyone's constants. If the library ever refuses `t = 1`, or hands out different shares, + * the inbox key cannot be made this way and the plan's fallback (a `t = n` ceremony and a + * reveal round) applies instead. + */ +class InboxKeyPremiseTest { + private val admins = listOf( + "1c0ffee0000000000000000000000000000000000000000000000000000000a1", + "2badc0de0000000000000000000000000000000000000000000000000000005b", + "3deadbee00000000000000000000000000000000000000000000000000000c37", + ).map { Admin(it.hexToBytes()) } + + @Test + fun `a threshold-1 ceremony leaves every admin the same secret`() { + val outputs = ceremony(admins) + + val secrets = outputs.map { assertNotNull(it.secretShare).value.toByteArray().toList() } + assertEquals(1, secrets.distinct().size, "the admins came out of the ceremony holding different secrets") + } + + @Test + fun `that secret is the key the ceremony announces`() { + val outputs = ceremony(admins) + + outputs.forEach { output -> + val secret = assertNotNull(output.secretShare) + assertEquals(assertNotNull(output.thresholdPublicKey), secret.publicKey()) + } + } + + @Test + fun `a NIP-44 conversation with the inbox key works whichever way round it is computed`() { + // The key goes in a 10044 as an x-only hex key, which drops the parity. A sender + // computes ECDH against the even point; the admins compute it with `e`, whatever the + // ceremony's key's parity was. Both land on the same x, which is all NIP-44 uses. + val outputs = ceremony(admins) + val e = assertNotNull(outputs.first().secretShare) + val inboxXOnly = e.publicKey().xOnly().value.toByteArray() + + val sender = PrivateKey(Crypto.sha256("a stranger".encodeToByteArray())) + val senderXOnly = sender.publicKey().xOnly().value.toByteArray() + + val nip44 = Nip44v2() + val fromSender = nip44.computeConversationKey(sender.value.toByteArray(), inboxXOnly) + val fromAdmins = nip44.computeConversationKey(e.value.toByteArray(), senderXOnly) + assertContentEquals(fromSender, fromAdmins) + + val payload = nip44.encrypt("hello, group", fromSender).encodePayload() + assertEquals("hello, group", nip44.decrypt(payload, fromAdmins)) + } + + /** One ceremony, every step in host-key order, as `ChillDkgRitualOrderingTest` runs one. */ + private fun ceremony(members: List): List { + val threshold = 1 + val ordered = members.sortedBy { it.hostPublicKey.toHex() } + val hostPublicKeys = ordered.map { it.hostPublicKey } + + val step1 = ordered.map { admin -> + ChillDKG.participantStep1(admin.hostSecretKey, hostPublicKeys, threshold, admin.round1Random) + } + val coordinator = ChillDKG.coordinatorStep1(step1.map { it.message }, hostPublicKeys, threshold) + assertTrue(coordinator.fault.isOk, "coordinator round 1 faulted") + + val step2 = ordered.mapIndexed { index, admin -> + ChillDKG.participantStep2(admin.hostSecretKey, step1[index].state, coordinator.message, admin.round2AuxRandom) + .also { assertTrue(it.fault.isOk, "round 2 faulted") } + } + val certified = ChillDKG.coordinatorFinalize( + coordinator.state, + step2.map { ByteVector64(it.certEqSignature) }, + threshold, + ) + assertTrue(certified.fault.isOk, "certificate faulted") + + return step2.map { result -> + ChillDKG.participantFinalize(result.state, certified.certificate, ordered.size, threshold) + .also { assertTrue(it.fault.isOk, "finalize faulted") } + } + } + + private class Admin(nostrPrivateKey: ByteArray) { + val hostSecretKey = ChillDkgRitualManager.deriveHostSecretKey(nostrPrivateKey) + val hostPublicKey: PublicKey = ChillDKG.hostPublicKey(hostSecretKey) + val round1Random = ByteVector32(Crypto.sha256(nostrPrivateKey + 1)) + val round2AuxRandom = ByteVector32(Crypto.sha256(nostrPrivateKey + 2)) + } + + private companion object { + fun String.hexToBytes(): ByteArray = chunked(2).map { it.toInt(16).toByte() }.toByteArray() + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SignedGroupKeyStateTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SignedGroupKeyStateTest.kt index 1cf6f4c0..018e8b6c 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SignedGroupKeyStateTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SignedGroupKeyStateTest.kt @@ -2,6 +2,7 @@ package mobi.giza.compose.managers import androidx.room3.Room import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher @@ -1284,6 +1285,49 @@ class SignedGroupKeyStateTest { } } + /** + * The premise of docs/group-inbox.md's replies (Phase 0, check 4): a NIP-17 seal is + * signed by its author's identity, and a group's identity is its room. A batch of kind + * 13 events the quorum signs has to verify as the room, or no recipient's app would + * accept a reply from the group's inbox, whatever was sealed inside it. + */ + @Test + fun `a batch of seals the group signs verifies as the room's own`() = runBlocking { + val creator = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + + val inboxKey = "a".repeat(64) + val seals = listOf("first", "second").map { ciphertext -> + EventTemplate( + createdAt = 1_700_000_000L, + kind = 13, + tags = arrayOf(arrayOf("n", inboxKey)), + content = ciphertext, + ) + } + val session = FrostSigningManager.proposeSigningBatch( + database = creator.db, + localChatRoom = creator.room, + userPublicKey = creator.publicKey, + events = seals, + ) + pump(creator, other) + FrostSigningManager.approve(other.db, other.room, session.id) + pump(creator, other) + + listOf(creator, other).forEach { device -> + val signed = device.items(session.id).map { + assertNotNull(device.db.groupSignedEventDao().getById(it.eventId)) + } + assertEquals(2, signed.size) + signed.forEach { seal -> + assertEquals(13, seal.kind) + assertEquals(adminRoomId, seal.publicKey) + assertTrue(seal.verifies(), "a seal the group signed must verify as the room") + } + } + } + @Test fun `a proposer cannot choose the key the group signs as`() = runBlocking { val other = device(members[1], signerIndex = 1) diff --git a/docs/group-inbox.md b/docs/group-inbox.md index 3c484e05..d9ebbf88 100644 --- a/docs/group-inbox.md +++ b/docs/group-inbox.md @@ -175,9 +175,9 @@ one admin can sign with alone would be found there. So the inbox ceremony is kep the way the confederation's is: - **Kinds:** a family of seven, the same shape as 30310–30316 (proposal, host key, round 1, - coordinator round 1, round 2, certificate, failure). Candidate numbers are 30390–30396. - Phase 0 checks them against the NIP kind table, quartz, Curare, Bennu and `RetiredKinds`, - as confederation Phase 0 did for 9430–9433. New kinds also keep a Bennu admin's device + coordinator round 1, round 2, certificate, failure). 30410–30416, checked in Phase 0 against the NIP + kind table, quartz, Curare, Bennu and `RetiredKinds`, as confederation Phase 0 did for + 9430–9433. New kinds also keep a Bennu admin's device from mistaking the ceremony for a subgroup's, which a 30310 with a subset of `p` tags in a Marmot room would be to it. - **Tables:** `InboxKeyCeremony` and `InboxKeyCeremonyMessage` (the ceremony's inputs and @@ -493,7 +493,7 @@ This document and its row in [README.md](./README.md). Then, before any code: key's discrete log (`secretShare·G == thresholdPublicKey`). If the library refuses `t = 1` or the shares differ, stop: the fallback is a `t = n` ceremony followed by a reveal round to host keys, checked against `publicShares`, and D2 and Phase 4 change. -2. **Kinds** (D3). 30390–30396 against the NIP README's table, quartz 2.20.1, Curare, +2. **Kinds** (D3). A family of seven against the NIP README's table, quartz 2.20.1, Curare, Bennu and `RetiredKinds`. Record the result here. 3. **quartz.** That `Nip44.v2.computeConversationKey` / `encrypt` / `decrypt` take an arbitrary secret and public key; that `EncryptionKeyListEvent` parses #1647's form; @@ -506,6 +506,16 @@ This document and its row in [README.md](./README.md). Then, before any code: *The specification, as it stands*. If #2361 has moved the `n` tag or added a second `p`, the wire phase follows it. +**Done**, on 2026-11-22: + +| check | result | +|---|---| +| 1. `t = 1` ChillDKG | holds. `InboxKeyPremiseTest` 3/3: three admins finish with one secret, that secret times `G` is the ceremony's threshold key, and NIP-44 between a stranger and the x-only inbox key agrees from both sides whatever the key's parity | +| 2. kinds | the plan's 30390–30396 **collide**: quartz 2.20.1 has 30392–30395 (experimental trusted lists). **30410–30416** are in none of the NIP README's table (whose 30300–30499 rows are 30311–30315, 30382–30384, 30402–30403), quartz, Curare at `dc1895ee`, Bennu at `2db6dde5`, `RetiredKinds` or the app. D3 now says 30410–30416. (The ceremony's own 30311–30315 and the confederation's 30382–30385 share numbers with public kinds; they travel only inside encryption, which is why that never mattered, and why it would not here either. A clean range costs nothing.) | +| 3. quartz | `Nip44v2.computeConversationKey`, `encrypt`, `encryptWithNonce` and `decrypt` take any secret and any x-only key. `EncryptionKeyListEvent` (kind 10044, `encryptionKey()`, `build(pubkey)`) and `KeyTag` read #1647's `["n", key]`. `EventTemplate(createdAt, 13, tags, content)` goes through `proposeSigningBatch` unchanged | +| 4. the premise | holds. `SignedGroupKeyStateTest`'s `a batch of seals the group signs verifies as the room's own`: two kind 13 events, signed by a quorum, authored by the room and passing `verifies()` on both devices | +| 5. the spec | #1647 read at its `per-device-keys` head (5 commits, last pushed 2025-10-08); #2361 at `bee7463` (2026-06-02). Neither merged. #2361 has one `p` on the wrap and the `n` on the seal, as this plan has it | + ### Phase 1: pin today Tests of *What Giza does today*, written to pass now and flipped on purpose later: @@ -799,6 +809,6 @@ else to rotate. ``` `wallet-audit.sh` greps for retired kinds and sats: none of 10044, 10050, 13, 14, 1059 or -30390–30396 is retired. `brand-audit.sh` fails on a Bennu name outside a comment, which the +30410–30416 is retired. `brand-audit.sh` fails on a Bennu name outside a comment, which the D4 explanation for a Bennu admin has to put in a comment or say without naming it ("an admin whose app cannot take part"). From dd16df9c408cec00aed294ab4f29832066d8f274 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 01:27:53 +0200 Subject: [PATCH 06/16] test: pin what a group's inbox events do today (group-inbox, Phase 1) A peer's kind 10044 or kind 13 proposal reaches the member as a bare number and nothing declines it; the only gift wraps the app asks for are its identity's own. Phases 5, 6 and 8 flip these. Co-Authored-By: Claude Opus 5.5 --- .../giza/compose/text/ProposedEventTest.kt | 11 +++ .../managers/GroupInboxTodayJvmTest.kt | 74 +++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt index 03bf3ef3..3ae38941 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt @@ -111,6 +111,17 @@ class ProposedEventTest { ) } + /** + * docs/group-inbox.md, Phase 1: the events a group's inbox is made of are, today, kinds + * the app has no words for. Phases 5 and 8 give them words. + */ + @Test + fun `an inbox key, a DM relay list and a seal are said by their numbers today`() { + listOf(10044, 10050, 13).forEach { kind -> + assertEquals("Event of kind $kind", ProposedEvent.summarize(event(kind)).label) + } + } + private fun event( kind: Int, tags: Array> = emptyArray(), diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt new file mode 100644 index 00000000..f103565e --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt @@ -0,0 +1,74 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.nostr.frost.FrostSigningEvents +import mobi.giza.compose.text.ProposedEvent + +/** + * What Giza does today with the events a group's inbox is made of (docs/group-inbox.md, + * Phase 1). Written to pass now and flipped on purpose by the phase that changes each: + * + * - a peer's proposal to sign a kind 10044 (an encryption key) or a kind 13 (a NIP-17 seal) + * reaches the member as a bare number, and nothing declines it. Phase 5 and Phase 8 put a + * refusal in front of each; + * - the only gift wraps the app asks relays for are its own identity's. Phase 6 adds the + * group's. + */ +class GroupInboxTodayJvmTest { + private val harness = SigningProposalHarness() + private val alice = harness.members[0] + private val bob = harness.members[1] + + @AfterTest + fun close() = harness.close() + + private fun proposeAndDeliver(kind: Int, tags: Array>, content: String) = runBlocking { + val sent = harness.propose(alice) { db, room -> + FrostSigningManager.proposeSigningBatch( + db, room, alice, + events = listOf(EventTemplate(1_700_000_000L, kind, tags, content)), + ) + } + harness.deliver(sent, bob) + sent + } + + private fun assertPutToTheMemberByNumber(sent: SigningProposalHarness.Sent, kind: Int) = runBlocking { + val session = assertNotNull(harness.db.frostSigningSessionDao().getSessionById(sent.session.id)) + assertNull(session.signDeclinedAt, "nothing declines it today") + assertTrue(FrostSigningManager.isAwaitingApproval(session, harness.db.frostSigningSessionDao().getItems(session.id))) + assertEquals(emptyList(), harness.queued(FrostSigningEvents.DECLINE)) + + val item = harness.db.frostSigningSessionDao().getItems(session.id).single() + assertEquals("Event of kind $kind", ProposedEvent.summarize(Event.fromJson(item.unsignedEventJson)).label) + } + + @Test + fun `a peer's inbox key reaches the member as a number, and can be signed`() { + val sent = proposeAndDeliver(10044, arrayOf(arrayOf("n", "e".repeat(64))), "") + assertPutToTheMemberByNumber(sent, 10044) + } + + @Test + fun `a peer's sealed ciphertext reaches the member as a number, and can be signed`() { + // The member is asked to sign bytes it cannot read: the rubber stamp + // docs/giza-wallet-removal.md says a Giza device must not be. Phase 8 declines it. + val sent = proposeAndDeliver(13, arrayOf(arrayOf("n", "e".repeat(64))), "AnOpaqueCiphertext") + assertPutToTheMemberByNumber(sent, 13) + } + + @Test + fun `the only gift wraps asked for are the identity's own`() { + val filter = LiveSubscriptionManager.giftWrapFilter(alice) + assertEquals(listOf(1059), filter.kinds) + assertEquals(mapOf("p" to listOf(alice)), filter.tags) + } +} From e215cff843ee564795789eef0e17d10abb89e633 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 01:32:42 +0200 Subject: [PATCH 07/16] feat: the group inbox's wire, in one package (group-inbox, Phase 2) nostr/inbox: the inbox key ceremony's kinds (30410-30416) and tags; the group's 10044 and 10050 through quartz's own events, with the strict shape a group signs; NIP-17 seals and gift wraps with a decoupled key, built by hand per nostr-protocol/nips#2361 because quartz's encrypt to the key they tag; the reply manifest a signer reads, sealed to the inbox key; and the conversation id. InboxWireTest checks every layer, including both directions against quartz's own wraps. Co-Authored-By: Claude Opus 5.5 --- .../compose/nostr/inbox/InboxAnnouncement.kt | 85 ++++++ .../compose/nostr/inbox/InboxConversation.kt | 29 ++ .../nostr/inbox/InboxKeyRitualEvents.kt | 86 ++++++ .../compose/nostr/inbox/InboxReplyManifest.kt | 98 +++++++ .../giza/compose/nostr/inbox/InboxSeal.kt | 105 +++++++ .../giza/compose/nostr/inbox/InboxWire.kt | 41 +++ .../giza/compose/nostr/inbox/InboxWrap.kt | 70 +++++ .../giza/compose/nostr/inbox/InboxWireTest.kt | 264 ++++++++++++++++++ 8 files changed, 778 insertions(+) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxAnnouncement.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxConversation.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxKeyRitualEvents.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxReplyManifest.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxSeal.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxWire.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxWrap.kt create mode 100644 composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/inbox/InboxWireTest.kt diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxAnnouncement.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxAnnouncement.kt new file mode 100644 index 00000000..30829f34 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxAnnouncement.kt @@ -0,0 +1,85 @@ +package mobi.giza.compose.nostr.inbox + +import com.vitorpamplona.quartz.experimental.decoupling.setup.EncryptionKeyListEvent +import com.vitorpamplona.quartz.experimental.decoupling.setup.tags.KeyTag +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip17Dm.settings.DmRelayListEvent +import com.vitorpamplona.quartz.nip17Dm.settings.tags.RelayTag +import mobi.giza.compose.nostr.RelayUrlInput + +/** + * The two public events that make a group writable to (docs/group-inbox.md, D5 and D6), both + * signed by the group's quorum: + * + * - a kind **10044**, NIP-4E's announcement (nostr-protocol/nips#1647): `[["n", E]]` and nothing + * else, where `E` is the inbox key; + * - a kind **10050**, NIP-17's DM relay list: where senders should put what they write. + * + * Read by quartz's own [EncryptionKeyListEvent] and [DmRelayListEvent], so the group's events + * parse the way every other client's do. + */ +object InboxAnnouncement { + const val KEY_KIND = EncryptionKeyListEvent.KIND + const val RELAYS_KIND = DmRelayListEvent.KIND + + /** The group's 10044, naming [inboxKey] alone. */ + fun keyTemplate(inboxKey: HexKey, createdAt: Long): EventTemplate { + require(InboxWire.isHex32(inboxKey)) { "an inbox key is a 32-byte x-only key" } + val built = EncryptionKeyListEvent.build(inboxKey, createdAt) + return EventTemplate(built.createdAt, built.kind, built.tags, built.content) + } + + /** The group's 10050, listing [relays]. */ + fun relaysTemplate(relays: List, createdAt: Long): EventTemplate { + require(relays.isNotEmpty()) { "an inbox nobody can deliver to is not an inbox" } + return EventTemplate(createdAt, RELAYS_KIND, DmRelayListEvent.createTagArray(relays), "") + } + + /** + * The key a 10044 announces, read as any NIP-4E client reads it: the first well-formed `n`. + * For someone else's announcement, which may carry more than this app writes. + */ + fun announcedKeyOf(event: Event): HexKey? { + if (event.kind != KEY_KIND) return null + return event.tags.firstNotNullOfOrNull(KeyTag::parse)?.pubkey + } + + /** + * The key a group's own 10044 announces, or null if [event] is not shaped the way this app + * writes one: exactly one tag, an `n` with a key and no nonce, and no content. A signer + * refuses anything else (docs/group-inbox.md, D5): a second `n`, or a legacy nonce, would be + * the group announcing something nobody agreed to. + */ + fun groupKeyOf(event: Event): HexKey? = groupKeyOf(event.kind, event.tags, event.content) + + fun groupKeyOf(kind: Int, tags: Array>, content: String): HexKey? { + if (kind != KEY_KIND || content.isNotEmpty()) return null + val tag = tags.singleOrNull() ?: return null + if (tag.size != 2) return null + val key = KeyTag.parse(tag) ?: return null + return key.pubkey.takeIf { key.nonce == null && tag[1] == key.pubkey } + } + + /** + * The relays a group's 10050 lists, or null if [event] is not one a group should sign: no + * relays, anything but `relay` tags, content, or a relay a stranger could not reach + * ([RelayUrlInput.relayUrlOrNull]: `wss://`, not loopback). + */ + fun groupRelaysOf(event: Event): List? = groupRelaysOf(event.kind, event.tags, event.content) + + fun groupRelaysOf(kind: Int, tags: Array>, content: String): List? { + if (kind != RELAYS_KIND || content.isNotEmpty() || tags.isEmpty()) return null + val relays = tags.map { tag -> + if (tag.size < 2 || tag[0] != RelayTag.TAG_NAME) return null + RelayUrlInput.relayUrlOrNull(tag[1]) ?: return null + } + return relays.distinct() + } + + /** The relays anyone's 10050 lists, as NIP-17 senders read them. */ + fun announcedRelaysOf(event: Event): List = + if (event.kind != RELAYS_KIND) emptyList() else event.tags.mapNotNull(RelayTag::parse) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxConversation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxConversation.kt new file mode 100644 index 00000000..62bde27b --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxConversation.kt @@ -0,0 +1,29 @@ +package mobi.giza.compose.nostr.inbox + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Crypto +import mobi.giza.compose.extensions.toHex + +/** + * Which conversation a message in a group's inbox belongs to (docs/group-inbox.md, D8). + * + * NIP-17 defines a chat as the set of its author and its `p` tags. The group is in every one of + * its own, so it is left out: a message from Alice to the group and the group's reply to Alice + * are both the conversation `{Alice}`, whichever way round they were written. + */ +object InboxConversation { + /** The people in [rumor]'s conversation other than [group], sorted and without repeats. */ + fun participantsOf(rumor: Event, group: HexKey): List = + (listOf(rumor.pubKey) + rumor.tags.filter { it.size >= 2 && it[0] == "p" }.map { it[1] }) + .map { it.lowercase() } + .filter { it != group.lowercase() && InboxWire.isHex32(it) } + .distinct() + .sorted() + + /** A stable id for a set of [participants]: the same set gives the same id on every device. */ + fun idOf(participants: List): String = + Crypto.sha256(participants.map { it.lowercase() }.distinct().sorted().joinToString(",").encodeToByteArray()).toHex() + + fun idOf(rumor: Event, group: HexKey): String = idOf(participantsOf(rumor, group)) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxKeyRitualEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxKeyRitualEvents.kt new file mode 100644 index 00000000..dcbdd777 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxKeyRitualEvents.kt @@ -0,0 +1,86 @@ +package mobi.giza.compose.nostr.inbox + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind + +/** + * The group's inbox key ceremony on the wire (docs/group-inbox.md, D2 and D3): a ChillDKG + * ceremony at threshold 1 over the room's admins, carried as MLS inner events in the group's + * own Marmot room. + * + * The same seven steps as the group's signing ceremony ([mobi.giza.compose.nostr.dkg.DkgRitualEvents]), + * on kinds of their own. A `t = 1` key must never be filed where a signing key could be found, + * and a device that knows only the signing ceremony's kinds -- an older build, or a Bennu + * admin's -- would take a 30310 over a subset of the room for a subgroup's ceremony. On kinds it + * does not know it takes it for nothing. + * + * Rumor kinds: they only ever travel inside the group's encryption, so the replaceable range + * means nothing for them. 30410-30416 are in no NIP, quartz, Curare or Bennu (Phase 0). + * + * ``` + * coordinator --[ 30410 proposal ]-> the room "let's make the inbox key", p-tagging the admins + * admin --[ 30411 host key ]-> the room host pubkey + * admin --[ 30412 round 1 ]-> the room pmsg1: a contribution, encrypted to the admins' host keys + * coordinator --[ 30413 coord round 1 ]-> the room cmsg1 + * admin --[ 30414 round 2 ]-> the room CertEq signature + * coordinator --[ 30415 certificate ]-> the room cmsg2 + * anyone --[ 30416 failure ]-> the room abort, with a reason + * ``` + * + * Every member of the room receives all of it. ChillDKG encrypts each contribution to its + * recipients' host keys, so a member who is not an admin learns the inbox's public key and + * nothing else. + */ +object InboxKeyRitualEvents { + const val PROPOSAL: Kind = 30410 + const val HOST_KEY: Kind = 30411 + const val ROUND_1: Kind = 30412 + const val COORDINATOR_ROUND_1: Kind = 30413 + const val ROUND_2: Kind = 30414 + const val CERTIFICATE: Kind = 30415 + const val FAILURE: Kind = 30416 + + val ALL: Set = setOf(PROPOSAL, HOST_KEY, ROUND_1, COORDINATOR_ROUND_1, ROUND_2, CERTIFICATE, FAILURE) + + fun isInboxKeyKind(kind: Kind): Boolean = kind in ALL + + /** Binds a message to one ceremony, so a late one from an abandoned attempt is dropped. */ + const val SESSION_TAG = "inbox_key_session" + + /** Which generation of the room's inbox key the ceremony makes. On the proposal only. */ + const val GENERATION_TAG = "inbox_key_generation" + + /** The ceremony's threshold. Always 1; carried so a device can refuse anything else. */ + const val THRESHOLD_TAG = "inbox_key_threshold" + + const val THRESHOLD = 1 + + fun assembleTags( + sessionId: String, + generation: Int? = null, + participants: List = emptyList(), + ): Array> = buildList { + add(arrayOf(SESSION_TAG, sessionId)) + generation?.let { + add(arrayOf(GENERATION_TAG, it.toString())) + add(arrayOf(THRESHOLD_TAG, THRESHOLD.toString())) + } + participants.forEach { add(arrayOf("p", it)) } + }.toTypedArray() + + fun parseSessionId(tags: Array>): String? = + tags.firstOrNull { it.size >= 2 && it[0] == SESSION_TAG }?.get(1)?.takeIf(InboxWire::isHex32) + + fun parseGeneration(tags: Array>): Int? = + tags.firstOrNull { it.size >= 2 && it[0] == GENERATION_TAG }?.get(1)?.toIntOrNull()?.takeIf { it >= 0 } + + fun parseThreshold(tags: Array>): Int? = + tags.firstOrNull { it.size >= 2 && it[0] == THRESHOLD_TAG }?.get(1)?.toIntOrNull() + + /** The admins a proposal names, sorted and without repeats; null if any is malformed. */ + fun parseParticipants(tags: Array>): List? { + val named = tags.filter { it.isNotEmpty() && it[0] == "p" }.map { it.getOrNull(1) } + if (named.any { !InboxWire.isHex32(it) }) return null + return named.filterNotNull().distinct().sorted() + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxReplyManifest.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxReplyManifest.kt new file mode 100644 index 00000000..b02ec95c --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxReplyManifest.kt @@ -0,0 +1,98 @@ +package mobi.giza.compose.nostr.inbox + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonArray +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put + +/** + * What a signer of a reply needs beside the seals themselves (docs/group-inbox.md, D11): which + * seal is for whom, the key each was sealed to, and the evidence for that key. + * + * It rides the FROST proposal as an `inbox_manifest` tag, encrypted to the inbox key, so a + * member of the room who is not an admin sees how many seals the group is signing and nothing + * else: not the reply, and not who it goes to. + * + * The encoding is this app's own and is decoded strictly: a manifest with a field it does not + * know, or one missing, is no manifest, and a reply carrying one is declined. + */ +data class InboxReplyManifest( + /** The inbox key generation every seal is sealed from. */ + val generation: Int, + val seals: List, + /** Which of [seals] is the group's own copy, sealed to the inbox key itself. */ + val groupCopy: Int, +) { + data class Entry( + val recipient: HexKey, + /** The key the seal is encrypted to. */ + val key: HexKey, + /** The recipient's signed 10044, as JSON, when [key] came from one; null when [key] is their identity. */ + val announcement: String?, + ) + + fun encode(): String = buildJsonObject { + put("v", 1) + put("generation", generation) + put("seals", buildJsonArray { + seals.forEach { entry -> + add(buildJsonObject { + put("recipient", entry.recipient) + put("key", entry.key) + put("announcement", entry.announcement?.let(::JsonPrimitive) ?: JsonNull) + }) + } + }) + put("group_copy", groupCopy) + }.toString() + + /** Encrypted under `conv(e, E)`: only a holder of this generation's key reads it. */ + fun seal(inboxSecret: ByteArray): String = + InboxWire.encrypt(encode(), selfConversationKey(inboxSecret)) + + companion object { + const val TAG_NAME = "inbox_manifest" + + private val json = Json { ignoreUnknownKeys = false } + private val TOP = setOf("v", "generation", "seals", "group_copy") + private val ENTRY = setOf("recipient", "key", "announcement") + + fun tag(sealed: String): Array = arrayOf(TAG_NAME, sealed) + + /** The sealed manifest among a proposal's tags, or null. More than one is none. */ + fun sealedIn(tags: Array>): String? = + tags.filter { it.isNotEmpty() && it[0] == TAG_NAME }.singleOrNull()?.getOrNull(1)?.ifBlank { null } + + fun selfConversationKey(inboxSecret: ByteArray): ByteArray = + InboxWire.conversationKey(inboxSecret, InboxWire.publicKeyOf(inboxSecret)) + + /** [sealed] opened with [inboxSecret], or null if that key does not open it or it is not a manifest. */ + fun open(sealed: String, inboxSecret: ByteArray): InboxReplyManifest? = + InboxWire.decrypt(sealed, selfConversationKey(inboxSecret))?.let(::decode) + + fun decode(text: String): InboxReplyManifest? = runCatching { + val obj = json.parseToJsonElement(text) as JsonObject + require(obj.keys == TOP) + require((obj["v"] as JsonPrimitive).content == "1") + val generation = (obj["generation"] as JsonPrimitive).content.toInt().also { require(it >= 0) } + val seals = (obj["seals"] as JsonArray).map { element -> + val entry = element as JsonObject + require(entry.keys == ENTRY) + val announcement = entry["announcement"] + Entry( + recipient = (entry["recipient"] as JsonPrimitive).content.also { require(InboxWire.isHex32(it)) }, + key = (entry["key"] as JsonPrimitive).content.also { require(InboxWire.isHex32(it)) }, + announcement = if (announcement is JsonNull) null else (announcement as JsonPrimitive).also { require(it.isString) }.content, + ) + } + val groupCopy = (obj["group_copy"] as JsonPrimitive).content.toInt() + require(groupCopy in seals.indices) + InboxReplyManifest(generation, seals, groupCopy) + }.getOrNull() + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxSeal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxSeal.kt new file mode 100644 index 00000000..c4738c50 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxSeal.kt @@ -0,0 +1,105 @@ +package mobi.giza.compose.nostr.inbox + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.crypto.verify +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip59Giftwrap.rumors.Rumor +import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent + +/** + * A NIP-17 seal with a decoupled encryption key, as nostr-protocol/nips#2361 has it + * (docs/group-inbox.md): + * + * ``` + * seal (13) pubkey = the sender's identity signed by the identity + * tags = [["n", the sender's encryption key]] when it is not the identity + * content = nip44(rumor, conv(sender's encryption secret, receiver's encryption key)) + * ``` + * + * The split is what lets a group answer at all: the admins hold the encryption secret and can + * write the content; only the quorum can sign the seal. A group's seal is therefore built here + * as an unsigned template, and signed by the FROST session. + */ +object InboxSeal { + const val KIND = SealEvent.KIND + const val ENCRYPTION_KEY_TAG = "n" + + /** + * The unsigned seal of [rumor] from the inbox key [inboxSecret] to [recipientEncryptionKey]: + * the recipient's announced 10044 key, their identity if they announce none, or the inbox + * key itself for the group's own copy. + */ + fun template( + rumor: Event, + inboxSecret: ByteArray, + recipientEncryptionKey: HexKey, + createdAt: Long, + ): EventTemplate = EventTemplate( + createdAt = createdAt, + kind = KIND, + tags = arrayOf(arrayOf(ENCRYPTION_KEY_TAG, InboxWire.publicKeyOf(inboxSecret))), + content = InboxWire.encrypt(rumorJson(rumor), InboxWire.conversationKey(inboxSecret, recipientEncryptionKey)), + ) + + /** The rumor as NIP-59 puts it inside a seal: its id, no signature. */ + fun rumorJson(rumor: Event): String = Rumor.toJson(Rumor.create(rumor)) + + /** The `n` a seal names, or null when it names none or a malformed one. */ + fun encryptionKeyOf(tags: Array>): HexKey? { + val named = tags.filter { it.isNotEmpty() && it[0] == ENCRYPTION_KEY_TAG } + if (named.size != 1) return null + return named.single().getOrNull(1)?.lowercase()?.takeIf(InboxWire::isHex32) + } + + /** + * Which key the sender encrypted with, by #2361's rule and quartz's: the seal's `n` if it + * has one, else the key the sender's own 10044 announces if this device has seen it, else + * the sender's identity. + */ + fun senderEncryptionKey(seal: Event, senderAnnouncedKey: HexKey?): HexKey = + encryptionKeyOf(seal.tags) ?: senderAnnouncedKey ?: seal.pubKey + + data class Opened(val seal: Event, val rumor: Event, val senderEncryptionKey: HexKey) + + /** + * [seal], received, opened with [receiverSecret]. Null for every way that can fail: not a + * seal, a signature that does not verify, a key that does not open it, a rumor that is not + * one, or a rumor claiming an author the seal does not have -- NIP-17's impersonation check, + * the one thing that makes the seal's signature mean the rumor's author. + * + * If the seal names no `n`, [senderAnnouncedKey] is tried before the identity, and then the + * identity, since a sender's app may decouple without writing the tag. + */ + fun open(seal: Event, receiverSecret: ByteArray, senderAnnouncedKey: HexKey? = null): Opened? { + if (seal.kind != KIND || !seal.verify()) return null + val candidates = buildList { + encryptionKeyOf(seal.tags)?.let(::add) + senderAnnouncedKey?.let(::add) + add(seal.pubKey) + }.distinct() + for (key in candidates) { + val rumor = rumorInside(seal.content, InboxWire.conversationKey(receiverSecret, key), seal.pubKey) ?: continue + return Opened(seal, rumor, key) + } + return null + } + + /** + * The rumor inside a seal's [content] under [conversationKey], with its id computed rather + * than trusted, or null. [author] is the seal's pubkey: a rumor claiming anyone else is + * refused here, so no caller can forget to. + */ + fun rumorInside(content: String, conversationKey: ByteArray, author: HexKey): Event? { + val json = InboxWire.decrypt(content, conversationKey) ?: return null + val rumor = runCatching { Rumor.fromJson(json) }.getOrNull() ?: return null + if (rumor.pubKey != author) return null + val kind = rumor.kind ?: return null + val createdAt = rumor.createdAt ?: return null + val tags = rumor.tags ?: emptyArray() + val content = rumor.content ?: "" + val id = EventHasher.hashId(author, createdAt, kind, tags, content) + return Event(id, author, createdAt, kind, tags, content, "") + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxWire.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxWire.kt new file mode 100644 index 00000000..5c82137d --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxWire.kt @@ -0,0 +1,41 @@ +package mobi.giza.compose.nostr.inbox + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip44Encryption.Nip44v2 +import fr.acinq.bitcoin.PrivateKey +import mobi.giza.compose.extensions.toHex + +/** + * The arithmetic every piece of the group's inbox shares (docs/group-inbox.md). + * + * NIP-4E's keys are x-only, as every nostr key is. The inbox key's secret `e` comes out of a + * ChillDKG ceremony whose public key may have either parity; NIP-44 uses only the x of the + * shared point, which is the same for `e` and `-e`, so `e` is used as it is and nobody negates + * anything. `InboxKeyPremiseTest` checks that from both sides. + */ +object InboxWire { + /** One instance: [Nip44v2.computeConversationKey] is pure, and nothing here uses its cache. */ + val nip44 = Nip44v2() + + fun isHex32(hex: String?): Boolean = + hex != null && hex.length == 64 && hex.all { it in '0'..'9' || it in 'a'..'f' } + + /** `E`, x-only, lowercase hex, as it goes in a 10044's `n` and a seal's `n`. */ + fun publicKeyOf(secret: ByteArray): HexKey = PrivateKey(secret).publicKey().xOnly().value.toHex() + + /** + * The NIP-44 conversation key between [secret] and [publicKey], uncached: an inbox key is + * held by several admins and retired on rotation, and a process-wide cache of conversation + * keys would keep a retired one alive in memory for no gain. + */ + fun conversationKey(secret: ByteArray, publicKey: HexKey): ByteArray = + nip44.computeConversationKey(secret, publicKey.hexToByteArray()) + + fun encrypt(plaintext: String, conversationKey: ByteArray): String = + nip44.encrypt(plaintext, conversationKey).encodePayload() + + /** [payload] opened under [conversationKey], or null for any way that can fail. */ + fun decrypt(payload: String, conversationKey: ByteArray): String? = + runCatching { nip44.decrypt(payload, conversationKey) }.getOrNull() +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxWrap.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxWrap.kt new file mode 100644 index 00000000..48201982 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/inbox/InboxWrap.kt @@ -0,0 +1,70 @@ +package mobi.giza.compose.nostr.inbox + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.crypto.verify +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync +import com.vitorpamplona.quartz.nip01Core.tags.people.PTag +import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent +import com.vitorpamplona.quartz.utils.TimeUtils + +/** + * A NIP-59 gift wrap with a decoupled encryption key, as nostr-protocol/nips#2361 has it: + * + * ``` + * gift wrap (1059) pubkey = a fresh random key + * tags = [["p", the recipient's identity, relay]] + * content = nip44(seal, conv(wrapper secret, the recipient's encryption key)) + * ``` + * + * quartz's [GiftWrapEvent.create] encrypts to the key it tags, which is right when they are the + * same and wrong here, so the wrap is built by hand. The `p` stays the identity: it is how a + * recipient's relays and apps find their mail, and it names nothing about which key opens it. + * That is also why a reader with several keys has to try them ([open]). + */ +object InboxWrap { + const val KIND = GiftWrapEvent.KIND + + /** + * [seal], already signed, wrapped for [recipientIdentity] under [recipientEncryptionKey] with a + * throwaway key nobody keeps. + */ + fun wrap( + seal: Event, + recipientIdentity: HexKey, + recipientEncryptionKey: HexKey, + relayHint: NormalizedRelayUrl? = null, + createdAt: Long = TimeUtils.randomWithTwoDays(), + ): Event { + val signer = NostrSignerSync(KeyPair()) + val throwaway = requireNotNull(signer.keyPair.privKey) + val content = InboxWire.encrypt(seal.toJson(), InboxWire.conversationKey(throwaway, recipientEncryptionKey)) + return signer.sign( + createdAt = createdAt, + kind = KIND, + tags = arrayOf(PTag.assemble(recipientIdentity, relayHint)), + content = content, + ) + } + + /** Who a wrap is addressed to: its first `p`, which is a routing hint and proves nothing. */ + fun recipientOf(wrap: Event): HexKey? = + wrap.tags.firstOrNull { it.size >= 2 && it[0] == "p" }?.get(1) + + /** + * The seal inside [wrap], and the index into [secrets] of the key that opened it, or null if + * none does. Newest key first is the caller's order to give: a wrap is far likelier to be to + * the key the group announces now than to one it retired. + */ + fun open(wrap: Event, secrets: List): Pair? { + if (wrap.kind != KIND || !wrap.verify()) return null + secrets.forEachIndexed { index, secret -> + val json = InboxWire.decrypt(wrap.content, InboxWire.conversationKey(secret, wrap.pubKey)) ?: return@forEachIndexed + val seal = Event.fromJsonOrNull(json) ?: return@forEachIndexed + if (seal.kind == InboxSeal.KIND) return index to seal + } + return null + } +} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/inbox/InboxWireTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/inbox/InboxWireTest.kt new file mode 100644 index 00000000..0fa5fdea --- /dev/null +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/inbox/InboxWireTest.kt @@ -0,0 +1,264 @@ +package mobi.giza.compose.nostr.inbox + +import com.vitorpamplona.quartz.experimental.decoupling.setup.EncryptionKeyListEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync +import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler +import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent +import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent +import fr.acinq.bitcoin.Crypto +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.test.runTest + +/** + * The group inbox's wire, byte for byte where it matters (docs/group-inbox.md, Phase 2). The + * group's FROST key is stood in for by a plain key here: what is under test is the layering, and + * `SignedGroupKeyStateTest` shows the quorum signs a seal as the room. + */ +class InboxWireTest { + private fun secret(label: String) = Crypto.sha256(label.encodeToByteArray()) + + private val group = KeyPair(secret("the group's identity")) + private val inboxSecret = secret("the inbox key") + private val inboxKey = InboxWire.publicKeyOf(inboxSecret) + + private val alice = KeyPair(secret("alice")) + private val aliceEncryptionSecret = secret("alice's encryption key") + private val aliceEncryptionKey = InboxWire.publicKeyOf(aliceEncryptionSecret) + + private fun KeyPair.hex(): HexKey = pubKey.toHexKey() + + private fun rumor(author: HexKey, to: List, text: String, createdAt: Long = 1_700_000_000L): Event = + RumorAssembler.assembleRumor( + pubKey = author, + ev = EventTemplate(createdAt, 14, to.map { arrayOf("p", it) }.toTypedArray(), text), + ) + + // ---- the ceremony's tags + + @Test + fun `a proposal's tags carry the session, the generation, threshold 1 and the admins`() { + val session = "ab".repeat(32) + val admins = listOf("c".repeat(64), "b".repeat(64), "c".repeat(64)) + val tags = InboxKeyRitualEvents.assembleTags(session, generation = 2, participants = admins) + + assertEquals(session, InboxKeyRitualEvents.parseSessionId(tags)) + assertEquals(2, InboxKeyRitualEvents.parseGeneration(tags)) + assertEquals(1, InboxKeyRitualEvents.parseThreshold(tags)) + assertEquals(listOf("b".repeat(64), "c".repeat(64)), InboxKeyRitualEvents.parseParticipants(tags)) + assertNull(InboxKeyRitualEvents.parseParticipants(tags + arrayOf(arrayOf("p", "not a key")))) + } + + // ---- the announcement + + @Test + fun `the group's 10044 names its key alone, and quartz reads it`() { + val template = InboxAnnouncement.keyTemplate(inboxKey, 1_700_000_000L) + val signed = NostrSignerSync(group).sign(template) + + assertEquals(10044, signed.kind) + assertEquals(inboxKey, InboxAnnouncement.groupKeyOf(signed)) + assertEquals(inboxKey, InboxAnnouncement.announcedKeyOf(signed)) + assertEquals(inboxKey, (signed as EncryptionKeyListEvent).encryptionKey()?.pubkey) + } + + @Test + fun `a 10044 with a second key, a nonce or content is not one the group would sign`() { + val other = "d".repeat(64) + assertNull(InboxAnnouncement.groupKeyOf(10044, arrayOf(arrayOf("n", inboxKey), arrayOf("n", other)), "")) + assertNull(InboxAnnouncement.groupKeyOf(10044, arrayOf(arrayOf("n", inboxKey, "ab".repeat(16))), "")) + assertNull(InboxAnnouncement.groupKeyOf(10044, arrayOf(arrayOf("n", inboxKey)), "hello")) + assertNull(InboxAnnouncement.groupKeyOf(10044, arrayOf(arrayOf("n", inboxKey.uppercase())), "")) + // Someone else's may carry more; the first key is still theirs. + assertEquals(inboxKey, InboxAnnouncement.announcedKeyOf( + Event("a".repeat(64), alice.hex(), 1, 10044, arrayOf(arrayOf("n", inboxKey), arrayOf("n", other)), "", ""), + )) + } + + @Test + fun `the group's 10050 lists public relays only`() { + val relay = assertNotNull(RelayUrlNormalizer.normalizeOrNull("wss://relay.example.com")) + val template = InboxAnnouncement.relaysTemplate(listOf(relay), 1_700_000_000L) + assertEquals(listOf(relay), InboxAnnouncement.groupRelaysOf(template.kind, template.tags, template.content)) + + assertNull(InboxAnnouncement.groupRelaysOf(10050, arrayOf(arrayOf("relay", "ws://relay.example.com")), "")) + assertNull(InboxAnnouncement.groupRelaysOf(10050, emptyArray(), "")) + assertNull(InboxAnnouncement.groupRelaysOf(10050, arrayOf(arrayOf("r", "wss://relay.example.com")), "")) + } + + // ---- the seal + + @Test + fun `a seal from the inbox key opens with the recipient's encryption key`() { + val reply = rumor(group.hex(), listOf(alice.hex()), "Thank you for writing") + val seal = NostrSignerSync(group).sign(InboxSeal.template(reply, inboxSecret, aliceEncryptionKey, 1_700_000_000L)) + + assertEquals(listOf(listOf("n", inboxKey)), seal.tags.map { it.toList() }) + val opened = assertNotNull(InboxSeal.open(seal, aliceEncryptionSecret)) + assertEquals(reply.id, opened.rumor.id) + assertEquals("Thank you for writing", opened.rumor.content) + assertEquals(inboxKey, opened.senderEncryptionKey) + } + + @Test + fun `a seal to a recipient with no 10044 opens with their identity`() { + val reply = rumor(group.hex(), listOf(alice.hex()), "Hello") + val seal = NostrSignerSync(group).sign(InboxSeal.template(reply, inboxSecret, alice.hex(), 1_700_000_000L)) + + assertNotNull(InboxSeal.open(seal, assertNotNull(alice.privKey))) + assertNull(InboxSeal.open(seal, aliceEncryptionSecret), "only the key it was sealed to opens it") + } + + @Test + fun `the group's own copy opens with the inbox key`() { + val reply = rumor(group.hex(), listOf(alice.hex()), "Hello") + val seal = NostrSignerSync(group).sign(InboxSeal.template(reply, inboxSecret, inboxKey, 1_700_000_000L)) + assertEquals("Hello", assertNotNull(InboxSeal.open(seal, inboxSecret)).rumor.content) + } + + @Test + fun `a seal from a sender who does not decouple opens with their identity`() { + // A stock NIP-17 seal, as any app writes one, to the group's announced key. + val message = rumor(alice.hex(), listOf(group.hex()), "Can I join?") + val content = InboxWire.encrypt(InboxSeal.rumorJson(message), InboxWire.conversationKey(assertNotNull(alice.privKey), inboxKey)) + val seal = NostrSignerSync(alice).sign(1_700_000_000L, 13, emptyArray(), content) + + val opened = assertNotNull(InboxSeal.open(seal, inboxSecret)) + assertEquals("Can I join?", opened.rumor.content) + assertEquals(alice.hex(), opened.senderEncryptionKey) + } + + @Test + fun `a seal from a sender who decoupled opens by its n tag, or by their 10044 without one`() { + val message = rumor(alice.hex(), listOf(group.hex()), "From my other key") + val content = InboxWire.encrypt(InboxSeal.rumorJson(message), InboxWire.conversationKey(aliceEncryptionSecret, inboxKey)) + + val tagged = NostrSignerSync(alice).sign(1_700_000_000L, 13, arrayOf(arrayOf("n", aliceEncryptionKey)), content) + assertEquals(aliceEncryptionKey, assertNotNull(InboxSeal.open(tagged, inboxSecret)).senderEncryptionKey) + + val untagged = NostrSignerSync(alice).sign(1_700_000_000L, 13, emptyArray(), content) + assertNull(InboxSeal.open(untagged, inboxSecret), "without the tag or the 10044 there is nothing to try but the identity") + assertNotNull(InboxSeal.open(untagged, inboxSecret, senderAnnouncedKey = aliceEncryptionKey)) + } + + @Test + fun `a rumor claiming another author is refused`() { + val forged = rumor(group.hex(), listOf(group.hex()), "I am the group") + val content = InboxWire.encrypt(InboxSeal.rumorJson(forged), InboxWire.conversationKey(assertNotNull(alice.privKey), inboxKey)) + val seal = NostrSignerSync(alice).sign(1_700_000_000L, 13, emptyArray(), content) + assertNull(InboxSeal.open(seal, inboxSecret)) + } + + @Test + fun `an unsigned or tampered seal is refused`() { + val reply = rumor(group.hex(), listOf(alice.hex()), "Hello") + val template = InboxSeal.template(reply, inboxSecret, aliceEncryptionKey, 1_700_000_000L) + val unsigned = Event("a".repeat(64), group.hex(), template.createdAt, template.kind, template.tags, template.content, "") + assertNull(InboxSeal.open(unsigned, aliceEncryptionSecret)) + } + + // ---- the wrap + + @Test + fun `a wrap names the identity and opens with the encryption key`() { + val seal = NostrSignerSync(group).sign(InboxSeal.template(rumor(group.hex(), listOf(alice.hex()), "Hi"), inboxSecret, aliceEncryptionKey, 1L)) + val relay = RelayUrlNormalizer.normalizeOrNull("wss://inbox.example.com") + val wrap = InboxWrap.wrap(seal, alice.hex(), aliceEncryptionKey, relay, createdAt = 2L) + + assertEquals(1059, wrap.kind) + assertEquals(alice.hex(), InboxWrap.recipientOf(wrap)) + assertTrue(wrap.pubKey != group.hex() && wrap.pubKey != alice.hex(), "nothing outside names the sender") + + val (index, opened) = assertNotNull(InboxWrap.open(wrap, listOf(secret("a retired key"), aliceEncryptionSecret))) + assertEquals(1, index) + assertEquals(seal.id, opened.id) + assertNull(InboxWrap.open(wrap, listOf(assertNotNull(alice.privKey))), "the identity does not open a wrap to the encryption key") + } + + @Test + fun `a wrap built here is still a NIP-59 wrap to quartz, when the keys are the same`() = runTest { + val message = rumor(group.hex(), listOf(alice.hex()), "Plain NIP-17") + val content = InboxWire.encrypt(InboxSeal.rumorJson(message), InboxWire.conversationKey(assertNotNull(group.privKey), alice.hex())) + val seal = NostrSignerSync(group).sign(1L, 13, emptyArray(), content) + val wrap = InboxWrap.wrap(seal, alice.hex(), alice.hex(), createdAt = 2L) as GiftWrapEvent + + val opened = assertNotNull(wrap.unwrapAndUnsealOrNull(NostrSignerInternal(alice))) + assertEquals("Plain NIP-17", opened.content) + assertEquals(group.hex(), opened.pubKey) + } + + @Test + fun `a wrap quartz builds to the inbox key opens here`() = runTest { + // A sender whose app follows NIP-4E only so far as encrypting to the announced key. + val message = rumor(alice.hex(), listOf(group.hex()), "Quartz wrote this") + val seal = NostrSignerSync(alice).sign( + 1L, 13, emptyArray(), + InboxWire.encrypt(InboxSeal.rumorJson(message), InboxWire.conversationKey(assertNotNull(alice.privKey), inboxKey)), + ) + val wrap = GiftWrapEvent.create(event = seal, recipientPubKey = inboxKey, createdAt = 2L) + + val (_, unwrapped) = assertNotNull(InboxWrap.open(wrap, listOf(inboxSecret))) + assertEquals("Quartz wrote this", assertNotNull(InboxSeal.open(unwrapped, inboxSecret)).rumor.content) + } + + // ---- the manifest + + private val manifest = InboxReplyManifest( + generation = 3, + seals = listOf( + InboxReplyManifest.Entry(alice.hex(), aliceEncryptionKey, """{"kind":10044}"""), + InboxReplyManifest.Entry(group.hex(), inboxKey, null), + ), + groupCopy = 1, + ) + + @Test + fun `a manifest opens only with the inbox key it was sealed under`() { + val sealed = manifest.seal(inboxSecret) + assertEquals(manifest, InboxReplyManifest.open(sealed, inboxSecret)) + assertNull(InboxReplyManifest.open(sealed, secret("another generation"))) + assertEquals(sealed, InboxReplyManifest.sealedIn(arrayOf(InboxReplyManifest.tag(sealed), arrayOf("x", "y")))) + assertNull(InboxReplyManifest.sealedIn(arrayOf(InboxReplyManifest.tag(sealed), InboxReplyManifest.tag(sealed)))) + } + + @Test + fun `a manifest with a stray field, a missing one or a copy out of range is none`() { + val encoded = manifest.encode() + assertEquals(manifest, InboxReplyManifest.decode(encoded)) + assertNull(InboxReplyManifest.decode(encoded.replaceFirst("{\"v\":1", "{\"v\":1,\"extra\":true"))) + assertNull(InboxReplyManifest.decode(encoded.replace(",\"group_copy\":1", ""))) + assertNull(InboxReplyManifest.decode(encoded.replace("\"group_copy\":1", "\"group_copy\":2"))) + assertNull(InboxReplyManifest.decode(encoded.replace("\"v\":1", "\"v\":2"))) + } + + // ---- the conversation + + @Test + fun `a message and its reply are one conversation, whatever the order of its people`() { + val bob = KeyPair(secret("bob")).hex() + val incoming = rumor(alice.hex(), listOf(group.hex(), bob), "To the group and Bob") + val reply = rumor(group.hex(), listOf(bob, alice.hex()), "To both") + + assertEquals(listOf(alice.hex(), bob).sorted(), InboxConversation.participantsOf(incoming, group.hex())) + assertEquals(InboxConversation.idOf(incoming, group.hex()), InboxConversation.idOf(reply, group.hex())) + assertTrue(InboxConversation.idOf(rumor(alice.hex(), listOf(group.hex()), "Just us"), group.hex()) != InboxConversation.idOf(incoming, group.hex())) + } + + @Test + fun `the inbox key's hex is the x-only key of its secret`() { + assertEquals(64, inboxKey.length) + assertEquals(32, inboxKey.hexToByteArray().size) + assertEquals(inboxKey, inboxKey.lowercase()) + } +} From 1f66c39f2f6ea912f9f22a2b70fe1b945fc27c50 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 01:36:20 +0200 Subject: [PATCH 08/16] feat: where a group's inbox is kept, schema 44 to 45 (group-inbox, Phase 3) InboxKeyCeremony, InboxKeyCeremonyMessage and InboxKey, apart from DkgSession so no signing path can find a threshold-1 key; and GroupInboxWrap (the ledger, opened or not), GroupInboxMessage (one row per rumor) and GroupInboxPublication (what this device owes relays). New tables only, so an AutoMigration. InboxStorageJvmTest pins redelivery, the wipe and that the signing lookups see none of it. Co-Authored-By: Claude Opus 5.5 --- .../45.json | 6469 +++++++++++++++++ .../giza/compose/database/GizaDatabase.kt | 25 +- .../compose/database/dao/GroupInboxDao.kt | 84 + .../giza/compose/database/dao/InboxKeyDao.kt | 78 + .../giza/compose/database/model/GroupInbox.kt | 114 + .../database/model/InboxKeyCeremony.kt | 138 + .../compose/database/InboxStorageJvmTest.kt | 131 + .../ShippedProfileUpgradeJvmTest.kt | 7 +- 8 files changed, 7042 insertions(+), 4 deletions(-) create mode 100644 composeApp/schemas/mobi.giza.compose.database.GizaDatabase/45.json create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupInboxDao.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/InboxKeyDao.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupInbox.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/InboxKeyCeremony.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/InboxStorageJvmTest.kt diff --git a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/45.json b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/45.json new file mode 100644 index 00000000..15430737 --- /dev/null +++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/45.json @@ -0,0 +1,6469 @@ +{ + "formatVersion": 1, + "database": { + "version": 45, + "identityHash": "690e3d5ecde4b3bfe7f46f8e530c249a", + "entities": [ + { + "tableName": "BroadcastNostrEventReceipt", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `nostrEventId` TEXT NOT NULL, `unsignedNostrEventId` INTEGER, `isAccepted` INTEGER NOT NULL, `isSync` INTEGER NOT NULL, `relayURL` TEXT NOT NULL, `messages` TEXT, FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "isAccepted", + "columnName": "isAccepted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isSync", + "columnName": "isSync", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messages", + "columnName": "messages", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_BroadcastNostrEventReceipt_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventReceipt_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_BroadcastNostrEventReceipt_isAccepted", + "unique": false, + "columnNames": [ + "isAccepted" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventReceipt_isAccepted` ON `${TABLE_NAME}` (`isAccepted`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "BroadcastNostrEventRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `nostrEventId` TEXT NOT NULL, `unsignedNostrEventId` INTEGER, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_BroadcastNostrEventRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_BroadcastNostrEventRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Connection", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sourcePublicKey` TEXT NOT NULL, `destinationPublicKey` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`sourcePublicKey`, `destinationPublicKey`), FOREIGN KEY(`sourcePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`destinationPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sourcePublicKey", + "columnName": "sourcePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "destinationPublicKey", + "columnName": "destinationPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sourcePublicKey", + "destinationPublicKey" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sourcePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "destinationPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + } + ] + }, + { + "tableName": "ChatMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `senderPublicKey` TEXT NOT NULL, `isUserMessage` INTEGER NOT NULL, `giftWrapPayloadId` TEXT, `marmotGroupEventId` TEXT, `marmotInnerEventId` TEXT, `chatRoomId` TEXT NOT NULL, `replyToMessageId` INTEGER, `quotedMessageId` INTEGER, `content` TEXT NOT NULL, `messageType` TEXT NOT NULL, `directMessageRecipientPublicKey` TEXT, `frostSigningSessionId` TEXT, `dkgSessionId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`giftWrapPayloadId`) REFERENCES `GiftWrapPayload`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`marmotGroupEventId`) REFERENCES `MarmotGroupEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`marmotInnerEventId`) REFERENCES `MarmotInnerEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isUserMessage", + "columnName": "isUserMessage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "giftWrapPayloadId", + "columnName": "giftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotInnerEventId", + "columnName": "marmotInnerEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToMessageId", + "columnName": "replyToMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "quotedMessageId", + "columnName": "quotedMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messageType", + "columnName": "messageType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "directMessageRecipientPublicKey", + "columnName": "directMessageRecipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ChatMessage_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ChatMessage_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "GiftWrapPayload", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapPayloadId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MarmotGroupEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotGroupEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MarmotInnerEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotInnerEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageBroadcastNostrEventRequestRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `broadcastNostrEventRequestId` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`broadcastNostrEventRequestId`) REFERENCES `BroadcastNostrEventRequest`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "broadcastNostrEventRequestId", + "columnName": "broadcastNostrEventRequestId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "BroadcastNostrEventRequest", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "broadcastNostrEventRequestId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageBroadcastNostrEventReceiptRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `broadcastNostrEventReceiptId` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`broadcastNostrEventReceiptId`) REFERENCES `BroadcastNostrEventReceipt`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "broadcastNostrEventReceiptId", + "columnName": "broadcastNostrEventReceiptId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "BroadcastNostrEventReceipt", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "broadcastNostrEventReceiptId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageNostrEventRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatRoom", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `subject` TEXT, `description` TEXT, `mlsGroupState` TEXT, `initialGiftWrapPayloadId` TEXT, `leftGroupAt` INTEGER, `joinedGroupAt` INTEGER, `chronicleRequestedAt` INTEGER, `parentChatRoomId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`userPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`initialGiftWrapPayloadId`) REFERENCES `GiftWrapPayload`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT" + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT" + }, + { + "fieldPath": "mlsGroupState", + "columnName": "mlsGroupState", + "affinity": "TEXT" + }, + { + "fieldPath": "initialGiftWrapPayloadId", + "columnName": "initialGiftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "leftGroupAt", + "columnName": "leftGroupAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "joinedGroupAt", + "columnName": "joinedGroupAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "chronicleRequestedAt", + "columnName": "chronicleRequestedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "userPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "GiftWrapPayload", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "initialGiftWrapPayloadId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Confederation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `ceremonyId` TEXT NOT NULL, `name` TEXT NOT NULL, `roster` TEXT NOT NULL, `keyState` TEXT NOT NULL, `genesis` TEXT NOT NULL, `configSeq` INTEGER NOT NULL, `rosterHash` TEXT NOT NULL, `keyStateHash` TEXT NOT NULL, `recoveryPackages` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ceremonyId", + "columnName": "ceremonyId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roster", + "columnName": "roster", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyState", + "columnName": "keyState", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "genesis", + "columnName": "genesis", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "configSeq", + "columnName": "configSeq", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rosterHash", + "columnName": "rosterHash", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyStateHash", + "columnName": "keyStateHash", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "recoveryPackages", + "columnName": "recoveryPackages", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Confederation_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Confederation_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + } + ] + }, + { + "tableName": "ConfederationCeremony", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `openingJson` TEXT NOT NULL, `stage` TEXT NOT NULL, `approvedAt` INTEGER, `dealerSeeds` TEXT, `recoveryNonces` TEXT, `keyState` TEXT, `transitionHash` TEXT, `genesis` TEXT, `recoveryPackages` TEXT, `confederationPublicKey` TEXT, `failureReason` TEXT, `culprit` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "openingJson", + "columnName": "openingJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "approvedAt", + "columnName": "approvedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "dealerSeeds", + "columnName": "dealerSeeds", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryNonces", + "columnName": "recoveryNonces", + "affinity": "TEXT" + }, + { + "fieldPath": "keyState", + "columnName": "keyState", + "affinity": "TEXT" + }, + { + "fieldPath": "transitionHash", + "columnName": "transitionHash", + "affinity": "TEXT" + }, + { + "fieldPath": "genesis", + "columnName": "genesis", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryPackages", + "columnName": "recoveryPackages", + "affinity": "TEXT" + }, + { + "fieldPath": "confederationPublicKey", + "columnName": "confederationPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "culprit", + "columnName": "culprit", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ConfederationCeremony_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationCeremony_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_ConfederationCeremony_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationCeremony_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationMember", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`confederationId` TEXT NOT NULL, `groupPublicKey` TEXT NOT NULL, PRIMARY KEY(`confederationId`, `groupPublicKey`))", + "fields": [ + { + "fieldPath": "confederationId", + "columnName": "confederationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "groupPublicKey", + "columnName": "groupPublicKey", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "confederationId", + "groupPublicKey" + ] + }, + "indices": [ + { + "name": "index_ConfederationMember_groupPublicKey", + "unique": false, + "columnNames": [ + "groupPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationMember_groupPublicKey` ON `${TABLE_NAME}` (`groupPublicKey`)" + } + ] + }, + { + "tableName": "ConfederationCeremonyMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `senderPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `ConfederationCeremony`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "senderPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "ConfederationCeremony", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `kind` INTEGER NOT NULL, `pubKey` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `eventCreatedAt` INTEGER NOT NULL, `eventJson` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, `ownSessionId` TEXT, `publishedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventCreatedAt", + "columnName": "eventCreatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "eventJson", + "columnName": "eventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "ownSessionId", + "columnName": "ownSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "publishedAt", + "columnName": "publishedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ConfederationEvent_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + }, + { + "name": "index_ConfederationEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_ConfederationEvent_publishedAt", + "unique": false, + "columnNames": [ + "publishedAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_publishedAt` ON `${TABLE_NAME}` (`publishedAt`)" + } + ] + }, + { + "tableName": "ConfederationInvitee", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`proposalId` TEXT NOT NULL, `groupPublicKey` TEXT NOT NULL, PRIMARY KEY(`proposalId`, `groupPublicKey`))", + "fields": [ + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "groupPublicKey", + "columnName": "groupPublicKey", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "proposalId", + "groupPublicKey" + ] + }, + "indices": [ + { + "name": "index_ConfederationInvitee_groupPublicKey", + "unique": false, + "columnNames": [ + "groupPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationInvitee_groupPublicKey` ON `${TABLE_NAME}` (`groupPublicKey`)" + } + ] + }, + { + "tableName": "ConfederationSigning", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `sealSecret` TEXT, `proposalJson` TEXT, `refusal` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sealSecret", + "columnName": "sealSecret", + "affinity": "TEXT" + }, + { + "fieldPath": "proposalJson", + "columnName": "proposalJson", + "affinity": "TEXT" + }, + { + "fieldPath": "refusal", + "columnName": "refusal", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId" + ] + }, + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "DkgParticipantMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `participantPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `participantPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "participantPublicKey", + "kind" + ] + }, + "indices": [ + { + "name": "index_DkgParticipantMessage_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_DkgParticipantMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "DkgSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "DkgSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `threshold` INTEGER NOT NULL, `participantCount` INTEGER NOT NULL, `participantPublicKeys` TEXT, `subject` TEXT, `walletPolicy` TEXT, `stage` TEXT NOT NULL, `hostPublicKey` TEXT NOT NULL, `round1Random` TEXT NOT NULL, `round2AuxRandom` TEXT NOT NULL, `coordinatorRound1` TEXT, `certificate` TEXT, `thresholdPublicKey` TEXT, `secretShare` TEXT, `publicShares` TEXT, `recoveryData` TEXT, `failureReason` TEXT, `hostKeyApprovedAt` INTEGER, `round1ApprovedAt` INTEGER, `round2ApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `parentChatRoomId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "threshold", + "columnName": "threshold", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantCount", + "columnName": "participantCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantPublicKeys", + "columnName": "participantPublicKeys", + "affinity": "TEXT" + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT" + }, + { + "fieldPath": "walletPolicy", + "columnName": "walletPolicy", + "affinity": "TEXT" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "hostPublicKey", + "columnName": "hostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round1Random", + "columnName": "round1Random", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round2AuxRandom", + "columnName": "round2AuxRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorRound1", + "columnName": "coordinatorRound1", + "affinity": "TEXT" + }, + { + "fieldPath": "certificate", + "columnName": "certificate", + "affinity": "TEXT" + }, + { + "fieldPath": "thresholdPublicKey", + "columnName": "thresholdPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "secretShare", + "columnName": "secretShare", + "affinity": "TEXT" + }, + { + "fieldPath": "publicShares", + "columnName": "publicShares", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "hostKeyApprovedAt", + "columnName": "hostKeyApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "round1ApprovedAt", + "columnName": "round1ApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "round2ApprovedAt", + "columnName": "round2ApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedThrough", + "columnName": "approvalRequestedThrough", + "affinity": "TEXT" + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_DkgSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_DkgSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSignerMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `signerPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `signerPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signerPublicKey", + "columnName": "signerPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "signerPublicKey", + "kind" + ] + }, + "indices": [ + { + "name": "index_FrostSignerMessage_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSignerMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSigningItem", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `itemIndex` INTEGER NOT NULL, `unsignedEventJson` TEXT NOT NULL, `eventId` TEXT NOT NULL, `nonceRandom` TEXT NOT NULL, `aggregatedNonce` TEXT, `signature` TEXT, PRIMARY KEY(`sessionId`, `itemIndex`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "itemIndex", + "columnName": "itemIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "unsignedEventJson", + "columnName": "unsignedEventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventId", + "columnName": "eventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nonceRandom", + "columnName": "nonceRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "aggregatedNonce", + "columnName": "aggregatedNonce", + "affinity": "TEXT" + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "itemIndex" + ] + }, + "indices": [ + { + "name": "index_FrostSigningItem_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningItem_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSigningSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `threshold` INTEGER NOT NULL, `participantCount` INTEGER NOT NULL, `signerId` INTEGER NOT NULL, `derivationPath` TEXT, `generation` INTEGER, `stage` TEXT NOT NULL, `signerIds` TEXT, `failureReason` TEXT, `signApprovedAt` INTEGER, `signDeclinedAt` INTEGER, `approvalRequestedAt` INTEGER, `resentAt` INTEGER, `subject` TEXT NOT NULL DEFAULT 'EVENTS', `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "threshold", + "columnName": "threshold", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantCount", + "columnName": "participantCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "signerId", + "columnName": "signerId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT" + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signerIds", + "columnName": "signerIds", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "signApprovedAt", + "columnName": "signApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "signDeclinedAt", + "columnName": "signDeclinedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedAt", + "columnName": "approvalRequestedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "resentAt", + "columnName": "resentAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'EVENTS'" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_FrostSigningSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_FrostSigningSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `receiverPublicKey` TEXT NOT NULL, `receiverRelayHit` TEXT, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "receiverPublicKey", + "columnName": "receiverPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receiverRelayHit", + "columnName": "receiverRelayHit", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapSeal", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `giftWrapMessageId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapMessageId`) REFERENCES `GiftWrapMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "giftWrapMessageId", + "columnName": "giftWrapMessageId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "GiftWrapMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapMessageId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapPayload", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `quotedEventId` TEXT, `giftWrapSealId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapSealId`) REFERENCES `GiftWrapSeal`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedEventId", + "columnName": "quotedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "giftWrapSealId", + "columnName": "giftWrapSealId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "GiftWrapSeal", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapSealId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupInboxMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `rumorId` TEXT NOT NULL, `wrapId` TEXT, `conversationId` TEXT NOT NULL, `participants` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `rumorJson` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `generation` INTEGER NOT NULL, `outgoing` INTEGER NOT NULL, `signingSessionId` TEXT, `readAt` INTEGER, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`, `rumorId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "rumorId", + "columnName": "rumorId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapId", + "columnName": "wrapId", + "affinity": "TEXT" + }, + { + "fieldPath": "conversationId", + "columnName": "conversationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participants", + "columnName": "participants", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rumorJson", + "columnName": "rumorJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "outgoing", + "columnName": "outgoing", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "signingSessionId", + "columnName": "signingSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "readAt", + "columnName": "readAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "rumorId" + ] + }, + "indices": [ + { + "name": "index_GroupInboxMessage_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxMessage_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupInboxMessage_conversationId", + "unique": false, + "columnNames": [ + "conversationId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxMessage_conversationId` ON `${TABLE_NAME}` (`conversationId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupInboxPublication", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`eventId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `eventJson` TEXT NOT NULL, `relays` TEXT NOT NULL, `signingSessionId` TEXT, `recipientPublicKey` TEXT, `attempts` INTEGER NOT NULL, `nextAttemptAt` INTEGER, `publishedAt` INTEGER, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`eventId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "eventId", + "columnName": "eventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "eventJson", + "columnName": "eventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relays", + "columnName": "relays", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signingSessionId", + "columnName": "signingSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "recipientPublicKey", + "columnName": "recipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "attempts", + "columnName": "attempts", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nextAttemptAt", + "columnName": "nextAttemptAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "publishedAt", + "columnName": "publishedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "eventId" + ] + }, + "indices": [ + { + "name": "index_GroupInboxPublication_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxPublication_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupInboxPublication_signingSessionId", + "unique": false, + "columnNames": [ + "signingSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxPublication_signingSessionId` ON `${TABLE_NAME}` (`signingSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupInboxWrap", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `wrapJson` TEXT NOT NULL, `wrapCreatedAt` INTEGER NOT NULL, `openedGeneration` INTEGER, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapJson", + "columnName": "wrapJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapCreatedAt", + "columnName": "wrapCreatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "openedGeneration", + "columnName": "openedGeneration", + "affinity": "INTEGER" + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GroupInboxWrap_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxWrap_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupKeyState", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `thresholdPublicKey` TEXT NOT NULL, `derivationPath` TEXT NOT NULL, `announcedBy` TEXT NOT NULL, `announcedAt` INTEGER NOT NULL, `parentChatRoomId` TEXT, `birthCertificateJson` TEXT, `generation` INTEGER, `publicSharesHash` TEXT, `memberBindings` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thresholdPublicKey", + "columnName": "thresholdPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcedBy", + "columnName": "announcedBy", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcedAt", + "columnName": "announcedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "birthCertificateJson", + "columnName": "birthCertificateJson", + "affinity": "TEXT" + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER" + }, + { + "fieldPath": "publicSharesHash", + "columnName": "publicSharesHash", + "affinity": "TEXT" + }, + { + "fieldPath": "memberBindings", + "columnName": "memberBindings", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId" + ] + }, + "indices": [ + { + "name": "index_GroupKeyState_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupKeyState_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupSignedEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `derivationPath` TEXT, `frostSigningSessionId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT" + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GroupSignedEvent_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupSignedEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_GroupSignedEvent_frostSigningSessionId", + "unique": false, + "columnNames": [ + "frostSigningSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_frostSigningSessionId` ON `${TABLE_NAME}` (`frostSigningSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InboxKey", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `generation` INTEGER NOT NULL, `publicKey` TEXT NOT NULL, `secretKey` TEXT, `recoveryData` TEXT, `ceremonyId` TEXT NOT NULL, `state` TEXT NOT NULL, `announcementEventId` TEXT, `createdAt` INTEGER NOT NULL, `announcedAt` INTEGER, `wipedAt` INTEGER, PRIMARY KEY(`chatRoomId`, `userPublicKey`, `generation`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "secretKey", + "columnName": "secretKey", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "ceremonyId", + "columnName": "ceremonyId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcementEventId", + "columnName": "announcementEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "announcedAt", + "columnName": "announcedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "wipedAt", + "columnName": "wipedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "userPublicKey", + "generation" + ] + }, + "indices": [ + { + "name": "index_InboxKey_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_InboxKey_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InboxKeyCeremony", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `participantPublicKeys` TEXT NOT NULL, `stage` TEXT NOT NULL, `hostPublicKey` TEXT, `round1Random` TEXT, `round2AuxRandom` TEXT, `inboxPublicKey` TEXT, `failureReason` TEXT, `culprit` TEXT, `lastMessageAt` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantPublicKeys", + "columnName": "participantPublicKeys", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "hostPublicKey", + "columnName": "hostPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "round1Random", + "columnName": "round1Random", + "affinity": "TEXT" + }, + { + "fieldPath": "round2AuxRandom", + "columnName": "round2AuxRandom", + "affinity": "TEXT" + }, + { + "fieldPath": "inboxPublicKey", + "columnName": "inboxPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "culprit", + "columnName": "culprit", + "affinity": "TEXT" + }, + { + "fieldPath": "lastMessageAt", + "columnName": "lastMessageAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_InboxKeyCeremony_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_InboxKeyCeremony_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InboxKeyCeremonyMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `senderPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `InboxKeyCeremony`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "senderPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "InboxKeyCeremony", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "KeyShareGeneration", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `secretShare` TEXT, `publicShares` TEXT NOT NULL, `state` TEXT NOT NULL, `refreshSessionId` TEXT, `recoveryData` TEXT, `activatedAt` INTEGER, `wipedAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `generation`), FOREIGN KEY(`dkgSessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "secretShare", + "columnName": "secretShare", + "affinity": "TEXT" + }, + { + "fieldPath": "publicShares", + "columnName": "publicShares", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "refreshSessionId", + "columnName": "refreshSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "activatedAt", + "columnName": "activatedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "wipedAt", + "columnName": "wipedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "dkgSessionId", + "generation" + ] + }, + "indices": [ + { + "name": "index_KeyShareGeneration_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_KeyShareGeneration_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "DkgSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dkgSessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "KeyShareMember", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `participantId` INTEGER NOT NULL, `memberPublicKey` TEXT NOT NULL, `hostPublicKey` TEXT NOT NULL, `standing` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `generation`, `participantId`), FOREIGN KEY(`dkgSessionId`, `generation`) REFERENCES `KeyShareGeneration`(`dkgSessionId`, `generation`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantId", + "columnName": "participantId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "memberPublicKey", + "columnName": "memberPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "hostPublicKey", + "columnName": "hostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "standing", + "columnName": "standing", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "dkgSessionId", + "generation", + "participantId" + ] + }, + "indices": [ + { + "name": "index_KeyShareMember_dkgSessionId_generation", + "unique": false, + "columnNames": [ + "dkgSessionId", + "generation" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_KeyShareMember_dkgSessionId_generation` ON `${TABLE_NAME}` (`dkgSessionId`, `generation`)" + } + ], + "foreignKeys": [ + { + "table": "KeyShareGeneration", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dkgSessionId", + "generation" + ], + "referencedColumns": [ + "dkgSessionId", + "generation" + ] + } + ] + }, + { + "tableName": "ShareRefreshConfirmation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `baseGeneration` INTEGER NOT NULL, `refreshSessionId` TEXT NOT NULL, `confirmedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `baseGeneration`))", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "baseGeneration", + "columnName": "baseGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "refreshSessionId", + "columnName": "refreshSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "confirmedAt", + "columnName": "confirmedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "dkgSessionId", + "baseGeneration" + ] + } + }, + { + "tableName": "ShareRefreshMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `participantPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `participantPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `ShareRefreshSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "participantPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "ShareRefreshSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ShareRefreshSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `baseGeneration` INTEGER NOT NULL, `recipientIds` TEXT NOT NULL, `withheld` TEXT, `stage` TEXT NOT NULL, `round1Random` TEXT NOT NULL, `auxRandom` TEXT NOT NULL, `dealApprovedAt` INTEGER, `confirmApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `coordinatorRound1` TEXT, `certificate` TEXT, `failureReason` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "baseGeneration", + "columnName": "baseGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recipientIds", + "columnName": "recipientIds", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "withheld", + "columnName": "withheld", + "affinity": "TEXT" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round1Random", + "columnName": "round1Random", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "auxRandom", + "columnName": "auxRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dealApprovedAt", + "columnName": "dealApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "confirmApprovedAt", + "columnName": "confirmApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedThrough", + "columnName": "approvalRequestedThrough", + "affinity": "TEXT" + }, + { + "fieldPath": "coordinatorRound1", + "columnName": "coordinatorRound1", + "affinity": "TEXT" + }, + { + "fieldPath": "certificate", + "columnName": "certificate", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ShareRefreshSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRefreshSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_ShareRefreshSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRefreshSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ShareRepairMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `recipientPublicKey` TEXT NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `senderPublicKey`, `kind`, `recipientPublicKey`), FOREIGN KEY(`sessionId`) REFERENCES `ShareRepairSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recipientPublicKey", + "columnName": "recipientPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "senderPublicKey", + "kind", + "recipientPublicKey" + ] + }, + "foreignKeys": [ + { + "table": "ShareRepairSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ShareRepairSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `targetId` INTEGER NOT NULL, `targetPublicKey` TEXT NOT NULL, `targetHostPublicKey` TEXT NOT NULL, `helperIds` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `stage` TEXT NOT NULL, `sessionRandom` TEXT NOT NULL, `helpApprovedAt` INTEGER, `approvalRequested` INTEGER NOT NULL, `failureReason` TEXT, `nParticipants` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "targetId", + "columnName": "targetId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "targetPublicKey", + "columnName": "targetPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "targetHostPublicKey", + "columnName": "targetHostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "helperIds", + "columnName": "helperIds", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sessionRandom", + "columnName": "sessionRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "helpApprovedAt", + "columnName": "helpApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequested", + "columnName": "approvalRequested", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "nParticipants", + "columnName": "nParticipants", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ShareRepairSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRepairSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_ShareRepairSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRepairSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GovernanceProposal", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `routingId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `frostSigningSessionId` TEXT NOT NULL, `commitEventId` TEXT NOT NULL, `commitEventJson` TEXT NOT NULL, `peerKeyPackageEventId` TEXT, `priorStateHex` TEXT NOT NULL, `pendingStateHex` TEXT NOT NULL, `stage` TEXT NOT NULL, `thenRotateWithout` TEXT, `promotionOfferId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "routingId", + "columnName": "routingId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "epoch", + "columnName": "epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "commitEventId", + "columnName": "commitEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "commitEventJson", + "columnName": "commitEventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "peerKeyPackageEventId", + "columnName": "peerKeyPackageEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "priorStateHex", + "columnName": "priorStateHex", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "pendingStateHex", + "columnName": "pendingStateHex", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thenRotateWithout", + "columnName": "thenRotateWithout", + "affinity": "TEXT" + }, + { + "fieldPath": "promotionOfferId", + "columnName": "promotionOfferId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GovernanceProposal_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GovernanceProposal_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GovernanceProposal_frostSigningSessionId", + "unique": false, + "columnNames": [ + "frostSigningSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GovernanceProposal_frostSigningSessionId` ON `${TABLE_NAME}` (`frostSigningSessionId`)" + }, + { + "name": "index_GovernanceProposal_commitEventId", + "unique": false, + "columnNames": [ + "commitEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GovernanceProposal_commitEventId` ON `${TABLE_NAME}` (`commitEventId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InReplyToRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`replyingNostrEventId` TEXT NOT NULL, `inReplyToNostrEventId` TEXT NOT NULL, `inReplyToProfilePublicKey` TEXT, `inReplyToRootNostrEventId` TEXT, `inReplyToRootProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`replyingNostrEventId`, `inReplyToNostrEventId`), FOREIGN KEY(`inReplyToProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`inReplyToRootProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`inReplyToNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`inReplyToRootNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "replyingNostrEventId", + "columnName": "replyingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "inReplyToNostrEventId", + "columnName": "inReplyToNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "inReplyToProfilePublicKey", + "columnName": "inReplyToProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootNostrEventId", + "columnName": "inReplyToRootNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootProfilePublicKey", + "columnName": "inReplyToRootProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "replyingNostrEventId", + "inReplyToNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToRootProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToRootNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotCommitResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `peerKeyPackageEventId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `isOneMemberInitialGroupCreation` INTEGER NOT NULL, `commitBytes` BLOB NOT NULL, `welcomeBytes` BLOB, `groupInfoBytes` BLOB, `framedCommitBytes` BLOB NOT NULL, `preCommitExporterSecret` BLOB NOT NULL, `obligationId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "peerKeyPackageEventId", + "columnName": "peerKeyPackageEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isOneMemberInitialGroupCreation", + "columnName": "isOneMemberInitialGroupCreation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "commitBytes", + "columnName": "commitBytes", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "welcomeBytes", + "columnName": "welcomeBytes", + "affinity": "BLOB" + }, + { + "fieldPath": "groupInfoBytes", + "columnName": "groupInfoBytes", + "affinity": "BLOB" + }, + { + "fieldPath": "framedCommitBytes", + "columnName": "framedCommitBytes", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "preCommitExporterSecret", + "columnName": "preCommitExporterSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "obligationId", + "columnName": "obligationId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "MarmotGroupEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `signature` TEXT NOT NULL, `encryptedContent` TEXT NOT NULL, `expiresAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`id`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "encryptedContent", + "columnName": "encryptedContent", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "expiresAt", + "columnName": "expiresAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "id" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotInnerEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `quotedEventId` TEXT, `marmotGroupEventId` TEXT, `directMessageRecipientPublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`marmotGroupEventId`) REFERENCES `MarmotGroupEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedEventId", + "columnName": "quotedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "directMessageRecipientPublicKey", + "columnName": "directMessageRecipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "MarmotGroupEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotGroupEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotKeyPackage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `tlsEncodedMarmotKeyPackage` BLOB NOT NULL, `profile` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`publicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "tlsEncodedMarmotKeyPackage", + "columnName": "tlsEncodedMarmotKeyPackage", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "profile", + "columnName": "profile", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "publicKey" + ], + "referencedColumns": [ + "publicKey" + ] + } + ] + }, + { + "tableName": "MarmotKeyPackageBundle", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `tlsEncodedMarmotKeyPackage` BLOB NOT NULL, `ncryptsecInitPrivateKey` TEXT NOT NULL, `ncryptsecEncryptionPrivateKey` TEXT NOT NULL, `ncryptsecSignaturePrivateKey` TEXT NOT NULL, `consumed` INTEGER NOT NULL, `rotated` INTEGER NOT NULL, `profile` TEXT, `dTag` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "tlsEncodedMarmotKeyPackage", + "columnName": "tlsEncodedMarmotKeyPackage", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "ncryptsecInitPrivateKey", + "columnName": "ncryptsecInitPrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ncryptsecEncryptionPrivateKey", + "columnName": "ncryptsecEncryptionPrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ncryptsecSignaturePrivateKey", + "columnName": "ncryptsecSignaturePrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "consumed", + "columnName": "consumed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rotated", + "columnName": "rotated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "profile", + "columnName": "profile", + "affinity": "TEXT" + }, + { + "fieldPath": "dTag", + "columnName": "dTag", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_MarmotKeyPackageBundle_publicKey", + "unique": false, + "columnNames": [ + "publicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MarmotKeyPackageBundle_publicKey` ON `${TABLE_NAME}` (`publicKey`)" + } + ] + }, + { + "tableName": "MarmotRouting", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`routingId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `activeFromEpoch` INTEGER NOT NULL, `retiredAtEpoch` INTEGER, PRIMARY KEY(`routingId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "routingId", + "columnName": "routingId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "activeFromEpoch", + "columnName": "activeFromEpoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "retiredAtEpoch", + "columnName": "retiredAtEpoch", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "routingId" + ] + }, + "indices": [ + { + "name": "index_MarmotRouting_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MarmotRouting_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotPublishObligation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`obligationId` TEXT NOT NULL, `bytes` BLOB NOT NULL, PRIMARY KEY(`obligationId`))", + "fields": [ + { + "fieldPath": "obligationId", + "columnName": "obligationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "bytes", + "columnName": "bytes", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "obligationId" + ] + } + }, + { + "tableName": "MarmotOutboundGate", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`groupId` TEXT NOT NULL, `gate` TEXT NOT NULL, PRIMARY KEY(`groupId`))", + "fields": [ + { + "fieldPath": "groupId", + "columnName": "groupId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "gate", + "columnName": "gate", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "groupId" + ] + } + }, + { + "tableName": "MarmotRetainedEpochSecret", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `senderDataSecret` BLOB NOT NULL, `encryptionSecret` BLOB NOT NULL, `leafCount` INTEGER NOT NULL, `exporterSecret` BLOB NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`, `epoch`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "epoch", + "columnName": "epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderDataSecret", + "columnName": "senderDataSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "encryptionSecret", + "columnName": "encryptionSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "leafCount", + "columnName": "leafCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "exporterSecret", + "columnName": "exporterSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "epoch" + ] + }, + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotSenderRatchet", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `leafIndex` INTEGER NOT NULL, `applicationGeneration` INTEGER NOT NULL, `record` BLOB NOT NULL, PRIMARY KEY(`chatRoomId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "epoch", + "columnName": "epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "leafIndex", + "columnName": "leafIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "applicationGeneration", + "columnName": "applicationGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "record", + "columnName": "record", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId" + ] + }, + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Mention", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `mentionedPublicKey` TEXT NOT NULL, `mentioningNostrEventId` TEXT, `relayUrl` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, FOREIGN KEY(`mentionedPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`mentioningNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mentionedPublicKey", + "columnName": "mentionedPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "mentioningNostrEventId", + "columnName": "mentioningNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "relayUrl", + "columnName": "relayUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "mentionedPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "mentioningNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NegentropySynchronizeRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `uuid` TEXT NOT NULL, `purpose` TEXT NOT NULL, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `isRecommendedRelay` INTEGER NOT NULL, `level` INTEGER NOT NULL, `synchronizationFilter` TEXT NOT NULL, `ownerPublicKey` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "uuid", + "columnName": "uuid", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isRecommendedRelay", + "columnName": "isRecommendedRelay", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "level", + "columnName": "level", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "synchronizationFilter", + "columnName": "synchronizationFilter", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerPublicKey", + "columnName": "ownerPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_NegentropySynchronizeRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NegentropySynchronizeRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_NegentropySynchronizeRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NegentropySynchronizeRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NegentropySynchronizeResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `status` TEXT NOT NULL, `negentropySynchronizeRequestId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`negentropySynchronizeRequestId`) REFERENCES `SynchronizeNostrEventResult`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "negentropySynchronizeRequestId", + "columnName": "negentropySynchronizeRequestId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "SynchronizeNostrEventResult", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "negentropySynchronizeRequestId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NostrEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `pubKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `sig` TEXT NOT NULL, `relayUrl` TEXT, `quotedNostrEventId` TEXT, `quotedAuthorPublicKey` TEXT, `inReplyToNostrEventId` TEXT, `inReplyToAuthorPublicKey` TEXT, `inReplyToRootNostrEventId` TEXT, `inReplyToRootAuthorPublicKey` TEXT, `repostedNostrEventId` TEXT, `repostedAuthorPublicKey` TEXT, `unsignedNostrEventId` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sig", + "columnName": "sig", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayUrl", + "columnName": "relayUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "quotedNostrEventId", + "columnName": "quotedNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "quotedAuthorPublicKey", + "columnName": "quotedAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToNostrEventId", + "columnName": "inReplyToNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToAuthorPublicKey", + "columnName": "inReplyToAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootNostrEventId", + "columnName": "inReplyToRootNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootAuthorPublicKey", + "columnName": "inReplyToRootAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "repostedNostrEventId", + "columnName": "repostedNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "repostedAuthorPublicKey", + "columnName": "repostedAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_NostrEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_NostrEvent_pubKey", + "unique": false, + "columnNames": [ + "pubKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_pubKey` ON `${TABLE_NAME}` (`pubKey`)" + }, + { + "name": "index_NostrEvent_quotedNostrEventId", + "unique": false, + "columnNames": [ + "quotedNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_quotedNostrEventId` ON `${TABLE_NAME}` (`quotedNostrEventId`)" + }, + { + "name": "index_NostrEvent_inReplyToNostrEventId", + "unique": false, + "columnNames": [ + "inReplyToNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_inReplyToNostrEventId` ON `${TABLE_NAME}` (`inReplyToNostrEventId`)" + }, + { + "name": "index_NostrEvent_inReplyToRootNostrEventId", + "unique": false, + "columnNames": [ + "inReplyToRootNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_inReplyToRootNostrEventId` ON `${TABLE_NAME}` (`inReplyToRootNostrEventId`)" + } + ] + }, + { + "tableName": "NostrEventRelay", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`relayURL` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`nostrEventId`, `relayURL`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "nostrEventId", + "relayURL" + ] + }, + "indices": [ + { + "name": "index_NostrEventRelay_relayURL", + "unique": false, + "columnNames": [ + "relayURL" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEventRelay_relayURL` ON `${TABLE_NAME}` (`relayURL`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Participant", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `participantPublicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `adminAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, FOREIGN KEY(`participantPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "adminAt", + "columnName": "adminAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "participantPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Post", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `repostId` TEXT, `quote` TEXT, `content` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `replyToId` TEXT, `profilePublicKey` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`profilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyToId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostId", + "columnName": "repostId", + "affinity": "TEXT" + }, + { + "fieldPath": "quote", + "columnName": "quote", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToId", + "columnName": "replyToId", + "affinity": "TEXT" + }, + { + "fieldPath": "profilePublicKey", + "columnName": "profilePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Post_profilePublicKey", + "unique": false, + "columnNames": [ + "profilePublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_profilePublicKey` ON `${TABLE_NAME}` (`profilePublicKey`)" + }, + { + "name": "index_Post_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Post_replyToId", + "unique": false, + "columnNames": [ + "replyToId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_replyToId` ON `${TABLE_NAME}` (`replyToId`)" + }, + { + "name": "index_Post_repostId", + "unique": false, + "columnNames": [ + "repostId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_repostId` ON `${TABLE_NAME}` (`repostId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "profilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyToId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Profile", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`publicKey` TEXT NOT NULL, `userName` TEXT, `displayName` TEXT, `picture` TEXT, `banner` TEXT, `website` TEXT, `about` TEXT, `bot` INTEGER, `pronouns` TEXT, `nip05` TEXT, `domain` TEXT, `lud06` TEXT, `lud16` TEXT, `twitter` TEXT, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`publicKey`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userName", + "columnName": "userName", + "affinity": "TEXT" + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT" + }, + { + "fieldPath": "picture", + "columnName": "picture", + "affinity": "TEXT" + }, + { + "fieldPath": "banner", + "columnName": "banner", + "affinity": "TEXT" + }, + { + "fieldPath": "website", + "columnName": "website", + "affinity": "TEXT" + }, + { + "fieldPath": "about", + "columnName": "about", + "affinity": "TEXT" + }, + { + "fieldPath": "bot", + "columnName": "bot", + "affinity": "INTEGER" + }, + { + "fieldPath": "pronouns", + "columnName": "pronouns", + "affinity": "TEXT" + }, + { + "fieldPath": "nip05", + "columnName": "nip05", + "affinity": "TEXT" + }, + { + "fieldPath": "domain", + "columnName": "domain", + "affinity": "TEXT" + }, + { + "fieldPath": "lud06", + "columnName": "lud06", + "affinity": "TEXT" + }, + { + "fieldPath": "lud16", + "columnName": "lud16", + "affinity": "TEXT" + }, + { + "fieldPath": "twitter", + "columnName": "twitter", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "publicKey" + ] + }, + "indices": [ + { + "name": "index_Profile_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Profile_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "QuotedRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`quotingNostrEventId` TEXT NOT NULL, `quotedNostrEventId` TEXT NOT NULL, `quotedProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`quotingNostrEventId`, `quotedNostrEventId`), FOREIGN KEY(`quotedProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`quotingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`quotedNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "quotingNostrEventId", + "columnName": "quotingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedNostrEventId", + "columnName": "quotedNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedProfilePublicKey", + "columnName": "quotedProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "quotingNostrEventId", + "quotedNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotedProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Reaction", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `content` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `replyToId` TEXT NOT NULL, `profilePublicKey` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`profilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyToId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToId", + "columnName": "replyToId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "profilePublicKey", + "columnName": "profilePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Reaction_profilePublicKey", + "unique": false, + "columnNames": [ + "profilePublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_profilePublicKey` ON `${TABLE_NAME}` (`profilePublicKey`)" + }, + { + "name": "index_Reaction_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Reaction_replyToId", + "unique": false, + "columnNames": [ + "replyToId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_replyToId` ON `${TABLE_NAME}` (`replyToId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "profilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyToId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "RecentSearch", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`query` TEXT NOT NULL, `synchronizationFilters` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`query`))", + "fields": [ + { + "fieldPath": "query", + "columnName": "query", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "synchronizationFilters", + "columnName": "synchronizationFilters", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "query" + ] + } + }, + { + "tableName": "Relay", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`publicKey` TEXT NOT NULL, `type` TEXT NOT NULL, `url` TEXT NOT NULL, `read` INTEGER NOT NULL, `write` INTEGER NOT NULL, PRIMARY KEY(`publicKey`, `type`, `url`))", + "fields": [ + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "read", + "columnName": "read", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "write", + "columnName": "write", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "publicKey", + "type", + "url" + ] + } + }, + { + "tableName": "RepostedRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`repostingNostrEventId` TEXT NOT NULL, `repostedNostrEventId` TEXT NOT NULL, `repostedProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`repostingNostrEventId`, `repostedNostrEventId`), FOREIGN KEY(`repostedProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostedNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "repostingNostrEventId", + "columnName": "repostingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostedNostrEventId", + "columnName": "repostedNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostedProfilePublicKey", + "columnName": "repostedProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "repostingNostrEventId", + "repostedNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostedProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "SynchronizeNostrEventRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `purpose` TEXT NOT NULL, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `isRecommendedRelay` INTEGER NOT NULL, `level` INTEGER NOT NULL, `synchronizationFilters` TEXT NOT NULL, `ownerPublicKey` TEXT, `nostrEventId` TEXT, `unsignedNostrEventId` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isRecommendedRelay", + "columnName": "isRecommendedRelay", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "level", + "columnName": "level", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "synchronizationFilters", + "columnName": "synchronizationFilters", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerPublicKey", + "columnName": "ownerPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_SynchronizeNostrEventRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_SynchronizeNostrEventRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "SynchronizeNostrEventResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_SynchronizeNostrEventResult_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventResult_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "UnsignedNostrEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `pubKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `privateTags` TEXT, `content` TEXT NOT NULL, `signedAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "privateTags", + "columnName": "privateTags", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signedAt", + "columnName": "signedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_UnsignedNostrEvent_pubKey", + "unique": false, + "columnNames": [ + "pubKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_UnsignedNostrEvent_pubKey` ON `${TABLE_NAME}` (`pubKey`)" + }, + { + "name": "index_UnsignedNostrEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_UnsignedNostrEvent_kind` ON `${TABLE_NAME}` (`kind`)" + } + ] + }, + { + "tableName": "Zap", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `postId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `receiverPublicKey` TEXT NOT NULL, `message` TEXT, `invoice` TEXT, `amountInMillisatoshis` INTEGER, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`senderPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`receiverPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`postId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "postId", + "columnName": "postId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receiverPublicKey", + "columnName": "receiverPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "message", + "columnName": "message", + "affinity": "TEXT" + }, + { + "fieldPath": "invoice", + "columnName": "invoice", + "affinity": "TEXT" + }, + { + "fieldPath": "amountInMillisatoshis", + "columnName": "amountInMillisatoshis", + "affinity": "INTEGER" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Zap_senderPublicKey", + "unique": false, + "columnNames": [ + "senderPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_senderPublicKey` ON `${TABLE_NAME}` (`senderPublicKey`)" + }, + { + "name": "index_Zap_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Zap_postId", + "unique": false, + "columnNames": [ + "postId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_postId` ON `${TABLE_NAME}` (`postId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "senderPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "receiverPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "postId" + ], + "referencedColumns": [ + "id" + ] + } + ] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '690e3d5ecde4b3bfe7f46f8e530c249a')" + ] + } +} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt index baf26602..9131398d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt @@ -25,6 +25,8 @@ import mobi.giza.compose.database.dao.GiftWrapPayloadDao import mobi.giza.compose.database.dao.GiftWrapSealDao import mobi.giza.compose.database.dao.GroupKeyStateDao import mobi.giza.compose.database.dao.GroupSignedEventDao +import mobi.giza.compose.database.dao.GroupInboxDao +import mobi.giza.compose.database.dao.InboxKeyDao import mobi.giza.compose.database.dao.InReplyToRelationDao import mobi.giza.compose.database.dao.KeyShareDao import mobi.giza.compose.database.dao.ShareRefreshDao @@ -112,6 +114,12 @@ import mobi.giza.compose.database.model.Reaction import mobi.giza.compose.database.model.RecentSearch import mobi.giza.compose.database.model.DkgParticipantMessage import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.GroupInboxMessage +import mobi.giza.compose.database.model.GroupInboxPublication +import mobi.giza.compose.database.model.GroupInboxWrap +import mobi.giza.compose.database.model.InboxKey +import mobi.giza.compose.database.model.InboxKeyCeremony +import mobi.giza.compose.database.model.InboxKeyCeremonyMessage import mobi.giza.compose.database.model.FrostSignerMessage import mobi.giza.compose.database.model.FrostSigningItem import mobi.giza.compose.database.model.FrostSigningSession @@ -150,8 +158,14 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) GiftWrapMessage::class, GiftWrapSeal::class, GiftWrapPayload::class, + GroupInboxMessage::class, + GroupInboxPublication::class, + GroupInboxWrap::class, GroupKeyState::class, GroupSignedEvent::class, + InboxKey::class, + InboxKeyCeremony::class, + InboxKeyCeremonyMessage::class, KeyShareGeneration::class, KeyShareMember::class, ShareRefreshConfirmation::class, @@ -189,7 +203,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) UnsignedNostrEvent::class, Zap::class ], - version = 44, + version = 45, autoMigrations = [ // v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can // generate the migration itself — nothing existing changes shape. @@ -461,6 +475,11 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) // Phases 11 and 12): ConfederationCeremony, ConfederationCeremonyMessage, Confederation // and ConfederationMember. New tables only, so Room generates it. AutoMigration(from = 43, to = 44), + // v45 adds the group's inbox (docs/group-inbox.md, Phase 3): InboxKeyCeremony, + // InboxKeyCeremonyMessage and InboxKey, kept apart from DkgSession so no signing path + // can find a threshold-1 key, and GroupInboxWrap, GroupInboxMessage and + // GroupInboxPublication. New tables only, so Room generates it. + AutoMigration(from = 44, to = 45), ] ) @ConstructedBy(GizaDatabaseConstructor::class) @@ -506,6 +525,10 @@ abstract class GizaDatabase: RoomDatabase() { abstract fun groupSignedEventDao(): GroupSignedEventDao + abstract fun inboxKeyDao(): InboxKeyDao + + abstract fun groupInboxDao(): GroupInboxDao + abstract fun connectionDao(): ConnectionDao diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupInboxDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupInboxDao.kt new file mode 100644 index 00000000..d306b318 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupInboxDao.kt @@ -0,0 +1,84 @@ +package mobi.giza.compose.database.dao + +import androidx.room3.Dao +import androidx.room3.Insert +import androidx.room3.OnConflictStrategy +import androidx.room3.Query +import androidx.room3.Upsert +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.flow.Flow +import mobi.giza.compose.database.model.GroupInboxMessage +import mobi.giza.compose.database.model.GroupInboxPublication +import mobi.giza.compose.database.model.GroupInboxWrap +import kotlin.time.Instant + +/** What a group's inbox has received, filed and owes relays (docs/group-inbox.md, Phase 3). */ +@Dao +interface GroupInboxDao { + /** The ledger is keyed by the wrap's id: a second copy of one changes nothing. */ + @Insert(onConflict = OnConflictStrategy.IGNORE) + suspend fun insertWrap(wrap: GroupInboxWrap): Long + + @Query("SELECT * FROM GroupInboxWrap WHERE id = :id") + suspend fun getWrap(id: HexKey): GroupInboxWrap? + + @Query("SELECT * FROM GroupInboxWrap WHERE chatRoomId = :chatRoomId AND openedGeneration IS NULL ORDER BY receivedAt") + suspend fun getUnopenedWraps(chatRoomId: String): List + + @Query("SELECT COUNT(*) FROM GroupInboxWrap WHERE chatRoomId = :chatRoomId AND openedGeneration IS NULL") + fun observeUnopenedCount(chatRoomId: String): Flow + + /** The newest wrap's own time in a room: where a catch-up starts, less NIP-59's two days. */ + @Query("SELECT MAX(wrapCreatedAt) FROM GroupInboxWrap WHERE chatRoomId = :chatRoomId") + suspend fun newestWrapCreatedAt(chatRoomId: String): Long? + + @Query("UPDATE GroupInboxWrap SET openedGeneration = :generation WHERE id = :id") + suspend fun markOpened(id: HexKey, generation: Int) + + /** Keyed by room and rumor: two wraps of one rumor are one message, and the first is kept. */ + @Insert(onConflict = OnConflictStrategy.IGNORE) + suspend fun insertMessage(message: GroupInboxMessage): Long + + @Query("SELECT * FROM GroupInboxMessage WHERE chatRoomId = :chatRoomId AND rumorId = :rumorId") + suspend fun getMessage(chatRoomId: String, rumorId: HexKey): GroupInboxMessage? + + @Query("SELECT * FROM GroupInboxMessage WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC") + fun observeMessages(chatRoomId: String): Flow> + + @Query("SELECT * FROM GroupInboxMessage WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC") + suspend fun getMessages(chatRoomId: String): List + + @Query("SELECT * FROM GroupInboxMessage WHERE chatRoomId = :chatRoomId AND conversationId = :conversationId ORDER BY createdAt ASC") + fun observeConversation(chatRoomId: String, conversationId: String): Flow> + + @Query("SELECT * FROM GroupInboxMessage WHERE chatRoomId = :chatRoomId AND conversationId = :conversationId ORDER BY createdAt ASC") + suspend fun getConversation(chatRoomId: String, conversationId: String): List + + @Query("SELECT COUNT(*) FROM GroupInboxMessage WHERE chatRoomId = :chatRoomId AND outgoing = 0 AND readAt IS NULL") + fun observeUnreadCount(chatRoomId: String): Flow + + @Query("UPDATE GroupInboxMessage SET readAt = :at WHERE chatRoomId = :chatRoomId AND conversationId = :conversationId AND readAt IS NULL") + suspend fun markConversationRead(chatRoomId: String, conversationId: String, at: Instant) + + @Query("DELETE FROM GroupInboxMessage WHERE chatRoomId = :chatRoomId") + suspend fun deleteMessages(chatRoomId: String) + + @Query("DELETE FROM GroupInboxWrap WHERE chatRoomId = :chatRoomId") + suspend fun deleteWraps(chatRoomId: String) + + @Upsert + suspend fun upsertPublication(publication: GroupInboxPublication) + + @Query("SELECT * FROM GroupInboxPublication WHERE eventId = :eventId") + suspend fun getPublication(eventId: HexKey): GroupInboxPublication? + + /** What is still owed and due by [now], oldest first. */ + @Query("SELECT * FROM GroupInboxPublication WHERE publishedAt IS NULL AND (nextAttemptAt IS NULL OR nextAttemptAt <= :now) ORDER BY createdAt") + suspend fun getDuePublications(now: Instant): List + + @Query("SELECT * FROM GroupInboxPublication WHERE signingSessionId = :signingSessionId") + suspend fun getPublicationsFor(signingSessionId: String): List + + @Query("SELECT * FROM GroupInboxPublication WHERE signingSessionId = :signingSessionId") + fun observePublicationsFor(signingSessionId: String): Flow> +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/InboxKeyDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/InboxKeyDao.kt new file mode 100644 index 00000000..aec555e9 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/InboxKeyDao.kt @@ -0,0 +1,78 @@ +package mobi.giza.compose.database.dao + +import androidx.room3.Dao +import androidx.room3.Insert +import androidx.room3.OnConflictStrategy +import androidx.room3.Query +import androidx.room3.Upsert +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import kotlinx.coroutines.flow.Flow +import mobi.giza.compose.database.model.InboxKey +import mobi.giza.compose.database.model.InboxKeyCeremony +import mobi.giza.compose.database.model.InboxKeyCeremonyMessage +import kotlin.time.Instant + +/** The group inbox's key ceremonies and the keys they leave (docs/group-inbox.md, Phase 3). */ +@Dao +interface InboxKeyDao { + @Query("SELECT * FROM InboxKeyCeremony WHERE id = :id") + suspend fun getCeremony(id: String): InboxKeyCeremony? + + @Query("SELECT * FROM InboxKeyCeremony WHERE id = :id") + fun observeCeremony(id: String): Flow + + @Query("SELECT * FROM InboxKeyCeremony WHERE chatRoomId = :chatRoomId AND userPublicKey = :userPublicKey ORDER BY createdAt DESC LIMIT 1") + suspend fun getLatestCeremony(chatRoomId: String, userPublicKey: HexKey): InboxKeyCeremony? + + @Query("SELECT * FROM InboxKeyCeremony WHERE chatRoomId = :chatRoomId AND userPublicKey = :userPublicKey ORDER BY createdAt DESC LIMIT 1") + fun observeLatestCeremony(chatRoomId: String, userPublicKey: HexKey): Flow + + @Query("SELECT * FROM InboxKeyCeremony WHERE userPublicKey = :userPublicKey AND stage NOT IN ('COMPLETE', 'FAILED')") + suspend fun getRunningCeremonies(userPublicKey: HexKey): List + + @Query("SELECT * FROM InboxKeyCeremony WHERE chatRoomId = :chatRoomId AND stage NOT IN ('COMPLETE', 'FAILED')") + suspend fun getRunningCeremoniesIn(chatRoomId: String): List + + @Upsert + suspend fun upsertCeremony(ceremony: InboxKeyCeremony) + + @Query("SELECT * FROM InboxKeyCeremonyMessage WHERE sessionId = :sessionId") + suspend fun getMessages(sessionId: String): List + + @Query("SELECT * FROM InboxKeyCeremonyMessage WHERE sessionId = :sessionId") + fun observeMessages(sessionId: String): Flow> + + @Query("SELECT * FROM InboxKeyCeremonyMessage WHERE sessionId = :sessionId AND senderPublicKey = :sender AND kind = :kind") + suspend fun getMessage(sessionId: String, sender: HexKey, kind: Kind): InboxKeyCeremonyMessage? + + /** Ignores a second copy: relays redeliver, and the first one a ceremony read is the one it used. */ + @Insert(onConflict = OnConflictStrategy.IGNORE) + suspend fun insertMessage(message: InboxKeyCeremonyMessage): Long + + @Query("SELECT * FROM InboxKey WHERE chatRoomId = :chatRoomId AND userPublicKey = :userPublicKey ORDER BY generation DESC") + suspend fun getKeys(chatRoomId: String, userPublicKey: HexKey): List + + @Query("SELECT * FROM InboxKey WHERE chatRoomId = :chatRoomId AND userPublicKey = :userPublicKey ORDER BY generation DESC") + fun observeKeys(chatRoomId: String, userPublicKey: HexKey): Flow> + + @Query("SELECT * FROM InboxKey WHERE chatRoomId = :chatRoomId AND userPublicKey = :userPublicKey AND generation = :generation") + suspend fun getKey(chatRoomId: String, userPublicKey: HexKey, generation: Int): InboxKey? + + /** Every key this identity can still open mail with, in every room, newest generation first. */ + @Query("SELECT * FROM InboxKey WHERE userPublicKey = :userPublicKey AND secretKey IS NOT NULL ORDER BY chatRoomId, generation DESC") + suspend fun getHeldKeys(userPublicKey: HexKey): List + + @Query("SELECT * FROM InboxKey WHERE userPublicKey = :userPublicKey AND secretKey IS NOT NULL ORDER BY chatRoomId, generation DESC") + fun observeHeldKeys(userPublicKey: HexKey): Flow> + + /** Any key a 10044 could name in this room, held here or not: [publicKey] is public. */ + @Query("SELECT * FROM InboxKey WHERE chatRoomId = :chatRoomId AND publicKey = :publicKey LIMIT 1") + suspend fun findByPublicKey(chatRoomId: String, publicKey: HexKey): InboxKey? + + @Upsert + suspend fun upsertKey(key: InboxKey) + + @Query("UPDATE InboxKey SET secretKey = NULL, recoveryData = NULL, state = 'WIPED', wipedAt = :at WHERE chatRoomId = :chatRoomId AND userPublicKey = :userPublicKey") + suspend fun wipeKeys(chatRoomId: String, userPublicKey: HexKey, at: Instant) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupInbox.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupInbox.kt new file mode 100644 index 00000000..9a56c742 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupInbox.kt @@ -0,0 +1,114 @@ +package mobi.giza.compose.database.model + +import androidx.room3.Entity +import androidx.room3.ForeignKey +import androidx.room3.Index +import androidx.room3.PrimaryKey +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import kotlin.time.Clock +import kotlin.time.Instant + +/** + * Every gift wrap addressed to a group this device keeps an inbox for, opened or not + * (docs/group-inbox.md, D8). + * + * The ledger is what makes redelivery a no-op, and what lets a key that arrives later -- a + * restore, a ceremony that finished after the mail did -- reopen what is already here. A wrap + * no held key opens stays with [openedGeneration] null, and is counted on the inbox screen + * rather than hidden. + * + * Never a `GiftWrapMessage`: those belong to the personal inbox, which would file the group's + * correspondents into the admin's own direct messages. + */ +@Entity( + foreignKeys = [ + ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE) + ], + indices = [Index("chatRoomId")], +) +data class GroupInboxWrap( + @PrimaryKey + val id: HexKey, + val chatRoomId: String, + /** The wrap as it arrived, so it can be tried again with a key this device gets later. */ + val wrapJson: String, + /** The wrap's own `created_at`: back-dated by up to two days, as NIP-59 has it. */ + val wrapCreatedAt: Long, + /** The inbox key generation that opened it, or null while none has. */ + val openedGeneration: Int? = null, + val receivedAt: Instant = Clock.System.now(), +) + +/** + * A message in a group's inbox, incoming or outgoing (docs/group-inbox.md, D8 and D10): one row + * per rumor, however many wraps carried it. + */ +@Entity( + primaryKeys = ["chatRoomId", "rumorId"], + foreignKeys = [ + ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE) + ], + indices = [Index("chatRoomId"), Index("conversationId")], +) +data class GroupInboxMessage( + val chatRoomId: String, + /** Computed from the rumor, never taken from it. */ + val rumorId: HexKey, + /** The first wrap it arrived in; null for an outgoing message filed before its copy came back. */ + val wrapId: HexKey?, + /** [mobi.giza.compose.nostr.inbox.InboxConversation.idOf] over [participants]. */ + val conversationId: String, + /** Everyone in the conversation but the group, sorted, comma-separated. */ + val participants: String, + val senderPublicKey: HexKey, + val kind: Kind, + /** The rumor as NIP-59 carries it: its id and no signature. */ + val rumorJson: String, + /** The rumor's own `created_at`, unfuzzed: when the sender says they wrote it. */ + val createdAt: Long, + /** The inbox key generation that opened it, or sealed it if outgoing. */ + val generation: Int, + /** Written by the group: a reply. */ + val outgoing: Boolean, + /** The signing session a reply came from, when this device knows it. */ + val signingSessionId: String? = null, + val readAt: Instant? = null, + val receivedAt: Instant = Clock.System.now(), +) { + fun participantList(): List = participants.split(",").map { it.trim() }.filter { it.isNotEmpty() } +} + +/** + * An event this device owes relays on the group's behalf (docs/group-inbox.md, D7 and D10): a + * signed 10044 or 10050 the group agreed to, or a gift wrap carrying a reply it signed. Sent with + * backoff until a relay takes it, as `ConfederationPublisher` sends confederation events. + * + * Never a `NostrEvent` row, for the reasons group-nostr-profile-and-posts.md D7 gives: the group's + * events are not the feed's, and a kind 0 or 10050 there would make a profile of the group. + */ +@Entity( + foreignKeys = [ + ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE) + ], + indices = [Index("chatRoomId"), Index("signingSessionId")], +) +data class GroupInboxPublication( + @PrimaryKey + val eventId: HexKey, + val chatRoomId: String, + val kind: Kind, + val eventJson: String, + /** Where it goes, comma-separated; the app's publish set is added to these. */ + val relays: String, + /** The signing session it came from. */ + val signingSessionId: String?, + /** For a wrap: who it is to. Null for the group's own announcements. */ + val recipientPublicKey: HexKey?, + val attempts: Int = 0, + val nextAttemptAt: Instant? = null, + val publishedAt: Instant? = null, + val createdAt: Instant = Clock.System.now(), +) { + fun relayList(): List = relays.split(",").map { it.trim() }.filter { it.isNotEmpty() } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/InboxKeyCeremony.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/InboxKeyCeremony.kt new file mode 100644 index 00000000..018dfdb9 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/InboxKeyCeremony.kt @@ -0,0 +1,138 @@ +package mobi.giza.compose.database.model + +import androidx.room3.Entity +import androidx.room3.ForeignKey +import androidx.room3.Index +import androidx.room3.PrimaryKey +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import kotlin.time.Clock +import kotlin.time.Instant + +/** + * One device's part in a group's inbox key ceremony (docs/group-inbox.md, D2 and D3): ChillDKG + * at threshold 1 over the room's admins. + * + * Kept apart from [DkgSession] on purpose. Every completed `DkgSession` is a key the signing + * path may find, and a threshold-1 key there would be a key any one admin could sign as the + * group with. Nothing that looks for a signing key reads this table. + * + * Inputs, never protocol state, as `DkgSession` keeps them: every step is a pure function of + * the randomness here and the messages in [InboxKeyCeremonyMessage], so a device that dies + * between rounds recomputes the step on the next message. The secret it produces is not kept + * here but in [InboxKey], once, when the ceremony completes. + */ +@Entity( + foreignKeys = [ + ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE) + ], + indices = [Index("chatRoomId")], +) +data class InboxKeyCeremony( + @PrimaryKey + val id: String, + /** The group's Marmot room: the ceremony runs in it, and its admins are the participants. */ + val chatRoomId: String, + /** Which generation of the room's inbox key this ceremony makes. */ + val generation: Int, + val coordinatorPublicKey: HexKey, + /** The identity on this device taking part, or watching. */ + val userPublicKey: HexKey, + /** The admins the proposal named, sorted, comma-separated. */ + val participantPublicKeys: String, + val stage: InboxKeyCeremonyStage = InboxKeyCeremonyStage.COLLECTING_HOST_KEYS, + /** Null on the device of a member who is not a participant: it only watches. */ + val hostPublicKey: HexKey? = null, + val round1Random: HexKey? = null, + val round2AuxRandom: HexKey? = null, + /** The ceremony's public key `E`, x-only, once it is certified. */ + val inboxPublicKey: HexKey? = null, + val failureReason: String? = null, + /** Whose fault a failure was, when ChillDKG could say. */ + val culprit: HexKey? = null, + /** When the last message arrived: what "waiting since" is measured from. */ + val lastMessageAt: Instant = Clock.System.now(), + val createdAt: Instant = Clock.System.now(), + val updatedAt: Instant = createdAt, +) { + val isRunning: Boolean + get() = stage != InboxKeyCeremonyStage.COMPLETE && stage != InboxKeyCeremonyStage.FAILED + + fun isCoordinator(): Boolean = coordinatorPublicKey == userPublicKey + + fun participants(): List = participantPublicKeys.split(",").map { it.trim() }.filter { it.isNotEmpty() } + + fun isParticipant(): Boolean = userPublicKey in participants() + + companion object { + fun formatParticipants(publicKeys: Collection): String = publicKeys.distinct().sorted().joinToString(",") + } +} + +/** Where an inbox key ceremony has got to, as a label for screens. */ +enum class InboxKeyCeremonyStage { + COLLECTING_HOST_KEYS, + ROUND_1, + ROUND_2, + COMPLETE, + FAILED, +} + +/** One message an inbox key ceremony has received or sent, written once per sender and kind. */ +@Entity( + primaryKeys = ["sessionId", "senderPublicKey", "kind"], + foreignKeys = [ + ForeignKey(entity = InboxKeyCeremony::class, parentColumns = ["id"], childColumns = ["sessionId"], onDelete = ForeignKey.CASCADE) + ], +) +data class InboxKeyCeremonyMessage( + val sessionId: String, + val senderPublicKey: HexKey, + val kind: Kind, + val payload: String, + val receivedAt: Instant = Clock.System.now(), +) + +/** + * One generation of a group's inbox key, as this device holds it (docs/group-inbox.md, D14). + * + * [secretKey] is the whole secret `e`: every admin holds it, which is the point of it. It is + * kept as a share is kept, and wiped as a share is wiped -- [state] goes to [InboxKeyState.WIPED] + * and the secret to null, while [publicKey] stays so the device can still say which key it was. + */ +@Entity( + primaryKeys = ["chatRoomId", "userPublicKey", "generation"], + foreignKeys = [ + ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE) + ], + indices = [Index("chatRoomId")], +) +data class InboxKey( + val chatRoomId: String, + val userPublicKey: HexKey, + val generation: Int, + /** `E`, x-only hex: what the group's 10044 names. */ + val publicKey: HexKey, + /** `e`, hex; null once wiped. */ + val secretKey: HexKey?, + /** ChillDKG's recovery data: with the host secret from the nsec, it restores [secretKey]. */ + val recoveryData: HexKey?, + val ceremonyId: String, + val state: InboxKeyState = InboxKeyState.HELD, + /** The signed 10044 that announced this generation, once there is one. */ + val announcementEventId: HexKey? = null, + val createdAt: Instant = Clock.System.now(), + val announcedAt: Instant? = null, + val wipedAt: Instant? = null, +) + +enum class InboxKeyState { + /** Made, not yet announced: nobody has been told to write to it. */ + HELD, + /** The key the group's newest signed 10044 names: replies are sealed from it. */ + ANNOUNCED, + /** Replaced by a later generation: used to open, never to seal. */ + RETIRED, + /** Gone from this device: the admin was removed, or the device asked to forget. */ + WIPED, +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/InboxStorageJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/InboxStorageJvmTest.kt new file mode 100644 index 00000000..c56b8628 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/InboxStorageJvmTest.kt @@ -0,0 +1,131 @@ +package mobi.giza.compose.database + +import androidx.room3.Room +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.GroupInboxMessage +import mobi.giza.compose.database.model.GroupInboxWrap +import mobi.giza.compose.database.model.InboxKey +import mobi.giza.compose.database.model.InboxKeyCeremony +import mobi.giza.compose.database.model.InboxKeyCeremonyMessage +import mobi.giza.compose.database.model.InboxKeyCeremonyStage +import mobi.giza.compose.database.model.InboxKeyState +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.managers.FrostSigningManager +import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents + +/** + * Where a group's inbox is kept (docs/group-inbox.md, Phase 3): redelivery changes nothing, + * a wipe keeps the key's name and loses its secret, and nothing a signing path reads can find a + * threshold-1 key. + */ +class InboxStorageJvmTest { + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + private val room = "f".repeat(64) + private val admin = "a".repeat(64) + + @AfterTest + fun close() = db.close() + + private fun seedRoom() = runBlocking { + // A room belongs to a profile, which belongs to the event that made it. + val profileEvent = "9".repeat(64) + db.nostrEventDao().upsert(NostrEvent(id = profileEvent, pubKey = admin, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = admin, nostrEventId = profileEvent)) + db.chatRoomDao().upsert(ChatRoom(id = room, userPublicKey = admin, subject = "#Ekklesia", description = "", mlsGroupState = null)) + } + + private fun completedCeremonyAndKey() = runBlocking { + seedRoom() + db.inboxKeyDao().upsertCeremony( + InboxKeyCeremony( + id = "c".repeat(64), + chatRoomId = room, + generation = 0, + coordinatorPublicKey = admin, + userPublicKey = admin, + participantPublicKeys = InboxKeyCeremony.formatParticipants(listOf(admin, "b".repeat(64))), + stage = InboxKeyCeremonyStage.COMPLETE, + hostPublicKey = "02" + "1".repeat(64), + round1Random = "2".repeat(64), + round2AuxRandom = "3".repeat(64), + inboxPublicKey = "e".repeat(64), + ) + ) + db.inboxKeyDao().upsertKey( + InboxKey( + chatRoomId = room, + userPublicKey = admin, + generation = 0, + publicKey = "e".repeat(64), + secretKey = "5".repeat(64), + recoveryData = "66", + ceremonyId = "c".repeat(64), + ) + ) + } + + @Test + fun `a ceremony message delivered twice is kept once, as first received`() = runBlocking { + completedCeremonyAndKey() + val first = InboxKeyCeremonyMessage("c".repeat(64), admin, InboxKeyRitualEvents.HOST_KEY, "first") + assertTrue(db.inboxKeyDao().insertMessage(first) > 0) + assertEquals(-1L, db.inboxKeyDao().insertMessage(first.copy(payload = "second"))) + assertEquals("first", db.inboxKeyDao().getMessage("c".repeat(64), admin, InboxKeyRitualEvents.HOST_KEY)?.payload) + } + + @Test + fun `a wrap or a rumor delivered twice is one row`() = runBlocking { + seedRoom() + val wrap = GroupInboxWrap(id = "1".repeat(64), chatRoomId = room, wrapJson = "{}", wrapCreatedAt = 10) + db.groupInboxDao().insertWrap(wrap) + db.groupInboxDao().insertWrap(wrap.copy(wrapJson = "{\"again\":true}")) + assertEquals(listOf(wrap.id to wrap.wrapJson), db.groupInboxDao().getUnopenedWraps(room).map { it.id to it.wrapJson }) + + val message = GroupInboxMessage( + chatRoomId = room, rumorId = "2".repeat(64), wrapId = wrap.id, conversationId = "x", + participants = "b".repeat(64), senderPublicKey = "b".repeat(64), kind = 14, + rumorJson = "{}", createdAt = 5, generation = 0, outgoing = false, + ) + db.groupInboxDao().insertMessage(message) + db.groupInboxDao().insertMessage(message.copy(wrapId = "3".repeat(64))) + assertEquals(listOf(message.wrapId), db.groupInboxDao().getMessages(room).map { it.wrapId }) + assertEquals(1, db.groupInboxDao().observeUnreadCount(room).first()) + + db.groupInboxDao().markOpened(wrap.id, 0) + assertEquals(0, db.groupInboxDao().observeUnopenedCount(room).first()) + } + + @Test + fun `a wipe loses the secret and keeps the key's name`() = runBlocking { + completedCeremonyAndKey() + db.inboxKeyDao().wipeKeys(room, admin, Clock.System.now()) + + val key = assertNotNull(db.inboxKeyDao().getKey(room, admin, 0)) + assertNull(key.secretKey) + assertNull(key.recoveryData) + assertEquals(InboxKeyState.WIPED, key.state) + assertEquals("e".repeat(64), key.publicKey) + assertEquals(emptyList(), db.inboxKeyDao().getHeldKeys(admin)) + } + + @Test + fun `no signing path can find an inbox key`() = runBlocking { + // D3: a threshold-1 key any one admin holds, found by the signing path, would let one + // admin sign as the group. It lives where nothing that signs looks. + completedCeremonyAndKey() + assertEquals(emptyList(), db.dkgSessionDao().getKeyHoldingSessions()) + assertNull(FrostSigningManager.completedKey(db, room)) + assertEquals(false, FrostSigningManager.canSign(db, room)) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt index c76db20d..38cbbc44 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt @@ -66,10 +66,11 @@ class ShippedProfileUpgradeJvmTest { * refresh and 40 for share repair (docs/frost-share-refresh.md, Phases 6, 7 and * 10), 41 for governance proposals and 42 for what follows them * (docs/member-admin-promotion.md, Phases 5, 8 and 9), 43 for the confederation - * (docs/confederation.md, Phase 4) and 44 for its key ceremony (Phase 11), so the upgrade - * crosses eight generated migrations and the file has to come out at the last. + * (docs/confederation.md, Phase 4), 44 for its key ceremony (Phase 11) and 45 for the group's + * inbox (docs/group-inbox.md, Phase 3), so the upgrade crosses nine generated migrations and + * the file has to come out at the last. */ - private val current = 44 + private val current = 45 private val directory: File = Files.createTempDirectory("giza-shipped-profile").toFile() private val file: File = File(directory, "aux.db") From 057d0b79d9ac6e152b94502d69cbdbc5251d2176 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 01:41:46 +0200 Subject: [PATCH 09/16] feat: the group's inbox key, made by its admins at threshold 1 (group-inbox, Phase 4) InboxKeyRitualManager runs ChillDKG at t = 1 over the room's admins as MLS inner events on 30410-30416, so every admin ends with the same secret and the group a key nobody chose alone. Nobody is asked: an admin's device takes part on arrival, and a proposal over anyone but the admins as this device reads them fails out loud with the difference named. A member who is not an admin watches and holds nothing. The secret is checked against the key on every run and written once to InboxKey; the sweep resumes a ceremony left mid-round. The ceremony's screen moves to Phase 7 with the inbox's others. Co-Authored-By: Claude Opus 5.5 --- .../mobi/giza/compose/ExperimentalFeatures.kt | 13 + .../giza/compose/database/dao/NostrDao.kt | 17 + .../compose/database/model/ChatMessage.kt | 24 +- .../repository/DatabaseNostrRepository.kt | 5 + .../compose/managers/InboxFollowThrough.kt | 15 + .../compose/managers/InboxKeyRitualManager.kt | 557 ++++++++++++++++++ .../compose/managers/GroupInboxHarness.kt | 175 ++++++ .../compose/managers/InboxKeyRitualJvmTest.kt | 202 +++++++ 8 files changed, 1007 insertions(+), 1 deletion(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxFollowThrough.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxHarness.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxKeyRitualJvmTest.kt diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt index 0de7ed92..38495efb 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt @@ -28,6 +28,19 @@ object ExperimentalFeatures { */ val confederation: Boolean get() = confederationOverride ?: isDevelopmentBuild() + + /** Set by a test that has to see the build a release would be. */ + var groupInboxOverride: Boolean? = null + + /** + * A group that can be written to privately (docs/group-inbox.md): an inbox key its admins + * make together and the group announces, the messages sent to it, and replies the quorum + * signs. Off in a release while NIP-4E is a draft: off, the app offers no inbox, starts no + * ceremony and listens for nothing. A device still declines, out loud, an inbox + * announcement or a reply it finds wrong -- that is a refusal, not a feature. + */ + val groupInbox: Boolean + get() = groupInboxOverride ?: isDevelopmentBuild() } /** Whether this is a debug or development build of the app, rather than a release. */ diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt index aefdadb5..b3e1f83a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt @@ -88,6 +88,8 @@ import mobi.giza.compose.nostr.Relays import mobi.giza.compose.nostr.dkg.DkgRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.managers.ConfederationRitualManager +import mobi.giza.compose.managers.InboxKeyRitualManager +import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.nostr.frost.ShareRefreshEvents import mobi.giza.compose.nostr.frost.ShareRepairEvents @@ -1703,6 +1705,21 @@ abstract class NostrDao( nostrPrivateKey = activeKeyPair.privKey!! ) + // The group's inbox key, made by its admins in the group's own + // room (docs/group-inbox.md, D3). Off with the feature: a release + // build takes no part in a ceremony for a key it would not use. + InboxKeyRitualEvents.isInboxKeyKind(innerEvent.kind) -> { + if (ExperimentalFeatures.groupInbox) { + InboxKeyRitualManager.process( + database = database, + localChatRoom = localChatRoom, + innerEvent = innerEvent, + userPublicKey = activeKeyPair.pubKey.toHex(), + nostrPrivateKey = activeKeyPair.privKey!! + ) + } + } + // And a repair, in the same room (Phase 10). ShareRepairEvents.isShareRepairKind(innerEvent.kind) -> ShareRepairManager.processRepairPayload( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt index 16f51b26..8012d5b1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt @@ -4,6 +4,7 @@ import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import mobi.giza.compose.nostr.GroupNostrProfile import mobi.giza.compose.nostr.RetiredKinds import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents import androidx.room3.Entity import androidx.room3.ForeignKey @@ -555,6 +556,23 @@ data class ChatMessage( TYPE_CONFEDERATION_FORMED, ) + /** + * The group's inbox (docs/group-inbox.md): its key ceremony starting, finishing or + * failing, written by `InboxKeyRitualManager` on every device in the room. Three lines a + * ceremony rather than a ladder per step: nobody is asked anything in it, so there is + * nobody whose door the ladder would tell a member to knock on until it stalls, and the + * ceremony's screen names them then. + */ + const val TYPE_INBOX_KEY_STARTED = "inboxKeyStarted" + const val TYPE_INBOX_KEY_COMPLETE = "inboxKeyComplete" + const val TYPE_INBOX_KEY_FAILED = "inboxKeyFailed" + + val INBOX_TYPES = setOf( + TYPE_INBOX_KEY_STARTED, + TYPE_INBOX_KEY_COMPLETE, + TYPE_INBOX_KEY_FAILED, + ) + val GROUP_IDENTITY_TYPES = setOf( TYPE_GROUP_PROFILE_SIGNED, TYPE_LEGACY_GROUP_RELAYS_SIGNED, @@ -562,7 +580,7 @@ data class ChatMessage( TYPE_LEGACY_GROUP_SCHEMA_SIGNED, TYPE_LEGACY_GROUP_ENTRY_CURATED, TYPE_WALLET_NOT_TAKEN_PART_IN, - ) + CONFEDERATION_TYPES + ) + CONFEDERATION_TYPES + INBOX_TYPES /** * Every subgroup line, for the one check the transcript dispatches on. @@ -1269,6 +1287,10 @@ data class ChatMessage( in ShareRefreshEvents.ALL -> null in ShareRepairEvents.ALL -> null + // The inbox key ceremony's messages (docs/group-inbox.md). + // `InboxKeyRitualManager` files them and writes its own lines. + in InboxKeyRitualEvents.ALL -> null + ChatEvent.KIND -> { ChatMessage( giftWrapPayloadId = null, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt index 7d105ec7..16f3416a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt @@ -61,6 +61,7 @@ import kotlinx.coroutines.sync.withLock import mobi.giza.compose.managers.ChillDkgRitualManager import mobi.giza.compose.managers.FrostSigningManager import mobi.giza.compose.managers.ShareRefreshManager +import mobi.giza.compose.managers.InboxKeyRitualManager import com.vitorpamplona.quartz.nip01Core.core.toHexKey import mobi.giza.compose.identity.Identity @@ -158,6 +159,10 @@ class DatabaseNostrRepository( ) + FrostSigningManager.resumeVouched( database = database, userPublicKey = userPublicKey, + ) + InboxKeyRitualManager.resumeRunning( + database = database, + userPublicKey = userPublicKey, + nostrPrivateKey = privateKey ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxFollowThrough.kt new file mode 100644 index 00000000..5cda7ba7 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxFollowThrough.kt @@ -0,0 +1,15 @@ +package mobi.giza.compose.managers + +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.InboxKeyCeremony +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom + +/** + * What follows an inbox key ceremony on the device that coordinated it (docs/group-inbox.md, + * D5 and D6): proposing the group's announcement of the key it made. + */ +object InboxFollowThrough { + /** Called once, on every participant's device, when [ceremony] has made its key. */ + @Suppress("UNUSED_PARAMETER", "RedundantSuspendModifier") + suspend fun onKeyMade(database: GizaDatabase, localChatRoom: LocalChatRoom, ceremony: InboxKeyCeremony) = Unit +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt new file mode 100644 index 00000000..33e4e9c1 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt @@ -0,0 +1,557 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.crypto.random.RandomInstance +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.ByteVector64 +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import fr.acinq.bitcoin.crypto.dkg.chill.ChillDKG +import fr.acinq.secp256k1.ChilldkgFault +import kotlin.time.Clock +import kotlin.time.Instant +import kotlinx.coroutines.CancellationException +import mobi.giza.compose.ExperimentalFeatures +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.InboxKey +import mobi.giza.compose.database.model.InboxKeyCeremony +import mobi.giza.compose.database.model.InboxKeyCeremonyMessage +import mobi.giza.compose.database.model.InboxKeyCeremonyStage +import mobi.giza.compose.database.model.MarmotInnerEvent +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents +import mobi.giza.compose.nostr.inbox.InboxWire + +/** + * The group's inbox key ceremony (docs/group-inbox.md, D2, D3 and D4): ChillDKG at threshold 1 + * over the room's admins, which leaves every one of them holding the same secret `e` and the + * group a public key `E` nobody chose alone. + * + * The rounds are [ChillDkgRitualManager]'s, on kinds and tables of their own, with three + * differences: + * + * - **The participants are the room's admins**, exactly. Every device checks the proposal's + * `p` tags against its own reading of the room's admin policy, and a disagreement ends the + * ceremony out loud with the difference named. + * - **Nobody is asked.** Being an admin is the decision to hold the key; deciding to *have* an + * inbox is the group signing its announcement (D5). An admin's device takes part on arrival. + * - **The output is a whole secret**, written once to [InboxKey]. Nothing that looks for a + * signing key reads that table. + * + * Every message is an MLS inner event in the group's own room. Every member receives them all; + * ChillDKG encrypts each contribution to its recipients' host keys, so a member who is not an + * admin learns `E` and nothing else, and files three lines in the transcript. + */ +object InboxKeyRitualManager { + private val logger = Logger.withTag("InboxKeyRitualManager") + + /** + * A hash input, spelled the house way. Bound to the room so the host key an admin uses for + * one group's inbox says nothing about another's, and to nothing else, so the nsec alone + * recovers it. + */ + private const val HOST_KEY_TAG = "mantra/inbox-key/host-key/v1" + + const val MINIMUM_ADMINS = 2 + + const val ABANDONED = "Abandoned by an admin" + + fun deriveHostSecretKey(nostrPrivateKey: ByteArray, chatRoomId: String): PrivateKey = + PrivateKey(Crypto.sha256(HOST_KEY_TAG.encodeToByteArray() + nostrPrivateKey + chatRoomId.hexToByteArray())) + + fun deriveHostPublicKey(nostrPrivateKey: ByteArray, chatRoomId: String): PublicKey = + ChillDKG.hostPublicKey(deriveHostSecretKey(nostrPrivateKey, chatRoomId)) + + /** + * Why [userPublicKey] cannot open an inbox key ceremony in [localChatRoom] now, or null if + * they can. Read by the screens, so a button that could only fail is never offered. + */ + suspend fun refusal(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey): String? { + if (!ExperimentalFeatures.groupInbox) return "This build has no group inbox" + val room = localChatRoom.chatRoom + if (room.mlsGroupState == null || room.leftGroupAt != null) return "Only a group's own room can have an inbox" + val key = FrostSigningManager.completedKey(database, room.id) + ?: return "The group has no key to announce an inbox with" + val admins = RoomAdmins.of(database, room.id)?.admins ?: return "This device cannot read who the group's admins are" + if (userPublicKey !in admins) return "Only an admin can set up the group's inbox" + if (admins.size < MINIMUM_ADMINS) return "The group needs at least $MINIMUM_ADMINS admins for an inbox" + when (val hold = ShareRefreshManager.rotationHold(database, localChatRoom, key)) { + is RotationHold.Running, is RotationHold.AdminChangeInFlight, is RotationHold.Enrolling -> return hold.reason.replaceFirstChar { it.uppercase() } + else -> Unit + } + return null + } + + /** The generation a new ceremony in [chatRoomId] makes: one past any this device has seen. */ + suspend fun nextGeneration(database: GizaDatabase, chatRoomId: String, userPublicKey: HexKey): Int { + val keys = database.inboxKeyDao().getKeys(chatRoomId, userPublicKey).maxOfOrNull { it.generation } + val ceremony = database.inboxKeyDao().getLatestCeremony(chatRoomId, userPublicKey) + ?.takeIf { it.stage == InboxKeyCeremonyStage.COMPLETE }?.generation + return listOfNotNull(keys, ceremony).maxOrNull()?.plus(1) ?: 0 + } + + /** + * Opens a ceremony over the room's current admins, making this device its coordinator. A + * ceremony already running in the room is handed back instead of a second one. Throws with + * [refusal]'s reason when the room cannot have one. + */ + suspend fun propose( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + ): InboxKeyCeremony { + val roomId = localChatRoom.chatRoom.id + database.inboxKeyDao().getRunningCeremoniesIn(roomId).firstOrNull { it.userPublicKey == userPublicKey }?.let { return it } + + refusal(database, localChatRoom, userPublicKey)?.let { throw IllegalStateException(it) } + val admins = RoomAdmins.of(database, roomId)!!.admins + + val ceremony = InboxKeyCeremony( + id = RandomInstance.bytes(32).toHex(), + chatRoomId = roomId, + generation = nextGeneration(database, roomId, userPublicKey), + coordinatorPublicKey = userPublicKey, + userPublicKey = userPublicKey, + participantPublicKeys = InboxKeyCeremony.formatParticipants(admins), + hostPublicKey = deriveHostPublicKey(nostrPrivateKey, roomId).value.toHex(), + round1Random = RandomInstance.bytes(32).toHex(), + round2AuxRandom = RandomInstance.bytes(32).toHex(), + ) + database.inboxKeyDao().upsertCeremony(ceremony) + announceStarted(database, ceremony) + logger.i("Proposing inbox key ceremony ${ceremony.id.take(8)} at generation ${ceremony.generation} over ${admins.size} admins") + + broadcast( + database, localChatRoom, ceremony, InboxKeyRitualEvents.PROPOSAL, "", + proposal = true, + ) + advance(database, localChatRoom, ceremony.id, nostrPrivateKey) + return database.inboxKeyDao().getCeremony(ceremony.id)!! + } + + /** + * Feeds one inbound ceremony message in and moves the ceremony as far as it will go. Safe to + * call twice with the same message: every write is keyed and every step recomputed. + */ + suspend fun process( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + innerEvent: Event, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + ) { + val sessionId = InboxKeyRitualEvents.parseSessionId(innerEvent.tags) ?: run { + logger.w("Inbox key message ${innerEvent.id.take(8)} names no session; dropping") + return + } + + val ceremony = if (innerEvent.kind == InboxKeyRitualEvents.PROPOSAL) { + accept(database, localChatRoom, innerEvent, sessionId, userPublicKey, nostrPrivateKey) + } else { + // Relays and MLS hand messages back in no particular order; a round can arrive + // before its proposal. It is already stored as an inner event, and [accept] + // replays it once the proposal turns up. + database.inboxKeyDao().getCeremony(sessionId) + } ?: return + + if (!ceremony.isRunning) return + if (!record(database, ceremony, innerEvent)) return + if (ceremony.isParticipant()) advance(database, localChatRoom, ceremony.id, nostrPrivateKey) + } + + /** + * Moves every inbox key ceremony [userPublicKey] takes part in as far as its stored + * messages allow, for a ceremony left mid-round by a crash. Returns how many it looked at. + */ + suspend fun resumeRunning(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray): Int { + val running = database.inboxKeyDao().getRunningCeremonies(userPublicKey).filter { it.isParticipant() } + running.forEach { ceremony -> + val room = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return@forEach + advance(database, room, ceremony.id, nostrPrivateKey) + } + return running.size + } + + /** + * Ends a running ceremony for everyone in it. Only an admin it names can: a member who was + * never in it walking away is not the ceremony failing. Returns whether it was ended. + */ + suspend fun abandon(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String): Boolean { + val ceremony = database.inboxKeyDao().getCeremony(sessionId) ?: return false + if (!ceremony.isRunning || !ceremony.isParticipant()) return false + fail(database, ceremony, ABANDONED, ceremony.userPublicKey) + broadcast(database, localChatRoom, ceremony, InboxKeyRitualEvents.FAILURE, ABANDONED) + return true + } + + // ---- arrival ------------------------------------------------------------------------------- + + private suspend fun accept( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + innerEvent: Event, + sessionId: String, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + ): InboxKeyCeremony? { + database.inboxKeyDao().getCeremony(sessionId)?.let { return it } + val roomId = localChatRoom.chatRoom.id + + if (localChatRoom.chatRoom.mlsGroupState == null) { + logger.w("Inbox key proposal ${sessionId.take(8)} outside a Marmot room; dropping") + return null + } + val generation = InboxKeyRitualEvents.parseGeneration(innerEvent.tags) + val named = InboxKeyRitualEvents.parseParticipants(innerEvent.tags) + if (generation == null || named == null || InboxKeyRitualEvents.parseThreshold(innerEvent.tags) != InboxKeyRitualEvents.THRESHOLD) { + logger.w("Inbox key proposal ${sessionId.take(8)} is malformed; dropping") + return null + } + val participants = (named + innerEvent.pubKey).distinct().sorted() + + val base = InboxKeyCeremony( + id = sessionId, + chatRoomId = roomId, + generation = generation, + coordinatorPublicKey = innerEvent.pubKey, + userPublicKey = userPublicKey, + participantPublicKeys = InboxKeyCeremony.formatParticipants(participants), + ) + + // A member who is not named only watches: it files the lines, and holds nothing. + val mine = if (userPublicKey in participants) { + base.copy( + hostPublicKey = deriveHostPublicKey(nostrPrivateKey, roomId).value.toHex(), + round1Random = RandomInstance.bytes(32).toHex(), + round2AuxRandom = RandomInstance.bytes(32).toHex(), + ) + } else { + base + } + database.inboxKeyDao().upsertCeremony(mine) + announceStarted(database, mine) + + // D4: the participants are the admins, exactly, as this device reads them. A + // ceremony over anyone else would hand the group's mail to whoever the coordinator + // put in it, or leave an admin without it. An admin the proposal left out says so as + // loudly as a named one does. + val admins = RoomAdmins.of(database, roomId)?.admins + val mismatch = when { + admins == null -> null // nothing to compare with; the others will + admins.toSet() != participants.toSet() -> describeMismatch(admins, participants) + else -> null + } + if (mismatch != null && (userPublicKey in participants || userPublicKey in admins.orEmpty())) { + logger.w("Inbox key ceremony ${sessionId.take(8)}: $mismatch") + fail(database, mine, mismatch, userPublicKey) + broadcast(database, localChatRoom, mine, InboxKeyRitualEvents.FAILURE, mismatch) + return database.inboxKeyDao().getCeremony(sessionId) + } + + replayStored(database, localChatRoom, mine) + return database.inboxKeyDao().getCeremony(sessionId) + } + + private fun describeMismatch(admins: Set, participants: List): String { + val missing = admins - participants.toSet() + val extra = participants.toSet() - admins + return buildList { + if (missing.isNotEmpty()) add("leaves out ${missing.size} admin${if (missing.size == 1) "" else "s"} (${missing.sorted().joinToString { it.take(8) }})") + if (extra.isNotEmpty()) add("names ${extra.size} who ${if (extra.size == 1) "is not an admin" else "are not admins"} (${extra.sorted().joinToString { it.take(8) }})") + }.joinToString(" and ", prefix = "The inbox key ceremony ") + } + + /** Every message of [ceremony] that arrived before its proposal, read back out of the room's inner events. */ + private suspend fun replayStored(database: GizaDatabase, localChatRoom: LocalChatRoom, ceremony: InboxKeyCeremony) { + val stored = database.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId = ceremony.chatRoomId, kinds = (InboxKeyRitualEvents.ALL - InboxKeyRitualEvents.PROPOSAL).toList()) + .filter { InboxKeyRitualEvents.parseSessionId(it.tags) == ceremony.id } + stored.forEach { row -> + val event = Event(row.id, row.publicKey, row.createdAt.epochSeconds, row.kind, row.tags, row.content, "") + if (!record(database, ceremony, event)) return + } + } + + /** + * Files one message. Returns false when it ends the ceremony. Round messages count only + * from a participant, the coordinator's aggregates only from the coordinator: taking either + * from anyone else would let any member stall the ceremony by getting a bogus one in first. + */ + private suspend fun record(database: GizaDatabase, ceremony: InboxKeyCeremony, innerEvent: Event): Boolean { + val participants = ceremony.participants() + val sender = innerEvent.pubKey + when (innerEvent.kind) { + InboxKeyRitualEvents.PROPOSAL -> Unit + InboxKeyRitualEvents.HOST_KEY, InboxKeyRitualEvents.ROUND_1, InboxKeyRitualEvents.ROUND_2 -> { + if (sender !in participants) return true + store(database, ceremony, sender, innerEvent.kind, innerEvent.content) + } + InboxKeyRitualEvents.COORDINATOR_ROUND_1 -> { + if (sender != ceremony.coordinatorPublicKey) return true + store(database, ceremony, sender, innerEvent.kind, innerEvent.content) + } + InboxKeyRitualEvents.CERTIFICATE -> { + if (sender != ceremony.coordinatorPublicKey) return true + store(database, ceremony, sender, innerEvent.kind, innerEvent.content) + // A member who only watches cannot check the certificate; the admins can, and + // will fail it out loud if it is wrong. The watcher's line says it was issued. + if (!ceremony.isParticipant()) { + val current = database.inboxKeyDao().getCeremony(ceremony.id) ?: ceremony + if (current.isRunning) { + database.inboxKeyDao().upsertCeremony(current.copy(stage = InboxKeyCeremonyStage.COMPLETE, updatedAt = Clock.System.now())) + announce(database, current, ChatMessage.TYPE_INBOX_KEY_COMPLETE, "The group's admins finished making its inbox key.", current.coordinatorPublicKey) + } + } + } + InboxKeyRitualEvents.FAILURE -> { + if (sender !in participants && sender !in (RoomAdmins.of(database, ceremony.chatRoomId)?.admins ?: emptySet())) return true + fail(database, ceremony, innerEvent.content.ifBlank { ABANDONED }, sender) + return false + } + } + return true + } + + private suspend fun store(database: GizaDatabase, ceremony: InboxKeyCeremony, sender: HexKey, kind: Kind, payload: String) { + val inserted = database.inboxKeyDao().insertMessage(InboxKeyCeremonyMessage(ceremony.id, sender, kind, payload)) + if (inserted > 0) { + database.inboxKeyDao().getCeremony(ceremony.id)?.let { + database.inboxKeyDao().upsertCeremony(it.copy(lastMessageAt = Clock.System.now(), updatedAt = Clock.System.now())) + } + } + } + + // ---- the rounds ---------------------------------------------------------------------------- + + /** + * Takes every step the stored messages allow, stopping at the first one still waiting on + * somebody. Each step asks whether its output exists rather than what the stage says, so a + * re-entry repeats no work and skips none. + */ + private suspend fun advance(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) { + val start = database.inboxKeyDao().getCeremony(sessionId) ?: return + if (!start.isRunning || !start.isParticipant()) return + val roomId = start.chatRoomId + val hostSecret = deriveHostSecretKey(nostrPrivateKey, roomId) + val threshold = InboxKeyRitualEvents.THRESHOLD + + try { + if (own(database, start, InboxKeyRitualEvents.HOST_KEY) == null) { + publishOwn(database, localChatRoom, start, InboxKeyRitualEvents.HOST_KEY, requireNotNull(start.hostPublicKey)) + } + val hostPublicKeys = hostPublicKeys(database, start) ?: return + + val step1 = ChillDKG.participantStep1(hostSecret, hostPublicKeys, threshold, ByteVector32(requireNotNull(start.round1Random))) + if (own(database, start, InboxKeyRitualEvents.ROUND_1) == null) { + publishOwn(database, localChatRoom, start, InboxKeyRitualEvents.ROUND_1, step1.message.toHex()) + } + moveTo(database, start, InboxKeyCeremonyStage.ROUND_1) + + if (start.isCoordinator() && coordinatorMessage(database, start, InboxKeyRitualEvents.COORDINATOR_ROUND_1) == null) { + val pmsgs1 = ordered(database, start, InboxKeyRitualEvents.ROUND_1) ?: return + val cmsg1 = coordinatorStep1(pmsgs1, hostPublicKeys).message.toHex() + publishOwn(database, localChatRoom, start, InboxKeyRitualEvents.COORDINATOR_ROUND_1, cmsg1) + } + val cmsg1 = coordinatorMessage(database, start, InboxKeyRitualEvents.COORDINATOR_ROUND_1) ?: return + + // The check that stops a coordinator substituting a key the admins never + // contributed to: participantStep2 faults on a mismatch, and the catch below fails + // the ceremony for everyone. + val step2 = ChillDKG.participantStep2(hostSecret, step1.state, ByteVector(cmsg1.hexToByteArray()), ByteVector32(requireNotNull(start.round2AuxRandom))) + step2.fault.raiseIfFaulty("round 2") + if (own(database, start, InboxKeyRitualEvents.ROUND_2) == null) { + publishOwn(database, localChatRoom, start, InboxKeyRitualEvents.ROUND_2, step2.certEqSignature.toHex()) + } + moveTo(database, start, InboxKeyCeremonyStage.ROUND_2) + + if (start.isCoordinator() && coordinatorMessage(database, start, InboxKeyRitualEvents.CERTIFICATE) == null) { + val pmsgs2 = ordered(database, start, InboxKeyRitualEvents.ROUND_2) ?: return + val pmsgs1 = ordered(database, start, InboxKeyRitualEvents.ROUND_1) ?: return + val certified = ChillDKG.coordinatorFinalize(coordinatorStep1(pmsgs1, hostPublicKeys).state, pmsgs2.map { ByteVector64(it) }, threshold) + certified.fault.raiseIfFaulty("certificate") + publishOwn(database, localChatRoom, start, InboxKeyRitualEvents.CERTIFICATE, certified.certificate.toHex()) + } + val certificate = coordinatorMessage(database, start, InboxKeyRitualEvents.CERTIFICATE) ?: return + + val output = ChillDKG.participantFinalize(step2.state, ByteVector(certificate.hexToByteArray()), hostPublicKeys.size, threshold) + output.fault.raiseIfFaulty("finalize") + + // D2's premise, checked on every run rather than trusted from Phase 0: at t = 1 + // the share is the whole secret, so it has to be the discrete log of the key. + val secret = requireNotNull(output.secretShare) { "the ceremony left no secret" } + val thresholdKey = requireNotNull(output.thresholdPublicKey) { "the ceremony left no key" } + check(secret.publicKey() == thresholdKey) { "the inbox key's secret is not its key's: the ceremony was not at threshold 1" } + val secretBytes = secret.value.toByteArray() + val inboxKey = InboxWire.publicKeyOf(secretBytes) + + database.inboxKeyDao().upsertKey( + InboxKey( + chatRoomId = roomId, + userPublicKey = start.userPublicKey, + generation = start.generation, + publicKey = inboxKey, + secretKey = secretBytes.toHex(), + recoveryData = output.recovery?.toHex(), + ceremonyId = start.id, + ) + ) + val done = (database.inboxKeyDao().getCeremony(sessionId) ?: start) + .copy(stage = InboxKeyCeremonyStage.COMPLETE, inboxPublicKey = inboxKey, updatedAt = Clock.System.now()) + database.inboxKeyDao().upsertCeremony(done) + announce( + database, done, ChatMessage.TYPE_INBOX_KEY_COMPLETE, + "The group's admins made its inbox key. It reaches nobody until the group announces it.", + done.coordinatorPublicKey, + ) + logger.i("Inbox key ceremony ${sessionId.take(8)} complete: generation ${done.generation}") + InboxFollowThrough.onKeyMade(database, localChatRoom, done) + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + logger.e("Inbox key ceremony ${sessionId.take(8)} failed", e) + val reason = e.message ?: "The inbox key ceremony failed" + val current = database.inboxKeyDao().getCeremony(sessionId) ?: start + fail(database, current, reason, current.userPublicKey) + broadcast(database, localChatRoom, current, InboxKeyRitualEvents.FAILURE, reason) + } + } + + /** The participants' host keys, sorted, or null while any is outstanding. */ + private suspend fun hostPublicKeys(database: GizaDatabase, ceremony: InboxKeyCeremony): List? { + val participants = ceremony.participants() + val hostKeys = database.inboxKeyDao().getMessages(ceremony.id) + .filter { it.kind == InboxKeyRitualEvents.HOST_KEY && it.senderPublicKey in participants } + if (hostKeys.size < participants.size) return null + return hostKeys.map { it.payload.lowercase() }.sorted().map { PublicKey(ByteVector(it.hexToByteArray())) } + } + + /** A round's messages, one per participant, in host-key order; null while any is missing. */ + private suspend fun ordered(database: GizaDatabase, ceremony: InboxKeyCeremony, kind: Kind): List? { + val messages = database.inboxKeyDao().getMessages(ceremony.id) + val hostKeyOf = messages.filter { it.kind == InboxKeyRitualEvents.HOST_KEY }.associate { it.senderPublicKey to it.payload.lowercase() } + val participants = ceremony.participants() + val round = participants.map { participant -> + val message = messages.firstOrNull { it.kind == kind && it.senderPublicKey == participant } ?: return null + val hostKey = hostKeyOf[participant] ?: return null + hostKey to message.payload + } + return round.sortedBy { it.first }.map { it.second.hexToByteArray() } + } + + private fun coordinatorStep1(pmsgs1: List, hostPublicKeys: List) = + ChillDKG.coordinatorStep1(pmsgs1.map { ByteVector(it) }, hostPublicKeys, InboxKeyRitualEvents.THRESHOLD) + .also { it.fault.raiseIfFaulty("coordinator round 1") } + + private fun ChilldkgFault.raiseIfFaulty(step: String) { + if (isOk) return + val culprit = participantIndex?.let { " (participant $it)" } ?: "" + val reason = when (code) { + ChilldkgFault.FAULTY_COORDINATOR -> "the coordinator is faulty" + ChilldkgFault.FAULTY_PARTICIPANT -> "a participant is faulty" + ChilldkgFault.FAULTY_PARTICIPANT_OR_COORDINATOR -> "a participant or the coordinator is faulty" + ChilldkgFault.UNKNOWN_FAULTY_PARTICIPANT_OR_COORDINATOR -> "an unidentified participant or the coordinator is faulty" + ChilldkgFault.INVALID_INPUT -> "invalid input" + else -> "unrecognised fault code $code" + } + throw IllegalStateException("The inbox key ceremony's $step failed: $reason$culprit") + } + + private suspend fun own(database: GizaDatabase, ceremony: InboxKeyCeremony, kind: Kind) = + database.inboxKeyDao().getMessage(ceremony.id, ceremony.userPublicKey, kind) + + private suspend fun coordinatorMessage(database: GizaDatabase, ceremony: InboxKeyCeremony, kind: Kind): String? = + database.inboxKeyDao().getMessage(ceremony.id, ceremony.coordinatorPublicKey, kind)?.payload + + private suspend fun moveTo(database: GizaDatabase, ceremony: InboxKeyCeremony, stage: InboxKeyCeremonyStage) { + val current = database.inboxKeyDao().getCeremony(ceremony.id) ?: return + if (!current.isRunning || current.stage.ordinal >= stage.ordinal) return + database.inboxKeyDao().upsertCeremony(current.copy(stage = stage, updatedAt = Clock.System.now())) + } + + private suspend fun fail(database: GizaDatabase, ceremony: InboxKeyCeremony, reason: String, culprit: HexKey) { + val current = database.inboxKeyDao().getCeremony(ceremony.id) ?: ceremony + if (current.stage == InboxKeyCeremonyStage.FAILED) return + database.inboxKeyDao().upsertCeremony( + current.copy(stage = InboxKeyCeremonyStage.FAILED, failureReason = reason, culprit = culprit, updatedAt = Clock.System.now()) + ) + announce(database, current, ChatMessage.TYPE_INBOX_KEY_FAILED, "ended the inbox key ceremony: $reason. No key was made, and it is safe to run it again.", culprit) + } + + // ---- the wire ------------------------------------------------------------------------------ + + /** Sends one of this device's messages and records it, so its own is in every aggregation. */ + private suspend fun publishOwn(database: GizaDatabase, localChatRoom: LocalChatRoom, ceremony: InboxKeyCeremony, kind: Kind, content: String) { + broadcast(database, localChatRoom, ceremony, kind, content) + store(database, ceremony, ceremony.userPublicKey, kind, content) + } + + /** + * Queues one ceremony message as an MLS inner event for the room, the path chat messages + * take. The proposal carries the admins as `p` tags, the participant set every device + * rebuilds; nothing later needs them. + */ + private suspend fun broadcast( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + ceremony: InboxKeyCeremony, + kind: Kind, + content: String, + proposal: Boolean = false, + ) { + val tags = InboxKeyRitualEvents.assembleTags( + sessionId = ceremony.id, + generation = if (proposal) ceremony.generation else null, + participants = if (proposal) ceremony.participants().filterNot { it == ceremony.userPublicKey } else emptyList(), + ) + val createdAt = Clock.System.now().epochSeconds + val id = EventHasher.hashId(ceremony.userPublicKey, createdAt, kind, tags, content) + database.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = id, + publicKey = ceremony.userPublicKey, + kind = kind, + createdAt = Instant.fromEpochSeconds(createdAt), + tags = tags, + content = content, + chatRoomId = localChatRoom.chatRoom.id, + ) + ) + } + + // ---- the transcript ------------------------------------------------------------------------ + + private suspend fun announceStarted(database: GizaDatabase, ceremony: InboxKeyCeremony) { + val n = ceremony.participants().size + val text = if (ceremony.generation == 0) { + "started making the group's inbox key with its $n admins. Every admin will hold it, and it finishes once all of them have taken part." + } else { + "started changing the group's inbox key with its $n admins. Every admin will hold the new one, and it finishes once all of them have taken part." + } + announce(database, ceremony, ChatMessage.TYPE_INBOX_KEY_STARTED, text, ceremony.coordinatorPublicKey) + } + + private suspend fun announce(database: GizaDatabase, ceremony: InboxKeyCeremony, type: String, content: String, actor: HexKey) { + database.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = actor, + isUserMessage = actor == ceremony.userPublicKey, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = ceremony.chatRoomId, + content = content, + messageType = type, + ) + ) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxHarness.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxHarness.kt new file mode 100644 index 00000000..6dc7963d --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxHarness.kt @@ -0,0 +1,175 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.crypto.frost.Frost +import fr.acinq.bitcoin.crypto.frost.KeyMaterial +import mobi.giza.compose.ExperimentalFeatures +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.DkgParticipantMessage +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.MarmotInnerEvent +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.dkg.DkgRitualEvents +import mobi.giza.compose.nostr.frost.FrostSigningEvents +import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents + +/** + * One keyed group, a device per member, for the group inbox's tests (docs/group-inbox.md). + * + * Every member has a real nostr key, because the inbox ceremony derives its host keys from the + * nsec and the inbox opens NIP-44 with real secrets. The group's signing key stands in for a + * finished ceremony (a trusted dealer, as `SignedGroupKeyStateTest` has it), and the room is a + * Marmot one by its column -- nothing here runs MLS, so what a device sends is read off its + * inner events and handed to the others by [pump], stored first, as the inbound path would. + * + * Who a device sees as the room's admins is [admins], through [RoomAdmins.override]. + */ +class GroupInboxHarness( + names: List = listOf("alice", "bob", "carol"), + /** Members of the room who are not admins and hold no share. */ + watchers: List = emptyList(), + val threshold: Int = 2, +) { + val secrets: Map = (names + watchers).associateWith { Crypto.sha256("giza inbox $it".encodeToByteArray()) } + val keyOf: Map = secrets.mapValues { KeyPair(it.value).pubKey.toHexKey() } + val signers: List = names.map { keyOf.getValue(it) } + val everyone: List = (names + watchers).map { keyOf.getValue(it) } + + val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( + thresholdSecretKey = PrivateKey(ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1")), + nParticipants = names.size, + threshold = threshold, + ) + val thresholdPublicKey = keyMaterial.thresholdPublicKey.value.toHex() + val roomId: String = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + private val ceremonyId = "ceremony".padEnd(64, '0') + // Chosen to sort as the signers read, so signer i holds share i. + private val signingHostKeys = names.indices.map { "2${('a' + it)}".padEnd(66, '0') } + + /** Who every device reads as the room's admins. */ + var admins: Set = signers.toSet() + + val devices = mutableListOf() + + init { + ExperimentalFeatures.groupInboxOverride = true + RoomAdmins.override = { id -> if (id == roomId) RoomAdmins(admins, governed = false) else null } + } + + fun close() { + devices.forEach { it.db.close() } + RoomAdmins.override = null + ExperimentalFeatures.groupInboxOverride = null + } + + inner class Device(val name: String, val publicKey: HexKey, val secret: ByteArray, val db: GizaDatabase) { + /** Inner events already handed to this device, so a pump terminates. */ + val received = mutableSetOf() + + suspend fun room(): LocalChatRoom = db.chatRoomDao().findChatRoomById(roomId)!! + + suspend fun keys() = db.inboxKeyDao().getKeys(roomId, publicKey) + + suspend fun ceremony(id: String) = db.inboxKeyDao().getCeremony(id) + + suspend fun lines(types: Set) = + db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage }.filter { it.messageType in types } + } + + suspend fun device(name: String): Device { + val publicKey = keyOf.getValue(name) + val db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + everyone.forEach { member -> + val eventId = "e$member".take(64) + db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = member, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = member, nostrEventId = eventId)) + } + db.chatRoomDao().upsert( + ChatRoom( + id = roomId, + userPublicKey = publicKey, + subject = "#Ekklesia", + description = SharedKeyDerivation.describe("Admins of the group."), + mlsGroupState = "00", + ) + ) + + val signerIndex = signers.indexOf(publicKey) + if (signerIndex >= 0) { + db.dkgSessionDao().upsert( + DkgSession( + id = ceremonyId, + chatRoomId = roomId, + coordinatorPublicKey = signers.first(), + userPublicKey = publicKey, + threshold = threshold, + participantCount = signers.size, + stage = DkgRitualStage.COMPLETE, + hostPublicKey = signingHostKeys[signerIndex], + round1Random = "1".repeat(64), + round2AuxRandom = "2".repeat(64), + thresholdPublicKey = thresholdPublicKey, + secretShare = keyMaterial.secretShares[signerIndex].value.toHex(), + publicShares = keyMaterial.publicShares.joinToString(",") { it.value.toHex() }, + ) + ) + signers.forEachIndexed { index, signer -> + db.dkgSessionDao().upsert( + DkgParticipantMessage(sessionId = ceremonyId, participantPublicKey = signer, kind = DkgRitualEvents.HOST_KEY, payload = signingHostKeys[index]) + ) + } + } + return Device(name, publicKey, secrets.getValue(name), db).also { devices += it } + } + + /** The kinds [pump] carries between devices. */ + var carried: Set = FrostSigningEvents.ALL + InboxKeyRitualEvents.ALL + + private suspend fun outbox(device: Device): List = + device.db.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId = roomId, kinds = carried.toList()) + .filter { it.publicKey == device.publicKey } + .sortedWith(compareBy({ it.createdAt }, { it.kind })) + + /** + * Hands everything each device has sent to every other, until nobody has anything new. + * [except] devices are offline: they neither send nor receive. + */ + suspend fun pump(vararg between: Device = devices.toTypedArray(), except: Set = emptySet()) { + val online = between.filter { it !in except } + var moved = true + while (moved) { + moved = false + for (from in online) for (to in online) { + if (from === to) continue + outbox(from).forEach { row -> + if (!to.received.add(row.id)) return@forEach + moved = true + to.db.marmotInnerEventDao().upsert(row.copy()) + val event = Event(row.id, row.publicKey, row.createdAt.epochSeconds, row.kind, row.tags, row.content, "") + val room = to.room() + when { + FrostSigningEvents.isFrostSigningKind(row.kind) -> + FrostSigningManager.processSigningPayload(to.db, room, event, to.publicKey) + InboxKeyRitualEvents.isInboxKeyKind(row.kind) -> + InboxKeyRitualManager.process(to.db, room, event, to.publicKey, to.secret) + } + } + } + } + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxKeyRitualJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxKeyRitualJvmTest.kt new file mode 100644 index 00000000..3378262f --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxKeyRitualJvmTest.kt @@ -0,0 +1,202 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.ExperimentalFeatures +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.InboxKeyCeremonyStage +import mobi.giza.compose.database.model.InboxKeyState +import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents +import mobi.giza.compose.nostr.inbox.InboxWire + +/** + * The group's inbox key ceremony across devices (docs/group-inbox.md, Phase 4): three admins + * and a member who is not one, each on their own database, with what each sends handed to the + * others. + */ +class InboxKeyRitualJvmTest { + private val harness = GroupInboxHarness(watchers = listOf("dineo")) + + @AfterTest + fun close() = harness.close() + + private suspend fun group() = listOf("alice", "bob", "carol", "dineo").map { harness.device(it) } + + @Test + fun `every admin ends with the same secret, and it is the key the ceremony made`() = runBlocking { + val (alice, bob, carol, dineo) = group() + + val ceremony = InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + assertEquals(0, ceremony.generation) + harness.pump() + + val keys = listOf(alice, bob, carol).map { assertNotNull(it.keys().singleOrNull(), "${it.name} holds the key") } + assertEquals(1, keys.map { it.secretKey }.distinct().size, "every admin holds one secret") + keys.forEach { key -> + assertEquals(InboxKeyState.HELD, key.state, "made, not yet announced") + assertEquals(key.publicKey, InboxWire.publicKeyOf(assertNotNull(key.secretKey).hexToByteArray())) + assertNotNull(key.recoveryData) + } + listOf(alice, bob, carol).forEach { + assertEquals(InboxKeyCeremonyStage.COMPLETE, it.ceremony(ceremony.id)?.stage) + assertEquals(keys.first().publicKey, it.ceremony(ceremony.id)?.inboxPublicKey) + } + + // The member who is not an admin watched it happen and holds nothing. + assertEquals(emptyList(), dineo.keys()) + assertEquals(InboxKeyCeremonyStage.COMPLETE, dineo.ceremony(ceremony.id)?.stage) + assertEquals(1, dineo.lines(setOf(ChatMessage.TYPE_INBOX_KEY_STARTED)).size) + assertEquals(1, dineo.lines(setOf(ChatMessage.TYPE_INBOX_KEY_COMPLETE)).size) + } + + @Test + fun `nobody is asked, and each device says it once`() = runBlocking { + val (alice, bob, carol, _) = group() + InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + harness.pump() + harness.pump() // redelivery changes nothing + + listOf(alice, bob, carol).forEach { device -> + assertEquals(1, device.lines(setOf(ChatMessage.TYPE_INBOX_KEY_STARTED)).size) + assertEquals(1, device.lines(setOf(ChatMessage.TYPE_INBOX_KEY_COMPLETE)).size) + assertEquals(0, device.lines(setOf(ChatMessage.TYPE_INBOX_KEY_FAILED)).size) + } + } + + @Test + fun `a proposal that leaves out an admin fails out loud on every device`() = runBlocking { + val (alice, bob, carol, dineo) = group() + // Alice's device does not yet see Carol as an admin; everyone else does. + harness.admins = setOf(alice.publicKey, bob.publicKey) + val ceremony = InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + harness.admins = setOf(alice.publicKey, bob.publicKey, carol.publicKey) + harness.pump() + + listOf(alice, bob, carol, dineo).forEach { device -> + val seen = assertNotNull(device.ceremony(ceremony.id)) + assertEquals(InboxKeyCeremonyStage.FAILED, seen.stage, "${device.name} sees it failed") + assertTrue(seen.failureReason.orEmpty().contains("leaves out 1 admin"), seen.failureReason) + assertEquals(emptyList(), device.keys()) + } + } + + @Test + fun `a proposal that names someone who is not an admin fails out loud`() = runBlocking { + val (alice, bob, carol, dineo) = group() + harness.admins = setOf(alice.publicKey, bob.publicKey, carol.publicKey, dineo.publicKey) + val ceremony = InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + harness.admins = setOf(alice.publicKey, bob.publicKey, carol.publicKey) + harness.pump() + + listOf(bob, carol).forEach { device -> + val seen = assertNotNull(device.ceremony(ceremony.id)) + assertEquals(InboxKeyCeremonyStage.FAILED, seen.stage) + assertTrue(seen.failureReason.orEmpty().contains("is not an admin"), seen.failureReason) + } + assertEquals(emptyList(), dineo.keys()) + } + + @Test + fun `a ceremony interrupted mid-round finishes when its admins come back`() = runBlocking { + val (alice, bob, carol, dineo) = group() + val ceremony = InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + // Carol is offline for the first rounds: the rest can go no further than her host key. + harness.pump(except = setOf(carol)) + assertEquals(emptyList(), alice.keys()) + assertTrue(assertNotNull(alice.ceremony(ceremony.id)).isRunning) + + harness.pump() + assertEquals(1, alice.keys().size) + assertEquals(alice.keys().single().publicKey, carol.keys().single().publicKey) + assertEquals(alice.keys().single().publicKey, bob.keys().single().publicKey) + assertEquals(emptyList(), dineo.keys()) + } + + @Test + fun `a message delivered before its proposal is replayed, not lost`() = runBlocking { + val (alice, bob, _, _) = group() + InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + + // Bob gets Alice's host key ahead of her proposal. + val rows = alice.db.marmotInnerEventDao().getByChatRoomAndKinds(harness.roomId, InboxKeyRitualEvents.ALL.toList()) + val hostKey = rows.single { it.kind == InboxKeyRitualEvents.HOST_KEY } + val proposal = rows.single { it.kind == InboxKeyRitualEvents.PROPOSAL } + listOf(hostKey, proposal).forEach { row -> + bob.db.marmotInnerEventDao().upsert(row) + bob.received += row.id + InboxKeyRitualManager.process( + bob.db, bob.room(), + com.vitorpamplona.quartz.nip01Core.core.Event(row.id, row.publicKey, row.createdAt.epochSeconds, row.kind, row.tags, row.content, ""), + bob.publicKey, bob.secret, + ) + } + val ceremonyOnBob = assertNotNull(bob.db.inboxKeyDao().getLatestCeremony(harness.roomId, bob.publicKey)) + assertNotNull(bob.db.inboxKeyDao().getMessage(ceremonyOnBob.id, alice.publicKey, InboxKeyRitualEvents.HOST_KEY)) + + harness.pump() + assertEquals(alice.keys().single().publicKey, bob.keys().single().publicKey) + } + + @Test + fun `an admin can abandon a ceremony, and nobody else can`() = runBlocking { + val (alice, bob, carol, dineo) = group() + val ceremony = InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + harness.pump(except = setOf(carol)) + + assertTrue(!InboxKeyRitualManager.abandon(dineo.db, dineo.room(), ceremony.id), "a member who is not in it cannot end it") + assertTrue(InboxKeyRitualManager.abandon(bob.db, bob.room(), ceremony.id)) + harness.pump() + + listOf(alice, bob, carol, dineo).forEach { + assertEquals(InboxKeyCeremonyStage.FAILED, it.ceremony(ceremony.id)?.stage, "${it.name} sees it ended") + assertEquals(emptyList(), it.keys()) + } + } + + @Test + fun `only an admin can start one, one at a time, and not in a release build`() = runBlocking { + val (alice, _, _, dineo) = group() + + assertNotNull(InboxKeyRitualManager.refusal(dineo.db, dineo.room(), dineo.publicKey)) + assertFailsWith { InboxKeyRitualManager.propose(dineo.db, dineo.room(), dineo.publicKey, dineo.secret) } + + assertNull(InboxKeyRitualManager.refusal(alice.db, alice.room(), alice.publicKey)) + val first = InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + val again = InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + assertEquals(first.id, again.id, "a running ceremony is handed back, not doubled") + + ExperimentalFeatures.groupInboxOverride = false + assertNotNull(InboxKeyRitualManager.refusal(alice.db, alice.room(), alice.publicKey)) + } + + @Test + fun `a second ceremony makes the next generation, and a different key`() = runBlocking { + val (alice, bob, _, _) = group() + InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + harness.pump() + val second = InboxKeyRitualManager.propose(bob.db, bob.room(), bob.publicKey, bob.secret) + assertEquals(1, second.generation) + harness.pump() + + val keys = alice.keys() + assertEquals(listOf(1, 0), keys.map { it.generation }) + assertTrue(keys[0].publicKey != keys[1].publicKey) + assertEquals(bob.keys().map { it.publicKey }, keys.map { it.publicKey }) + } + + @Test + fun `host keys are bound to the room and come from the nsec alone`() { + val secret = harness.secrets.getValue("alice") + val here = InboxKeyRitualManager.deriveHostPublicKey(secret, harness.roomId) + assertEquals(here, InboxKeyRitualManager.deriveHostPublicKey(secret, harness.roomId)) + assertTrue(here != InboxKeyRitualManager.deriveHostPublicKey(secret, "1".repeat(64))) + assertTrue(here != ChillDkgRitualManager.deriveHostPublicKey(secret), "not the signing ceremony's host key") + } +} From 1c29df61d87379a402b69abc53aaf46c0f151d5b Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 01:49:03 +0200 Subject: [PATCH 10/16] feat: the group announces its inbox, and declines a wrong announcement out loud (group-inbox, Phase 5) The coordinator of a finished inbox key ceremony asks the group to sign its announcement: the first time a 10044 and a 10050 in one batch, which is the group deciding to have an inbox and is asked; after that a rotation's 10044 alone, which every admin's device vouches for and signs unasked. InboxRefusal declines, in all four places, a 10044 naming a key the admins did not make together, one since replaced, or one made over admins the room no longer has, and a 10050 a stranger could not reach. An announcement that arrives before this device has finished the same ceremony waits rather than being declined, and is looked at again when it finishes. A member who only watched the ceremony aggregates its public messages to learn the key, so it can check too. Once signed, the key moves to ANNOUNCED and the ones before it to RETIRED; the transcript says the group has an inbox, or changed its key; and the proposer's device sends both events through GroupInboxPublisher until a relay takes them, never through a NostrEvent row. InboxSigning (reasons kept for the decline) and InboxKeyCeremony.announceRelays fold into schema 45, which has not shipped. Co-Authored-By: Claude Opus 5.5 --- .../45.json | 75 ++++++- .../giza/compose/database/GizaDatabase.kt | 4 +- .../compose/database/dao/GroupInboxDao.kt | 15 ++ .../giza/compose/database/dao/InboxKeyDao.kt | 4 + .../compose/database/model/ChatMessage.kt | 38 ++++ .../giza/compose/database/model/GroupInbox.kt | 22 ++ .../database/model/InboxKeyCeremony.kt | 6 + .../DatabaseGroupInboxRepository.kt | 20 ++ .../compose/managers/FrostSigningManager.kt | 78 +++++++- .../compose/managers/GroupInboxPublisher.kt | 107 ++++++++++ .../compose/managers/InboxAnnouncements.kt | 87 ++++++++ .../compose/managers/InboxFollowThrough.kt | 44 +++- .../compose/managers/InboxKeyRitualManager.kt | 41 +++- .../giza/compose/managers/InboxRefusal.kt | 119 +++++++++++ .../repository/GroupInboxRepository.kt | 14 ++ .../mobi/giza/compose/text/ProposedEvent.kt | 15 ++ .../ui/composable/navigation/GizaNavHost.kt | 8 + .../BroadcastGroupSignedEventViewModel.kt | 7 +- .../ui/view/model/SynchronizationViewModel.kt | 21 ++ .../giza/compose/text/ProposedEventTest.kt | 17 +- .../managers/GroupInboxTodayJvmTest.kt | 14 +- .../managers/InboxAnnouncementJvmTest.kt | 188 ++++++++++++++++++ 22 files changed, 919 insertions(+), 25 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxPublisher.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxAnnouncements.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxAnnouncementJvmTest.kt diff --git a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/45.json b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/45.json index 15430737..a2416ed5 100644 --- a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/45.json +++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/45.json @@ -2,7 +2,7 @@ "formatVersion": 1, "database": { "version": 45, - "identityHash": "690e3d5ecde4b3bfe7f46f8e530c249a", + "identityHash": "90282c397105fcf65d10a5228ecc2185", "entities": [ { "tableName": "BroadcastNostrEventReceipt", @@ -2819,7 +2819,7 @@ }, { "tableName": "InboxKeyCeremony", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `participantPublicKeys` TEXT NOT NULL, `stage` TEXT NOT NULL, `hostPublicKey` TEXT, `round1Random` TEXT, `round2AuxRandom` TEXT, `inboxPublicKey` TEXT, `failureReason` TEXT, `culprit` TEXT, `lastMessageAt` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `participantPublicKeys` TEXT NOT NULL, `stage` TEXT NOT NULL, `hostPublicKey` TEXT, `round1Random` TEXT, `round2AuxRandom` TEXT, `announceRelays` TEXT, `inboxPublicKey` TEXT, `failureReason` TEXT, `culprit` TEXT, `lastMessageAt` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", "fields": [ { "fieldPath": "id", @@ -2878,6 +2878,11 @@ "columnName": "round2AuxRandom", "affinity": "TEXT" }, + { + "fieldPath": "announceRelays", + "columnName": "announceRelays", + "affinity": "TEXT" + }, { "fieldPath": "inboxPublicKey", "columnName": "inboxPublicKey", @@ -3000,6 +3005,70 @@ } ] }, + { + "tableName": "InboxSigning", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `manifest` TEXT, `refusal` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "manifest", + "columnName": "manifest", + "affinity": "TEXT" + }, + { + "fieldPath": "refusal", + "columnName": "refusal", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId" + ] + }, + "indices": [ + { + "name": "index_InboxSigning_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_InboxSigning_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, { "tableName": "KeyShareGeneration", "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `secretShare` TEXT, `publicShares` TEXT NOT NULL, `state` TEXT NOT NULL, `refreshSessionId` TEXT, `recoveryData` TEXT, `activatedAt` INTEGER, `wipedAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `generation`), FOREIGN KEY(`dkgSessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", @@ -6463,7 +6532,7 @@ ], "setupQueries": [ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", - "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '690e3d5ecde4b3bfe7f46f8e530c249a')" + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '90282c397105fcf65d10a5228ecc2185')" ] } } \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt index 9131398d..37a5f391 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt @@ -120,6 +120,7 @@ import mobi.giza.compose.database.model.GroupInboxWrap import mobi.giza.compose.database.model.InboxKey import mobi.giza.compose.database.model.InboxKeyCeremony import mobi.giza.compose.database.model.InboxKeyCeremonyMessage +import mobi.giza.compose.database.model.InboxSigning import mobi.giza.compose.database.model.FrostSignerMessage import mobi.giza.compose.database.model.FrostSigningItem import mobi.giza.compose.database.model.FrostSigningSession @@ -166,6 +167,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) InboxKey::class, InboxKeyCeremony::class, InboxKeyCeremonyMessage::class, + InboxSigning::class, KeyShareGeneration::class, KeyShareMember::class, ShareRefreshConfirmation::class, @@ -478,7 +480,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) // v45 adds the group's inbox (docs/group-inbox.md, Phase 3): InboxKeyCeremony, // InboxKeyCeremonyMessage and InboxKey, kept apart from DkgSession so no signing path // can find a threshold-1 key, and GroupInboxWrap, GroupInboxMessage and - // GroupInboxPublication. New tables only, so Room generates it. + // GroupInboxPublication, and InboxSigning (Phase 5). New tables only, so Room generates it. AutoMigration(from = 44, to = 45), ] ) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupInboxDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupInboxDao.kt index d306b318..1a3e7eb5 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupInboxDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupInboxDao.kt @@ -79,6 +79,21 @@ interface GroupInboxDao { @Query("SELECT * FROM GroupInboxPublication WHERE signingSessionId = :signingSessionId") suspend fun getPublicationsFor(signingSessionId: String): List + @Query("SELECT * FROM GroupInboxPublication WHERE publishedAt IS NULL ORDER BY createdAt") + fun observeUnpublished(): Flow> + + @Query("UPDATE GroupInboxPublication SET publishedAt = :at WHERE eventId = :eventId") + suspend fun markPublished(eventId: HexKey, at: Instant) + + @Query("UPDATE GroupInboxPublication SET attempts = attempts + 1, nextAttemptAt = :next WHERE eventId = :eventId") + suspend fun markAttempted(eventId: HexKey, next: Instant) + + @Upsert + suspend fun upsertSigning(signing: mobi.giza.compose.database.model.InboxSigning) + + @Query("SELECT * FROM InboxSigning WHERE sessionId = :sessionId") + suspend fun getSigning(sessionId: String): mobi.giza.compose.database.model.InboxSigning? + @Query("SELECT * FROM GroupInboxPublication WHERE signingSessionId = :signingSessionId") fun observePublicationsFor(signingSessionId: String): Flow> } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/InboxKeyDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/InboxKeyDao.kt index aec555e9..e060e5c4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/InboxKeyDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/InboxKeyDao.kt @@ -34,6 +34,10 @@ interface InboxKeyDao { @Query("SELECT * FROM InboxKeyCeremony WHERE chatRoomId = :chatRoomId AND stage NOT IN ('COMPLETE', 'FAILED')") suspend fun getRunningCeremoniesIn(chatRoomId: String): List + /** Every finished ceremony in a room as this identity saw it, newest generation first. */ + @Query("SELECT * FROM InboxKeyCeremony WHERE chatRoomId = :chatRoomId AND userPublicKey = :userPublicKey AND stage = 'COMPLETE' ORDER BY generation DESC, createdAt DESC") + suspend fun getCompletedCeremonies(chatRoomId: String, userPublicKey: HexKey): List + @Upsert suspend fun upsertCeremony(ceremony: InboxKeyCeremony) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt index 8012d5b1..b57832dc 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt @@ -4,6 +4,7 @@ import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import mobi.giza.compose.nostr.GroupNostrProfile import mobi.giza.compose.nostr.RetiredKinds import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.inbox.InboxAnnouncement import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents import androidx.room3.Entity @@ -567,10 +568,16 @@ data class ChatMessage( const val TYPE_INBOX_KEY_COMPLETE = "inboxKeyComplete" const val TYPE_INBOX_KEY_FAILED = "inboxKeyFailed" + /** The group signed an announcement of its inbox's key (10044) or relays (10050). */ + const val TYPE_INBOX_ANNOUNCED = "inboxAnnounced" + const val TYPE_INBOX_RELAYS_ANNOUNCED = "inboxRelaysAnnounced" + val INBOX_TYPES = setOf( TYPE_INBOX_KEY_STARTED, TYPE_INBOX_KEY_COMPLETE, TYPE_INBOX_KEY_FAILED, + TYPE_INBOX_ANNOUNCED, + TYPE_INBOX_RELAYS_ANNOUNCED, ) val GROUP_IDENTITY_TYPES = setOf( @@ -1383,6 +1390,37 @@ data class ChatMessage( // through the room -- identity plumbing nobody sends on purpose -- // and is neither a line nor a raw-JSON bubble. // docs/group-nostr-profile-and-posts.md. + // The group announcing its inbox (docs/group-inbox.md, D5 and D6): a 10044 + // naming the key its admins made, or a 10050 naming where mail should go. + // Verified, as a post is, so no member can put the announcement in the group's + // mouth; anything else of these kinds says nothing here. + InboxAnnouncement.KEY_KIND, InboxAnnouncement.RELAYS_KIND -> { + val signed = GroupSignedEvent.fromEvent(event, chatRoomId = groupId) + if (!event.pubKey.equals(groupId, ignoreCase = true) || !signed.verifies()) return null + val content = if (event.kind == InboxAnnouncement.KEY_KIND) { + val announced = database.groupSignedEventDao().getByChatRoomIdAndKind(groupId, InboxAnnouncement.KEY_KIND) + .count { it.publicKey.equals(groupId, ignoreCase = true) } + if (announced <= 1) { + "The group has an inbox. Anyone on nostr can now write to it privately, and every admin can read what arrives." + } else { + "The group changed its inbox key. Mail sent to the old key can still be read by the admins who held it." + } + } else { + "The group said where its private mail should arrive." + } + ChatMessage( + giftWrapPayloadId = null, + messageType = if (event.kind == InboxAnnouncement.KEY_KIND) TYPE_INBOX_ANNOUNCED else TYPE_INBOX_RELAYS_ANNOUNCED, + marmotGroupEventId = marmotGroupEventId, + marmotInnerEventId = marmotInnerEventId, + senderPublicKey = senderPublicKey, + isUserMessage = isUserMessage, + chatRoomId = groupId, + createdAt = createdAt, + content = content, + ) + } + MetadataEvent.KIND -> { if (!event.pubKey.equals(groupId, ignoreCase = true)) return null diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupInbox.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupInbox.kt index 9a56c742..286d0e0f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupInbox.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupInbox.kt @@ -112,3 +112,25 @@ data class GroupInboxPublication( ) { fun relayList(): List = relays.split(",").map { it.trim() }.filter { it.isNotEmpty() } } + +/** + * What a signing session that touches the group's inbox carried, and why this device refused it, + * if it did (docs/group-inbox.md, D5 and D12): kept past arrival because approval checks again, + * and the decline has to say why. + */ +@Entity( + foreignKeys = [ + ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE) + ], + indices = [Index("chatRoomId")], +) +data class InboxSigning( + @PrimaryKey + val sessionId: String, + val chatRoomId: String, + /** A reply's sealed manifest, as its proposal carried it (D11). */ + val manifest: String? = null, + /** Why this device declined, in the words the decline carries. */ + val refusal: String? = null, + val createdAt: Instant = Clock.System.now(), +) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/InboxKeyCeremony.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/InboxKeyCeremony.kt index 018dfdb9..2cb4984e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/InboxKeyCeremony.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/InboxKeyCeremony.kt @@ -45,6 +45,12 @@ data class InboxKeyCeremony( val hostPublicKey: HexKey? = null, val round1Random: HexKey? = null, val round2AuxRandom: HexKey? = null, + /** + * Where the group's mail should arrive, comma-separated, as the member who opened the first + * ceremony chose it: the 10050 the coordinator proposes beside the first 10044 (D6). Null + * for a rotation, which keeps the relays the group already announced. + */ + val announceRelays: String? = null, /** The ceremony's public key `E`, x-only, once it is certified. */ val inboxPublicKey: HexKey? = null, val failureReason: String? = null, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt new file mode 100644 index 00000000..24f6393c --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt @@ -0,0 +1,20 @@ +package mobi.giza.compose.database.repository + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.Flow +import kotlin.time.Instant +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.GroupInboxPublication +import mobi.giza.compose.repository.GroupInboxRepository + +class DatabaseGroupInboxRepository( + private val database: GizaDatabase, + @Suppress("unused") private val scope: CoroutineScope, +) : GroupInboxRepository { + override fun observeUnpublished(): Flow> = + database.groupInboxDao().observeUnpublished() + + override suspend fun markPublished(eventId: HexKey, at: Instant) = + database.groupInboxDao().markPublished(eventId, at) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt index 9d03ff40..720eb208 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt @@ -720,6 +720,22 @@ object FrostSigningManager { return declined } + // The group's inbox: an announcement of a key its admins did not make together, or + // of one since replaced, or relays a stranger could not reach, is declined before + // anybody is asked. docs/group-inbox.md, D5. + if (InboxRefusal.involves(unsignedEvents)) { + InboxRefusal.of(database, localChatRoom, userPublicKey, unsignedEvents)?.let { why -> + logger.w("Signing proposal $sessionId: $why") + val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0, participantCount = n) + .copy(signDeclinedAt = Clock.System.now()) + database.frostSigningSessionDao().upsert(declined) + database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents)) + InboxRefusal.remember(database, sessionId, localChatRoom.chatRoom.id, why) + announceStarted(database, declined) + return declined + } + } + // A share of the generation the proposal names, or a refusal said out loud. // Signing with any other generation's share would put a partial signature // behind the wrong public share -- it cannot aggregate -- and staying @@ -1042,6 +1058,32 @@ object FrostSigningManager { ) } + /** + * The one inbox question a device answers for its owner: the group's announcement of the + * key a rotation made, once the group has announced an inbox before and this device holds + * the new key. docs/group-inbox.md, D5. + */ + private suspend fun announcesItsRotatedInbox(database: GizaDatabase, session: FrostSigningSession): Boolean { + val current = database.frostSigningSessionDao().getSessionById(session.id) ?: return false + if (current.signApprovedAt != null || current.signDeclinedAt != null) return false + if (current.stage == FrostSigningStage.COMPLETE || current.stage == FrostSigningStage.FAILED) return false + val room = database.chatRoomDao().findChatRoomById(current.chatRoomId) ?: return false + return InboxRefusal.vouchesFor(database, room, current, database.frostSigningSessionDao().getItems(current.id)) + } + + /** The inbox refusal that applies to [session] now. docs/group-inbox.md, D5. */ + private suspend fun inboxRefusalNow( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + session: FrostSigningSession, + items: List + ): String? { + if (session.subject != FrostSigningSubject.EVENTS) return null + val events = items.mapNotNull { Event.fromJsonOrNull(it.unsignedEventJson) } + if (!InboxRefusal.involves(events)) return null + return InboxRefusal.of(database, localChatRoom, session.userPublicKey, events) + } + /** Whether [session] is waiting on this device and is a wallet's to sign. */ private suspend fun declinesAsWallet(database: GizaDatabase, session: FrostSigningSession): Boolean = session.signApprovedAt == null && session.signDeclinedAt == null && @@ -1418,6 +1460,14 @@ object FrostSigningManager { logger.e("Signed session ${session.id} but could not publish its change", e) } + // The group's inbox announced: its key's state moves, and the device that + // proposed the announcement owes it to relays. docs/group-inbox.md, D7. + try { + InboxAnnouncements.onSigned(database, session, signedEvents) + } catch (e: Throwable) { + logger.e("Signed session ${session.id} but could not file its inbox announcement", e) + } + // A confederation event: filed, and owed to relays by the device that // proposed it. docs/confederation.md, D9. try { @@ -2074,6 +2124,20 @@ object FrostSigningManager { } } + /** + * Takes another pass at every open session in [localChatRoom] once an inbox key ceremony has + * finished here (docs/group-inbox.md, D5): an announcement of the key it made, proposed + * before this device had made it, can now be vouched for or asked about. + */ + suspend fun resumeInboxAnnouncements(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey) { + database.frostSigningSessionDao().getOpenUnansweredSessionsFor(userPublicKey) + .filter { it.chatRoomId == localChatRoom.chatRoom.id } + .forEach { session -> + approveIfVouched(database, session) + advance(database, localChatRoom, session.id) + } + } + /** * Signs every open key state this user's device can now vouch for and has not * been answered about -- what a build that asked about them left waiting. Run @@ -2093,7 +2157,7 @@ object FrostSigningManager { /** Approves [session] on its owner's behalf when [signsAsItsOwnKeyState] says this device can. */ private suspend fun approveIfVouched(database: GizaDatabase, session: FrostSigningSession): Boolean { - if (!signsAsItsOwnKeyState(database, session)) return false + if (!signsAsItsOwnKeyState(database, session) && !announcesItsRotatedInbox(database, session)) return false logger.i("Session ${session.id} is a key state this device can vouch for; signing") update(database, session) { it.copy(signApprovedAt = Clock.System.now()) } return true @@ -2234,6 +2298,16 @@ object FrostSigningManager { return } + // And the inbox's, checked again: a newer key can be made, or the admins change, + // while a member decides. docs/group-inbox.md, D5. + inboxRefusalNow(database, localChatRoom, session, items)?.let { why -> + logger.w("Session $sessionId: $why") + InboxRefusal.remember(database, sessionId, localChatRoom.chatRoom.id, why) + update(database, session) { it.copy(signDeclinedAt = Clock.System.now()) } + advance(database, localChatRoom, sessionId) + return + } + update(database, session) { it.copy(signApprovedAt = Clock.System.now()) } logger.i("Session $sessionId: signing approved") @@ -2718,8 +2792,10 @@ object FrostSigningManager { ) { val items = database.frostSigningSessionDao().getItems(session.id) val confederationReason = ConfederationRefusal.reasonFor(database, session.id) + val inboxReason = InboxRefusal.reasonFor(database, session.id) val reason = when { confederationReason != null -> confederationReason + inboxReason != null -> inboxReason isWalletSession(session, items) -> WalletRefusal.REASON isUnshowableSession(session, items) -> GroupStatementRefusal.REASON !holdsShareFor(database, session) -> GENERATION_REFUSAL diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxPublisher.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxPublisher.kt new file mode 100644 index 00000000..0e53d98b --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxPublisher.kt @@ -0,0 +1,107 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.Event +import kotlin.time.Clock +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.minutes +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.take +import kotlinx.coroutines.withTimeout +import mobi.giza.compose.database.model.GroupInboxPublication +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.network.dto.RelayDTO +import mobi.giza.compose.network.relays.EventPublishTransport +import mobi.giza.compose.network.relays.RelayPool +import mobi.giza.compose.network.sockets.NostrIncomingMessage +import mobi.giza.compose.nostr.Relays +import mobi.giza.compose.repository.GroupInboxRepository + +/** + * Sends what this device owes relays for its groups' inboxes (docs/group-inbox.md, D7 and D10): + * the announcements it asked the group to sign, and the gift wraps around the replies it + * proposed. Keeps trying until a relay takes each, backing off from a minute to half an hour, as + * `ConfederationPublisher` does for its events and for the same reason: never through a + * `NostrEvent` row. + */ +class GroupInboxPublisher( + private val repository: GroupInboxRepository, + private val transport: EventPublishTransport, + private val firstRetry: Duration = 1.minutes, + private val lastRetry: Duration = 30.minutes, +) { + private val logger = Logger.withTag("GroupInboxPublisher") + + /** Runs until cancelled. */ + suspend fun run() { + repository.observeUnpublished().collectLatest { owed -> + var wait = firstRetry + var remaining = owed + while (remaining.isNotEmpty()) { + remaining = remaining.filterNot { publish(it) } + if (remaining.isEmpty()) break + logger.w("${remaining.size} inbox event(s) not yet taken by any relay; trying again in $wait") + delay(wait) + wait = minOf(wait * 2, lastRetry) + } + } + } + + /** + * Sends [owed] to its relays. An announcement goes to the publish set too, so a stranger's + * app finds it wherever it looks; a wrap goes only where its recipient reads, or the + * publish set when they have said nowhere. Whether any relay accepted it. + */ + suspend fun publish(owed: GroupInboxPublication): Boolean { + val own = owed.relayList() + val targets = when { + owed.recipientPublicKey == null -> own + Relays.eventPublishRelaySet.map { it.url } + own.isEmpty() -> Relays.eventPublishRelaySet.map { it.url } + else -> own + }.map { it.trim() }.filter { it.startsWith("wss://") || it.startsWith("ws://") }.distinct() + + val wire = wireEventOf(owed) ?: return false + var accepted = false + try { + withTimeout((RelayPool.PUBLISH_TIMEOUT * 2).milliseconds) { + transport.publishEvent( + nostrEvent = wire, + relays = targets.map { RelayDTO(url = it, read = false, write = true) }.toSet(), + ).take(targets.size).collect { result -> + val ok = result.result as? NostrIncomingMessage.OkMessage + if (result.error == null && ok?.success == true) accepted = true + } + } + } catch (e: TimeoutCancellationException) { + // A relay that never answers. Whatever answered in time counts. + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + logger.e("Could not send inbox event ${owed.eventId.take(8)}", e) + } + if (accepted) { + repository.markPublished(owed.eventId, Clock.System.now()) + logger.i("Inbox event ${owed.eventId.take(8)} of kind ${owed.kind} is on a relay") + } + return accepted + } + + private companion object { + /** The event as the pool wants it. Never written to the `NostrEvent` table. */ + fun wireEventOf(owed: GroupInboxPublication): NostrEvent? = Event.fromJsonOrNull(owed.eventJson)?.let { + NostrEvent( + id = it.id, + pubKey = it.pubKey, + kind = it.kind, + tags = it.tags, + content = it.content, + sig = it.sig, + createdAt = kotlin.time.Instant.fromEpochSeconds(it.createdAt), + ) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxAnnouncements.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxAnnouncements.kt new file mode 100644 index 00000000..09749f91 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxAnnouncements.kt @@ -0,0 +1,87 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl +import kotlin.time.Clock +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.GroupInboxPublication +import mobi.giza.compose.database.model.InboxKeyState +import mobi.giza.compose.nostr.Relays +import mobi.giza.compose.nostr.inbox.InboxAnnouncement + +/** + * What a signed announcement of the group's inbox changes on a device (docs/group-inbox.md, D7 + * and D14): the key it names becomes the one replies are sealed from, the ones before it are + * kept to open with, and the device that proposed it owes it to relays. + */ +object InboxAnnouncements { + /** Called by [FrostSigningManager.complete] on every device, with what the session signed. */ + suspend fun onSigned(database: GizaDatabase, session: FrostSigningSession, signedEvents: List) { + val roomId = session.chatRoomId + val ours = signedEvents.filter { + it.pubKey.equals(roomId, ignoreCase = true) && + (it.kind == InboxAnnouncement.KEY_KIND || it.kind == InboxAnnouncement.RELAYS_KIND) + } + if (ours.isEmpty()) return + + ours.firstOrNull { it.kind == InboxAnnouncement.KEY_KIND }?.let { announcement -> + InboxAnnouncement.groupKeyOf(announcement)?.let { key -> settle(database, roomId, session.userPublicKey, key, announcement.id) } + } + + // Only the device that asked for the signature sends it, as for a confederation + // event: one sender, retrying until a relay takes it, rather than every signer racing. + if (!session.isCoordinator()) return + val relays = (relaysOf(database, roomId, signedEvents) + Relays.DefaultDMRelayList).distinct() + ours.forEach { event -> + database.groupInboxDao().upsertPublication( + GroupInboxPublication( + eventId = event.id, + chatRoomId = roomId, + kind = event.kind, + eventJson = event.toJson(), + relays = relays.joinToString(",") { it.url }, + signingSessionId = session.id, + recipientPublicKey = null, + ) + ) + } + } + + /** + * [key] is the group's announced inbox key now: its generation is [InboxKeyState.ANNOUNCED] + * and every earlier one this device still holds is [InboxKeyState.RETIRED]. A later + * generation made but not yet announced stays as it is. + */ + private suspend fun settle(database: GizaDatabase, roomId: String, userPublicKey: String, key: String, eventId: String) { + val keys = database.inboxKeyDao().getKeys(roomId, userPublicKey) + val named = keys.firstOrNull { it.publicKey == key } ?: return + val now = Clock.System.now() + keys.forEach { held -> + val next = when { + held.generation == named.generation -> held.copy(state = InboxKeyState.ANNOUNCED, announcementEventId = eventId, announcedAt = now) + held.generation < named.generation && held.state != InboxKeyState.WIPED -> held.copy(state = InboxKeyState.RETIRED) + else -> held + } + if (next != held) database.inboxKeyDao().upsertKey(next) + } + } + + /** The relays the group's mail should go to: this batch's 10050, else the newest one it signed. */ + suspend fun relaysOf(database: GizaDatabase, roomId: String, batch: List = emptyList()): List { + batch.firstOrNull { it.kind == InboxAnnouncement.RELAYS_KIND && it.pubKey.equals(roomId, ignoreCase = true) } + ?.let { InboxAnnouncement.groupRelaysOf(it) }?.let { return it } + return database.groupSignedEventDao().getByChatRoomIdAndKind(roomId, InboxAnnouncement.RELAYS_KIND) + .filter { it.publicKey.equals(roomId, ignoreCase = true) } + .maxByOrNull { it.createdAt } + ?.let { InboxAnnouncement.groupRelaysOf(it.kind, it.tags, it.content) } + .orEmpty() + } + + /** The key the group's newest signed 10044 names, or null if it has announced none. */ + suspend fun announcedKey(database: GizaDatabase, roomId: String): String? = + database.groupSignedEventDao().getByChatRoomIdAndKind(roomId, InboxAnnouncement.KEY_KIND) + .filter { it.publicKey.equals(roomId, ignoreCase = true) } + .maxByOrNull { it.createdAt } + ?.let { InboxAnnouncement.groupKeyOf(it.kind, it.tags, it.content) } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxFollowThrough.kt index 5cda7ba7..41a262e8 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxFollowThrough.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxFollowThrough.kt @@ -1,15 +1,53 @@ package mobi.giza.compose.managers +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import kotlin.time.Clock +import kotlinx.coroutines.CancellationException import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.InboxKeyCeremony import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.Relays +import mobi.giza.compose.nostr.inbox.InboxAnnouncement /** * What follows an inbox key ceremony on the device that coordinated it (docs/group-inbox.md, - * D5 and D6): proposing the group's announcement of the key it made. + * D5 and D6): asking the group to announce the key it made. + * + * The first time, that is a batch of two -- the 10044 naming the key and the 10050 naming where + * mail should arrive -- and the group's members are asked, since signing it is the group + * deciding to have an inbox at all. After that, a rotation's 10044 alone, which every admin's + * device can vouch for and signs unasked ([InboxRefusal.vouchesFor]). */ object InboxFollowThrough { + private val logger = Logger.withTag("InboxFollowThrough") + /** Called once, on every participant's device, when [ceremony] has made its key. */ - @Suppress("UNUSED_PARAMETER", "RedundantSuspendModifier") - suspend fun onKeyMade(database: GizaDatabase, localChatRoom: LocalChatRoom, ceremony: InboxKeyCeremony) = Unit + suspend fun onKeyMade(database: GizaDatabase, localChatRoom: LocalChatRoom, ceremony: InboxKeyCeremony) { + if (!ceremony.isCoordinator()) return + val key = database.inboxKeyDao().getKey(ceremony.chatRoomId, ceremony.userPublicKey, ceremony.generation) ?: return + val now = Clock.System.now().epochSeconds + + val events = buildList> { + add(InboxAnnouncement.keyTemplate(key.publicKey, now)) + if (InboxAnnouncements.announcedKey(database, ceremony.chatRoomId) == null) { + val chosen = ceremony.announceRelays.orEmpty().split(",") + .mapNotNull { RelayUrlNormalizer.normalizeOrNull(it.trim()) } + add(InboxAnnouncement.relaysTemplate(chosen.ifEmpty { Relays.DefaultDMRelayList }, now)) + } + } + + try { + val session = FrostSigningManager.proposeSigningBatch(database, localChatRoom, ceremony.userPublicKey, events = events) + logger.i("Asked the group to announce inbox key generation ${ceremony.generation} in session ${session.id.take(8)}") + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + // The key is made and kept either way; an admin can ask again from the inbox's + // settings. Not a ceremony failure, so not said as one. + logger.e("Made inbox key generation ${ceremony.generation} but could not ask the group to announce it", e) + } + } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt index 33e4e9c1..6f653cdc 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt @@ -28,7 +28,9 @@ import mobi.giza.compose.database.model.InboxKeyCeremonyStage import mobi.giza.compose.database.model.MarmotInnerEvent import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.Relays import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl import mobi.giza.compose.nostr.inbox.InboxWire /** @@ -109,6 +111,8 @@ object InboxKeyRitualManager { localChatRoom: LocalChatRoom, userPublicKey: HexKey, nostrPrivateKey: ByteArray, + /** Where the group's mail should arrive, for the first generation's 10050 (D6). */ + relays: List = Relays.DefaultDMRelayList, ): InboxKeyCeremony { val roomId = localChatRoom.chatRoom.id database.inboxKeyDao().getRunningCeremoniesIn(roomId).firstOrNull { it.userPublicKey == userPublicKey }?.let { return it } @@ -116,10 +120,12 @@ object InboxKeyRitualManager { refusal(database, localChatRoom, userPublicKey)?.let { throw IllegalStateException(it) } val admins = RoomAdmins.of(database, roomId)!!.admins + val generation = nextGeneration(database, roomId, userPublicKey) val ceremony = InboxKeyCeremony( id = RandomInstance.bytes(32).toHex(), chatRoomId = roomId, - generation = nextGeneration(database, roomId, userPublicKey), + generation = generation, + announceRelays = relays.takeIf { generation == 0 }?.joinToString(",") { it.url }, coordinatorPublicKey = userPublicKey, userPublicKey = userPublicKey, participantPublicKeys = InboxKeyCeremony.formatParticipants(admins), @@ -303,12 +309,17 @@ object InboxKeyRitualManager { InboxKeyRitualEvents.CERTIFICATE -> { if (sender != ceremony.coordinatorPublicKey) return true store(database, ceremony, sender, innerEvent.kind, innerEvent.content) - // A member who only watches cannot check the certificate; the admins can, and - // will fail it out loud if it is wrong. The watcher's line says it was issued. + // A member who only watches holds no secret, but every message the + // coordinator aggregated is public in the room, so it can aggregate them too + // and learn the key the admins made -- which is what lets it check the + // group's announcement of that key before signing it (D5). if (!ceremony.isParticipant()) { val current = database.inboxKeyDao().getCeremony(ceremony.id) ?: ceremony if (current.isRunning) { - database.inboxKeyDao().upsertCeremony(current.copy(stage = InboxKeyCeremonyStage.COMPLETE, updatedAt = Clock.System.now())) + val watched = runCatching { watchedKey(database, current) }.getOrNull() + database.inboxKeyDao().upsertCeremony( + current.copy(stage = InboxKeyCeremonyStage.COMPLETE, inboxPublicKey = watched, updatedAt = Clock.System.now()) + ) announce(database, current, ChatMessage.TYPE_INBOX_KEY_COMPLETE, "The group's admins finished making its inbox key.", current.coordinatorPublicKey) } } @@ -415,6 +426,7 @@ object InboxKeyRitualManager { ) logger.i("Inbox key ceremony ${sessionId.take(8)} complete: generation ${done.generation}") InboxFollowThrough.onKeyMade(database, localChatRoom, done) + FrostSigningManager.resumeInboxAnnouncements(database, localChatRoom, done.userPublicKey) } catch (e: CancellationException) { throw e } catch (e: Throwable) { @@ -426,6 +438,27 @@ object InboxKeyRitualManager { } } + /** + * The key a ceremony made, as a member who only watched it can compute: the coordinator's + * two aggregations need no secret, and every message they take is in the room. Null while + * any is missing, or if they do not aggregate. + */ + internal suspend fun keyWatched(database: GizaDatabase, ceremony: InboxKeyCeremony): HexKey? = + runCatching { watchedKey(database, ceremony) }.getOrNull()?.also { key -> + database.inboxKeyDao().getCeremony(ceremony.id)?.let { database.inboxKeyDao().upsertCeremony(it.copy(inboxPublicKey = key)) } + } + + private suspend fun watchedKey(database: GizaDatabase, ceremony: InboxKeyCeremony): HexKey? { + val hostPublicKeys = hostPublicKeys(database, ceremony) ?: return null + val pmsgs1 = ordered(database, ceremony, InboxKeyRitualEvents.ROUND_1) ?: return null + val pmsgs2 = ordered(database, ceremony, InboxKeyRitualEvents.ROUND_2) ?: return null + val state = ChillDKG.coordinatorStep1(pmsgs1.map { ByteVector(it) }, hostPublicKeys, InboxKeyRitualEvents.THRESHOLD) + .takeIf { it.fault.isOk }?.state ?: return null + val certified = ChillDKG.coordinatorFinalize(state, pmsgs2.map { ByteVector64(it) }, InboxKeyRitualEvents.THRESHOLD) + .takeIf { it.fault.isOk } ?: return null + return certified.thresholdPublicKey?.xOnly()?.value?.toHex() + } + /** The participants' host keys, sorted, or null while any is outstanding. */ private suspend fun hostPublicKeys(database: GizaDatabase, ceremony: InboxKeyCeremony): List? { val participants = ceremony.participants() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt new file mode 100644 index 00000000..12914330 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt @@ -0,0 +1,119 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.FrostSigningItem +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.InboxKeyCeremony +import mobi.giza.compose.database.model.InboxSigning +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.inbox.InboxAnnouncement + +/** + * What a device declines, out loud, when the group is asked to sign something about its inbox + * (docs/group-inbox.md, D5): the announcement of its key (10044) and of where its mail goes + * (10050). + * + * The signer has no allowlist, so without this a peer's 10044 reached the member as "Event of + * kind 10044" and could be signed whatever key it named -- including one a removed admin made, + * or one nobody in the group holds, either of which hands the group's mail to someone the + * group did not choose. Giza signs only what it can check. + * + * Checked in the four places every refusal sits in [FrostSigningManager]: on arrival, again at + * approval, as the decline's reason, and (for a session filed before this existed) at approval + * through the same call. + */ +object InboxRefusal { + const val KEY_NOT_MADE = "Giza doesn't sign an inbox key the group's admins didn't make together" + const val KEY_NOT_NEWEST = "Giza doesn't sign an inbox key the group has since replaced" + const val KEY_NOT_ADMINS = "Giza doesn't sign an inbox key made by anyone but the group's current admins" + const val KEY_SHAPE = "Giza doesn't sign an inbox key announcement it would not write" + const val RELAYS_SHAPE = "Giza doesn't sign a list of inbox relays a stranger could not reach" + + /** Whether any of [events] is one this refusal is about. */ + fun involves(events: List): Boolean = + events.any { it.kind == InboxAnnouncement.KEY_KIND || it.kind == InboxAnnouncement.RELAYS_KIND } + + /** + * Why this device declines to sign [events] in [localChatRoom] as [userPublicKey] sees it, or + * null when it would sign them. + */ + suspend fun of( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + events: List, + ): String? { + for (event in events) { + when (event.kind) { + InboxAnnouncement.RELAYS_KIND -> + if (InboxAnnouncement.groupRelaysOf(event) == null) return RELAYS_SHAPE + InboxAnnouncement.KEY_KIND -> { + val key = InboxAnnouncement.groupKeyOf(event) ?: return KEY_SHAPE + keyRefusal(database, localChatRoom, userPublicKey, key)?.let { return it } + } + } + } + return null + } + + /** + * D5's three checks on the key a 10044 names: it is what a ceremony in this room made, the + * newest one, and that ceremony was run over the admins the room has now. + */ + private suspend fun keyRefusal(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, key: HexKey): String? { + val roomId = localChatRoom.chatRoom.id + val completed = database.inboxKeyDao().getCompletedCeremonies(roomId, userPublicKey) + val maker = completed.firstOrNull { keyOf(database, it) == key } + if (maker == null) { + // The coordinator asks for the announcement the moment its own copy of the key is + // made, which is routinely before this device has finished the same ceremony. Not a + // refusal yet: the session waits, approval checks again, and the ceremony finishing + // here asks again ([FrostSigningManager.resumeInboxAnnouncements]). + val running = database.inboxKeyDao().getRunningCeremoniesIn(roomId).any { it.userPublicKey == userPublicKey } + return if (running) null else KEY_NOT_MADE + } + if (completed.any { it.generation > maker.generation }) return KEY_NOT_NEWEST + val admins = RoomAdmins.of(database, roomId)?.admins ?: return null + if (admins != maker.participants().toSet()) return KEY_NOT_ADMINS + return null + } + + /** The key [ceremony] made, recomputing it on a watcher's device that missed it at the time. */ + private suspend fun keyOf(database: GizaDatabase, ceremony: InboxKeyCeremony): HexKey? = + ceremony.inboxPublicKey ?: InboxKeyRitualManager.keyWatched(database, ceremony) + + /** + * Whether this device can sign [items] on its owner's behalf (D5): a rotation's 10044 alone, + * naming a key this device holds the secret of, in a room whose quorum has announced an + * inbox before. The decision to have an inbox was asked; keeping it is what a rotation is. + */ + suspend fun vouchesFor(database: GizaDatabase, localChatRoom: LocalChatRoom, session: FrostSigningSession, items: List): Boolean { + val events = items.mapNotNull { Event.fromJsonOrNull(it.unsignedEventJson) } + val announcement = events.singleOrNull()?.takeIf { it.kind == InboxAnnouncement.KEY_KIND } ?: return false + if (of(database, localChatRoom, session.userPublicKey, events) != null) return false + val key = InboxAnnouncement.groupKeyOf(announcement) ?: return false + val roomId = localChatRoom.chatRoom.id + // Never on the strength of a ceremony still running: the refusal lets one wait, and + // vouching is for a key this device has. + val held = database.inboxKeyDao().getKeys(roomId, session.userPublicKey) + if (held.none { it.publicKey == key && it.secretKey != null }) return false + val announcedBefore = database.groupSignedEventDao().getByChatRoomIdAndKind(roomId, InboxAnnouncement.KEY_KIND) + return announcedBefore.any { it.publicKey == roomId && InboxAnnouncement.groupKeyOf(it.kind, it.tags, it.content) != key } + } + + /** Keeps why [sessionId] was refused, so the decline can say it. */ + suspend fun remember(database: GizaDatabase, sessionId: String, chatRoomId: String, refusal: String?, manifest: String? = null) { + val existing = database.groupInboxDao().getSigning(sessionId) + database.groupInboxDao().upsertSigning( + (existing ?: InboxSigning(sessionId = sessionId, chatRoomId = chatRoomId)).copy( + refusal = refusal ?: existing?.refusal, + manifest = manifest ?: existing?.manifest, + ) + ) + } + + suspend fun reasonFor(database: GizaDatabase, sessionId: String): String? = + database.groupInboxDao().getSigning(sessionId)?.refusal +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt new file mode 100644 index 00000000..fddd5d99 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt @@ -0,0 +1,14 @@ +package mobi.giza.compose.repository + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.flow.Flow +import kotlin.time.Instant +import mobi.giza.compose.database.model.GroupInboxPublication + +/** The group's inbox, as the screens and the sync see it (docs/group-inbox.md). */ +interface GroupInboxRepository { + /** What this device owes relays on its groups' behalf and has not yet got onto one. */ + fun observeUnpublished(): Flow> + + suspend fun markPublished(eventId: HexKey, at: Instant) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt index 4fb9f820..6a064943 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt @@ -10,6 +10,7 @@ import mobi.giza.compose.managers.SharedKeyDerivation import mobi.giza.compose.managers.WalletRefusal import mobi.giza.compose.nostr.RetiredKinds import mobi.giza.compose.nostr.frost.GovernanceStatementEvent +import mobi.giza.compose.nostr.inbox.InboxAnnouncement import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent @@ -92,6 +93,20 @@ object ProposedEvent { ) } ?: Summary(label = "A change to this group that cannot be read", detail = "") + // The group's inbox (docs/group-inbox.md, D5 and D6): the key anyone writing to + // the group will encrypt to, shown by its fingerprint, and the relays its mail is + // to arrive on. Deciding to sign the first is deciding the group has an inbox. + InboxAnnouncement.KEY_KIND -> Summary( + label = "The group's inbox key", + detail = InboxAnnouncement.announcedKeyOf(event)?.let { "Key ${it.take(8)}…${it.takeLast(8)}" } + ?: "Names no key", + ) + InboxAnnouncement.RELAYS_KIND -> Summary( + label = "Where the group receives private messages", + detail = InboxAnnouncement.announcedRelaysOf(event).joinToString(", ") { it.url.removePrefix("wss://").trimEnd('/') } + .ifEmpty { "No relays" }, + ) + // The group's own profile. Named by what the group would be called and // what it would say about itself, which is the whole of what is being // decided; the JSON in the content is the one thing a signer should not diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index 66e2df5b..5845867a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -46,6 +46,7 @@ import mobi.giza.compose.GizaGlobal import mobi.giza.compose.database.repository.DatabaseChatRepository import mobi.giza.compose.database.repository.DatabaseDkgRepository import mobi.giza.compose.database.repository.DatabaseConfederationRepository +import mobi.giza.compose.database.repository.DatabaseGroupInboxRepository import mobi.giza.compose.database.repository.DatabaseFrostSigningRepository import mobi.giza.compose.database.repository.DatabaseMarmotRepository import mobi.giza.compose.database.repository.DatabaseNostrRepository @@ -223,6 +224,12 @@ fun GizaNavHost( activeIdentity = sovereignWalletViewModel.activeIdentity, ) } + val databaseGroupInboxRepository = remember { + DatabaseGroupInboxRepository( + database = auxDatabaseManager.auxDatabase, + applicationIOScope, + ) + } val databaseMarmotRepository = remember { DatabaseMarmotRepository( database = auxDatabaseManager.auxDatabase, @@ -264,6 +271,7 @@ fun GizaNavHost( relayRepository = databaseNostrRepository, scope = applicationIOScope, confederationRepository = databaseConfederationRepository, + groupInboxRepository = databaseGroupInboxRepository, ) ) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt index 7af1e335..fccf2892 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt @@ -32,6 +32,7 @@ import mobi.giza.compose.exceptions.NostrPublishException import mobi.giza.compose.network.dto.RelayDTO import mobi.giza.compose.network.relays.EventPublishTransport import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.inbox.InboxAnnouncement import mobi.giza.compose.network.relays.NostrPublishResult import mobi.giza.compose.network.relays.RelayPool import mobi.giza.compose.network.sockets.NostrIncomingMessage @@ -298,9 +299,11 @@ class BroadcastGroupSignedEventViewModel( /** * The kinds this screen will put on a relay: the group's profile and posts, and its * confederation events, which a member sends again by hand when the device that - * signed for them never got them out (docs/confederation.md, D9). + * signed for them never got them out (docs/confederation.md, D9), and its inbox's key + * and relays, for the same reason (docs/group-inbox.md, D7). */ - val BROADCASTABLE_KINDS: Set = setOf(MetadataEvent.KIND, TextNoteEvent.KIND) + ConfederationKinds.ALL + val BROADCASTABLE_KINDS: Set = setOf(MetadataEvent.KIND, TextNoteEvent.KIND) + ConfederationKinds.ALL + + setOf(InboxAnnouncement.KEY_KIND, InboxAnnouncement.RELAYS_KIND) /** * Sends [signedEvent] to [targets] and says what each relay answered. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt index b4a7e072..8baccdd6 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt @@ -61,6 +61,8 @@ import mobi.giza.compose.nostr.SignInSync import kotlinx.coroutines.sync.withPermit import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.managers.ConfederationPublisher +import mobi.giza.compose.managers.GroupInboxPublisher +import mobi.giza.compose.repository.GroupInboxRepository import mobi.giza.compose.repository.ConfederationRepository import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds @@ -72,6 +74,7 @@ class SynchronizationViewModel( val relayRepository: RelayRepository, val scope: CoroutineScope, val confederationRepository: ConfederationRepository? = null, + val groupInboxRepository: GroupInboxRepository? = null, ): ViewModel() { val relaysSocketManager = RelaysSocketManager( @@ -99,6 +102,11 @@ class SynchronizationViewModel( ConfederationPublisher(repository = it, transport = relaysSocketManager) } + /** Sends what this device owes relays for its groups' inboxes (docs/group-inbox.md, D7). */ + private val groupInboxPublisher = groupInboxRepository?.let { + GroupInboxPublisher(repository = it, transport = relaysSocketManager) + } + companion object { private const val TAG = "SynchronizationViewModel" @@ -150,6 +158,7 @@ class SynchronizationViewModel( relayRepository: RelayRepository, scope: CoroutineScope, confederationRepository: ConfederationRepository? = null, + groupInboxRepository: GroupInboxRepository? = null, ): ViewModelProvider.Factory = viewModelFactory { initializer { SynchronizationViewModel( @@ -159,6 +168,7 @@ class SynchronizationViewModel( relayRepository = relayRepository, scope = scope, confederationRepository = confederationRepository, + groupInboxRepository = groupInboxRepository, ) } } @@ -283,6 +293,17 @@ class SynchronizationViewModel( } } } + // The group inbox's announcements and replies this device + // owes relays. docs/group-inbox.md, D7 and D10. + groupInboxPublisher?.takeIf { ExperimentalFeatures.groupInbox }?.let { publisher -> + launch(Dispatchers.IO) { + runCatching { publisher.run() } + .onFailure { + if (it is CancellationException) throw it + logger.e("Publishing inbox events stopped", it) + } + } + } // A key ceremony this profile opened, taken from a key to a // working room without anybody pressing a button: the key // state proposed, a subgroup's certificate asked for, the diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt index 3ae38941..162fda95 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt @@ -112,14 +112,19 @@ class ProposedEventTest { } /** - * docs/group-inbox.md, Phase 1: the events a group's inbox is made of are, today, kinds - * the app has no words for. Phases 5 and 8 give them words. + * docs/group-inbox.md: the group's inbox key and its relays are said by what they are + * (Phase 5). A seal is still said by its number until Phase 8 gives it words. */ @Test - fun `an inbox key, a DM relay list and a seal are said by their numbers today`() { - listOf(10044, 10050, 13).forEach { kind -> - assertEquals("Event of kind $kind", ProposedEvent.summarize(event(kind)).label) - } + fun `an inbox key and its relays are named, and a seal is still a number`() { + val key = "e".repeat(64) + val announcement = ProposedEvent.summarize(event(10044, tags = arrayOf(arrayOf("n", key)))) + assertEquals("The group's inbox key", announcement.label) + assertEquals("Key eeeeeeee…eeeeeeee", announcement.detail) + val relays = ProposedEvent.summarize(event(10050, tags = arrayOf(arrayOf("relay", "wss://inbox.example.com/")))) + assertEquals("Where the group receives private messages", relays.label) + assertEquals("inbox.example.com", relays.detail) + assertEquals("Event of kind 13", ProposedEvent.summarize(event(13)).label) } private fun event( diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt index f103565e..66fb145f 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt @@ -16,9 +16,9 @@ import mobi.giza.compose.text.ProposedEvent * What Giza does today with the events a group's inbox is made of (docs/group-inbox.md, * Phase 1). Written to pass now and flipped on purpose by the phase that changes each: * - * - a peer's proposal to sign a kind 10044 (an encryption key) or a kind 13 (a NIP-17 seal) - * reaches the member as a bare number, and nothing declines it. Phase 5 and Phase 8 put a - * refusal in front of each; + * - a peer's proposal to sign a kind 13 (a NIP-17 seal) reaches the member as a bare number, + * and nothing declines it. Phase 8 puts a refusal in front of it, as Phase 5 did for a kind + * 10044 (an encryption key), which this pins declined now; * - the only gift wraps the app asks relays for are its own identity's. Phase 6 adds the * group's. */ @@ -52,9 +52,13 @@ class GroupInboxTodayJvmTest { } @Test - fun `a peer's inbox key reaches the member as a number, and can be signed`() { + fun `a peer's inbox key nobody here made is declined out loud`() = runBlocking { + // Flipped by Phase 5: the signer refuses an announcement of a key the group's + // admins did not make together (docs/group-inbox.md, D5). val sent = proposeAndDeliver(10044, arrayOf(arrayOf("n", "e".repeat(64))), "") - assertPutToTheMemberByNumber(sent, 10044) + val session = assertNotNull(harness.db.frostSigningSessionDao().getSessionById(sent.session.id)) + assertNotNull(session.signDeclinedAt) + assertEquals(listOf(InboxRefusal.KEY_NOT_MADE), harness.queued(FrostSigningEvents.DECLINE).map { it.content }) } @Test diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxAnnouncementJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxAnnouncementJvmTest.kt new file mode 100644 index 00000000..03eaa4a3 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxAnnouncementJvmTest.kt @@ -0,0 +1,188 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.types.FrostSigningStage +import mobi.giza.compose.database.model.InboxKeyState +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.repository.DatabaseGroupInboxRepository +import mobi.giza.compose.network.dto.RelayDTO +import mobi.giza.compose.network.relays.EventPublishTransport +import mobi.giza.compose.network.relays.NostrPublishResult +import mobi.giza.compose.network.sockets.NostrIncomingMessage +import mobi.giza.compose.nostr.frost.FrostSigningEvents +import mobi.giza.compose.nostr.inbox.InboxAnnouncement +import mobi.giza.compose.text.ProposedEvent + +/** + * The group announcing its inbox (docs/group-inbox.md, Phase 5): the first announcement is asked, + * a rotation's is vouched for, a wrong one is declined out loud, and the device that asked owes + * what was signed to relays. + */ +class InboxAnnouncementJvmTest { + private val harness = GroupInboxHarness() + + @AfterTest + fun close() = harness.close() + + private suspend fun group() = listOf("alice", "bob", "carol").map { harness.device(it) } + + private suspend fun GroupInboxHarness.Device.sessions(): List = + db.frostSigningSessionDao().getSessionsForChatRoom(harness.roomId) + + private suspend fun GroupInboxHarness.Device.events(session: FrostSigningSession): List = + db.frostSigningSessionDao().getItems(session.id).map { Event.fromJson(it.unsignedEventJson) } + + private suspend fun GroupInboxHarness.Device.awaiting(session: FrostSigningSession): Boolean { + val current = assertNotNull(db.frostSigningSessionDao().getSessionById(session.id)) + return FrostSigningManager.isAwaitingApproval(current, db.frostSigningSessionDao().getItems(session.id)) + } + + /** Makes the first key and has Bob approve its announcement. */ + private suspend fun announced(alice: GroupInboxHarness.Device, bob: GroupInboxHarness.Device): FrostSigningSession { + InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + harness.pump() + val session = alice.sessions().single() + FrostSigningManager.approve(bob.db, bob.room(), session.id) + harness.pump() + return session + } + + @Test + fun `the first key's announcement is the group deciding to have an inbox, and is asked`() = runBlocking { + val (alice, bob, carol) = group() + InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + harness.pump() + + val session = alice.sessions().single() + val kinds = alice.events(session).map { it.kind } + assertEquals(listOf(10044, 10050), kinds, "the key and where mail goes, in one batch") + assertEquals(alice.keys().single().publicKey, InboxAnnouncement.groupKeyOf(alice.events(session)[0])) + + listOf(bob, carol).forEach { assertTrue(it.awaiting(session), "${it.name} is asked") } + assertEquals("The group's inbox key", ProposedEvent.summarize(bob.events(session)[0]).label) + assertEquals("Where the group receives private messages", ProposedEvent.summarize(bob.events(session)[1]).label) + + FrostSigningManager.approve(bob.db, bob.room(), session.id) + harness.pump() + + listOf(alice, bob).forEach { device -> + assertEquals(FrostSigningStage.COMPLETE, device.db.frostSigningSessionDao().getSessionById(session.id)?.stage) + assertEquals(InboxKeyState.ANNOUNCED, device.keys().single().state) + assertEquals(1, device.lines(setOf(ChatMessage.TYPE_INBOX_ANNOUNCED)).size) + assertEquals(1, device.lines(setOf(ChatMessage.TYPE_INBOX_RELAYS_ANNOUNCED)).size) + } + } + + @Test + fun `a rotation's announcement is signed by every admin's device unasked`() = runBlocking { + val (alice, bob, carol) = group() + announced(alice, bob) + + InboxKeyRitualManager.propose(bob.db, bob.room(), bob.publicKey, bob.secret) + harness.pump() + + val rotation = bob.sessions().first { s -> bob.events(s).singleOrNull()?.kind == 10044 } + listOf(alice, bob, carol).forEach { device -> + assertEquals(FrostSigningStage.COMPLETE, device.db.frostSigningSessionDao().getSessionById(rotation.id)?.stage, "${device.name} signed it unasked") + val keys = device.keys() + assertEquals(listOf(1, 0), keys.map { it.generation }) + assertEquals(InboxKeyState.ANNOUNCED, keys[0].state) + assertEquals(InboxKeyState.RETIRED, keys[1].state) + assertNotNull(keys[1].secretKey, "a retired key is kept, to open with") + } + assertTrue(alice.lines(setOf(ChatMessage.TYPE_INBOX_ANNOUNCED)).any { it.content.startsWith("The group changed its inbox key") }) + } + + private suspend fun proposeByHand(from: GroupInboxHarness.Device, vararg templates: EventTemplate): FrostSigningSession = + FrostSigningManager.proposeSigningBatch(from.db, from.room(), from.publicKey, events = templates.toList()) + + private suspend fun declineReason(on: GroupInboxHarness.Device, session: FrostSigningSession): String? { + val current = assertNotNull(on.db.frostSigningSessionDao().getSessionById(session.id)) + assertNotNull(current.signDeclinedAt, "${on.name} declined") + return on.db.marmotInnerEventDao().getByChatRoomAndKinds(harness.roomId, listOf(FrostSigningEvents.DECLINE)) + .firstOrNull { it.publicKey == on.publicKey }?.content + } + + @Test + fun `an inbox key the admins never made is declined out loud`() = runBlocking { + val (alice, bob, _) = group() + val session = proposeByHand(alice, InboxAnnouncement.keyTemplate("e".repeat(64), 1_700_000_000L)) + harness.pump() + assertEquals(InboxRefusal.KEY_NOT_MADE, declineReason(bob, session)) + } + + @Test + fun `a key the group has since replaced is declined`() = runBlocking { + val (alice, bob, _) = group() + announced(alice, bob) + val old = alice.keys().single().publicKey + InboxKeyRitualManager.propose(bob.db, bob.room(), bob.publicKey, bob.secret) + harness.pump() + + val revert = proposeByHand(alice, InboxAnnouncement.keyTemplate(old, 1_700_000_000L)) + harness.pump() + assertEquals(InboxRefusal.KEY_NOT_NEWEST, declineReason(bob, revert)) + } + + @Test + fun `a key made by admins the room no longer has is declined`() = runBlocking { + val (alice, bob, carol) = group() + InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + harness.pump() + val session = alice.sessions().single() + // Carol stops being an admin before Bob decides. + harness.admins = setOf(alice.publicKey, bob.publicKey) + FrostSigningManager.approve(bob.db, bob.room(), session.id) + assertEquals(InboxRefusal.KEY_NOT_ADMINS, declineReason(bob, session)) + } + + @Test + fun `relays a stranger could not reach are declined`() = runBlocking { + val (alice, bob, _) = group() + val session = proposeByHand(alice, EventTemplate(1_700_000_000L, 10050, arrayOf(arrayOf("relay", "ws://localhost:7777")), "")) + harness.pump() + assertEquals(InboxRefusal.RELAYS_SHAPE, declineReason(bob, session)) + } + + /** Answers every relay with an OK, and keeps what it was handed. */ + private class Transport : EventPublishTransport { + val sent = mutableListOf() + override suspend fun publishEvent(nostrEvent: NostrEvent, relays: Set): Flow { + sent += nostrEvent + return flowOf(*relays.map { NostrPublishResult(result = NostrIncomingMessage.OkMessage(eventId = nostrEvent.id, success = true), relayUrl = it.url) }.toTypedArray()) + } + } + + @Test + fun `the device that asked owes what was signed, and sends it as signed without a feed row`() = runBlocking { + val (alice, bob, _) = group() + val session = announced(alice, bob) + + assertEquals(emptyList(), bob.db.groupInboxDao().getPublicationsFor(session.id), "only the proposer sends") + val owed = alice.db.groupInboxDao().getPublicationsFor(session.id) + assertEquals(setOf(10044, 10050), owed.map { it.kind }.toSet()) + + val transport = Transport() + val publisher = GroupInboxPublisher(DatabaseGroupInboxRepository(alice.db, this), transport) + owed.forEach { assertTrue(publisher.publish(it)) } + + val signed = alice.db.groupSignedEventDao().getByChatRoomIdAndKind(harness.roomId, 10044).single() + val wire = transport.sent.single { it.kind == 10044 } + assertEquals(signed.id, wire.id) + assertEquals(signed.signature, wire.sig) + assertNull(alice.db.nostrEventDao().getNostrEventById(signed.id), "no feed row for the group's event") + assertTrue(alice.db.groupInboxDao().getPublicationsFor(session.id).all { it.publishedAt != null }) + } +} From 5370527a4fa16c43c6f5161538053497f3f8d940 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 01:52:39 +0200 Subject: [PATCH 11/16] feat: the group's inbox, read on its admins' devices (group-inbox, Phase 6) live-group-inbox asks the relays a group's mail is announced to arrive on for every gift wrap tagged with the group's npub, as #2361 has a sender tag it, or with one of the inbox keys this device holds, as an app that knows only the announcement tags it. What arrives goes to GroupInboxManager, never through the personal inbox or a NostrEvent row: each wrap into a ledger, opened with the newest key that opens it, the seal by its n tag, the sender's own 10044, or their identity, and filed as one message per rumor in a conversation keyed by its people. A wrap no key opens is kept and counted; a key that arrives later reopens the ledger. A device that sees its owner is no longer an admin forgets the keys and the mail, and says so once. Peers' 10044s are now fetched with their other DM kinds. Co-Authored-By: Claude Opus 5.5 --- .../giza/compose/database/dao/InboxKeyDao.kt | 4 + .../compose/database/model/ChatMessage.kt | 4 + .../DatabaseGroupInboxRepository.kt | 15 ++ .../compose/managers/GroupInboxManager.kt | 133 +++++++++++++ .../compose/managers/InboxKeyRitualManager.kt | 1 + .../managers/LiveSubscriptionManager.kt | 60 ++++++ .../compose/managers/MarmotInboundManager.kt | 8 + .../compose/nostr/DirectMessagePeerSync.kt | 4 + .../repository/GroupInboxRepository.kt | 15 ++ .../ui/view/model/SynchronizationViewModel.kt | 1 + .../compose/managers/GroupInboxReadJvmTest.kt | 180 ++++++++++++++++++ .../managers/GroupInboxTodayJvmTest.kt | 9 +- 12 files changed, 431 insertions(+), 3 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxReadJvmTest.kt diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/InboxKeyDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/InboxKeyDao.kt index e060e5c4..4880c7b8 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/InboxKeyDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/InboxKeyDao.kt @@ -74,6 +74,10 @@ interface InboxKeyDao { @Query("SELECT * FROM InboxKey WHERE chatRoomId = :chatRoomId AND publicKey = :publicKey LIMIT 1") suspend fun findByPublicKey(chatRoomId: String, publicKey: HexKey): InboxKey? + /** The room an inbox key belongs to, for a wrap tagged with the key rather than the group. */ + @Query("SELECT * FROM InboxKey WHERE userPublicKey = :userPublicKey AND publicKey = :publicKey LIMIT 1") + suspend fun findHeldByPublicKey(userPublicKey: HexKey, publicKey: HexKey): InboxKey? + @Upsert suspend fun upsertKey(key: InboxKey) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt index b57832dc..e393cb76 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt @@ -572,12 +572,16 @@ data class ChatMessage( const val TYPE_INBOX_ANNOUNCED = "inboxAnnounced" const val TYPE_INBOX_RELAYS_ANNOUNCED = "inboxRelaysAnnounced" + /** This device wiped the group's inbox when its owner stopped being an admin (D14). */ + const val TYPE_INBOX_FORGOTTEN = "inboxForgotten" + val INBOX_TYPES = setOf( TYPE_INBOX_KEY_STARTED, TYPE_INBOX_KEY_COMPLETE, TYPE_INBOX_KEY_FAILED, TYPE_INBOX_ANNOUNCED, TYPE_INBOX_RELAYS_ANNOUNCED, + TYPE_INBOX_FORGOTTEN, ) val GROUP_IDENTITY_TYPES = setOf( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt index 24f6393c..75fbcae3 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt @@ -1,11 +1,17 @@ package mobi.giza.compose.database.repository +import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map import kotlin.time.Instant import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.GroupInboxMessage import mobi.giza.compose.database.model.GroupInboxPublication +import mobi.giza.compose.managers.GroupInboxManager +import mobi.giza.compose.managers.InboxAnnouncements import mobi.giza.compose.repository.GroupInboxRepository class DatabaseGroupInboxRepository( @@ -17,4 +23,13 @@ class DatabaseGroupInboxRepository( override suspend fun markPublished(eventId: HexKey, at: Instant) = database.groupInboxDao().markPublished(eventId, at) + + override fun observeRoutes(userPublicKey: HexKey): Flow> = + database.inboxKeyDao().observeHeldKeys(userPublicKey) + .map { keys -> keys.groupBy({ it.chatRoomId }, { it.publicKey }).toSortedMap() } + .distinctUntilChanged() + .map { byRoom -> byRoom.map { (room, keys) -> GroupInboxRepository.Route(room, keys, InboxAnnouncements.relaysOf(database, room)) } } + + override suspend fun receive(wrap: Event, userPublicKey: HexKey): GroupInboxMessage? = + GroupInboxManager.receive(database, wrap, userPublicKey) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt new file mode 100644 index 00000000..bfa4ff26 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt @@ -0,0 +1,133 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import kotlin.time.Clock +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.GroupInboxMessage +import mobi.giza.compose.database.model.GroupInboxWrap +import mobi.giza.compose.database.model.InboxKey +import mobi.giza.compose.nostr.inbox.InboxAnnouncement +import mobi.giza.compose.nostr.inbox.InboxConversation +import mobi.giza.compose.nostr.inbox.InboxSeal +import mobi.giza.compose.nostr.inbox.InboxWrap + +/** + * Reading a group's inbox (docs/group-inbox.md, D8 and D9): every gift wrap addressed to a group + * this device holds an inbox key for is put in the ledger, opened if any key it holds opens it, + * and filed as one message per rumor. + * + * Its own path, beside the personal inbox and never inside it. The personal path tries only the + * active identity's key and files what it opens into the admin's own direct messages; the + * group's correspondents are not the admin's, and nothing here writes a `GiftWrapMessage` or a + * `NostrEvent`. + */ +object GroupInboxManager { + private val logger = Logger.withTag("GroupInboxManager") + + /** The secrets this identity can open [chatRoomId]'s mail with, newest generation first. */ + private suspend fun openers(database: GizaDatabase, chatRoomId: String, userPublicKey: HexKey): List = + database.inboxKeyDao().getKeys(chatRoomId, userPublicKey).filter { it.secretKey != null } + + /** + * Files [wrap], heard on a relay, for whichever of [userPublicKey]'s groups it is addressed + * to. Returns the message it filed, or null when it filed none: not a group's, already + * known, or not one this device can open yet -- which is kept and counted, not dropped. + */ + suspend fun receive(database: GizaDatabase, wrap: Event, userPublicKey: HexKey): GroupInboxMessage? { + if (wrap.kind != InboxWrap.KIND) return null + val tagged = InboxWrap.recipientOf(wrap)?.lowercase() ?: return null + // The group's npub, as #2361 has it; or one of its inbox keys, as an app that only + // encrypts to the announced key tags it. + val roomId = if (openers(database, tagged, userPublicKey).isNotEmpty()) { + tagged + } else { + database.inboxKeyDao().findHeldByPublicKey(userPublicKey, tagged)?.chatRoomId ?: return null + } + val keys = openers(database, roomId, userPublicKey) + if (keys.isEmpty()) return null + + val inserted = database.groupInboxDao().insertWrap( + GroupInboxWrap(id = wrap.id, chatRoomId = roomId, wrapJson = wrap.toJson(), wrapCreatedAt = wrap.createdAt) + ) + if (inserted < 0 && database.groupInboxDao().getWrap(wrap.id)?.openedGeneration != null) return null + return open(database, roomId, userPublicKey, wrap, keys) + } + + /** + * Tries every wrap in [chatRoomId] no key has opened yet, with the keys held now: what a key + * that arrives after the mail -- a ceremony finishing, a restore -- is for. Returns how many + * it opened. + */ + suspend fun reopen(database: GizaDatabase, chatRoomId: String, userPublicKey: HexKey): Int { + val keys = openers(database, chatRoomId, userPublicKey) + if (keys.isEmpty()) return 0 + return database.groupInboxDao().getUnopenedWraps(chatRoomId).count { row -> + val wrap = Event.fromJsonOrNull(row.wrapJson) ?: return@count false + open(database, chatRoomId, userPublicKey, wrap, keys) != null + } + } + + private suspend fun open(database: GizaDatabase, roomId: String, userPublicKey: HexKey, wrap: Event, keys: List): GroupInboxMessage? { + val secrets = keys.map { it.secretKey!!.hexToByteArray() } + val (index, seal) = InboxWrap.open(wrap, secrets) ?: return null + val key = keys[index] + + // The sender's own 10044, if this device has heard it, for a seal from a decoupled + // sender whose app wrote no `n` tag. + val senderAnnounced = database.nostrEventDao().getNostrEventByPublicKeyAndKind(seal.pubKey, InboxAnnouncement.KEY_KIND) + ?.let { InboxAnnouncement.announcedKeyOf(it.toEvent()) } + val opened = InboxSeal.open(seal, secrets[index], senderAnnounced) ?: run { + logger.w("Wrap ${wrap.id.take(8)} to ${roomId.take(8)} opened, but its seal did not; leaving it counted") + return null + } + val rumor = opened.rumor + val participants = InboxConversation.participantsOf(rumor, roomId) + val message = GroupInboxMessage( + chatRoomId = roomId, + rumorId = rumor.id, + wrapId = wrap.id, + conversationId = InboxConversation.idOf(participants), + participants = participants.joinToString(","), + senderPublicKey = rumor.pubKey, + kind = rumor.kind, + rumorJson = InboxSeal.rumorJson(rumor), + createdAt = rumor.createdAt, + generation = key.generation, + outgoing = rumor.pubKey.equals(roomId, ignoreCase = true), + ) + database.groupInboxDao().insertMessage(message) + database.groupInboxDao().markOpened(wrap.id, key.generation) + return database.groupInboxDao().getMessage(roomId, rumor.id) + } + + /** + * Forgets [chatRoomId]'s inbox on this device when [userPublicKey] is no longer one of its + * admins (docs/group-inbox.md, D14): the keys' secrets and every message they opened. Said + * in the room, once. Cooperation, not enforcement: a device that does not run this keeps + * what it had, and the rotation that follows is what the group can do about it. + */ + suspend fun forgetIfNotAdmin(database: GizaDatabase, chatRoomId: String, userPublicKey: HexKey, stillAdmin: Boolean) { + if (stillAdmin) return + if (openers(database, chatRoomId, userPublicKey).isEmpty()) return + database.inboxKeyDao().wipeKeys(chatRoomId, userPublicKey, Clock.System.now()) + database.groupInboxDao().deleteMessages(chatRoomId) + database.groupInboxDao().deleteWraps(chatRoomId) + database.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = userPublicKey, + isUserMessage = true, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = chatRoomId, + content = "This device forgot the group's inbox key and its mail, since you are no longer an admin.", + messageType = ChatMessage.TYPE_INBOX_FORGOTTEN, + ) + ) + logger.i("Forgot the inbox of ${chatRoomId.take(8)}: no longer an admin") + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt index 6f653cdc..d6d94a55 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt @@ -427,6 +427,7 @@ object InboxKeyRitualManager { logger.i("Inbox key ceremony ${sessionId.take(8)} complete: generation ${done.generation}") InboxFollowThrough.onKeyMade(database, localChatRoom, done) FrostSigningManager.resumeInboxAnnouncements(database, localChatRoom, done.userPublicKey) + GroupInboxManager.reopen(database, roomId, done.userPublicKey) } catch (e: CancellationException) { throw e } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt index 53b1476e..5e75d1d7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt @@ -41,6 +41,8 @@ import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.nostr.confederation.ConfederationKinds import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.repository.GroupInboxRepository +import mobi.giza.compose.nostr.inbox.InboxWrap import kotlinx.coroutines.flow.combine import mobi.giza.compose.repository.NostrRepository import kotlin.concurrent.Volatile @@ -78,6 +80,12 @@ class LiveSubscriptionManager( * (docs/confederation.md, Phase 5). Null, or the feature off, and nothing is asked for. */ private val confederationRepository: ConfederationRepository? = null, + /** + * Where gift wraps to a group this identity holds an inbox key for are filed + * (docs/group-inbox.md, D8), never as `NostrEvent` rows nor through the personal inbox. + * Null, or the feature off, and nothing is asked for. + */ + private val groupInboxRepository: GroupInboxRepository? = null, ) { private val logger = Logger.withTag(TAG) @@ -96,6 +104,9 @@ class LiveSubscriptionManager( /** The confederation's public events, on the public relays they are published to. */ const val CONFEDERATION_SUB_ID = "live-confederation" + /** Gift wraps to the groups whose inbox key this identity holds (docs/group-inbox.md, D8). */ + const val GROUP_INBOX_SUB_ID = "live-group-inbox" + /** Ids per tag array in the confederation filter, for the reason [MAX_GROUPS_PER_SUBSCRIPTION] gives. */ private const val MAX_CONFEDERATION_IDS = 100 @@ -199,6 +210,18 @@ class LiveSubscriptionManager( Filter(kinds = ConfederationKinds.ANSWERS.toList(), tags = mapOf("e" to chunk), limit = INITIAL_GROUP_HISTORY_LIMIT) } + /** + * Every gift wrap `p`-tagged to one of [recipients]: a group's npub, which is its room's + * id and where nostr-protocol/nips#2361 has a sender tag it, and the group's inbox keys, + * where an app that only encrypts to the announced key tags it instead. No `since`, as + * for our own inbox: a wrap's `created_at` is back-dated by up to two days, and a + * `since` that looks safe is how mail goes missing. + */ + internal fun groupInboxFilters(recipients: List): List = + recipients.distinct().sorted().chunked(MAX_CONFEDERATION_IDS).map { chunk -> + Filter(kinds = listOf(InboxWrap.KIND), tags = mapOf("p" to chunk), limit = INITIAL_GROUP_HISTORY_LIMIT) + } + /** The keyed rooms a confederation could name: Marmot rooms we are still in, by their own ids. */ internal fun confederationRoomIdsFrom(rooms: List): List = rooms @@ -288,6 +311,43 @@ class LiveSubscriptionManager( confederationRepository?.takeIf { ExperimentalFeatures.confederation }?.let { repository -> launch { followConfederations(publicKey = publicKey, keyPair = keyPair, repository = repository) } } + + groupInboxRepository?.takeIf { ExperimentalFeatures.groupInbox }?.let { repository -> + launch { followGroupInboxes(publicKey = publicKey, keyPair = keyPair, repository = repository) } + } + } + + /** + * Keeps one subscription per relay a group's mail is announced to arrive on, for every + * group this identity holds an inbox key for, re-sent when that set changes. What arrives + * goes to [repository] (docs/group-inbox.md, D8). + */ + @OptIn(FlowPreview::class) + private suspend fun followGroupInboxes(publicKey: HexKey, keyPair: KeyPair, repository: GroupInboxRepository) { + repository.observeRoutes(publicKey) + .distinctUntilChanged() + .debounce(GROUP_CHANGE_DEBOUNCE) + .collectLatest { routes -> + if (routes.isEmpty()) return@collectLatest + val filters = groupInboxFilters(routes.flatMap { listOf(it.chatRoomId) + it.keys }) + val relays = (routes.flatMap { it.relays } + Relays.DefaultDMRelayList).map { it.url }.distinct() + coroutineScope { + relays.forEach { relay -> + launch { + runLiveSubscription( + subId = GROUP_INBOX_SUB_ID, + relayUrl = relay, + filters = { filters }, + keyPair = keyPair, + onEvent = { nostrEvent, _ -> + runCatching { repository.receive(nostrEvent.toEvent(), publicKey) } + .onFailure { logger.w(throwable = it) { "Could not file inbox wrap ${nostrEvent.id}" } } + }, + ) + } + } + } + } } /** diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt index 6360103e..d5d22228 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt @@ -278,6 +278,14 @@ object MarmotInboundManager { if ((disbanded || removedUs) && localChatRoom.chatRoom.leftGroupAt == null) { database.chatRoomDao().upsert(localChatRoom.chatRoom.copy(leftGroupAt = Clock.System.now())) } + + // An admin no longer: this device lets go of the group's inbox (docs/group-inbox.md, D14). + GroupInboxManager.forgetIfNotAdmin( + database = database, + chatRoomId = localChatRoom.chatRoom.id, + userPublicKey = userPublicKey, + stillAdmin = !disbanded && !removedUs && userPublicKey in mlsGroup.currentAdminIdentities(), + ) } private suspend fun memberName(database: GizaDatabase, publicKey: HexKey): String = diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/DirectMessagePeerSync.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/DirectMessagePeerSync.kt index 1462420f..37b255b4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/DirectMessagePeerSync.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/DirectMessagePeerSync.kt @@ -5,6 +5,7 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import com.vitorpamplona.quartz.nip17Dm.settings.DmRelayListEvent import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent +import mobi.giza.compose.nostr.inbox.InboxAnnouncement import mobi.giza.compose.database.model.NegentropySynchronizeRequest import mobi.giza.compose.database.model.SynchronizeNostrEventRequest import mobi.giza.compose.database.model.types.SynchronizationFilter @@ -51,6 +52,9 @@ object DirectMessagePeerSync { KeyPackageEvent.KIND, DmRelayListEvent.KIND, AdvertisedRelayListEvent.KIND, + // The key a peer reads encrypted mail with, if they decoupled it (NIP-4E): what a + // group's reply to them is sealed to (docs/group-inbox.md, D10). + InboxAnnouncement.KEY_KIND, ) /** diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt index fddd5d99..bcb9c4ba 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt @@ -1,8 +1,11 @@ package mobi.giza.compose.repository +import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl import kotlinx.coroutines.flow.Flow import kotlin.time.Instant +import mobi.giza.compose.database.model.GroupInboxMessage import mobi.giza.compose.database.model.GroupInboxPublication /** The group's inbox, as the screens and the sync see it (docs/group-inbox.md). */ @@ -11,4 +14,16 @@ interface GroupInboxRepository { fun observeUnpublished(): Flow> suspend fun markPublished(eventId: HexKey, at: Instant) + + /** + * A group whose mail this identity can open: its npub, the inbox keys this device holds for + * it, and where its mail is announced to arrive. + */ + data class Route(val chatRoomId: String, val keys: List, val relays: List) + + /** Every group [userPublicKey] holds an inbox key for, re-emitted when that changes (D8). */ + fun observeRoutes(userPublicKey: HexKey): Flow> + + /** Files a gift wrap heard on a relay for one of [userPublicKey]'s groups. */ + suspend fun receive(wrap: Event, userPublicKey: HexKey): GroupInboxMessage? } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt index 8baccdd6..dcdf3bf7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt @@ -95,6 +95,7 @@ class SynchronizationViewModel( chatRepository = chatRepository, isForeground = AppLifecycle.isForeground, confederationRepository = confederationRepository, + groupInboxRepository = groupInboxRepository, ) /** Sends the confederation events this device signed for (docs/confederation.md, D9). */ diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxReadJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxReadJvmTest.kt new file mode 100644 index 00000000..8853d1fe --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxReadJvmTest.kt @@ -0,0 +1,180 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync +import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler +import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent +import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent +import fr.acinq.bitcoin.Crypto +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.InboxKeyState +import mobi.giza.compose.nostr.inbox.InboxConversation +import mobi.giza.compose.nostr.inbox.InboxSeal +import mobi.giza.compose.nostr.inbox.InboxWire +import mobi.giza.compose.nostr.inbox.InboxWrap + +/** + * Reading the group's inbox (docs/group-inbox.md, Phase 6): mail a stranger writes to the group + * opens on every admin's device and on no other, whatever the stranger's app does with the + * announced key, and what nobody can open is counted rather than lost. + */ +class GroupInboxReadJvmTest { + private val harness = GroupInboxHarness(watchers = listOf("dineo")) + private val zola = KeyPair(Crypto.sha256("zola, who writes to the group".encodeToByteArray())) + private val zolaKey = zola.pubKey.toHexKey() + + @AfterTest + fun close() = harness.close() + + private suspend fun group() = listOf("alice", "bob", "carol", "dineo").map { harness.device(it) } + + private suspend fun keyed(): List { + val devices = group() + val alice = devices[0] + InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + harness.pump() + return devices + } + + private fun rumor(text: String, createdAt: Long = 1_700_000_000L): Event = RumorAssembler.assembleRumor( + pubKey = zolaKey, + ev = EventTemplate(createdAt, 14, arrayOf(arrayOf("p", harness.roomId)), text), + ) + + /** A stock NIP-17 seal from Zola's identity, to [toKey]. */ + private fun seal(message: Event, toKey: HexKey): Event = NostrSignerSync(zola).sign( + 1_700_000_000L, 13, emptyArray(), + InboxWire.encrypt(InboxSeal.rumorJson(message), InboxWire.conversationKey(zola.privKey!!, toKey)), + ) + + private suspend fun GroupInboxHarness.Device.inboxKey(): HexKey = keys().first().publicKey + + private suspend fun GroupInboxHarness.Device.receive(wrap: Event) = GroupInboxManager.receive(db, wrap, publicKey) + + @Test + fun `mail written to the group opens on every admin's device and on nobody else's`() = runBlocking { + val (alice, bob, carol, dineo) = keyed() + val e = alice.inboxKey() + val message = rumor("Can I join the reading group?") + val wrap = InboxWrap.wrap(seal(message, e), harness.roomId, e) + + listOf(alice, bob, carol).forEach { admin -> + val filed = assertNotNull(admin.receive(wrap), "${admin.name} opens it") + assertEquals(message.id, filed.rumorId) + assertEquals(zolaKey, filed.senderPublicKey) + assertFalse(filed.outgoing) + assertEquals(listOf(zolaKey), filed.participantList()) + assertEquals(InboxConversation.idOf(listOf(zolaKey)), filed.conversationId) + assertEquals("Can I join the reading group?", Event.fromJson(filed.rumorJson).content) + } + assertNull(dineo.receive(wrap), "a member who is not an admin holds nothing to open it with") + assertEquals(emptyList(), dineo.db.groupInboxDao().getMessages(harness.roomId)) + } + + @Test + fun `a wrap tagged with the inbox key rather than the group still arrives`() = runBlocking { + val (alice, _, _, _) = keyed() + val e = alice.inboxKey() + // quartz's own builder tags the key it encrypts to: what an app that knows only the + // announcement, and not #2361, sends. + val wrap = GiftWrapEvent.create(event = seal(rumor("Tagged to the key"), e), recipientPubKey = e) + assertEquals("Tagged to the key", Event.fromJson(assertNotNull(alice.receive(wrap)).rumorJson).content) + } + + @Test + fun `mail to the group's npub, which nobody can open, is counted and kept`() = runBlocking { + val (alice, _, _, _) = keyed() + val legacy = InboxWrap.wrap(seal(rumor("From an app with no NIP-4E"), harness.roomId), harness.roomId, harness.roomId) + + assertNull(alice.receive(legacy)) + assertEquals(1, alice.db.groupInboxDao().observeUnopenedCount(harness.roomId).first()) + assertNotNull(alice.db.groupInboxDao().getWrap(legacy.id), "kept in the ledger") + assertEquals(emptyList(), alice.db.groupInboxDao().getMessages(harness.roomId)) + } + + @Test + fun `one rumor in two wraps is one message, and a repeat changes nothing`() = runBlocking { + val (alice, _, _, _) = keyed() + val e = alice.inboxKey() + val message = rumor("Sent twice") + val first = InboxWrap.wrap(seal(message, e), harness.roomId, e) + val second = InboxWrap.wrap(seal(message, e), harness.roomId, e) + + assertNotNull(alice.receive(first)) + assertNull(alice.receive(first), "the same wrap again is not news") + alice.receive(second) + assertEquals(listOf(message.id), alice.db.groupInboxDao().getMessages(harness.roomId).map { it.rumorId }) + assertEquals(1, alice.db.groupInboxDao().observeUnreadCount(harness.roomId).first()) + } + + @Test + fun `mail to a retired key still opens`() = runBlocking { + val (alice, bob, _, _) = keyed() + val old = alice.inboxKey() + InboxKeyRitualManager.propose(bob.db, bob.room(), bob.publicKey, bob.secret) + harness.pump() + assertEquals(2, alice.keys().size) + + val late = InboxWrap.wrap(seal(rumor("Written from an old 10044"), old), harness.roomId, old) + assertEquals(0, assertNotNull(alice.receive(late)).generation) + } + + @Test + fun `mail filed while this device lacked the key opens once it has it`() = runBlocking { + val (alice, _, _, _) = keyed() + val held = alice.keys().single() + val wrap = InboxWrap.wrap(seal(rumor("Written before the key reached this device"), held.publicKey), harness.roomId, held.publicKey) + + // As though the key were still on its way here, with an older one held: the newer + // generation's secret is missing, so the wrap goes into the ledger unopened. + alice.db.inboxKeyDao().upsertKey(held.copy(generation = 7, publicKey = "f".repeat(64), secretKey = "11".repeat(32))) + alice.db.inboxKeyDao().upsertKey(held.copy(secretKey = null)) + assertNull(alice.receive(wrap)) + assertEquals(1, alice.db.groupInboxDao().observeUnopenedCount(harness.roomId).first()) + + // The key arrives -- a ceremony finishing runs exactly this. + alice.db.inboxKeyDao().upsertKey(held) + assertEquals(1, GroupInboxManager.reopen(alice.db, harness.roomId, alice.publicKey)) + assertEquals(0, alice.db.groupInboxDao().observeUnopenedCount(harness.roomId).first()) + assertEquals(listOf("Written before the key reached this device"), alice.db.groupInboxDao().getMessages(harness.roomId).map { Event.fromJson(it.rumorJson).content }) + } + + @Test + fun `an admin no longer forgets the inbox, and says so`() = runBlocking { + val (alice, _, _, _) = keyed() + val e = alice.inboxKey() + alice.receive(InboxWrap.wrap(seal(rumor("Before"), e), harness.roomId, e)) + + GroupInboxManager.forgetIfNotAdmin(alice.db, harness.roomId, alice.publicKey, stillAdmin = true) + assertEquals(1, alice.db.groupInboxDao().getMessages(harness.roomId).size, "an admin keeps it") + + GroupInboxManager.forgetIfNotAdmin(alice.db, harness.roomId, alice.publicKey, stillAdmin = false) + assertEquals(emptyList(), alice.db.groupInboxDao().getMessages(harness.roomId)) + assertTrue(alice.keys().all { it.secretKey == null && it.state == InboxKeyState.WIPED }) + assertEquals(1, alice.lines(setOf(ChatMessage.TYPE_INBOX_FORGOTTEN)).size) + assertNull(alice.receive(InboxWrap.wrap(seal(rumor("After"), e), harness.roomId, e)), "and opens nothing after") + + GroupInboxManager.forgetIfNotAdmin(alice.db, harness.roomId, alice.publicKey, stillAdmin = false) + assertEquals(1, alice.lines(setOf(ChatMessage.TYPE_INBOX_FORGOTTEN)).size, "said once") + } + + @Test + fun `the subscription asks for mail to the group and to each key it holds`() { + val filters = LiveSubscriptionManager.groupInboxFilters(listOf(harness.roomId, "e".repeat(64), harness.roomId)) + assertEquals(listOf(1059), filters.single().kinds) + assertEquals(mapOf("p" to listOf(harness.roomId, "e".repeat(64)).sorted()), filters.single().tags) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt index 66fb145f..a7d7152b 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt @@ -19,8 +19,8 @@ import mobi.giza.compose.text.ProposedEvent * - a peer's proposal to sign a kind 13 (a NIP-17 seal) reaches the member as a bare number, * and nothing declines it. Phase 8 puts a refusal in front of it, as Phase 5 did for a kind * 10044 (an encryption key), which this pins declined now; - * - the only gift wraps the app asks relays for are its own identity's. Phase 6 adds the - * group's. + * - the identity's own gift wraps are asked for on their own subscription, beside the + * group's that Phase 6 added. */ class GroupInboxTodayJvmTest { private val harness = SigningProposalHarness() @@ -70,9 +70,12 @@ class GroupInboxTodayJvmTest { } @Test - fun `the only gift wraps asked for are the identity's own`() { + fun `the identity's own gift wraps are asked for apart from its groups'`() { + // Flipped by Phase 6: a group's mail has its own subscription + // (`LiveSubscriptionManager.groupInboxFilters`), and the identity's stays its own. val filter = LiveSubscriptionManager.giftWrapFilter(alice) assertEquals(listOf(1059), filter.kinds) assertEquals(mapOf("p" to listOf(alice)), filter.tags) + assertEquals(mapOf("p" to listOf(harness.roomId)), LiveSubscriptionManager.groupInboxFilters(listOf(harness.roomId)).single().tags) } } From 12a93bd4d78368e078a53df3aa8be3c029b5a0d1 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 02:00:09 +0200 Subject: [PATCH 12/16] feat: the group's inbox, seen (group-inbox, Phase 7) Three screens, each with a way back, readableContent, the four states and the transition between them: the inbox (its conversations, newest first, with who they are with and what is unread; mail this device cannot open, counted with why; an inbox the group has not yet announced saying nobody can write to it; and for an admin promoted after the first key, why earlier mail is missing), a conversation (theirs on the leading edge, the group's replies marked as the group's), and the inbox's settings (setting one up with where mail should arrive, the key generation by generation, the ceremony with who it waits on and Abandon, and Rotate the inbox key). The group's screen gets an Inbox row with the unread count on a device that holds the key, the ceremony while it runs, or Set up an inbox for an admin who could start one. A member who is not an admin sees no row. The ceremony's own screen planned for Phase 4 is the settings screen's ceremony card. m3Audit at its budgets; compileDebugKotlinAndroid builds. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 33 ++ .../repository/DatabaseChatRepository.kt | 13 + .../DatabaseGroupInboxRepository.kt | 80 +++++ .../giza/compose/repository/ChatRepository.kt | 6 + .../repository/GroupInboxRepository.kt | 63 ++++ .../ui/composable/ChatRoomDetailScreen.kt | 71 +++++ .../GroupInboxConversationScreen.kt | 199 ++++++++++++ .../compose/ui/composable/GroupInboxScreen.kt | 255 +++++++++++++++ .../ui/composable/GroupInboxSettingsScreen.kt | 300 ++++++++++++++++++ .../ui/composable/navigation/GizaNavHost.kt | 45 +++ .../navigation/routes/GroupInboxRoute.kt | 31 ++ .../ui/view/model/ChatRoomDetailViewModel.kt | 1 + .../ui/view/model/GroupInboxViewModel.kt | 167 ++++++++++ .../ui/view/state/ChatRoomDetailUIState.kt | 2 + .../ui/view/state/GroupInboxUIState.kt | 54 ++++ .../compose/ui/view/state/InboxRowSummary.kt | 13 + .../compose/managers/GroupInboxRowJvmTest.kt | 54 ++++ .../ui/composable/GroupInboxScreenJvmTest.kt | 185 +++++++++++ 18 files changed, 1572 insertions(+) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxConversationScreen.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxScreen.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxSettingsScreen.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupInboxRoute.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupInboxViewModel.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupInboxUIState.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/InboxRowSummary.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxRowJvmTest.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupInboxScreenJvmTest.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index b9b806df..97a00b66 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -740,4 +740,37 @@ %1$s: %2$d of %3$d admins to sign Formed This is the room of the confederation %1$s. Its key is held by the admins of its groups together. Until the confederation can sign, who is in this room cannot change. + + Inbox + Inbox settings + No new messages + 1 new message + %1$d new messages + Set up an inbox + Let anyone on nostr write to the group privately + The admins are making the group's inbox key + Couldn't find the group + Nobody has written to the group yet. + Messages sent before you held the group's inbox key aren't on this device. + 1 message this device can't open + %1$d messages this device can't open + It was sent to the group's npub by an app that doesn't know the group's inbox key, or to a key from before you were an admin. + The group hasn't signed its inbox announcement yet, so nobody can write to it. + The group + The group: %1$s + %1$s and the group + The group's admins will make a key together. Every admin holds it and can read what arrives. Nobody can write to the group until it signs its announcement, and the group signs every reply. + Where mail should arrive + One relay per line, starting wss:// + Key %1$d, %2$s + Announced: anyone can write to it + Waiting for the group to sign its announcement + Retired, kept to open older mail + Mail arrives on %1$s + Waiting on %1$s + Rotate the inbox key + Makes a new key with the current admins. Mail sent to the old key can still be read by the admins who held it, and a removed admin keeps what they already read. + Couldn't start the ceremony + The inbox key ceremony started + None of those is a relay a stranger could reach diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 016b4102..a18dfc99 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -263,6 +263,19 @@ class DatabaseChatRepository( null } + override suspend fun inboxSummary(localChatRoom: LocalChatRoom): mobi.giza.compose.ui.view.state.InboxRowSummary? { + if (!mobi.giza.compose.ExperimentalFeatures.groupInbox || localChatRoom.chatRoom.mlsGroupState == null) return null + val roomId = localChatRoom.chatRoom.id + val user = localChatRoom.chatRoom.userPublicKey + val holds = database.inboxKeyDao().getKeys(roomId, user).any { it.secretKey != null } + val running = database.inboxKeyDao().getRunningCeremoniesIn(roomId).any { it.userPublicKey == user && it.isParticipant() } + val canSetUp = !holds && !running && + mobi.giza.compose.managers.InboxKeyRitualManager.refusal(database, localChatRoom, user) == null + if (!holds && !running && !canSetUp) return null + val unread = if (holds) database.groupInboxDao().getMessages(roomId).count { !it.outgoing && it.readAt == null } else 0 + return mobi.giza.compose.ui.view.state.InboxRowSummary(holdsKey = holds, unread = unread, ceremonyRunning = running, canSetUp = canSetUp) + } + override suspend fun confederationProposalCount(chatRoomId: String): Int = database.confederationDao().getProposalsNaming(chatRoomId).size diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt index 75fbcae3..0f6db750 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt @@ -2,21 +2,33 @@ package mobi.giza.compose.database.repository import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map +import kotlin.time.Clock import kotlin.time.Instant import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.GroupInboxMessage import mobi.giza.compose.database.model.GroupInboxPublication +import mobi.giza.compose.database.model.InboxKeyCeremony +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.identity.Identity import mobi.giza.compose.managers.GroupInboxManager import mobi.giza.compose.managers.InboxAnnouncements +import mobi.giza.compose.managers.InboxKeyRitualManager +import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents import mobi.giza.compose.repository.GroupInboxRepository class DatabaseGroupInboxRepository( private val database: GizaDatabase, @Suppress("unused") private val scope: CoroutineScope, + /** The identity the app runs as: its key takes part in the ceremonies it starts. */ + private val activeIdentity: StateFlow = MutableStateFlow(null), ) : GroupInboxRepository { override fun observeUnpublished(): Flow> = database.groupInboxDao().observeUnpublished() @@ -32,4 +44,72 @@ class DatabaseGroupInboxRepository( override suspend fun receive(wrap: Event, userPublicKey: HexKey): GroupInboxMessage? = GroupInboxManager.receive(database, wrap, userPublicKey) + + override fun observeConversations(chatRoomId: String): Flow> = + database.groupInboxDao().observeMessages(chatRoomId).map { messages -> + val names = namesOf(messages.flatMap { it.participantList() }.distinct()) + messages.groupBy { it.conversationId }.map { (id, inConversation) -> + val newest = inConversation.maxBy { it.createdAt } + val participants = newest.participantList() + GroupInboxRepository.ConversationSummary( + conversationId = id, + participants = participants, + names = participants.map { names[it] ?: it.take(8) }, + lastText = Event.fromJsonOrNull(newest.rumorJson)?.content.orEmpty(), + lastAt = newest.createdAt, + lastOutgoing = newest.outgoing, + unread = inConversation.count { !it.outgoing && it.readAt == null }, + ) + }.sortedByDescending { it.lastAt } + } + + override fun observeConversation(chatRoomId: String, conversationId: String): Flow> = + database.groupInboxDao().observeConversation(chatRoomId, conversationId) + + override fun observeUnopenedCount(chatRoomId: String): Flow = + database.groupInboxDao().observeUnopenedCount(chatRoomId) + + override fun observeStatus(localChatRoom: LocalChatRoom, userPublicKey: HexKey): Flow { + val roomId = localChatRoom.chatRoom.id + return combine( + database.inboxKeyDao().observeKeys(roomId, userPublicKey), + database.inboxKeyDao().observeLatestCeremony(roomId, userPublicKey), + ) { keys, ceremony -> + GroupInboxRepository.Status( + keys = keys, + ceremony = ceremony, + announcedKey = InboxAnnouncements.announcedKey(database, roomId), + relays = InboxAnnouncements.relaysOf(database, roomId), + setUpRefusal = InboxKeyRitualManager.refusal(database, localChatRoom, userPublicKey), + waitingOn = ceremony?.takeIf { it.isRunning }?.let { waitingOn(it) }.orEmpty(), + ) + } + } + + /** The admins a running ceremony has not heard a host key from: who to knock on the door of. */ + private suspend fun waitingOn(ceremony: InboxKeyCeremony): List { + val heard = database.inboxKeyDao().getMessages(ceremony.id) + .filter { it.kind == InboxKeyRitualEvents.HOST_KEY }.map { it.senderPublicKey }.toSet() + val silent = ceremony.participants().filter { it !in heard } + val names = namesOf(silent) + return silent.map { names[it] ?: it.take(8) } + } + + override suspend fun markRead(chatRoomId: String, conversationId: String) = + database.groupInboxDao().markConversationRead(chatRoomId, conversationId, Clock.System.now()) + + override suspend fun namesOf(publicKeys: List): Map = + database.profileDao().getProfileByPublicKeys(publicKeys).associate { it.publicKey to it.humanReadableNameOrPubkey() } + + private fun secret(): ByteArray = + activeIdentity.value?.nostrPrivateKey?.value?.toByteArray() ?: throw IllegalStateException("This identity cannot sign") + + override suspend fun setUp(localChatRoom: LocalChatRoom, relays: List): InboxKeyCeremony = + InboxKeyRitualManager.propose(database, localChatRoom, localChatRoom.chatRoom.userPublicKey, secret(), relays) + + override suspend fun rotate(localChatRoom: LocalChatRoom): InboxKeyCeremony = + InboxKeyRitualManager.propose(database, localChatRoom, localChatRoom.chatRoom.userPublicKey, secret()) + + override suspend fun abandon(localChatRoom: LocalChatRoom, ceremonyId: String): Boolean = + InboxKeyRitualManager.abandon(database, localChatRoom, ceremonyId) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index a43e518e..5275835c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -135,6 +135,12 @@ interface ChatRepository { /** How many confederation proposals naming [chatRoomId] this device holds. docs/confederation.md. */ suspend fun confederationProposalCount(chatRoomId: String): Int = 0 + /** + * The group's inbox as its row on the group's screen shows it, or null where this device + * has nothing of it to show (docs/group-inbox.md, D9). + */ + suspend fun inboxSummary(localChatRoom: LocalChatRoom): mobi.giza.compose.ui.view.state.InboxRowSummary? = null + /** The confederation whose room [chatRoomId] is, by name, if its record verifies here. docs/confederation.md, Phase 13. */ suspend fun confederationOfRoom(chatRoomId: String): String? = null diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt index bcb9c4ba..4fb6a9a7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt @@ -4,9 +4,14 @@ import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.flow.flowOf import kotlin.time.Instant import mobi.giza.compose.database.model.GroupInboxMessage import mobi.giza.compose.database.model.GroupInboxPublication +import mobi.giza.compose.database.model.InboxKey +import mobi.giza.compose.database.model.InboxKeyCeremony +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom /** The group's inbox, as the screens and the sync see it (docs/group-inbox.md). */ interface GroupInboxRepository { @@ -26,4 +31,62 @@ interface GroupInboxRepository { /** Files a gift wrap heard on a relay for one of [userPublicKey]'s groups. */ suspend fun receive(wrap: Event, userPublicKey: HexKey): GroupInboxMessage? + + // ---- the screens (Phase 7) ---------------------------------------------------------------- + + /** One conversation in a group's inbox, as its list shows it. */ + data class ConversationSummary( + val conversationId: String, + val participants: List, + val names: List, + val lastText: String, + val lastAt: Long, + val lastOutgoing: Boolean, + val unread: Int, + ) + + /** What a group's inbox is on this device: its keys, its newest ceremony, what it announced. */ + data class Status( + val keys: List, + val ceremony: InboxKeyCeremony?, + /** The key the group's newest signed 10044 names, or null if it has announced none. */ + val announcedKey: HexKey?, + val relays: List, + /** Why this identity cannot start a ceremony now, or null if it can. */ + val setUpRefusal: String?, + /** The admins a running ceremony waits on, by name. */ + val waitingOn: List, + ) { + val heldKey: InboxKey? get() = keys.firstOrNull { it.secretKey != null } + } + + fun observeConversations(chatRoomId: String): Flow> = emptyFlow() + + fun observeConversation(chatRoomId: String, conversationId: String): Flow> = flowOf(emptyList()) + + fun observeUnopenedCount(chatRoomId: String): Flow = flowOf(0) + + fun observeStatus(localChatRoom: LocalChatRoom, userPublicKey: HexKey): Flow = emptyFlow() + + suspend fun markRead(chatRoomId: String, conversationId: String) = Unit + + suspend fun namesOf(publicKeys: List): Map = emptyMap() + + /** Starts the first inbox key ceremony, with mail to arrive on [relays]. */ + suspend fun setUp(localChatRoom: LocalChatRoom, relays: List): InboxKeyCeremony = + throw UnsupportedOperationException() + + /** Starts a ceremony for the next generation of the key (D14). */ + suspend fun rotate(localChatRoom: LocalChatRoom): InboxKeyCeremony = throw UnsupportedOperationException() + + suspend fun abandon(localChatRoom: LocalChatRoom, ceremonyId: String): Boolean = false + + companion object { + val NO_OP = object : GroupInboxRepository { + override fun observeUnpublished(): Flow> = flowOf(emptyList()) + override suspend fun markPublished(eventId: HexKey, at: Instant) = Unit + override fun observeRoutes(userPublicKey: HexKey): Flow> = flowOf(emptyList()) + override suspend fun receive(wrap: Event, userPublicKey: HexKey): GroupInboxMessage? = null + } + } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 79fb2290..c1ff5fc5 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -9,6 +9,17 @@ import mobi.giza.compose.resources.one_post import mobi.giza.compose.resources.no_posts_yet import mobi.giza.compose.resources.posts import mobi.giza.compose.ui.composable.navigation.routes.GroupPostsRoute +import mobi.giza.compose.resources.inbox +import mobi.giza.compose.resources.set_up_an_inbox +import mobi.giza.compose.resources.no_new_messages +import mobi.giza.compose.resources.one_new_message +import mobi.giza.compose.resources.n_new_messages +import mobi.giza.compose.resources.the_admins_are_making_the_inbox_key +import mobi.giza.compose.resources.let_anyone_on_nostr_write_to_the_group_privately +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxRoute +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxSettingsRoute +import mobi.giza.compose.ui.view.state.InboxRowSummary +import androidx.compose.material.icons.filled.Mail import mobi.giza.compose.ui.composable.navigation.routes.ConfederationsRoute import mobi.giza.compose.ExperimentalFeatures import androidx.compose.material.icons.filled.Hub @@ -713,6 +724,26 @@ fun ChatRoomDetailScreen( ) } + // The group's inbox (docs/group-inbox.md, D9): on a device that + // holds its key, or whose identity could set one up. A member + // who is not an admin sees no row at all. + chatRoomDetailUIState.inbox?.let { inbox -> + item { + GroupInboxRow( + inbox = inbox, + onClick = { + onNavigateToRoute.invoke( + if (inbox.holdsKey) { + GroupInboxRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, relayHint = relayHint) + } else { + GroupInboxSettingsRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, relayHint = relayHint) + } + ) + } + ) + } + } + // The confederations naming this group, and the way into // proposing one (docs/confederation.md). Every member can // read them; the screen behind it gates proposing. @@ -2148,6 +2179,46 @@ private fun GroupPostsRow( } } +/** + * The row that opens the group's inbox, with how much is unread; or, where this device holds no + * key yet, the way to set one up or the ceremony making it. docs/group-inbox.md. + */ +@Composable +private fun GroupInboxRow( + inbox: InboxRowSummary, + onClick: () -> Unit, +) { + Card( + modifier = Modifier.fillMaxWidth(), + onClick = onClick + ) { + ListItem( + leadingContent = { + Icon(Icons.Default.Mail, contentDescription = Decorative) + }, + trailingContent = { + Icon(Icons.Default.ChevronRight, contentDescription = Decorative) + }, + headlineContent = { + Text(text = stringResource(if (inbox.holdsKey || inbox.ceremonyRunning) Res.string.inbox else Res.string.set_up_an_inbox)) + }, + supportingContent = { + Text( + text = when { + inbox.holdsKey -> when (inbox.unread) { + 0 -> stringResource(Res.string.no_new_messages) + 1 -> stringResource(Res.string.one_new_message) + else -> stringResource(Res.string.n_new_messages, inbox.unread) + } + inbox.ceremonyRunning -> stringResource(Res.string.the_admins_are_making_the_inbox_key) + else -> stringResource(Res.string.let_anyone_on_nostr_write_to_the_group_privately) + } + ) + } + ) + } +} + /** The row that opens a group's confederations: how many proposals name it. docs/confederation.md. */ @Composable private fun ConfederationsRow( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxConversationScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxConversationScreen.kt new file mode 100644 index 00000000..d6bab16a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxConversationScreen.kt @@ -0,0 +1,199 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Instant +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.extensions.toFormattedTimeAndDateString +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.GroupInboxRepository +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.couldn_t_find_the_group +import mobi.giza.compose.resources.nobody_has_written_to_the_group_yet +import mobi.giza.compose.resources.the_group +import mobi.giza.compose.resources.you_and_the_group +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.EmptyState +import mobi.giza.compose.ui.composable.widgets.ErrorState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.theme.ConformancePreviews +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.GroupInboxConversationViewModel +import mobi.giza.compose.ui.view.state.GroupInboxConversationUIState +import org.jetbrains.compose.resources.stringResource + +/** + * One conversation in the group's inbox (docs/group-inbox.md, D8 and D10): what the people in it + * wrote, and what the group answered, in the order they were written. A reply is the group's, + * not the admin's who drafted it, so it is marked as the group's. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GroupInboxConversationScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + relayHint: String?, + conversationId: String, + initialUIState: GroupInboxConversationUIState = GroupInboxConversationUIState.Loading, + chatRepository: ChatRepository, + inboxRepository: GroupInboxRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, + /** Below the conversation: the way to reply, when there is one (Phase 8). */ + composer: @Composable (GroupInboxConversationUIState.Loaded) -> Unit = {}, +) { + val viewModel: GroupInboxConversationViewModel = viewModel( + factory = GroupInboxConversationViewModel.factory(chatRoomId, conversationId, initialUIState, chatRepository, inboxRepository) + ) + LaunchedEffect(true) { + if (initialUIState == GroupInboxConversationUIState.Loading) viewModel.initiate() + } + val title = (viewModel.uiState as? GroupInboxConversationUIState.Loaded)?.names?.joinToString(", ") + ?.let { stringResource(Res.string.you_and_the_group, it) } + ?: stringResource(Res.string.the_group) + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + } + ) { padding -> + ScreenStateTransition(viewModel.uiState) { uiState -> + when (val state = uiState) { + is GroupInboxConversationUIState.Error -> ErrorState( + modifier = Modifier.padding(padding), + message = stringResource(Res.string.couldn_t_find_the_group), + onRetry = null, + ) + + GroupInboxConversationUIState.Loading -> Column( + modifier = Modifier.fillMaxWidth().padding(padding).padding(MaterialTheme.spacing.screenMargin), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) + LoadingDataIndicator(fillScreen = false) + } + + is GroupInboxConversationUIState.Loaded -> Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + if (state.lines.isEmpty()) { + EmptyState( + modifier = Modifier.weight(1f), + message = stringResource(Res.string.nobody_has_written_to_the_group_yet), + ) + } else { + LazyColumn( + modifier = Modifier.weight(1f).fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + items(state.lines, key = { it.rumorId }) { line -> MessageCard(line) } + } + } + composer(state) + } + } + } + } +} + +/** One message: theirs on the leading edge, the group's on the trailing one, in its own colours. */ +@Composable +private fun MessageCard(line: GroupInboxConversationUIState.Line) { + Column( + modifier = Modifier.fillMaxWidth(), + horizontalAlignment = if (line.outgoing) Alignment.End else Alignment.Start, + ) { + Card( + modifier = Modifier.widthIn(max = MaterialTheme.spacing.space400 * 8), + colors = if (line.outgoing) { + CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.primaryContainer, + contentColor = MaterialTheme.colorScheme.onPrimaryContainer, + ) + } else { + CardDefaults.cardColors() + }, + ) { + Column( + modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), + ) { + Text( + text = if (line.outgoing) stringResource(Res.string.the_group) else line.senderName, + style = MaterialTheme.typography.labelMedium, + ) + Text(text = line.text, style = MaterialTheme.typography.bodyMedium) + Text( + text = Instant.fromEpochSeconds(line.createdAt).toFormattedTimeAndDateString(), + style = MaterialTheme.typography.labelSmall, + ) + } + } + } +} + +@ConformancePreviews +@Composable +private fun GroupInboxConversationScreenPreview() { + val chatRoomId = "d".repeat(64) + GizaTheme { + Surface(modifier = Modifier.fillMaxSize()) { + GroupInboxConversationScreen( + activeUserPublicKey = "a".repeat(64), + chatRoomId = chatRoomId, + relayHint = null, + conversationId = "c1", + initialUIState = GroupInboxConversationUIState.Loaded( + localChatRoom = LocalChatRoom( + chatRoom = ChatRoom(id = chatRoomId, userPublicKey = "a".repeat(64), subject = "#Ekklesia", description = null, mlsGroupState = "state") + ), + names = listOf("Zola"), + lines = listOf( + GroupInboxConversationUIState.Line("r1", "Can I join the reading group?", 1_700_000_000, outgoing = false, senderName = "Zola"), + GroupInboxConversationUIState.Line("r2", "Yes. We meet on Thursdays.", 1_700_003_600, outgoing = true, senderName = ""), + ), + ), + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + inboxRepository = GroupInboxRepository.NO_OP, + onNavigateToRoute = {}, + onNavigateBack = {}, + ) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxScreen.kt new file mode 100644 index 00000000..63d110f9 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxScreen.kt @@ -0,0 +1,255 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ChevronRight +import androidx.compose.material.icons.filled.Lock +import androidx.compose.material.icons.filled.Mail +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material3.Badge +import androidx.compose.material3.Card +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Instant +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.extensions.toFormattedTimeAndDateString +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.GroupInboxRepository +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.couldn_t_find_the_group +import mobi.giza.compose.resources.earlier_mail_is_not_on_this_device +import mobi.giza.compose.resources.inbox +import mobi.giza.compose.resources.inbox_settings +import mobi.giza.compose.resources.n_messages_this_device_can_t_open +import mobi.giza.compose.resources.nobody_has_written_to_the_group_yet +import mobi.giza.compose.resources.one_message_this_device_can_t_open +import mobi.giza.compose.resources.the_group_wrote +import mobi.giza.compose.resources.the_group_hasn_t_announced_its_inbox +import mobi.giza.compose.resources.why_a_message_can_t_be_opened +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxConversationRoute +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxSettingsRoute +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.Decorative +import mobi.giza.compose.ui.composable.widgets.EmptyState +import mobi.giza.compose.ui.composable.widgets.ErrorState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.theme.ConformancePreviews +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.GroupInboxViewModel +import mobi.giza.compose.ui.view.state.GroupInboxUIState +import org.jetbrains.compose.resources.stringResource + +/** + * The group's inbox: the conversations people have started with the group by writing to its + * npub, newest first (docs/group-inbox.md, D8 and D9). + * + * Reached from the group's screen, and only on a device that holds the inbox key. Says what it + * cannot do as plainly as what it can: mail no key here opens is counted with why, and an inbox + * the group has made but not yet announced says nobody can write to it yet. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GroupInboxScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + relayHint: String?, + initialUIState: GroupInboxUIState = GroupInboxUIState.Loading, + chatRepository: ChatRepository, + inboxRepository: GroupInboxRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val viewModel: GroupInboxViewModel = viewModel( + factory = GroupInboxViewModel.factory(chatRoomId, initialUIState, chatRepository, inboxRepository) + ) + LaunchedEffect(true) { + if (initialUIState == GroupInboxUIState.Loading) viewModel.initiate() + } + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(stringResource(Res.string.inbox), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + actions = { + IconButton(onClick = { onNavigateToRoute(GroupInboxSettingsRoute(activeUserPublicKey, chatRoomId, relayHint)) }) { + Icon(Icons.Default.Settings, contentDescription = stringResource(Res.string.inbox_settings)) + } + }, + ) + } + ) { padding -> + ScreenStateTransition(viewModel.uiState) { uiState -> + when (val state = uiState) { + // Nothing to retry: the room came from a navigation argument. + is GroupInboxUIState.Error -> ErrorState( + modifier = Modifier.padding(padding), + message = stringResource(Res.string.couldn_t_find_the_group), + onRetry = null, + ) + + GroupInboxUIState.Loading -> Column( + modifier = Modifier.fillMaxWidth().padding(padding).padding(MaterialTheme.spacing.screenMargin), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) + LoadingDataIndicator(fillScreen = false) + } + + is GroupInboxUIState.Loaded -> LazyColumn( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + val status = state.status + if (status.announcedKey == null) { + item { NoticeCard(Icons.Default.Lock, stringResource(Res.string.the_group_hasn_t_announced_its_inbox)) } + } + if (state.unopenable > 0) { + item { + NoticeCard( + Icons.Default.Lock, + if (state.unopenable == 1) stringResource(Res.string.one_message_this_device_can_t_open) + else stringResource(Res.string.n_messages_this_device_can_t_open, state.unopenable), + stringResource(Res.string.why_a_message_can_t_be_opened), + ) + } + } + if (state.conversations.isEmpty()) { + item { + // D15: a promoted admin's first key opens nothing sent before it. + val joinedLate = status.keys.isNotEmpty() && status.keys.minOf { it.generation } > 0 + EmptyState( + message = stringResource( + if (joinedLate) Res.string.earlier_mail_is_not_on_this_device + else Res.string.nobody_has_written_to_the_group_yet + ) + ) + } + } else { + items(state.conversations, key = { it.conversationId }) { conversation -> + ConversationRow( + conversation = conversation, + onClick = { + onNavigateToRoute( + GroupInboxConversationRoute(activeUserPublicKey, chatRoomId, relayHint, conversation.conversationId) + ) + }, + ) + } + } + } + } + } + } +} + +@Composable +private fun NoticeCard(icon: androidx.compose.ui.graphics.vector.ImageVector, headline: String, supporting: String? = null) { + Card(modifier = Modifier.fillMaxWidth()) { + ListItem( + leadingContent = { Icon(icon, contentDescription = Decorative) }, + headlineContent = { Text(headline) }, + supportingContent = supporting?.let { { Text(it) } }, + ) + } +} + +/** One conversation: who it is with, the last line and when, and how much is unread. */ +@Composable +private fun ConversationRow(conversation: GroupInboxRepository.ConversationSummary, onClick: () -> Unit) { + val lastLine = if (conversation.lastOutgoing) { + stringResource(Res.string.the_group_wrote, conversation.lastText) + } else { + conversation.lastText + } + Card(modifier = Modifier.fillMaxWidth(), onClick = onClick) { + ListItem( + leadingContent = { Icon(Icons.Default.Mail, contentDescription = Decorative) }, + headlineContent = { + Text(conversation.names.joinToString(", "), maxLines = 1, overflow = TextOverflow.Ellipsis) + }, + supportingContent = { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + Text(lastLine, maxLines = 2, overflow = TextOverflow.Ellipsis) + Text( + Instant.fromEpochSeconds(conversation.lastAt).toFormattedTimeAndDateString(), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + }, + trailingContent = { + if (conversation.unread > 0) { + Badge { Text(conversation.unread.toString()) } + } else { + Icon(Icons.Default.ChevronRight, contentDescription = Decorative) + } + }, + ) + } +} + +@ConformancePreviews +@Composable +private fun GroupInboxScreenPreview() { + val chatRoomId = "d".repeat(64) + GizaTheme { + Surface(modifier = Modifier.fillMaxSize()) { + GroupInboxScreen( + activeUserPublicKey = "a".repeat(64), + chatRoomId = chatRoomId, + relayHint = null, + initialUIState = GroupInboxUIState.Loaded( + localChatRoom = LocalChatRoom( + chatRoom = ChatRoom(id = chatRoomId, userPublicKey = "a".repeat(64), subject = "#Ekklesia", description = null, mlsGroupState = "state") + ), + conversations = listOf( + GroupInboxRepository.ConversationSummary( + conversationId = "c1", participants = listOf("b".repeat(64)), names = listOf("Zola"), + lastText = "Can I join the reading group?", lastAt = 1_700_000_000, lastOutgoing = false, unread = 1, + ) + ), + unopenable = 2, + status = GroupInboxRepository.Status( + keys = emptyList(), ceremony = null, announcedKey = null, relays = emptyList(), setUpRefusal = null, waitingOn = emptyList(), + ), + ), + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + inboxRepository = GroupInboxRepository.NO_OP, + onNavigateToRoute = {}, + onNavigateBack = {}, + ) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxSettingsScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxSettingsScreen.kt new file mode 100644 index 00000000..064c573f --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxSettingsScreen.kt @@ -0,0 +1,300 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Autorenew +import androidx.compose.material.icons.filled.HourglassTop +import androidx.compose.material.icons.filled.Key +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.InboxKeyCeremonyStage +import mobi.giza.compose.database.model.InboxKeyState +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.RelayUrlInput +import mobi.giza.compose.nostr.Relays +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.GroupInboxRepository +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.abandon +import mobi.giza.compose.resources.announced_anyone_can_write_to_it +import mobi.giza.compose.resources.couldn_t_find_the_group +import mobi.giza.compose.resources.couldn_t_start_the_ceremony +import mobi.giza.compose.resources.inbox_key_generation +import mobi.giza.compose.resources.inbox_settings +import mobi.giza.compose.resources.inbox_setup_explainer +import mobi.giza.compose.resources.mail_arrives_on +import mobi.giza.compose.resources.no_inbox_relays_were_valid +import mobi.giza.compose.resources.one_relay_per_line +import mobi.giza.compose.resources.retired_kept_to_open_older_mail +import mobi.giza.compose.resources.rotate_explainer +import mobi.giza.compose.resources.rotate_the_inbox_key +import mobi.giza.compose.resources.set_up_an_inbox +import mobi.giza.compose.resources.the_admins_are_making_the_inbox_key +import mobi.giza.compose.resources.the_ceremony_ended +import mobi.giza.compose.resources.the_inbox_key_ceremony_started +import mobi.giza.compose.resources.try_again +import mobi.giza.compose.resources.waiting_for_the_group_to_sign_its_announcement +import mobi.giza.compose.resources.waiting_on +import mobi.giza.compose.resources.where_mail_should_arrive +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.Decorative +import mobi.giza.compose.ui.composable.widgets.ErrorState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.composable.widgets.rememberNotifier +import mobi.giza.compose.ui.theme.ConformancePreviews +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.GroupInboxSettingsViewModel +import mobi.giza.compose.ui.view.state.GroupInboxSettingsUIState +import org.jetbrains.compose.resources.stringResource + +/** + * The group's inbox key (docs/group-inbox.md, D2 to D7 and D14): setting one up, which is an + * admin starting the ceremony that makes it; where it stands, generation by generation; the + * ceremony while it runs, with who it waits on; and rotating it. + * + * Nothing here is the decision to have an inbox. That is the group signing its announcement, + * which the ceremony's coordinator asks for when the key is made, and which every member who + * holds a share is asked about on the signing screen. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GroupInboxSettingsScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + relayHint: String?, + initialUIState: GroupInboxSettingsUIState = GroupInboxSettingsUIState.Loading, + chatRepository: ChatRepository, + inboxRepository: GroupInboxRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val viewModel: GroupInboxSettingsViewModel = viewModel( + factory = GroupInboxSettingsViewModel.factory(chatRoomId, initialUIState, chatRepository, inboxRepository) + ) + LaunchedEffect(true) { + if (initialUIState == GroupInboxSettingsUIState.Loading) viewModel.initiate() + } + val notify = rememberNotifier(rememberCoroutineScope()) + val started = stringResource(Res.string.the_inbox_key_ceremony_started) + val noRelays = stringResource(Res.string.no_inbox_relays_were_valid) + val couldNotStart = stringResource(Res.string.couldn_t_start_the_ceremony) + val report: (String?) -> Unit = { failure -> notify(if (failure == null) started else couldNotStart) } + val canSign = LocalCanSign.current + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(stringResource(Res.string.inbox_settings), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + } + ) { padding -> + ScreenStateTransition(viewModel.uiState) { uiState -> + when (val state = uiState) { + is GroupInboxSettingsUIState.Error -> ErrorState( + modifier = Modifier.padding(padding), + message = stringResource(Res.string.couldn_t_find_the_group), + onRetry = null, + ) + + GroupInboxSettingsUIState.Loading -> Column( + modifier = Modifier.fillMaxWidth().padding(padding).padding(MaterialTheme.spacing.screenMargin), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) + LoadingDataIndicator(fillScreen = false) + } + + is GroupInboxSettingsUIState.Loaded -> Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap), + ) { + val status = state.status + val ceremony = status.ceremony + val running = ceremony?.isRunning == true + val visibleKeys = status.keys.filter { it.state != InboxKeyState.WIPED } + + if (visibleKeys.isEmpty() && !running) { + SetUp( + busy = state.busy, + refusal = status.setUpRefusal, + canSign = canSign, + onSetUp = { text -> + val relays = text.lines().mapNotNull { RelayUrlInput.relayUrlOrNull(it) } + if (relays.isEmpty()) notify(noRelays) else viewModel.setUp(relays, report) + }, + ) + } + + visibleKeys.forEach { key -> + Card(modifier = Modifier.fillMaxWidth()) { + ListItem( + leadingContent = { Icon(Icons.Default.Key, contentDescription = Decorative) }, + headlineContent = { + Text(stringResource(Res.string.inbox_key_generation, key.generation, fingerprint(key.publicKey))) + }, + supportingContent = { + Text( + when (key.state) { + InboxKeyState.ANNOUNCED -> stringResource(Res.string.announced_anyone_can_write_to_it) + InboxKeyState.RETIRED -> stringResource(Res.string.retired_kept_to_open_older_mail) + else -> stringResource(Res.string.waiting_for_the_group_to_sign_its_announcement) + } + ) + }, + ) + } + } + + if (status.relays.isNotEmpty()) { + Text( + text = stringResource(Res.string.mail_arrives_on, status.relays.joinToString(", ") { it.url.removePrefix("wss://").trimEnd('/') }), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + if (ceremony != null && running) { + Card(modifier = Modifier.fillMaxWidth()) { + ListItem( + leadingContent = { Icon(Icons.Default.HourglassTop, contentDescription = Decorative) }, + headlineContent = { Text(stringResource(Res.string.the_admins_are_making_the_inbox_key)) }, + supportingContent = status.waitingOn.takeIf { it.isNotEmpty() }?.let { names -> + { Text(stringResource(Res.string.waiting_on, names.joinToString(", "))) } + }, + trailingContent = if (ceremony.isParticipant() && canSign) { + { TextButton(onClick = { viewModel.abandon(ceremony.id) {} }, enabled = !state.busy) { Text(stringResource(Res.string.abandon)) } } + } else { + null + }, + ) + } + } else if (ceremony?.stage == InboxKeyCeremonyStage.FAILED && visibleKeys.isNotEmpty()) { + Text( + text = stringResource(Res.string.the_ceremony_ended, ceremony.failureReason.orEmpty()), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + ) + } + + if (visibleKeys.isNotEmpty() && !running) { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) { + Text(stringResource(Res.string.rotate_explainer), style = MaterialTheme.typography.bodyMedium) + status.setUpRefusal?.let { + Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + OutlinedButton( + onClick = { viewModel.rotate(report) }, + enabled = status.setUpRefusal == null && !state.busy && canSign, + ) { + Icon(Icons.Default.Autorenew, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) + Text( + stringResource( + if (ceremony?.stage == InboxKeyCeremonyStage.FAILED) Res.string.try_again else Res.string.rotate_the_inbox_key + ) + ) + } + } + } + } + } + } + } +} + +/** A key as a person can compare it across devices: its first and last eight characters. */ +private fun fingerprint(key: HexKey): String = key.take(8) + "\u2026" + key.takeLast(8) + +/** Starting the first ceremony: what it does, where mail should arrive, and the button. */ +@Composable +private fun SetUp(busy: Boolean, refusal: String?, canSign: Boolean, onSetUp: (String) -> Unit) { + var relays by remember { mutableStateOf(Relays.DefaultDMRelayList.joinToString("\n") { it.url }) } + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) { + Text(stringResource(Res.string.inbox_setup_explainer), style = MaterialTheme.typography.bodyLarge) + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + value = relays, + onValueChange = { relays = it }, + label = { Text(stringResource(Res.string.where_mail_should_arrive)) }, + supportingText = { Text(stringResource(Res.string.one_relay_per_line)) }, + minLines = 2, + ) + refusal?.let { + Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Button(onClick = { onSetUp(relays) }, enabled = refusal == null && !busy && canSign) { + Text(stringResource(Res.string.set_up_an_inbox)) + } + } +} + +@ConformancePreviews +@Composable +private fun GroupInboxSettingsScreenPreview() { + val chatRoomId = "d".repeat(64) + GizaTheme { + Surface(modifier = Modifier.fillMaxSize()) { + GroupInboxSettingsScreen( + activeUserPublicKey = "a".repeat(64), + chatRoomId = chatRoomId, + relayHint = null, + initialUIState = GroupInboxSettingsUIState.Loaded( + localChatRoom = LocalChatRoom( + chatRoom = ChatRoom(id = chatRoomId, userPublicKey = "a".repeat(64), subject = "#Ekklesia", description = null, mlsGroupState = "state") + ), + status = GroupInboxRepository.Status( + keys = emptyList(), ceremony = null, announcedKey = null, relays = emptyList(), setUpRefusal = null, waitingOn = emptyList(), + ), + ), + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + inboxRepository = GroupInboxRepository.NO_OP, + onNavigateToRoute = {}, + onNavigateBack = {}, + ) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index 5845867a..90f490c8 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -14,6 +14,12 @@ import mobi.giza.compose.ui.composable.navigation.routes.ProposeConfederationRou import mobi.giza.compose.ui.composable.ConfederationsScreen import mobi.giza.compose.ui.composable.ProposeConfederationScreen import mobi.giza.compose.ui.composable.navigation.routes.GroupPostsRoute +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxRoute +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxConversationRoute +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxSettingsRoute +import mobi.giza.compose.ui.composable.GroupInboxScreen +import mobi.giza.compose.ui.composable.GroupInboxConversationScreen +import mobi.giza.compose.ui.composable.GroupInboxSettingsScreen import mobi.giza.compose.ui.composable.AddGroupPostScreen import mobi.giza.compose.ui.composable.GroupPostsScreen import mobi.giza.compose.ui.composable.navigation.routes.EditGroupNostrProfileRoute @@ -228,6 +234,7 @@ fun GizaNavHost( DatabaseGroupInboxRepository( database = auxDatabaseManager.auxDatabase, applicationIOScope, + activeIdentity = sovereignWalletViewModel.activeIdentity, ) } val databaseMarmotRepository = remember { @@ -1373,6 +1380,44 @@ fun GizaNavHost( } ) } + // The group's inbox (docs/group-inbox.md, Phase 7). + composable { backStackEntry -> + val route = backStackEntry.toRoute() + GroupInboxScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + relayHint = route.relayHint, + chatRepository = databaseChatRepository, + inboxRepository = databaseGroupInboxRepository, + onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) }, + onNavigateBack = { navController.popBackStack() }, + ) + } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + GroupInboxConversationScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + relayHint = route.relayHint, + conversationId = route.conversationId, + chatRepository = databaseChatRepository, + inboxRepository = databaseGroupInboxRepository, + onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) }, + onNavigateBack = { navController.popBackStack() }, + ) + } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + GroupInboxSettingsScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + relayHint = route.relayHint, + chatRepository = databaseChatRepository, + inboxRepository = databaseGroupInboxRepository, + onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) }, + onNavigateBack = { navController.popBackStack() }, + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupInboxRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupInboxRoute.kt new file mode 100644 index 00000000..009f732a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupInboxRoute.kt @@ -0,0 +1,31 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** The group's inbox: its conversations, on an admin's device. docs/group-inbox.md, Phase 7. */ +@Serializable +data class GroupInboxRoute( + val activeUserPublicKey: String, + val chatRoomId: String, + val relayHint: String? +): Route() + +/** One conversation in the group's inbox, and the way to reply to it. docs/group-inbox.md. */ +@Serializable +data class GroupInboxConversationRoute( + val activeUserPublicKey: String, + val chatRoomId: String, + val relayHint: String?, + val conversationId: String, +): Route() + +/** + * The group's inbox key: setting one up, the ceremony that makes it, what the group announced, + * and rotating it. docs/group-inbox.md. + */ +@Serializable +data class GroupInboxSettingsRoute( + val activeUserPublicKey: String, + val chatRoomId: String, + val relayHint: String? +): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index d048388b..1f82f28a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -133,6 +133,7 @@ class ChatRoomDetailViewModel( groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), groupPosts = chatRepository.groupPosts(chatRoomId), confederationProposalCount = chatRepository.confederationProposalCount(chatRoomId), + inbox = chatRepository.inboxSummary(localChatRoom), confederationName = chatRepository.confederationOfRoom(chatRoomId), canProposeAsGroup = canSign && roomIsOpen, subgroupsNeedAWallet = canSign && subgroupsNeedAWallet, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupInboxViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupInboxViewModel.kt new file mode 100644 index 00000000..5effbc10 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupInboxViewModel.kt @@ -0,0 +1,167 @@ +package mobi.giza.compose.ui.view.model + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.launch +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.GroupInboxRepository +import mobi.giza.compose.ui.view.state.GroupInboxConversationUIState +import mobi.giza.compose.ui.view.state.GroupInboxSettingsUIState +import mobi.giza.compose.ui.view.state.GroupInboxUIState + +/** + * The group's inbox, watched rather than read once: mail arrives while the screen is open, and + * the point of the screen is to see it (docs/group-inbox.md, Phase 7). + */ +class GroupInboxViewModel( + val chatRoomId: String, + initialUIState: GroupInboxUIState, + val chatRepository: ChatRepository, + val inboxRepository: GroupInboxRepository, +): ViewModel() { + var uiState: GroupInboxUIState by mutableStateOf(initialUIState) + private set + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val room = chatRepository.getChatRoomByIdentifier(chatRoomId) ?: run { + uiState = GroupInboxUIState.Error("Couldn't find the group") + return@launch + } + combine( + inboxRepository.observeConversations(chatRoomId), + inboxRepository.observeUnopenedCount(chatRoomId), + inboxRepository.observeStatus(room, room.chatRoom.userPublicKey), + ) { conversations, unopenable, status -> + GroupInboxUIState.Loaded(room, conversations, unopenable, status) + }.collect { uiState = it } + } + } + + companion object { + fun factory( + chatRoomId: String, + initialUIState: GroupInboxUIState = GroupInboxUIState.Loading, + chatRepository: ChatRepository, + inboxRepository: GroupInboxRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { GroupInboxViewModel(chatRoomId, initialUIState, chatRepository, inboxRepository) } + } + } +} + +/** One conversation in the group's inbox, marked read as it is shown (docs/group-inbox.md, Phase 7). */ +class GroupInboxConversationViewModel( + val chatRoomId: String, + val conversationId: String, + initialUIState: GroupInboxConversationUIState, + val chatRepository: ChatRepository, + val inboxRepository: GroupInboxRepository, +): ViewModel() { + var uiState: GroupInboxConversationUIState by mutableStateOf(initialUIState) + private set + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val room = chatRepository.getChatRoomByIdentifier(chatRoomId) ?: run { + uiState = GroupInboxConversationUIState.Error("Couldn't find the group") + return@launch + } + inboxRepository.observeConversation(chatRoomId, conversationId).collect { messages -> + val participants = messages.lastOrNull()?.participantList().orEmpty() + val names = inboxRepository.namesOf(participants) + uiState = GroupInboxConversationUIState.Loaded( + localChatRoom = room, + names = participants.map { names[it] ?: it.take(8) }, + lines = messages.map { message -> + GroupInboxConversationUIState.Line( + rumorId = message.rumorId, + text = Event.fromJsonOrNull(message.rumorJson)?.content.orEmpty(), + createdAt = message.createdAt, + outgoing = message.outgoing, + senderName = if (message.outgoing) "" else names[message.senderPublicKey] ?: message.senderPublicKey.take(8), + ) + }, + ) + if (messages.any { !it.outgoing && it.readAt == null }) inboxRepository.markRead(chatRoomId, conversationId) + } + } + } + + companion object { + fun factory( + chatRoomId: String, + conversationId: String, + initialUIState: GroupInboxConversationUIState = GroupInboxConversationUIState.Loading, + chatRepository: ChatRepository, + inboxRepository: GroupInboxRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { GroupInboxConversationViewModel(chatRoomId, conversationId, initialUIState, chatRepository, inboxRepository) } + } + } +} + +/** The group's inbox key: setting one up, its ceremony, rotating it (docs/group-inbox.md, Phase 7). */ +class GroupInboxSettingsViewModel( + val chatRoomId: String, + initialUIState: GroupInboxSettingsUIState, + val chatRepository: ChatRepository, + val inboxRepository: GroupInboxRepository, +): ViewModel() { + var uiState: GroupInboxSettingsUIState by mutableStateOf(initialUIState) + private set + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val room = chatRepository.getChatRoomByIdentifier(chatRoomId) ?: run { + uiState = GroupInboxSettingsUIState.Error("Couldn't find the group") + return@launch + } + inboxRepository.observeStatus(room, room.chatRoom.userPublicKey).collect { status -> + val busy = (uiState as? GroupInboxSettingsUIState.Loaded)?.busy ?: false + uiState = GroupInboxSettingsUIState.Loaded(room, status, busy) + } + } + } + + private fun act(onDone: (String?) -> Unit, action: suspend (GroupInboxSettingsUIState.Loaded) -> Unit) { + val loaded = uiState as? GroupInboxSettingsUIState.Loaded ?: return + if (loaded.busy) return + uiState = loaded.copy(busy = true) + viewModelScope.launch(Dispatchers.IO) { + val failure = runCatching { action(loaded) }.exceptionOrNull() + (uiState as? GroupInboxSettingsUIState.Loaded)?.let { uiState = it.copy(busy = false) } + onDone(failure?.let { it.message ?: it::class.simpleName.orEmpty() }) + } + } + + /** Starts the first ceremony. [onDone] gets null, or why it could not. */ + fun setUp(relays: List, onDone: (String?) -> Unit) = + act(onDone) { inboxRepository.setUp(it.localChatRoom, relays) } + + fun rotate(onDone: (String?) -> Unit) = act(onDone) { inboxRepository.rotate(it.localChatRoom) } + + fun abandon(ceremonyId: String, onDone: (String?) -> Unit) = + act(onDone) { inboxRepository.abandon(it.localChatRoom, ceremonyId) } + + companion object { + fun factory( + chatRoomId: String, + initialUIState: GroupInboxSettingsUIState = GroupInboxSettingsUIState.Loading, + chatRepository: ChatRepository, + inboxRepository: GroupInboxRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { GroupInboxSettingsViewModel(chatRoomId, initialUIState, chatRepository, inboxRepository) } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt index 03a951bd..5a1033fe 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -74,6 +74,8 @@ sealed interface ChatRoomDetailUIState { val groupPosts: List = emptyList(), /** How many confederation proposals naming this group this device holds. docs/confederation.md. */ val confederationProposalCount: Int = 0, + /** The group's inbox, for its row; null where this device has nothing of it to show. */ + val inbox: InboxRowSummary? = null, /** The confederation whose room this is, by name: its membership is fixed until it can sign. */ val confederationName: String? = null, /** diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupInboxUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupInboxUIState.kt new file mode 100644 index 00000000..84ba89a9 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupInboxUIState.kt @@ -0,0 +1,54 @@ +package mobi.giza.compose.ui.view.state + +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.repository.GroupInboxRepository + +/** The group's inbox screen (docs/group-inbox.md, Phase 7). */ +sealed interface GroupInboxUIState { + data class Loaded( + val localChatRoom: LocalChatRoom, + val conversations: List, + /** Wraps addressed to the group that no key this device holds opens (D8). */ + val unopenable: Int, + val status: GroupInboxRepository.Status, + ): GroupInboxUIState + + data class Error(val message: String): GroupInboxUIState + + data object Loading: GroupInboxUIState +} + +/** One conversation in the group's inbox (docs/group-inbox.md, Phase 7 and 8). */ +sealed interface GroupInboxConversationUIState { + data class Line( + val rumorId: String, + val text: String, + val createdAt: Long, + val outgoing: Boolean, + val senderName: String, + ) + + data class Loaded( + val localChatRoom: LocalChatRoom, + val names: List, + val lines: List, + ): GroupInboxConversationUIState + + data class Error(val message: String): GroupInboxConversationUIState + + data object Loading: GroupInboxConversationUIState +} + +/** The group's inbox key and its ceremony (docs/group-inbox.md, Phase 7). */ +sealed interface GroupInboxSettingsUIState { + data class Loaded( + val localChatRoom: LocalChatRoom, + val status: GroupInboxRepository.Status, + /** Whether a request this screen made is still on its way. */ + val busy: Boolean = false, + ): GroupInboxSettingsUIState + + data class Error(val message: String): GroupInboxSettingsUIState + + data object Loading: GroupInboxSettingsUIState +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/InboxRowSummary.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/InboxRowSummary.kt new file mode 100644 index 00000000..74e7854a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/InboxRowSummary.kt @@ -0,0 +1,13 @@ +package mobi.giza.compose.ui.view.state + +/** + * The group's inbox as its row on the group's screen shows it (docs/group-inbox.md, Phase 7). + * Only on a device that holds the inbox key, has a ceremony running, or could start one: a + * member who is not an admin sees nothing of the inbox (D9). + */ +data class InboxRowSummary( + val holdsKey: Boolean, + val unread: Int, + val ceremonyRunning: Boolean, + val canSetUp: Boolean, +) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxRowJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxRowJvmTest.kt new file mode 100644 index 00000000..8115c83a --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxRowJvmTest.kt @@ -0,0 +1,54 @@ +package mobi.giza.compose.managers + +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.ExperimentalFeatures +import mobi.giza.compose.database.repository.DatabaseChatRepository +import mobi.giza.compose.ui.view.state.InboxRowSummary + +/** + * Who sees the group's inbox row (docs/group-inbox.md, D9): an admin who could set one up, an + * admin while the ceremony runs, an admin who holds the key with what is unread -- and a member + * who is not an admin, nobody. + */ +class GroupInboxRowJvmTest { + private val harness = GroupInboxHarness(watchers = listOf("dineo")) + + @AfterTest + fun close() = harness.close() + + private suspend fun GroupInboxHarness.Device.row(): InboxRowSummary? = + DatabaseChatRepository(db, CoroutineScope(Dispatchers.Default)).inboxSummary(room()) + + @Test + fun `an admin is offered to set one up, a member is shown nothing`() = runBlocking { + val alice = harness.device("alice") + val dineo = harness.device("dineo") + assertEquals(InboxRowSummary(holdsKey = false, unread = 0, ceremonyRunning = false, canSetUp = true), alice.row()) + assertNull(dineo.row()) + } + + @Test + fun `a running ceremony, then the key, show on the row`() = runBlocking { + val (alice, bob, carol) = listOf("alice", "bob", "carol").map { harness.device(it) } + InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + assertEquals(true, alice.row()?.ceremonyRunning) + harness.pump(alice, bob, carol) + val row = assertNotNull(bob.row()) + assertEquals(true, row.holdsKey) + assertEquals(0, row.unread) + } + + @Test + fun `a release build shows no row`() = runBlocking { + val alice = harness.device("alice") + ExperimentalFeatures.groupInboxOverride = false + assertNull(alice.row()) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupInboxScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupInboxScreenJvmTest.kt new file mode 100644 index 00000000..5b23b15e --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupInboxScreenJvmTest.kt @@ -0,0 +1,185 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.runDesktopComposeUiTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.InboxKey +import mobi.giza.compose.database.model.InboxKeyState +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.GroupInboxRepository +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxConversationRoute +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxSettingsRoute +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.view.state.GroupInboxConversationUIState +import mobi.giza.compose.ui.view.state.GroupInboxSettingsUIState +import mobi.giza.compose.ui.view.state.GroupInboxUIState + +/** + * The group's inbox on screen (docs/group-inbox.md, Phase 7): its conversations, what it cannot + * open and why, what an empty one means, and setting one up. + */ +@OptIn(ExperimentalTestApi::class) +class GroupInboxScreenJvmTest { + private val chatRoomId = "d".repeat(64) + private val me = "a".repeat(64) + private val room = LocalChatRoom(ChatRoom(id = chatRoomId, userPublicKey = me, subject = "#Ekklesia", description = null, mlsGroupState = "state")) + + private fun key(generation: Int, state: InboxKeyState = InboxKeyState.ANNOUNCED) = InboxKey( + chatRoomId = chatRoomId, userPublicKey = me, generation = generation, publicKey = "e".repeat(64), + secretKey = "5".repeat(64), recoveryData = null, ceremonyId = "c".repeat(64), state = state, + ) + + private fun status(keys: List = listOf(key(0)), announced: String? = "e".repeat(64), refusal: String? = null) = + GroupInboxRepository.Status(keys = keys, ceremony = null, announcedKey = announced, relays = emptyList(), setUpRefusal = refusal, waitingOn = emptyList()) + + private fun conversation(name: String, text: String, unread: Int = 0) = GroupInboxRepository.ConversationSummary( + conversationId = "conversation-$name", participants = listOf("b".repeat(64)), names = listOf(name), + lastText = text, lastAt = 1_700_000_000, lastOutgoing = false, unread = unread, + ) + + private fun renderInbox(state: GroupInboxUIState, onRoute: (Route) -> Unit = {}, assertions: ComposeUiTest.() -> Unit) = + runDesktopComposeUiTest(width = 400, height = 1600) { + setContent { + GizaTheme { + ProvideSnackbarHost { + Box(modifier = Modifier.fillMaxSize()) { + GroupInboxScreen( + activeUserPublicKey = me, chatRoomId = chatRoomId, relayHint = null, initialUIState = state, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, inboxRepository = GroupInboxRepository.NO_OP, + onNavigateToRoute = onRoute, onNavigateBack = {}, + ) + } + } + } + } + assertions() + } + + @Test + fun `a conversation shows who it is with and opens on a tap`() { + var opened: Route? = null + renderInbox(GroupInboxUIState.Loaded(room, listOf(conversation("Zola", "Can I join?", unread = 2)), 0, status()), { opened = it }) { + onNodeWithText("Zola").assertIsDisplayed() + onNodeWithText("Can I join?").assertIsDisplayed() + onNodeWithText("2").assertIsDisplayed() + onNodeWithText("Zola").performClick() + } + assertEquals(GroupInboxConversationRoute(me, chatRoomId, null, "conversation-Zola"), opened) + } + + @Test + fun `mail no key opens is counted, with why`() = renderInbox(GroupInboxUIState.Loaded(room, emptyList(), 2, status())) { + onNodeWithText("2 messages this device can't open").assertIsDisplayed() + onNodeWithText("It was sent to the group's npub", substring = true).assertIsDisplayed() + } + + @Test + fun `an empty inbox says nobody has written`() = renderInbox(GroupInboxUIState.Loaded(room, emptyList(), 0, status())) { + onNodeWithText("Nobody has written to the group yet.").assertIsDisplayed() + } + + @Test + fun `an admin who joined after the first key is told why earlier mail is missing`() = + renderInbox(GroupInboxUIState.Loaded(room, emptyList(), 0, status(keys = listOf(key(2))))) { + onNodeWithText("Messages sent before you held the group's inbox key aren't on this device.").assertIsDisplayed() + } + + @Test + fun `an inbox the group has not announced says nobody can write to it yet`() = + renderInbox(GroupInboxUIState.Loaded(room, emptyList(), 0, status(keys = listOf(key(0, InboxKeyState.HELD)), announced = null))) { + onNodeWithText("The group hasn't signed its inbox announcement yet, so nobody can write to it.").assertIsDisplayed() + } + + @Test + fun `the settings are a tap away`() { + var opened: Route? = null + renderInbox(GroupInboxUIState.Loaded(room, emptyList(), 0, status()), { opened = it }) { + onNodeWithContentDescription("Inbox settings").performClick() + } + assertIs(opened) + } + + @Test + fun `a conversation marks the group's replies as the group's`() = runDesktopComposeUiTest(width = 400, height = 1600) { + setContent { + GizaTheme { + ProvideSnackbarHost { + GroupInboxConversationScreen( + activeUserPublicKey = me, chatRoomId = chatRoomId, relayHint = null, conversationId = "c", + initialUIState = GroupInboxConversationUIState.Loaded( + room, listOf("Zola"), + listOf( + GroupInboxConversationUIState.Line("1", "Can I join?", 1_700_000_000, outgoing = false, senderName = "Zola"), + GroupInboxConversationUIState.Line("2", "Yes, on Thursday.", 1_700_000_100, outgoing = true, senderName = ""), + ), + ), + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, inboxRepository = GroupInboxRepository.NO_OP, + onNavigateToRoute = {}, onNavigateBack = {}, + ) + } + } + } + onNodeWithText("Zola and the group").assertIsDisplayed() + onNodeWithText("Yes, on Thursday.").assertIsDisplayed() + onNodeWithText("The group").assertIsDisplayed() + } + + private fun renderSettings(state: GroupInboxSettingsUIState, canSign: Boolean = true, assertions: ComposeUiTest.() -> Unit) = + runDesktopComposeUiTest(width = 400, height = 1600) { + setContent { + GizaTheme { + ProvideSnackbarHost { + CompositionLocalProvider(LocalCanSign provides canSign) { + GroupInboxSettingsScreen( + activeUserPublicKey = me, chatRoomId = chatRoomId, relayHint = null, initialUIState = state, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, inboxRepository = GroupInboxRepository.NO_OP, + onNavigateToRoute = {}, onNavigateBack = {}, + ) + } + } + } + } + assertions() + } + + @Test + fun `with no key, the settings offer to set one up and say what it means`() = + renderSettings(GroupInboxSettingsUIState.Loaded(room, status(keys = emptyList(), announced = null))) { + onNodeWithText("Set up an inbox").assertIsDisplayed() + onNodeWithText("Every admin holds it and can read what arrives", substring = true).assertIsDisplayed() + onNodeWithText("Where mail should arrive").assertIsDisplayed() + } + + @Test + fun `a refusal is said, and the button is not offered`() = + renderSettings(GroupInboxSettingsUIState.Loaded(room, status(keys = emptyList(), announced = null, refusal = "Only an admin can set up the group's inbox"))) { + onNodeWithText("Only an admin can set up the group's inbox").assertIsDisplayed() + onNodeWithText("Set up an inbox").assertIsNotEnabled() + } + + @Test + fun `with a key, the settings show it and offer to rotate it`() = + renderSettings(GroupInboxSettingsUIState.Loaded(room, status(keys = listOf(key(1), key(0, InboxKeyState.RETIRED))))) { + onNodeWithText("Key 1, eeeeeeee…eeeeeeee").assertIsDisplayed() + onNodeWithText("Announced: anyone can write to it").assertIsDisplayed() + onNodeWithText("Retired, kept to open older mail").assertIsDisplayed() + onNodeWithText("Rotate the inbox key").assertIsDisplayed() + } +} From d21d6ecd05c8994d673e7731a89dc57152693a75 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 02:05:46 +0200 Subject: [PATCH 13/16] feat: the group answers from its inbox, once its quorum has read and signed the reply (group-inbox, Phase 8) InboxReplies builds a reply as one rumor authored by the group, sealed from the announced inbox key to each recipient's announced key (or their identity) and once to the group itself, per nostr-protocol/nips#2361, and proposes the seals as one batch with the manifest beside them, sealed to the inbox key, so a member who is not an admin learns how many seals there are and nothing else. Every signer reads the reply before signing it: InboxRefusal opens the manifest and every seal, and declines out loud a copy that says something else, a seal to a key its recipient did not announce, a forged 10044, a recipient the reply does not name, a blank reply, a seal dated outside two days, or anything it cannot read -- including on a device that holds no inbox key. The manifest rides a resend, and the signing screen says the reply's words, its recipients, and who has announced no key. Once signed, the proposer's device wraps each seal for its recipient's relays and the group's copy for the group's, owed through GroupInboxPublisher, and files the copy at once; other admins file it when it arrives. A reply not yet on a relay offers Send again. The conversation screen gets the composer, which warns about a recipient whose app may not open a message from a group. A seal draws nothing in the room's transcript. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 8 + .../compose/database/model/ChatMessage.kt | 6 + .../DatabaseFrostSigningRepository.kt | 8 +- .../DatabaseGroupInboxRepository.kt | 15 + .../compose/managers/FrostSigningManager.kt | 18 +- .../giza/compose/managers/InboxRefusal.kt | 116 +++++++- .../giza/compose/managers/InboxReplies.kt | 221 +++++++++++++++ .../repository/FrostSigningRepository.kt | 7 +- .../repository/GroupInboxRepository.kt | 15 + .../mobi/giza/compose/text/ProposedEvent.kt | 8 + .../ui/composable/FrostSigningScreen.kt | 2 +- .../GroupInboxConversationScreen.kt | 93 ++++++- .../ui/view/model/FrostSigningViewModel.kt | 4 +- .../ui/view/model/GroupInboxViewModel.kt | 24 ++ .../ui/view/state/FrostSigningUIState.kt | 8 +- .../ui/view/state/GroupInboxUIState.kt | 6 + .../giza/compose/text/ProposedEventTest.kt | 6 +- .../managers/GroupInboxTodayJvmTest.kt | 16 +- .../compose/managers/InboxReplyJvmTest.kt | 259 ++++++++++++++++++ 19 files changed, 812 insertions(+), 28 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxReplyJvmTest.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 97a00b66..86a0f19a 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -773,4 +773,12 @@ Couldn't start the ceremony The inbox key ceremony started None of those is a relay a stranger could reach + Reply as the group + Ask the group to sign this reply + The group's quorum has to sign this before it is sent. It goes out in the group's name, not yours, and can't be taken back once signed. + %1$s has announced no inbox key, so their app may not be able to open a message from a group. + Couldn't ask the group to sign this reply. + Not yet on a relay + Send again + Sent again diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt index e393cb76..338d20da 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt @@ -1302,6 +1302,12 @@ data class ChatMessage( // `InboxKeyRitualManager` files them and writes its own lines. in InboxKeyRitualEvents.ALL -> null + // A reply's seals, signed by the group (docs/group-inbox.md, D10). The + // signing session's own lines say the group signed something; a line naming + // the reply would reach members who are not admins, who must learn nothing of + // the inbox (D9). + com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent.KIND -> null + ChatEvent.KIND -> { ChatMessage( giftWrapPayloadId = null, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt index 70797caf..764db422 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt @@ -27,8 +27,12 @@ class DatabaseFrostSigningRepository( ): FrostSigningRepository { private val logger = Logger.withTag(TAG) - override suspend fun confederationNotes(chatRoomId: String, sessionId: String, events: List): List = - runCatching { ConfederationRefusal.notes(database, chatRoomId, sessionId, events) }.getOrDefault(emptyList()) + override suspend fun proposalNotes(chatRoomId: String, sessionId: String, events: List): List = + runCatching { ConfederationRefusal.notes(database, chatRoomId, sessionId, events) }.getOrDefault(emptyList()) + + runCatching { + val user = database.frostSigningSessionDao().getSessionById(sessionId)?.userPublicKey ?: return@runCatching emptyList() + mobi.giza.compose.managers.InboxRefusal.notes(database, chatRoomId, user, sessionId, events) + }.getOrDefault(emptyList()) override fun observeSessionById(sessionId: String): Flow = database.frostSigningSessionDao().observeSessionById(sessionId) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt index 0f6db750..d4bc3727 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt @@ -21,6 +21,7 @@ import mobi.giza.compose.identity.Identity import mobi.giza.compose.managers.GroupInboxManager import mobi.giza.compose.managers.InboxAnnouncements import mobi.giza.compose.managers.InboxKeyRitualManager +import mobi.giza.compose.managers.InboxReplies import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents import mobi.giza.compose.repository.GroupInboxRepository @@ -112,4 +113,18 @@ class DatabaseGroupInboxRepository( override suspend fun abandon(localChatRoom: LocalChatRoom, ceremonyId: String): Boolean = InboxKeyRitualManager.abandon(database, localChatRoom, ceremonyId) + + override suspend fun proposeReply(localChatRoom: LocalChatRoom, conversationId: String, text: String): String = + InboxReplies.propose(database, localChatRoom, localChatRoom.chatRoom.userPublicKey, conversationId, text).id + + override suspend fun withoutAnnouncedKey(publicKeys: List): List = + publicKeys.filterNot { InboxReplies.hasAnnouncedKey(database, it) } + + override suspend fun unsentReplies(chatRoomId: String): Set = + database.groupInboxDao().getMessages(chatRoomId) + .mapNotNull { it.signingSessionId } + .filter { session -> database.groupInboxDao().getPublicationsFor(session).any { it.publishedAt == null } } + .toSet() + + override suspend fun sendAgain(sessionId: String): Boolean = InboxReplies.sendAgain(database, sessionId) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt index 720eb208..0b8336a4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt @@ -45,6 +45,7 @@ import mobi.giza.compose.database.model.types.ShareGenerationState import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.dkg.DkgRitualEvents import mobi.giza.compose.nostr.frost.FrostSigningEvents +import mobi.giza.compose.nostr.inbox.InboxReplyManifest import mobi.giza.compose.nostr.frost.GovernanceStatementEvent import mobi.giza.compose.nostr.frost.GroupKeyStateEvent @@ -723,14 +724,17 @@ object FrostSigningManager { // The group's inbox: an announcement of a key its admins did not make together, or // of one since replaced, or relays a stranger could not reach, is declined before // anybody is asked. docs/group-inbox.md, D5. + // A reply from the group's inbox carries its manifest beside the seals (D11), kept so + // approval can read the reply again and the signed seals can be sent. + val inboxManifest = InboxReplyManifest.sealedIn(innerEvent.tags) if (InboxRefusal.involves(unsignedEvents)) { - InboxRefusal.of(database, localChatRoom, userPublicKey, unsignedEvents)?.let { why -> + InboxRefusal.of(database, localChatRoom, userPublicKey, unsignedEvents, inboxManifest)?.let { why -> logger.w("Signing proposal $sessionId: $why") val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0, participantCount = n) .copy(signDeclinedAt = Clock.System.now()) database.frostSigningSessionDao().upsert(declined) database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents)) - InboxRefusal.remember(database, sessionId, localChatRoom.chatRoom.id, why) + InboxRefusal.remember(database, sessionId, localChatRoom.chatRoom.id, why, inboxManifest) announceStarted(database, declined) return declined } @@ -779,6 +783,9 @@ object FrostSigningManager { database.frostSigningSessionDao().upsert(session) database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents)) confederation?.let { ConfederationRefusal.remember(database, sessionId, it, null) } + if (inboxManifest != null && InboxRefusal.involves(unsignedEvents)) { + InboxRefusal.remember(database, sessionId, localChatRoom.chatRoom.id, null, inboxManifest) + } announceStarted(database, session) logger.i( @@ -1081,7 +1088,7 @@ object FrostSigningManager { if (session.subject != FrostSigningSubject.EVENTS) return null val events = items.mapNotNull { Event.fromJsonOrNull(it.unsignedEventJson) } if (!InboxRefusal.involves(events)) return null - return InboxRefusal.of(database, localChatRoom, session.userPublicKey, events) + return InboxRefusal.of(database, localChatRoom, session.userPublicKey, events, database.groupInboxDao().getSigning(session.id)?.manifest) } /** Whether [session] is waiting on this device and is a wallet's to sign. */ @@ -1464,6 +1471,7 @@ object FrostSigningManager { // proposed the announcement owes it to relays. docs/group-inbox.md, D7. try { InboxAnnouncements.onSigned(database, session, signedEvents) + InboxReplies.onSigned(database, session, signedEvents) } catch (e: Throwable) { logger.e("Signed session ${session.id} but could not file its inbox announcement", e) } @@ -2526,7 +2534,9 @@ object FrostSigningManager { FrostSigningEvents.PROPOSAL, FrostSigningEvents.encodeProposal(unsigned), // What a confederation event is checked with goes again with it. - ConfederationRefusal.carriedTagsFor(database, sessionId) + ConfederationRefusal.carriedTagsFor(database, sessionId) + + // And a reply's manifest (docs/group-inbox.md, D11). + InboxRefusal.carriedTagsFor(database, sessionId) ) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt index 12914330..e21aab0e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt @@ -9,6 +9,13 @@ import mobi.giza.compose.database.model.InboxKeyCeremony import mobi.giza.compose.database.model.InboxSigning import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.nostr.inbox.InboxAnnouncement +import mobi.giza.compose.nostr.inbox.InboxReplyManifest +import mobi.giza.compose.nostr.inbox.InboxSeal +import mobi.giza.compose.nostr.inbox.InboxWire +import mobi.giza.compose.database.model.InboxKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.verify +import kotlin.time.Clock /** * What a device declines, out loud, when the group is asked to sign something about its inbox @@ -31,9 +38,20 @@ object InboxRefusal { const val KEY_SHAPE = "Giza doesn't sign an inbox key announcement it would not write" const val RELAYS_SHAPE = "Giza doesn't sign a list of inbox relays a stranger could not reach" + // A reply (D12): every signer reads it before signing it. + const val REPLY_UNREADABLE = "Giza doesn't sign a sealed message it can't read" + const val REPLY_NO_KEY = "This device holds no inbox key for this group" + const val REPLY_MISMATCH = "Giza doesn't sign a reply whose copies don't all say the same thing to the people it names" + const val REPLY_WRONG_KEY = "Giza doesn't sign a reply sealed to a key its recipient didn't announce" + const val REPLY_BLANK = "Giza doesn't sign a reply with nothing in it" + const val REPLY_TIME = "Giza doesn't sign a reply dated outside the last two days" + + private const val TWO_DAYS = 2 * 24 * 60 * 60L + private const val CLOCK_SLACK = 10 * 60L + /** Whether any of [events] is one this refusal is about. */ fun involves(events: List): Boolean = - events.any { it.kind == InboxAnnouncement.KEY_KIND || it.kind == InboxAnnouncement.RELAYS_KIND } + events.any { it.kind == InboxAnnouncement.KEY_KIND || it.kind == InboxAnnouncement.RELAYS_KIND || it.kind == InboxSeal.KIND } /** * Why this device declines to sign [events] in [localChatRoom] as [userPublicKey] sees it, or @@ -44,7 +62,13 @@ object InboxRefusal { localChatRoom: LocalChatRoom, userPublicKey: HexKey, events: List, + /** A reply's sealed manifest, as its proposal carried it (D11). */ + manifest: String? = null, + now: Long = Clock.System.now().epochSeconds, ): String? { + if (events.any { it.kind == InboxSeal.KIND }) { + return replyRefusal(database, localChatRoom.chatRoom.id, userPublicKey, events, manifest, now) + } for (event in events) { when (event.kind) { InboxAnnouncement.RELAYS_KIND -> @@ -80,6 +104,96 @@ object InboxRefusal { return null } + /** What a signer reads a reply with: the key that opened its manifest, the manifest, and the one rumor. */ + data class ReadReply(val key: InboxKey, val manifest: InboxReplyManifest, val rumor: Event) + + /** + * D12's checks on a batch of seals. A signer reads the reply before signing it: it opens + * the manifest, checks every seal is sealed from the announced generation to the key its + * recipient announced (or their identity), opens every one, and refuses unless they all hold + * the same rumor, written by the group to exactly the people the manifest names. + */ + private suspend fun replyRefusal(database: GizaDatabase, roomId: HexKey, userPublicKey: HexKey, events: List, manifest: String?, now: Long): String? { + if (events.any { it.kind != InboxSeal.KIND }) return REPLY_UNREADABLE + val read = when (val result = readReply(database, roomId, userPublicKey, events, manifest)) { + is Read.Refused -> return result.reason + is Read.Ok -> result.reply + } + if (read.rumor.content.isBlank()) return REPLY_BLANK + if (events.any { it.createdAt < now - TWO_DAYS - CLOCK_SLACK || it.createdAt > now + CLOCK_SLACK }) return REPLY_TIME + return null + } + + private sealed interface Read { + data class Ok(val reply: ReadReply) : Read + data class Refused(val reason: String) : Read + } + + private suspend fun readReply(database: GizaDatabase, roomId: HexKey, userPublicKey: HexKey, events: List, manifest: String?): Read { + val sealed = manifest ?: return Read.Refused(REPLY_UNREADABLE) + val keys = database.inboxKeyDao().getKeys(roomId, userPublicKey).filter { it.secretKey != null } + val (key, opened) = keys.firstNotNullOfOrNull { k -> + InboxReplyManifest.open(sealed, k.secretKey!!.hexToByteArray())?.let { k to it } + } ?: return Read.Refused(REPLY_NO_KEY) + if (opened.generation != key.generation || opened.seals.size != events.size) return Read.Refused(REPLY_UNREADABLE) + events.forEach { seal -> + if (!seal.pubKey.equals(roomId, ignoreCase = true) || seal.tags.size != 1 || InboxSeal.encryptionKeyOf(seal.tags) != key.publicKey) { + return Read.Refused(REPLY_UNREADABLE) + } + } + opened.seals.forEachIndexed { index, entry -> + val keyIsRight = if (index == opened.groupCopy) { + entry.recipient.equals(roomId, ignoreCase = true) && entry.key == key.publicKey && entry.announcement == null + } else { + !entry.recipient.equals(roomId, ignoreCase = true) && when (val json = entry.announcement) { + null -> entry.key == entry.recipient + else -> Event.fromJsonOrNull(json)?.let { announcement -> + announcement.verify() && announcement.pubKey == entry.recipient && InboxAnnouncement.announcedKeyOf(announcement) == entry.key + } == true + } + } + if (!keyIsRight) return Read.Refused(REPLY_WRONG_KEY) + } + val secret = key.secretKey!!.hexToByteArray() + val rumors = events.mapIndexed { index, seal -> + InboxSeal.rumorInside(seal.content, InboxWire.conversationKey(secret, opened.seals[index].key), roomId) + ?: return Read.Refused(REPLY_MISMATCH) + } + if (rumors.map { it.id }.distinct().size != 1) return Read.Refused(REPLY_MISMATCH) + val rumor = rumors.first() + if (rumor.kind != 14) return Read.Refused(REPLY_UNREADABLE) + val named = rumor.tags.filter { it.size >= 2 && it[0] == "p" }.map { it[1].lowercase() }.distinct().sorted() + val manifestRecipients = opened.seals.filterIndexed { index, _ -> index != opened.groupCopy }.map { it.recipient.lowercase() }.distinct().sorted() + if (named != manifestRecipients || opened.seals.size != manifestRecipients.size + 1) return Read.Refused(REPLY_MISMATCH) + return Read.Ok(ReadReply(key, opened, rumor)) + } + + /** + * What the approval screen says about a reply (D12): its words, who it goes to, and what this + * device could not check -- a recipient who has announced no key may have an app that cannot + * open a message from a group (D13). + */ + suspend fun notes(database: GizaDatabase, chatRoomId: String, userPublicKey: HexKey, sessionId: String, events: List): List { + if (events.none { it.kind == InboxSeal.KIND }) return emptyList() + val manifest = database.groupInboxDao().getSigning(sessionId)?.manifest + val reply = (readReply(database, chatRoomId, userPublicKey, events, manifest) as? Read.Ok)?.reply + ?: return listOf("A private reply from the group's inbox, which this device cannot read") + val recipients = reply.manifest.seals.filterIndexed { index, _ -> index != reply.manifest.groupCopy } + val names = database.profileDao().getProfileByPublicKeys(recipients.map { it.recipient }) + .associate { it.publicKey to it.humanReadableNameOrPubkey() } + return buildList { + add("The group would say: " + reply.rumor.content) + add("To " + recipients.joinToString(", ") { names[it.recipient] ?: it.recipient.take(8) }) + recipients.filter { it.announcement == null }.forEach { + add((names[it.recipient] ?: it.recipient.take(8)) + " has announced no inbox key, so their app may not be able to open a message from a group") + } + } + } + + /** The manifest a resent proposal has to carry again, as it came. */ + suspend fun carriedTagsFor(database: GizaDatabase, sessionId: String): Array> = + database.groupInboxDao().getSigning(sessionId)?.manifest?.let { arrayOf(InboxReplyManifest.tag(it)) } ?: emptyArray() + /** The key [ceremony] made, recomputing it on a watcher's device that missed it at the time. */ private suspend fun keyOf(database: GizaDatabase, ceremony: InboxKeyCeremony): HexKey? = ceremony.inboxPublicKey ?: InboxKeyRitualManager.keyWatched(database, ceremony) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt new file mode 100644 index 00000000..ecdbe61a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt @@ -0,0 +1,221 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.verify +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler +import com.vitorpamplona.quartz.utils.TimeUtils +import kotlin.time.Clock +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.GroupInboxMessage +import mobi.giza.compose.database.model.GroupInboxPublication +import mobi.giza.compose.database.model.InboxKeyState +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.Relays +import mobi.giza.compose.nostr.inbox.InboxAnnouncement +import mobi.giza.compose.nostr.inbox.InboxConversation +import mobi.giza.compose.nostr.inbox.InboxReplyManifest +import mobi.giza.compose.nostr.inbox.InboxSeal +import mobi.giza.compose.nostr.inbox.InboxWire +import mobi.giza.compose.nostr.inbox.InboxWrap + +/** + * The group answering from its inbox (docs/group-inbox.md, D10 to D13). + * + * A reply is one rumor, authored by the group, sealed once per recipient and once to the group + * itself, from the inbox key the group announced. The seals are what the quorum signs; nothing + * leaves until it has. Then the device that proposed it wraps each signed seal and owes the + * wraps to the recipients' relays, and the group's copy to the group's, which is how every + * admin sees the reply. + */ +object InboxReplies { + private val logger = Logger.withTag("InboxReplies") + + /** Who a seal is to and the key it is sealed with, and the 10044 that says so. */ + data class Recipient(val publicKey: HexKey, val encryptionKey: HexKey, val announcement: Event?) + + /** A reply ready to propose: the seals to sign, in order, and the manifest that explains them. */ + data class Built(val rumor: Event, val seals: List>, val manifest: InboxReplyManifest) + + /** + * Builds a reply from the group of [roomId] to [recipients], answering [replyTo], from the + * inbox key [inboxSecret] of [generation]. + */ + fun build( + roomId: HexKey, + recipients: List, + text: String, + replyTo: HexKey?, + inboxSecret: ByteArray, + generation: Int, + now: Long = TimeUtils.now(), + sealTime: () -> Long = { TimeUtils.randomWithTwoDays() }, + ): Built { + require(text.isNotBlank()) { "A reply needs something to say" } + require(recipients.isNotEmpty()) { "A reply needs someone to go to" } + val ordered = recipients.distinctBy { it.publicKey }.sortedBy { it.publicKey } + val tags = buildList { + ordered.forEach { add(arrayOf("p", it.publicKey)) } + replyTo?.let { add(arrayOf("e", it, "", "reply")) } + }.toTypedArray() + val rumor = RumorAssembler.assembleRumor(pubKey = roomId, ev = EventTemplate(now, 14, tags, text)) + + val inboxKey = InboxWire.publicKeyOf(inboxSecret) + val entries = ordered.map { InboxReplyManifest.Entry(it.publicKey, it.encryptionKey, it.announcement?.toJson()) } + + InboxReplyManifest.Entry(roomId, inboxKey, null) + val seals = entries.map { InboxSeal.template(rumor, inboxSecret, it.key, sealTime()) } + return Built(rumor, seals, InboxReplyManifest(generation, entries, groupCopy = entries.lastIndex)) + } + + /** The key a person reads encrypted mail with, as this device last heard: their 10044, or their identity. */ + suspend fun recipientOf(database: GizaDatabase, publicKey: HexKey): Recipient { + val announcement = database.nostrEventDao().getNostrEventByPublicKeyAndKind(publicKey, InboxAnnouncement.KEY_KIND) + ?.toEvent()?.takeIf { it.verify() } + val key = announcement?.let { InboxAnnouncement.announcedKeyOf(it) } + return Recipient(publicKey, key ?: publicKey, announcement.takeIf { key != null }) + } + + /** Whether [publicKey] has said, with a 10044, which key reads their mail (D13's warning when not). */ + suspend fun hasAnnouncedKey(database: GizaDatabase, publicKey: HexKey): Boolean = + recipientOf(database, publicKey).announcement != null + + /** + * Proposes a reply in [localChatRoom]'s conversation [conversationId], answering its newest + * message, from the key the group has announced. Throws with a reason a person can read when + * there is nothing to answer, or no announced key this device holds. + */ + suspend fun propose( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + conversationId: String, + text: String, + ): FrostSigningSession { + val roomId = localChatRoom.chatRoom.id + val conversation = database.groupInboxDao().getConversation(roomId, conversationId) + val newest = conversation.lastOrNull() ?: throw IllegalStateException("There is nothing here to reply to") + // D14: sealed from the key the group announced, never a newer one it has not. + val key = database.inboxKeyDao().getKeys(roomId, userPublicKey) + .firstOrNull { it.state == InboxKeyState.ANNOUNCED && it.secretKey != null } + ?: throw IllegalStateException("The group has announced no inbox key this device holds") + val recipients = newest.participantList().map { recipientOf(database, it) } + val built = build( + roomId = roomId, + recipients = recipients, + text = text, + replyTo = conversation.lastOrNull { !it.outgoing }?.rumorId, + inboxSecret = key.secretKey!!.hexToByteArray(), + generation = key.generation, + ) + val sealed = built.manifest.seal(key.secretKey.hexToByteArray()) + val session = FrostSigningManager.proposeSigningBatch( + database, localChatRoom, userPublicKey, + events = built.seals, + proposalTags = arrayOf(InboxReplyManifest.tag(sealed)), + ) + InboxRefusal.remember(database, session.id, roomId, refusal = null, manifest = sealed) + logger.i("Proposed a reply to ${recipients.size} in ${roomId.take(8)} as session ${session.id.take(8)}") + return session + } + + /** + * What a signed reply leaves (D10), on every device that took part: on the device that + * proposed it, a wrap per seal owed to its recipient's relays and the group's copy filed as + * an outgoing message at once. Every other admin's device files the copy when it arrives. + */ + suspend fun onSigned(database: GizaDatabase, session: FrostSigningSession, signedEvents: List) { + val seals = signedEvents.filter { it.kind == InboxSeal.KIND && it.pubKey.equals(session.chatRoomId, ignoreCase = true) } + if (seals.isEmpty() || !session.isCoordinator()) return + wrapAndOwe(database, session, seals) + } + + /** + * Wraps [seals] again and owes them to relays: what a person does from the conversation when + * the device that proposed a reply never got it out. New wraps of the same seals; the group's + * side files them as the one message they are. + */ + suspend fun sendAgain(database: GizaDatabase, sessionId: String): Boolean { + val session = database.frostSigningSessionDao().getSessionById(sessionId) ?: return false + val seals = database.groupSignedEventDao().getByChatRoomIdAndKind(session.chatRoomId, InboxSeal.KIND) + .filter { it.frostSigningSessionId == sessionId } + .map { it.toEvent() } + if (seals.isEmpty()) return false + wrapAndOwe(database, session, seals) + return true + } + + private suspend fun wrapAndOwe(database: GizaDatabase, session: FrostSigningSession, seals: List) { + val roomId = session.chatRoomId + val signing = database.groupInboxDao().getSigning(session.id) ?: run { + logger.w("Signed reply ${session.id.take(8)} has no manifest here; not sending it") + return + } + val keys = database.inboxKeyDao().getKeys(roomId, session.userPublicKey).filter { it.secretKey != null } + val opened = keys.firstNotNullOfOrNull { key -> + signing.manifest?.let { InboxReplyManifest.open(it, key.secretKey!!.hexToByteArray()) }?.let { key to it } + } ?: run { + logger.w("Signed reply ${session.id.take(8)}: no key here opens its manifest; not sending it") + return + } + val (key, manifest) = opened + // In the order the proposal fixed, which is the manifest's. + val signedById = seals.associateBy { it.id } + val ordered = database.frostSigningSessionDao().getItems(session.id).sortedBy { it.itemIndex }.map { signedById[it.eventId] } + if (ordered.size != manifest.seals.size) return + + manifest.seals.forEachIndexed { index, entry -> + val seal = ordered[index] ?: return@forEachIndexed + val relays = if (index == manifest.groupCopy) { + InboxAnnouncements.relaysOf(database, roomId) + } else { + relaysOf(database, entry.recipient) + } + val wrap = InboxWrap.wrap(seal, entry.recipient, entry.key, relays.firstOrNull()) + database.groupInboxDao().upsertPublication( + GroupInboxPublication( + eventId = wrap.id, + chatRoomId = roomId, + kind = wrap.kind, + eventJson = wrap.toJson(), + relays = relays.joinToString(",") { it.url }, + signingSessionId = session.id, + recipientPublicKey = entry.recipient, + ) + ) + } + + // The group's copy, filed now so the reply is in the conversation before it comes back. + val copy = ordered[manifest.groupCopy] ?: return + val rumor = InboxSeal.rumorInside(copy.content, InboxReplyManifest.selfConversationKey(key.secretKey!!.hexToByteArray()), roomId) ?: return + val participants = InboxConversation.participantsOf(rumor, roomId) + database.groupInboxDao().insertMessage( + GroupInboxMessage( + chatRoomId = roomId, + rumorId = rumor.id, + wrapId = null, + conversationId = InboxConversation.idOf(participants), + participants = participants.joinToString(","), + senderPublicKey = roomId, + kind = rumor.kind, + rumorJson = InboxSeal.rumorJson(rumor), + createdAt = rumor.createdAt, + generation = manifest.generation, + outgoing = true, + signingSessionId = session.id, + readAt = Clock.System.now(), + ) + ) + } + + /** Where [publicKey] reads private mail: their 10050, as this device last heard it. */ + private suspend fun relaysOf(database: GizaDatabase, publicKey: HexKey): List = + database.nostrEventDao().getNostrEventByPublicKeyAndKind(publicKey, InboxAnnouncement.RELAYS_KIND) + ?.toEvent()?.let { InboxAnnouncement.announcedRelaysOf(it) } + ?.ifEmpty { null } + ?: Relays.DefaultDMRelayList +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt index 8f7e9022..1df371cc 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt @@ -82,7 +82,12 @@ interface FrostSigningRepository { suspend fun canSign(chatRoomId: String): Boolean /** What to read before approving a confederation event in [sessionId] (docs/confederation.md, D6). */ - suspend fun confederationNotes(chatRoomId: String, sessionId: String, events: List): List = emptyList() + /** + * What the signing screen says beside a proposal: for a confederation event, what it names + * and discloses (docs/confederation.md, D6); for a reply from the group's inbox, its words, + * who it goes to and what could not be checked (docs/group-inbox.md, D12). + */ + suspend fun proposalNotes(chatRoomId: String, sessionId: String, events: List): List = emptyList() /** * Opens a session asking the group to sign an event with these fields. The diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt index 4fb6a9a7..14aac74c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt @@ -81,6 +81,21 @@ interface GroupInboxRepository { suspend fun abandon(localChatRoom: LocalChatRoom, ceremonyId: String): Boolean = false + // ---- replying (Phase 8) ------------------------------------------------------------------- + + /** Asks the group to sign a reply to [conversationId]; the signing session's id. */ + suspend fun proposeReply(localChatRoom: LocalChatRoom, conversationId: String, text: String): String = + throw UnsupportedOperationException() + + /** Of [publicKeys], those who have announced no inbox key (D13's warning). */ + suspend fun withoutAnnouncedKey(publicKeys: List): List = emptyList() + + /** The reply sessions in [chatRoomId] whose wraps no relay has taken yet. */ + suspend fun unsentReplies(chatRoomId: String): Set = emptySet() + + /** Wraps a signed reply again and owes it to relays. */ + suspend fun sendAgain(sessionId: String): Boolean = false + companion object { val NO_OP = object : GroupInboxRepository { override fun observeUnpublished(): Flow> = flowOf(emptyList()) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt index 6a064943..9b94c86a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt @@ -11,6 +11,7 @@ import mobi.giza.compose.managers.WalletRefusal import mobi.giza.compose.nostr.RetiredKinds import mobi.giza.compose.nostr.frost.GovernanceStatementEvent import mobi.giza.compose.nostr.inbox.InboxAnnouncement +import mobi.giza.compose.nostr.inbox.InboxSeal import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent @@ -101,6 +102,13 @@ object ProposedEvent { detail = InboxAnnouncement.announcedKeyOf(event)?.let { "Key ${it.take(8)}…${it.takeLast(8)}" } ?: "Names no key", ) + // A reply from the group's inbox: sealed, so said for what it is. The signing screen + // reads it out for a device that holds the inbox key (docs/group-inbox.md, D12), and a + // member without one sees only that it exists (D11). + InboxSeal.KIND -> Summary( + label = "A private reply from the group's inbox", + detail = "Sealed: only the group's inbox key opens it", + ) InboxAnnouncement.RELAYS_KIND -> Summary( label = "Where the group receives private messages", detail = InboxAnnouncement.announcedRelaysOf(event).joinToString(", ") { it.url.removePrefix("wss://").trimEnd('/') } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt index 0a68b174..0bde2306 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt @@ -210,7 +210,7 @@ fun FrostSigningScreen( // A confederation event's terms and what this device could not check // about it, for the member to weigh. docs/confederation.md, D6. - state.confederationNotes.forEach { note -> + state.proposalNotes.forEach { note -> Text(text = note, style = MaterialTheme.typography.bodySmall) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxConversationScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxConversationScreen.kt index d6bab16a..f3c4af0a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxConversationScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxConversationScreen.kt @@ -10,7 +10,26 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items +import androidx.compose.material3.Button import androidx.compose.material3.Card +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.TextButton +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import mobi.giza.compose.resources.ask_the_group_to_sign_this_reply +import mobi.giza.compose.resources.could_not_ask_the_group_to_sign_this_reply +import mobi.giza.compose.resources.has_announced_no_inbox_key +import mobi.giza.compose.resources.not_yet_on_a_relay +import mobi.giza.compose.resources.reply_as_the_group +import mobi.giza.compose.resources.send_reply_again +import mobi.giza.compose.resources.sent_again +import mobi.giza.compose.resources.the_group_signs_a_reply +import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.rememberNotifier import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme @@ -69,8 +88,6 @@ fun GroupInboxConversationScreen( inboxRepository: GroupInboxRepository, onNavigateToRoute: (Route) -> Unit, onNavigateBack: () -> Unit, - /** Below the conversation: the way to reply, when there is one (Phase 8). */ - composer: @Composable (GroupInboxConversationUIState.Loaded) -> Unit = {}, ) { val viewModel: GroupInboxConversationViewModel = viewModel( factory = GroupInboxConversationViewModel.factory(chatRoomId, conversationId, initialUIState, chatRepository, inboxRepository) @@ -78,6 +95,11 @@ fun GroupInboxConversationScreen( LaunchedEffect(true) { if (initialUIState == GroupInboxConversationUIState.Loading) viewModel.initiate() } + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotPropose = stringResource(Res.string.could_not_ask_the_group_to_sign_this_reply) + val sentAgain = stringResource(Res.string.sent_again) + val canSign = LocalCanSign.current + var draft by rememberSaveable { mutableStateOf("") } val title = (viewModel.uiState as? GroupInboxConversationUIState.Loaded)?.names?.joinToString(", ") ?.let { stringResource(Res.string.you_and_the_group, it) } ?: stringResource(Res.string.the_group) @@ -122,19 +144,76 @@ fun GroupInboxConversationScreen( modifier = Modifier.weight(1f).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), ) { - items(state.lines, key = { it.rumorId }) { line -> MessageCard(line) } + items(state.lines, key = { it.rumorId }) { line -> + MessageCard(line, onSendAgain = { session -> viewModel.sendAgain(session) { if (it) notify(sentAgain) } }) + } } } - composer(state) + if (canSign && state.lines.isNotEmpty()) { + Composer( + draft = draft, + onDraft = { draft = it }, + withoutKey = state.withoutKey, + proposing = state.proposing, + onPropose = { + viewModel.propose(draft) { session -> + if (session == null) { + notify(couldNotPropose) + } else { + draft = "" + onNavigateToRoute(FrostSigningRoute(activeUserPublicKey, chatRoomId, session)) + } + } + }, + ) + } } } } } } +/** + * The way to answer (D10, D13): the words, what signing it means, a warning for every recipient + * whose app may not open a message from a group, and the button that asks the quorum. + */ +@Composable +private fun Composer( + draft: String, + onDraft: (String) -> Unit, + withoutKey: List, + proposing: Boolean, + onPropose: () -> Unit, +) { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) { + withoutKey.forEach { name -> + Text( + stringResource(Res.string.has_announced_no_inbox_key, name), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + value = draft, + onValueChange = onDraft, + label = { Text(stringResource(Res.string.reply_as_the_group)) }, + minLines = 2, + ) + Text( + stringResource(Res.string.the_group_signs_a_reply), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Button(onClick = onPropose, enabled = draft.isNotBlank() && !proposing) { + Text(stringResource(Res.string.ask_the_group_to_sign_this_reply)) + } + } +} + /** One message: theirs on the leading edge, the group's on the trailing one, in its own colours. */ @Composable -private fun MessageCard(line: GroupInboxConversationUIState.Line) { +private fun MessageCard(line: GroupInboxConversationUIState.Line, onSendAgain: (String) -> Unit) { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = if (line.outgoing) Alignment.End else Alignment.Start, @@ -163,6 +242,10 @@ private fun MessageCard(line: GroupInboxConversationUIState.Line) { text = Instant.fromEpochSeconds(line.createdAt).toFormattedTimeAndDateString(), style = MaterialTheme.typography.labelSmall, ) + line.unsentSessionId?.let { session -> + Text(stringResource(Res.string.not_yet_on_a_relay), style = MaterialTheme.typography.labelSmall) + TextButton(onClick = { onSendAgain(session) }) { Text(stringResource(Res.string.send_reply_again)) } + } } } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt index ba42a39f..76835ff5 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt @@ -81,7 +81,7 @@ class FrostSigningViewModel( ) { session, messages, items, holders -> Observed(session, messages, items, holders) } .collect { (session, messages, items, holders) -> if (notes == null && items.isNotEmpty()) { - notes = frostSigningRepository.confederationNotes(chatRoomId, sessionId, proposedEvents(items)) + notes = frostSigningRepository.proposalNotes(chatRoomId, sessionId, proposedEvents(items)) } // Read per emission rather than derived from `messages`: who // the session is waiting on is the manager's rule, and it is @@ -107,7 +107,7 @@ class FrostSigningViewModel( .map { it.signerPublicKey } .toSet(), silent = owed, - confederationNotes = notes.orEmpty(), + proposalNotes = notes.orEmpty(), ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupInboxViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupInboxViewModel.kt index 5effbc10..78349c1c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupInboxViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupInboxViewModel.kt @@ -80,9 +80,13 @@ class GroupInboxConversationViewModel( inboxRepository.observeConversation(chatRoomId, conversationId).collect { messages -> val participants = messages.lastOrNull()?.participantList().orEmpty() val names = inboxRepository.namesOf(participants) + val unsent = inboxRepository.unsentReplies(chatRoomId) + val withoutKey = inboxRepository.withoutAnnouncedKey(participants) uiState = GroupInboxConversationUIState.Loaded( localChatRoom = room, names = participants.map { names[it] ?: it.take(8) }, + withoutKey = withoutKey.map { names[it] ?: it.take(8) }, + proposing = (uiState as? GroupInboxConversationUIState.Loaded)?.proposing ?: false, lines = messages.map { message -> GroupInboxConversationUIState.Line( rumorId = message.rumorId, @@ -90,6 +94,7 @@ class GroupInboxConversationViewModel( createdAt = message.createdAt, outgoing = message.outgoing, senderName = if (message.outgoing) "" else names[message.senderPublicKey] ?: message.senderPublicKey.take(8), + unsentSessionId = message.signingSessionId?.takeIf { it in unsent }, ) }, ) @@ -98,6 +103,25 @@ class GroupInboxConversationViewModel( } } + /** + * Asks the group to sign [text] as a reply. [onDone] gets the signing session's id, or null + * when it could not be asked. + */ + fun propose(text: String, onDone: (String?) -> Unit) { + val loaded = uiState as? GroupInboxConversationUIState.Loaded ?: return + if (loaded.proposing || text.isBlank()) return + uiState = loaded.copy(proposing = true) + viewModelScope.launch(Dispatchers.IO) { + val session = runCatching { inboxRepository.proposeReply(loaded.localChatRoom, conversationId, text.trim()) }.getOrNull() + (uiState as? GroupInboxConversationUIState.Loaded)?.let { uiState = it.copy(proposing = false) } + onDone(session) + } + } + + fun sendAgain(sessionId: String, onDone: (Boolean) -> Unit) { + viewModelScope.launch(Dispatchers.IO) { onDone(inboxRepository.sendAgain(sessionId)) } + } + companion object { fun factory( chatRoomId: String, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt index 4244db04..f9d0c3e8 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt @@ -24,8 +24,12 @@ sealed interface FrostSigningUIState { */ val items: List = emptyList(), - /** For a confederation event: who it names, what it discloses, what could not be checked. docs/confederation.md, D6. */ - val confederationNotes: List = emptyList(), + /** + * What the screen says beside the events: for a confederation event, who it names, what it + * discloses and what could not be checked (docs/confederation.md, D6); for a reply from the + * group's inbox, its words and recipients (docs/group-inbox.md, D12). + */ + val proposalNotes: List = emptyList(), /** Who has offered a nonce, so the screen can name who it is waiting on. */ val offeredNonce: Set = emptySet(), diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupInboxUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupInboxUIState.kt index 84ba89a9..ba226b95 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupInboxUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupInboxUIState.kt @@ -26,12 +26,18 @@ sealed interface GroupInboxConversationUIState { val createdAt: Long, val outgoing: Boolean, val senderName: String, + /** For a reply this device proposed: its signing session, while no relay has taken it. */ + val unsentSessionId: String? = null, ) data class Loaded( val localChatRoom: LocalChatRoom, val names: List, val lines: List, + /** Recipients who have announced no inbox key (D13): their app may not open the reply. */ + val withoutKey: List = emptyList(), + /** Whether a reply this screen asked for is still on its way to the signing session. */ + val proposing: Boolean = false, ): GroupInboxConversationUIState data class Error(val message: String): GroupInboxConversationUIState diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt index 162fda95..76d84077 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt @@ -113,10 +113,10 @@ class ProposedEventTest { /** * docs/group-inbox.md: the group's inbox key and its relays are said by what they are - * (Phase 5). A seal is still said by its number until Phase 8 gives it words. + * (Phase 5), and a seal as the sealed reply it is (Phase 8). */ @Test - fun `an inbox key and its relays are named, and a seal is still a number`() { + fun `an inbox key, its relays and a sealed reply are named`() { val key = "e".repeat(64) val announcement = ProposedEvent.summarize(event(10044, tags = arrayOf(arrayOf("n", key)))) assertEquals("The group's inbox key", announcement.label) @@ -124,7 +124,7 @@ class ProposedEventTest { val relays = ProposedEvent.summarize(event(10050, tags = arrayOf(arrayOf("relay", "wss://inbox.example.com/")))) assertEquals("Where the group receives private messages", relays.label) assertEquals("inbox.example.com", relays.detail) - assertEquals("Event of kind 13", ProposedEvent.summarize(event(13)).label) + assertEquals("A private reply from the group's inbox", ProposedEvent.summarize(event(13)).label) } private fun event( diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt index a7d7152b..5f85f351 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxTodayJvmTest.kt @@ -16,9 +16,9 @@ import mobi.giza.compose.text.ProposedEvent * What Giza does today with the events a group's inbox is made of (docs/group-inbox.md, * Phase 1). Written to pass now and flipped on purpose by the phase that changes each: * - * - a peer's proposal to sign a kind 13 (a NIP-17 seal) reaches the member as a bare number, - * and nothing declines it. Phase 8 puts a refusal in front of it, as Phase 5 did for a kind - * 10044 (an encryption key), which this pins declined now; + * - a peer's proposal to sign a kind 10044 (an encryption key) nobody made, or a kind 13 (a + * NIP-17 seal) with no manifest to read it by, is declined out loud: Phases 5 and 8 put a + * refusal in front of each; * - the identity's own gift wraps are asked for on their own subscription, beside the * group's that Phase 6 added. */ @@ -62,11 +62,13 @@ class GroupInboxTodayJvmTest { } @Test - fun `a peer's sealed ciphertext reaches the member as a number, and can be signed`() { - // The member is asked to sign bytes it cannot read: the rubber stamp - // docs/giza-wallet-removal.md says a Giza device must not be. Phase 8 declines it. + fun `a peer's sealed ciphertext with nothing to read it by is declined out loud`() = runBlocking { + // Flipped by Phase 8: a member asked to sign bytes it cannot read would be the rubber + // stamp docs/giza-wallet-removal.md says a Giza device must not be (docs/group-inbox.md, D12). val sent = proposeAndDeliver(13, arrayOf(arrayOf("n", "e".repeat(64))), "AnOpaqueCiphertext") - assertPutToTheMemberByNumber(sent, 13) + val session = assertNotNull(harness.db.frostSigningSessionDao().getSessionById(sent.session.id)) + assertNotNull(session.signDeclinedAt) + assertEquals(listOf(InboxRefusal.REPLY_UNREADABLE), harness.queued(FrostSigningEvents.DECLINE).map { it.content }) } @Test diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxReplyJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxReplyJvmTest.kt new file mode 100644 index 00000000..76aae9ae --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxReplyJvmTest.kt @@ -0,0 +1,259 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.crypto.verify +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync +import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler +import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent +import fr.acinq.bitcoin.Crypto +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.types.FrostSigningStage +import mobi.giza.compose.nostr.frost.FrostSigningEvents +import mobi.giza.compose.nostr.inbox.InboxAnnouncement +import mobi.giza.compose.nostr.inbox.InboxReplyManifest +import mobi.giza.compose.nostr.inbox.InboxSeal +import mobi.giza.compose.nostr.inbox.InboxWire +import mobi.giza.compose.nostr.inbox.InboxWrap +import mobi.giza.compose.text.ProposedEvent +import kotlin.time.Instant + +/** + * The group answering from its inbox (docs/group-inbox.md, Phase 8): a reply is proposed by one + * admin, read and signed by the quorum, and reaches its recipient as a NIP-17 message from the + * group; a wrong one is declined out loud; and a member who is not an admin learns nothing of it. + */ +class InboxReplyJvmTest { + private val harness = GroupInboxHarness(watchers = listOf("dineo")) + private val zola = KeyPair(Crypto.sha256("zola, who writes to the group".encodeToByteArray())) + private val zolaKey = zola.pubKey.toHexKey() + private val zolaEncryption = Crypto.sha256("zola's decoupled key".encodeToByteArray()) + private val zolaEncryptionKey = InboxWire.publicKeyOf(zolaEncryption) + private val now get() = kotlin.time.Clock.System.now().epochSeconds + + @AfterTest + fun close() = harness.close() + + private lateinit var alice: GroupInboxHarness.Device + private lateinit var bob: GroupInboxHarness.Device + private lateinit var carol: GroupInboxHarness.Device + private lateinit var dineo: GroupInboxHarness.Device + + /** Three admins with an announced inbox, Zola's message in Alice's, and a member who is not an admin. */ + private suspend fun announced() { + val devices = listOf("alice", "bob", "carol", "dineo").map { harness.device(it) } + alice = devices[0]; bob = devices[1]; carol = devices[2]; dineo = devices[3] + InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + harness.pump() + val announcement = alice.db.frostSigningSessionDao().getSessionsForChatRoom(harness.roomId).single() + FrostSigningManager.approve(bob.db, bob.room(), announcement.id) + harness.pump() + + val e = alice.keys().single().publicKey + val message = RumorAssembler.assembleRumor(zolaKey, EventTemplate(now - 60, 14, arrayOf(arrayOf("p", harness.roomId)), "Can I join?")) + val seal = NostrSignerSync(zola).sign(now - 60, 13, emptyArray(), + InboxWire.encrypt(InboxSeal.rumorJson(message), InboxWire.conversationKey(zola.privKey!!, e))) + assertNotNull(GroupInboxManager.receive(alice.db, InboxWrap.wrap(seal, harness.roomId, e), alice.publicKey)) + } + + private suspend fun conversationId(): String = alice.db.groupInboxDao().getMessages(harness.roomId).first { !it.outgoing }.conversationId + + private suspend fun session(on: GroupInboxHarness.Device, id: String): FrostSigningSession = + assertNotNull(on.db.frostSigningSessionDao().getSessionById(id)) + + /** Zola announces a decoupled key, and Alice's device has heard it. */ + private suspend fun zolaAnnounces(on: GroupInboxHarness.Device) { + val signed = NostrSignerSync(zola).sign(InboxAnnouncement.keyTemplate(zolaEncryptionKey, now - 3600)) + on.db.nostrEventDao().upsert( + NostrEvent(id = signed.id, pubKey = signed.pubKey, kind = signed.kind, tags = signed.tags, content = signed.content, sig = signed.sig, createdAt = Instant.fromEpochSeconds(signed.createdAt)) + ) + } + + /** The wrap Alice's device owes Zola, opened with [secret]. */ + private suspend fun zolaOpens(secret: ByteArray, sessionId: String): Event { + val owed = alice.db.groupInboxDao().getPublicationsFor(sessionId).single { it.recipientPublicKey == zolaKey } + val wrap = Event.fromJson(owed.eventJson) + assertEquals(zolaKey, InboxWrap.recipientOf(wrap), "tagged with Zola's identity, as #2361 has it") + val (_, seal) = assertNotNull(InboxWrap.open(wrap, listOf(secret)), "Zola's key opens the wrap") + assertTrue(seal.verify(), "the seal is signed") + assertEquals(harness.roomId, seal.pubKey, "by the group") + return assertNotNull(InboxSeal.open(seal, secret)).rumor + } + + @Test + fun `a reply signed by the quorum reaches Zola from the group`() = runBlocking { + announced() + val sessionId = InboxReplies.propose(alice.db, alice.room(), alice.publicKey, conversationId(), "Yes, on Thursday.").id + harness.pump() + assertTrue(FrostSigningManager.isAwaitingApproval(session(bob, sessionId), bob.db.frostSigningSessionDao().getItems(sessionId)), "Bob is asked") + FrostSigningManager.approve(bob.db, bob.room(), sessionId) + harness.pump() + assertEquals(FrostSigningStage.COMPLETE, session(alice, sessionId).stage) + + val reply = zolaOpens(zola.privKey!!, sessionId) + assertEquals("Yes, on Thursday.", reply.content) + assertEquals(harness.roomId, reply.pubKey) + assertTrue(reply.tags.any { it[0] == "p" && it[1] == zolaKey }) + + // Alice's device filed the group's copy at once, in the same conversation. + val filed = alice.db.groupInboxDao().getConversation(harness.roomId, conversationId()) + assertEquals(listOf(false, true), filed.map { it.outgoing }) + // Only the proposer sends. + assertEquals(emptyList(), bob.db.groupInboxDao().getPublicationsFor(sessionId)) + } + + @Test + fun `a reply to someone who decoupled opens with their encryption key`() = runBlocking { + announced() + zolaAnnounces(alice) + val sessionId = InboxReplies.propose(alice.db, alice.room(), alice.publicKey, conversationId(), "To your new key").id + harness.pump() + FrostSigningManager.approve(bob.db, bob.room(), sessionId) + harness.pump() + assertEquals("To your new key", zolaOpens(zolaEncryption, sessionId).content) + } + + @Test + fun `the group's copy comes back to every admin as an outgoing message`() = runBlocking { + announced() + val sessionId = InboxReplies.propose(alice.db, alice.room(), alice.publicKey, conversationId(), "For the record").id + harness.pump() + FrostSigningManager.approve(bob.db, bob.room(), sessionId) + harness.pump() + + val copy = alice.db.groupInboxDao().getPublicationsFor(sessionId).single { it.recipientPublicKey == harness.roomId } + val filed = assertNotNull(GroupInboxManager.receive(carol.db, Event.fromJson(copy.eventJson), carol.publicKey)) + assertTrue(filed.outgoing) + assertEquals("For the record", Event.fromJson(filed.rumorJson).content) + assertNull(GroupInboxManager.receive(dineo.db, Event.fromJson(copy.eventJson), dineo.publicKey), "nothing for a member who is not an admin") + } + + @Test + fun `a reply proposed after its relays never took it can be sent again`() = runBlocking { + announced() + val sessionId = InboxReplies.propose(alice.db, alice.room(), alice.publicKey, conversationId(), "Again").id + harness.pump() + FrostSigningManager.approve(bob.db, bob.room(), sessionId) + harness.pump() + val first = alice.db.groupInboxDao().getPublicationsFor(sessionId).map { it.eventId }.toSet() + assertTrue(InboxReplies.sendAgain(alice.db, sessionId)) + val all = alice.db.groupInboxDao().getPublicationsFor(sessionId).map { it.eventId }.toSet() + assertEquals(4, all.size, "new wraps of the same seals") + assertTrue(all.containsAll(first)) + assertEquals(1, alice.db.groupInboxDao().getConversation(harness.roomId, conversationId()).count { it.outgoing }, "still one message") + } + + // ---- what a signer refuses (D12) --------------------------------------------------------- + + /** Proposes [seals] with [manifest] by hand, from Alice, and returns what Bob's device says. */ + private suspend fun bobSays(seals: List>, manifest: InboxReplyManifest, sealWith: ByteArray? = null): String? { + val secret = sealWith ?: alice.keys().first().secretKey!!.hexToByteArray() + val session = FrostSigningManager.proposeSigningBatch(alice.db, alice.room(), alice.publicKey, events = seals, + proposalTags = arrayOf(InboxReplyManifest.tag(manifest.seal(secret)))) + harness.pump() + val onBob = session(bob, session.id) + if (onBob.signDeclinedAt == null) return null + return bob.db.marmotInnerEventDao().getByChatRoomAndKinds(harness.roomId, listOf(FrostSigningEvents.DECLINE)) + .firstOrNull { it.publicKey == bob.publicKey }?.content + } + + private suspend fun built(text: String = "Fine", recipients: List = listOf(InboxReplies.Recipient(zolaKey, zolaKey, null))): InboxReplies.Built { + val key = alice.keys().first() + return InboxReplies.build(harness.roomId, recipients, text, null, key.secretKey!!.hexToByteArray(), key.generation, now = now, sealTime = { now - 30 }) + } + + @Test + fun `a well-made reply is put to the member, not declined`() = runBlocking { + announced() + val reply = built() + assertNull(bobSays(reply.seals, reply.manifest)) + } + + @Test + fun `a group copy that says something else is declined`() = runBlocking { + announced() + val reply = built("What Zola reads") + val other = built("What the admins read") + val seals = reply.seals.toMutableList().also { it[reply.manifest.groupCopy] = other.seals[other.manifest.groupCopy] } + assertEquals(InboxRefusal.REPLY_MISMATCH, bobSays(seals, reply.manifest)) + } + + @Test + fun `a seal to a key the recipient never announced is declined`() = runBlocking { + announced() + val stranger = InboxWire.publicKeyOf(Crypto.sha256("someone else's key".encodeToByteArray())) + val reply = built(recipients = listOf(InboxReplies.Recipient(zolaKey, stranger, null))) + assertEquals(InboxRefusal.REPLY_WRONG_KEY, bobSays(reply.seals, reply.manifest)) + } + + @Test + fun `a 10044 signed by someone else is declined`() = runBlocking { + announced() + val forger = KeyPair(Crypto.sha256("a forger".encodeToByteArray())) + val forged = NostrSignerSync(forger).sign(InboxAnnouncement.keyTemplate(zolaEncryptionKey, now)) + val reply = built(recipients = listOf(InboxReplies.Recipient(zolaKey, zolaEncryptionKey, forged))) + assertEquals(InboxRefusal.REPLY_WRONG_KEY, bobSays(reply.seals, reply.manifest)) + } + + @Test + fun `a recipient the reply does not name is declined`() = runBlocking { + announced() + val yusuf = KeyPair(Crypto.sha256("yusuf".encodeToByteArray())).pubKey.toHexKey() + val toZola = built() + val toBoth = built(recipients = listOf(InboxReplies.Recipient(zolaKey, zolaKey, null), InboxReplies.Recipient(yusuf, yusuf, null))) + // Yusuf's seal holds a rumor naming only Zola: a reply sent to someone it does not address. + val key = alice.keys().first().secretKey!!.hexToByteArray() + val yusufIndex = toBoth.manifest.seals.indexOfFirst { it.recipient == yusuf } + val seals = toBoth.manifest.seals.map { InboxSeal.template(toZola.rumor, key, it.key, now - 30) } + assertEquals(yusufIndex >= 0, true) + assertEquals(InboxRefusal.REPLY_MISMATCH, bobSays(seals, toBoth.manifest)) + } + + @Test + fun `a blank reply is declined`() = runBlocking { + announced() + val key = alice.keys().first() + val blank = RumorAssembler.assembleRumor(harness.roomId, EventTemplate(now, 14, arrayOf(arrayOf("p", zolaKey)), " ")) + val manifest = built().manifest + val seals = manifest.seals.map { InboxSeal.template(blank, key.secretKey!!.hexToByteArray(), it.key, now - 30) } + assertEquals(InboxRefusal.REPLY_BLANK, bobSays(seals, manifest)) + } + + @Test + fun `a signer whose device holds no inbox key declines, rather than sign what it cannot read`() = runBlocking { + announced() + bob.db.inboxKeyDao().wipeKeys(harness.roomId, bob.publicKey, kotlin.time.Clock.System.now()) + val reply = built() + assertEquals(InboxRefusal.REPLY_NO_KEY, bobSays(reply.seals, reply.manifest)) + } + + @Test + fun `a member who is not an admin learns no text and no recipient`() = runBlocking { + announced() + val sessionId = InboxReplies.propose(alice.db, alice.room(), alice.publicKey, conversationId(), "Private words").id + harness.pump() + val sealed = assertNotNull(alice.db.groupInboxDao().getSigning(sessionId)?.manifest) + assertNull(InboxReplyManifest.open(sealed, Crypto.sha256("any key dineo could have".encodeToByteArray()))) + + val items = alice.db.frostSigningSessionDao().getItems(sessionId).map { Event.fromJson(it.unsignedEventJson) } + assertEquals("A private reply from the group's inbox", ProposedEvent.summarize(items.first()).label) + items.forEach { seal -> + assertTrue("Private words" !in seal.content && zolaKey !in seal.content && seal.tags.none { zolaKey in it }) + } + // Bob, who holds the key, reads it on the signing screen. + val notes = InboxRefusal.notes(bob.db, harness.roomId, bob.publicKey, sessionId, items) + assertEquals("The group would say: Private words", notes.first()) + } +} From 6b59282ebefdc5b63cc03675cb3d974b9fe647ff Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 02:09:01 +0200 Subject: [PATCH 14/16] test: two pins Phase 8 moved, moved with it (group-inbox, Phase 8) A DM peer's sync now asks for their 10044 too, and Phase 0's seal premise in SignedGroupKeyStateTest is a seal nobody can read, which a signer now declines (D12). The premise itself is checked end to end in InboxReplyJvmTest; this one now pins the decline. Co-Authored-By: Claude Opus 5.5 --- .../nostr/DirectMessagePeerSyncTest.kt | 4 ++- .../managers/SignedGroupKeyStateTest.kt | 32 ++++++------------- 2 files changed, 12 insertions(+), 24 deletions(-) diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/DirectMessagePeerSyncTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/DirectMessagePeerSyncTest.kt index c9bf9bba..1adf0727 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/DirectMessagePeerSyncTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/DirectMessagePeerSyncTest.kt @@ -34,7 +34,9 @@ class DirectMessagePeerSyncTest { // Level 0: somebody is waiting on this one. assertEquals(0, request.level) assertEquals( - listOf(MetadataEvent.KIND, KeyPackageEvent.KIND, DmRelayListEvent.KIND, AdvertisedRelayListEvent.KIND), + // And the key they read encrypted mail with, if they announced one: what a + // group's reply to them is sealed to (docs/group-inbox.md, D10). + listOf(MetadataEvent.KIND, KeyPackageEvent.KIND, DmRelayListEvent.KIND, AdvertisedRelayListEvent.KIND, 10044), request.synchronizationFilter.kinds?.toList(), ) assertEquals(listOf(alice), request.synchronizationFilter.authors?.toList()) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SignedGroupKeyStateTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SignedGroupKeyStateTest.kt index 018e8b6c..43ee6931 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SignedGroupKeyStateTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SignedGroupKeyStateTest.kt @@ -1286,24 +1286,19 @@ class SignedGroupKeyStateTest { } /** - * The premise of docs/group-inbox.md's replies (Phase 0, check 4): a NIP-17 seal is - * signed by its author's identity, and a group's identity is its room. A batch of kind - * 13 events the quorum signs has to verify as the room, or no recipient's app would - * accept a reply from the group's inbox, whatever was sealed inside it. + * docs/group-inbox.md's replies (Phase 0, check 4, as Phase 8 left it). The premise -- that + * a batch of kind 13 seals the quorum signs verifies as the room -- held when Phase 0 checked + * it here, and `InboxReplyJvmTest` now checks it end to end with real seals. What this + * harness can still say is what changed since: a seal no signer can read, with no manifest + * and no inbox key behind it, is declined rather than signed, which is D12's rule. */ @Test - fun `a batch of seals the group signs verifies as the room's own`() = runBlocking { + fun `a batch of seals nobody can read is declined, not signed`() = runBlocking { val creator = device(members[0], signerIndex = 0) val other = device(members[1], signerIndex = 1) - val inboxKey = "a".repeat(64) val seals = listOf("first", "second").map { ciphertext -> - EventTemplate( - createdAt = 1_700_000_000L, - kind = 13, - tags = arrayOf(arrayOf("n", inboxKey)), - content = ciphertext, - ) + EventTemplate(createdAt = 1_700_000_000L, kind = 13, tags = arrayOf(arrayOf("n", "a".repeat(64))), content = ciphertext) } val session = FrostSigningManager.proposeSigningBatch( database = creator.db, @@ -1312,19 +1307,10 @@ class SignedGroupKeyStateTest { events = seals, ) pump(creator, other) - FrostSigningManager.approve(other.db, other.room, session.id) - pump(creator, other) + assertNotNull(other.session(session.id)?.signDeclinedAt, "the second signer declines what it cannot read") listOf(creator, other).forEach { device -> - val signed = device.items(session.id).map { - assertNotNull(device.db.groupSignedEventDao().getById(it.eventId)) - } - assertEquals(2, signed.size) - signed.forEach { seal -> - assertEquals(13, seal.kind) - assertEquals(adminRoomId, seal.publicKey) - assertTrue(seal.verifies(), "a seal the group signed must verify as the room") - } + assertTrue(device.items(session.id).all { it.signature == null }, "nothing was signed") } } From 8bc7ab3e335418b728392c7b997965aa8bdeeff6 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 02:09:01 +0200 Subject: [PATCH 15/16] feat: the inbox key changes with the group's admins (group-inbox, Phase 9) InboxRotation reads what every admin's device already holds: the key was made over one set of admins and the room's policy now names another. That covers a removal, a demotion, a step-down and a promotion alike, and a change that landed while the app was closed. The admin whose key sorts first starts the new ceremony, asking nobody, after any share rotation the same change owes; the rotated key's announcement is vouched for and signed unasked; the removed admin's device has already let go. Run by the governance follow-through and the sweep, and offered by hand in the settings, which say when the admins have changed since the key was made. Two admins who start a rotation at once end in one ceremony on every device: each keeps the one whose session id sorts first and ends the other out loud. A proposal for a generation a device already has is dropped. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 1 + .../DatabaseGroupInboxRepository.kt | 2 + .../repository/DatabaseNostrRepository.kt | 5 + .../managers/GovernanceFollowThrough.kt | 6 + .../compose/managers/InboxKeyRitualManager.kt | 23 +++ .../giza/compose/managers/InboxRotation.kt | 70 ++++++++ .../repository/GroupInboxRepository.kt | 2 + .../ui/composable/GroupInboxSettingsScreen.kt | 8 + .../compose/managers/InboxRotationJvmTest.kt | 163 ++++++++++++++++++ 9 files changed, 280 insertions(+) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRotation.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxRotationJvmTest.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 86a0f19a..09c2bf4c 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -781,4 +781,5 @@ Not yet on a relay Send again Sent again + The group's admins have changed since this key was made. It changes on its own once an admin's device starts a new ceremony, or you can rotate it now. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt index d4bc3727..28a6fb70 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt @@ -22,6 +22,7 @@ import mobi.giza.compose.managers.GroupInboxManager import mobi.giza.compose.managers.InboxAnnouncements import mobi.giza.compose.managers.InboxKeyRitualManager import mobi.giza.compose.managers.InboxReplies +import mobi.giza.compose.managers.InboxRotation import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents import mobi.giza.compose.repository.GroupInboxRepository @@ -83,6 +84,7 @@ class DatabaseGroupInboxRepository( relays = InboxAnnouncements.relaysOf(database, roomId), setUpRefusal = InboxKeyRitualManager.refusal(database, localChatRoom, userPublicKey), waitingOn = ceremony?.takeIf { it.isRunning }?.let { waitingOn(it) }.orEmpty(), + rotationOwed = InboxRotation.isOwed(database, localChatRoom, userPublicKey), ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt index 16f3416a..60c1ddcf 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt @@ -62,6 +62,7 @@ import mobi.giza.compose.managers.ChillDkgRitualManager import mobi.giza.compose.managers.FrostSigningManager import mobi.giza.compose.managers.ShareRefreshManager import mobi.giza.compose.managers.InboxKeyRitualManager +import mobi.giza.compose.managers.InboxRotation import com.vitorpamplona.quartz.nip01Core.core.toHexKey import mobi.giza.compose.identity.Identity @@ -163,6 +164,10 @@ class DatabaseNostrRepository( database = database, userPublicKey = userPublicKey, nostrPrivateKey = privateKey + ) + InboxRotation.pass( + database = database, + userPublicKey = userPublicKey, + nostrPrivateKey = privateKey ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt index 6e9bcbc3..63438c11 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt @@ -58,6 +58,12 @@ object GovernanceFollowThrough { /** One pass over everything owed. */ suspend fun pass(database: GizaDatabase, keyPair: KeyPair) = mutex.withLock { rotationsOwed(database).forEach { proposal -> rotateAway(database, keyPair, proposal) } + // The group's inbox key, made over admins the room no longer has (docs/group-inbox.md, + // D14). After the share rotation above, which its refusal waits on. + keyPair.privKey?.let { secret -> + runCatching { InboxRotation.pass(database, keyPair.pubKey.toHexKey(), secret) } + .onFailure { if (it is CancellationException) throw it; logger.w("An inbox rotation pass failed: ${it.message}") } + } if (!ExperimentalFeatures.shareRefresh) return@withLock val me = keyPair.pubKey.toHexKey() val privateKey = keyPair.privKey ?: return@withLock diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt index d6d94a55..f2e05904 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxKeyRitualManager.kt @@ -67,6 +67,9 @@ object InboxKeyRitualManager { const val ABANDONED = "Abandoned by an admin" + /** Why one of two crossing ceremonies ends: the other went on. */ + const val CROSSED = "Another admin started the same ceremony at the same time, and that one went on" + fun deriveHostSecretKey(nostrPrivateKey: ByteArray, chatRoomId: String): PrivateKey = PrivateKey(Crypto.sha256(HOST_KEY_TAG.encodeToByteArray() + nostrPrivateKey + chatRoomId.hexToByteArray())) @@ -225,6 +228,13 @@ object InboxKeyRitualManager { } val participants = (named + innerEvent.pubKey).distinct().sorted() + // A generation this device already finished is not made twice: a late or replayed + // proposal for it opens nothing. + if (database.inboxKeyDao().getCompletedCeremonies(roomId, userPublicKey).any { it.generation >= generation }) { + logger.w("Inbox key proposal ${sessionId.take(8)} is for generation $generation, which this device has; dropping") + return null + } + val base = InboxKeyCeremony( id = sessionId, chatRoomId = roomId, @@ -264,6 +274,19 @@ object InboxKeyRitualManager { return database.inboxKeyDao().getCeremony(sessionId) } + // Two admins who each started a rotation before hearing the other's: every device keeps + // the one whose session id sorts first and ends the other out loud, so all of them end + // up in the same ceremony and nobody holds a key the others do not. + val crossing = database.inboxKeyDao().getRunningCeremoniesIn(roomId) + .filter { it.userPublicKey == userPublicKey && it.id != sessionId } + crossing.forEach { other -> + val loser = if (other.id < sessionId) mine else other + val reason = CROSSED + fail(database, loser, reason, loser.coordinatorPublicKey) + if (loser.isParticipant()) broadcast(database, localChatRoom, loser, InboxKeyRitualEvents.FAILURE, reason) + } + if (database.inboxKeyDao().getCeremony(sessionId)?.isRunning != true) return database.inboxKeyDao().getCeremony(sessionId) + replayStored(database, localChatRoom, mine) return database.inboxKeyDao().getCeremony(sessionId) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRotation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRotation.kt new file mode 100644 index 00000000..348a44ca --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRotation.kt @@ -0,0 +1,70 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.CancellationException +import mobi.giza.compose.ExperimentalFeatures +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.InboxKeyState +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom + +/** + * When the group's inbox key has to change because its admins have (docs/group-inbox.md, D14). + * + * The rule is read off what every admin's device already holds, rather than off the change that + * caused it: the key was made by a ceremony over some set of admins, and the room's admin policy + * now names another. That covers a removal, a demotion, a step-down and a promotion the same way, + * and a change that landed while the app was closed. + * + * One admin starts it, so the devices do not race: the one whose key sorts first among the + * admins now. Nobody is asked -- the group's signature on the admin change was the decision -- + * and if that admin's device is away, any admin can rotate by hand from the inbox's settings. + * It waits for whatever share rotation the same change owes ([InboxKeyRitualManager.refusal] + * reads the same hold), so the two run in turn. + */ +object InboxRotation { + private val logger = Logger.withTag("InboxRotation") + + /** + * Whether [localChatRoom]'s inbox key was made over admins the room no longer has, as + * [userPublicKey]'s device sees it. False where there is no key, or the admins cannot be read. + */ + suspend fun isOwed(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey): Boolean { + val roomId = localChatRoom.chatRoom.id + val keys = database.inboxKeyDao().getKeys(roomId, userPublicKey).filter { it.state != InboxKeyState.WIPED } + if (keys.isEmpty()) return false + val newest = database.inboxKeyDao().getCompletedCeremonies(roomId, userPublicKey).firstOrNull() ?: return false + val admins = RoomAdmins.of(database, roomId)?.admins ?: return false + return admins != newest.participants().toSet() + } + + /** Whether [userPublicKey] is the admin whose device starts an owed rotation in [chatRoomId]. */ + suspend fun startsIt(database: GizaDatabase, chatRoomId: String, userPublicKey: HexKey): Boolean = + RoomAdmins.of(database, chatRoomId)?.admins?.minOrNull() == userPublicKey + + /** + * Starts every rotation [userPublicKey]'s device owes. Run by the governance follow-through and + * the sweep; repeats nothing, since a running ceremony is not started twice. Returns how many it + * started. + */ + suspend fun pass(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray): Int { + if (!ExperimentalFeatures.groupInbox) return 0 + var started = 0 + database.inboxKeyDao().getHeldKeys(userPublicKey).map { it.chatRoomId }.distinct().forEach { roomId -> + val room = database.chatRoomDao().findChatRoomById(roomId) ?: return@forEach + if (!isOwed(database, room, userPublicKey) || !startsIt(database, roomId, userPublicKey)) return@forEach + if (database.inboxKeyDao().getRunningCeremoniesIn(roomId).any { it.userPublicKey == userPublicKey }) return@forEach + if (InboxKeyRitualManager.refusal(database, room, userPublicKey) != null) return@forEach + try { + InboxKeyRitualManager.propose(database, room, userPublicKey, nostrPrivateKey) + started += 1 + logger.i("The admins of ${roomId.take(8)} changed; rotating its inbox key") + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + logger.w("Could not rotate the inbox key of ${roomId.take(8)}: ${e.message}") + } + } + return started + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt index 14aac74c..58973034 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt @@ -56,6 +56,8 @@ interface GroupInboxRepository { val setUpRefusal: String?, /** The admins a running ceremony waits on, by name. */ val waitingOn: List, + /** The key was made over admins the room no longer has (D14). */ + val rotationOwed: Boolean = false, ) { val heldKey: InboxKey? get() = keys.firstOrNull { it.secretKey != null } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxSettingsScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxSettingsScreen.kt index 064c573f..c9dea7fd 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxSettingsScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxSettingsScreen.kt @@ -65,6 +65,7 @@ import mobi.giza.compose.resources.rotate_the_inbox_key import mobi.giza.compose.resources.set_up_an_inbox import mobi.giza.compose.resources.the_admins_are_making_the_inbox_key import mobi.giza.compose.resources.the_ceremony_ended +import mobi.giza.compose.resources.the_admins_have_changed_since_this_key_was_made import mobi.giza.compose.resources.the_inbox_key_ceremony_started import mobi.giza.compose.resources.try_again import mobi.giza.compose.resources.waiting_for_the_group_to_sign_its_announcement @@ -222,6 +223,13 @@ fun GroupInboxSettingsScreen( if (visibleKeys.isNotEmpty() && !running) { Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) { + if (status.rotationOwed) { + Text( + stringResource(Res.string.the_admins_have_changed_since_this_key_was_made), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + ) + } Text(stringResource(Res.string.rotate_explainer), style = MaterialTheme.typography.bodyMedium) status.setUpRefusal?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxRotationJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxRotationJvmTest.kt new file mode 100644 index 00000000..3c491fd0 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/InboxRotationJvmTest.kt @@ -0,0 +1,163 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync +import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler +import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent +import fr.acinq.bitcoin.Crypto +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.model.InboxKeyCeremonyStage +import mobi.giza.compose.database.model.InboxKeyState +import mobi.giza.compose.database.model.types.FrostSigningStage +import mobi.giza.compose.nostr.inbox.InboxSeal +import mobi.giza.compose.nostr.inbox.InboxWire +import mobi.giza.compose.nostr.inbox.InboxWrap + +/** + * The inbox key changing with the group's admins (docs/group-inbox.md, Phase 9): nobody is asked, + * one admin's device starts it, a removed admin cannot open what is sent to the new key, a promoted + * one holds only the new key, and a reply proposed before the change still goes out after it. + */ +class InboxRotationJvmTest { + private val harness = GroupInboxHarness() + private val zola = KeyPair(Crypto.sha256("zola, who writes to the group".encodeToByteArray())) + private val now get() = kotlin.time.Clock.System.now().epochSeconds + + @AfterTest + fun close() = harness.close() + + private lateinit var devices: Map + private fun device(name: String) = devices.getValue(name) + + private suspend fun open(names: List = listOf("alice", "bob", "carol")) { + devices = names.associateWith { harness.device(it) } + } + + /** Makes and announces the first key among whoever the harness has as admins. */ + private suspend fun announced(by: String = "alice", approver: String = "bob") { + val proposer = device(by) + InboxKeyRitualManager.propose(proposer.db, proposer.room(), proposer.publicKey, proposer.secret) + harness.pump() + val session = proposer.db.frostSigningSessionDao().getSessionsForChatRoom(harness.roomId).single() + FrostSigningManager.approve(device(approver).db, device(approver).room(), session.id) + harness.pump() + assertEquals(InboxKeyState.ANNOUNCED, proposer.keys().single().state) + } + + /** Every device takes its rotation pass, then everything is delivered. */ + private suspend fun passAndPump() { + devices.values.forEach { InboxRotation.pass(it.db, it.publicKey, it.secret) } + harness.pump() + } + + private fun mailTo(key: HexKey, text: String): Event { + val message = RumorAssembler.assembleRumor(zola.pubKey.toHexKey(), EventTemplate(now, 14, arrayOf(arrayOf("p", harness.roomId)), text)) + val seal = NostrSignerSync(zola).sign(now, 13, emptyArray(), + InboxWire.encrypt(InboxSeal.rumorJson(message), InboxWire.conversationKey(zola.privKey!!, key))) + return InboxWrap.wrap(seal, harness.roomId, key) + } + + @Test + fun `removing an admin rotates the key with nobody asked, and the removed admin cannot read the new one`() = runBlocking { + open() + announced() + val alice = device("alice"); val bob = device("bob"); val carol = device("carol") + + // Carol stops being an admin. Her device lets go of the inbox; the others owe a rotation. + harness.admins = setOf(alice.publicKey, bob.publicKey) + GroupInboxManager.forgetIfNotAdmin(carol.db, harness.roomId, carol.publicKey, stillAdmin = false) + assertTrue(InboxRotation.isOwed(alice.db, alice.room(), alice.publicKey)) + assertEquals(1, listOf(alice, bob).count { InboxRotation.startsIt(it.db, harness.roomId, it.publicKey) }, "one admin starts it") + + passAndPump() + + listOf(alice, bob).forEach { admin -> + val keys = admin.keys() + assertEquals(listOf(1, 0), keys.map { it.generation }, "${admin.name} holds both") + assertEquals(InboxKeyState.ANNOUNCED, keys[0].state, "${admin.name}'s device signed the new announcement unasked") + assertEquals(InboxKeyState.RETIRED, keys[1].state) + assertFalse(InboxRotation.isOwed(admin.db, admin.room(), admin.publicKey)) + } + assertTrue(carol.keys().all { it.secretKey == null }, "Carol's device kept nothing") + + val newKey = alice.keys()[0].publicKey + val oldKey = alice.keys()[1].publicKey + assertNotNull(GroupInboxManager.receive(bob.db, mailTo(newKey, "To the new key"), bob.publicKey)) + assertNotNull(GroupInboxManager.receive(bob.db, mailTo(oldKey, "To the old key"), bob.publicKey), "old mail still opens") + assertNull(GroupInboxManager.receive(carol.db, mailTo(newKey, "Not for Carol"), carol.publicKey)) + } + + @Test + fun `a promoted admin holds only the new key`() = runBlocking { + open() + val alice = device("alice"); val bob = device("bob"); val carol = device("carol") + harness.admins = setOf(alice.publicKey, bob.publicKey) + announced() + assertEquals(emptyList(), carol.keys()) + + harness.admins = setOf(alice.publicKey, bob.publicKey, carol.publicKey) + passAndPump() + + assertEquals(listOf(1), carol.keys().map { it.generation }, "nothing from before") + assertEquals(alice.keys().first().publicKey, carol.keys().single().publicKey) + assertEquals(InboxKeyState.ANNOUNCED, carol.keys().single().state) + } + + @Test + fun `a reply proposed before a rotation still goes out after it`() = runBlocking { + open() + announced() + val alice = device("alice"); val bob = device("bob") + val firstKey = alice.keys().single().publicKey + assertNotNull(GroupInboxManager.receive(alice.db, mailTo(firstKey, "Hello"), alice.publicKey)) + val conversation = alice.db.groupInboxDao().getMessages(harness.roomId).single().conversationId + val reply = InboxReplies.propose(alice.db, alice.room(), alice.publicKey, conversation, "Sealed before the change").id + harness.pump() + + InboxKeyRitualManager.propose(bob.db, bob.room(), bob.publicKey, bob.secret) + harness.pump() + assertEquals(InboxKeyState.ANNOUNCED, alice.keys().first { it.generation == 1 }.state) + + FrostSigningManager.approve(bob.db, bob.room(), reply) + harness.pump() + assertEquals(FrostSigningStage.COMPLETE, alice.db.frostSigningSessionDao().getSessionById(reply)?.stage) + assertEquals(2, alice.db.groupInboxDao().getPublicationsFor(reply).size, "Zola's wrap and the group's copy") + } + + @Test + fun `two rotations started at once end as one, on every device`() = runBlocking { + open() + announced() + val alice = device("alice"); val bob = device("bob"); val carol = device("carol") + val first = InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + val second = InboxKeyRitualManager.propose(bob.db, bob.room(), bob.publicKey, bob.secret) + harness.pump() + + val (winner, loser) = if (first.id < second.id) first to second else second to first + listOf(alice, bob, carol).forEach { admin -> + assertEquals(InboxKeyCeremonyStage.COMPLETE, admin.ceremony(winner.id)?.stage, "${admin.name} finished one") + assertEquals(InboxKeyCeremonyStage.FAILED, admin.ceremony(loser.id)?.stage, "${admin.name} ended the other") + assertEquals(listOf(1, 0), admin.keys().map { it.generation }) + } + assertEquals(1, listOf(alice, bob, carol).map { it.keys().first().publicKey }.distinct().size, "one key for everyone") + } + + @Test + fun `nothing is owed while the admins are the ones who made the key`() = runBlocking { + open() + announced() + devices.values.forEach { assertFalse(InboxRotation.isOwed(it.db, it.room(), it.publicKey)) } + devices.values.forEach { assertEquals(0, InboxRotation.pass(it.db, it.publicKey, it.secret)) } + } +} From 31bcb3a3ffd947901eca9bb4d1df4ba5e6ea8f0b Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 02:11:47 +0200 Subject: [PATCH 16/16] docs: the group's inbox is built, and what it chose differently (group-inbox, Phase 10) Marks the plan built behind its flag, with a what-the-plan-said table: the kinds moved to 30410-30416, one publication table, announcements that wait for a ceremony still finishing, watchers who learn the key, wraps routed by key as well as by npub, rotation read off what every device holds with crossing ceremonies settled the same way everywhere. The README row says so, and confederation.md's D5 gets a since note: something can now be encrypted to a group that has an inbox. Not done: the device run. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 2 +- docs/confederation.md | 6 ++++++ docs/group-inbox.md | 36 ++++++++++++++++++++++++++++++++++-- 3 files changed, 41 insertions(+), 3 deletions(-) diff --git a/docs/README.md b/docs/README.md index e9037d6d..c67fcdca 100644 --- a/docs/README.md +++ b/docs/README.md @@ -41,7 +41,7 @@ the [retired](./retired/) notes now. | [dependency-update.md](./dependency-update.md) | moving everything else in the catalogue to its newest stable release, phased and built but for a mac, devices and pushing the submodule branches — why the libraries go first and need no newer Kotlin, why AGP and Kotlin can only move down the whole submodule chain at once, the material3 alpha that was built for an older Compose than the app's, and what has to keep opening on a device afterwards | | [giza-wallet-removal.md](./giza-wallet-removal.md) | taking every wallet out of Giza, phased and built but for moving off the wallet library (7b). Covers why a Giza member declines a Bennu peer's wallet proposal instead of ignoring or signing it, why the wallet's kinds are retired rather than freed, why a recovery phrase stays as a key backup that has to derive the same npub and id byte for byte, and why the threshold crypto keeps the build tied to the wallet library until the last phase | | [group-nostr-profile-and-posts.md](./group-nostr-profile-and-posts.md) | bringing back the group's nostr profile and its posts, ported from Curare, phased and built but for its device run: why it is a port and not a revert of `b21f4c4d`, what Giza does today with a peer's kind:0 or kind:1, why relay lists stay out, why the group's lightning address is kept but never offered, why a broadcast never writes a `NostrEvent` row and sends nothing but those two kinds, and declining what no reader would show | -| [group-inbox.md](./group-inbox.md) | a group that can be written to privately: a phased plan, not built, for NIP-4E on a group's npub. A ChillDKG ceremony at threshold 1 leaves every admin holding the same inbox key, the group announces it in a signed 10044, admins read the NIP-17 messages sent to it, and a reply is a batch of seals the quorum signs before the proposer's device wraps and sends them. Covers why the key is its own ceremony and never a signing key, why the proposal hides the reply from members who are not admins, what every signer checks before signing a seal, and the rotation on every admin change with what it cannot undo | +| [group-inbox.md](./group-inbox.md) | a group that can be written to privately: a phased plan, built but for its device run and behind a flag that is off in release, for NIP-4E on a group's npub. A ChillDKG ceremony at threshold 1 leaves every admin holding the same inbox key, the group announces it in a signed 10044, admins read the NIP-17 messages sent to it, and a reply is a batch of seals the quorum signs before the proposer's device wraps and sends them. Covers why the key is its own ceremony and never a signing key, why the proposal hides the reply from members who are not admins, what every signer checks before signing a seal, and the rotation on every admin change with what it cannot undo | | [giza-app-icon.md](./giza-app-icon.md) | the sphinx icon on iOS, desktop and in the app, phased and built but for the checks on a mac, a phone and Windows — one master SVG and one generator for every raster, why the iOS light icon must carry no alpha channel, why its dark icon is transparent and its tinted one grayscale, the desktop installers and window that show Java's icon today, and why the mark's cutouts need no fill rule | | [member-admin-promotion.md](./member-admin-promotion.md) | making a member an admin and back, phased and built, promotion with a share and demotion with a refresh under the experimental enrollment, under three rules: every admin holds a share, every commit in a keyed room is a proposal until the group's threshold signature is on it, and a robust group keeps at least three admins. Covers why the commit rides inside the group's signature and the rule inside the group's state, which lets every device refuse an unsigned commit with the libraries as they are, why a member's own leave stays exempt, and why a removed admin comes back as an admin when re-invited today | | [admin-change-rotation.md](./admin-change-rotation.md) | an admin change carries its rotation with it: a phased plan, built but for its device session, in which the rotation that follows removing an admin, and the one before a first promotion, asks nobody, because the group's signature on the change already decided who is withheld, and in which admin changes and rotations take turns. Covers the five ways the two overlap today, a removed admin who keeps a live share among them, and the one check a device makes to take part unasked | diff --git a/docs/confederation.md b/docs/confederation.md index 7f740e09..a6d9580f 100644 --- a/docs/confederation.md +++ b/docs/confederation.md @@ -258,6 +258,12 @@ everything else, and D7 makes sure they cannot substitute a roster. ### D5. Encrypting the admin list: a seal every signer can recompute +> **Since [group-inbox.md](./group-inbox.md):** something *can* now be encrypted to a group, +> through the inbox key its admins make and its quorum announces (NIP-4E), and from one, by +> sealing with that key and signing the seal as the group. Only for a group that has set up an +> inbox, and the seal below is unchanged. Whether a confederation should use the inbox is its +> own question. + Nobody holds a group's secret key. So an acceptance **cannot** be NIP-44-encrypted *from* the group in the usual way, because NIP-44's conversation key is an ECDH between the sender's secret and the recipient's pubkey. For the same reason, nothing can be gift-wrapped diff --git a/docs/group-inbox.md b/docs/group-inbox.md index d9ebbf88..ab3e1f67 100644 --- a/docs/group-inbox.md +++ b/docs/group-inbox.md @@ -31,8 +31,40 @@ change already runs, which D14 adds to; and [marmot-direct-messages.md](./marmot-direct-messages.md), for the last time this app built a gift wrap by hand. -**Planned, not built.** Written against `5ac4c053`, on 2026-11-22. Paths starting `K/` are -under `composeApp/src/commonMain/kotlin/mobi/giza/compose/`. +**Built** on `claude/nip4e-group-profiles-38d2ac`, against `5ac4c053`, on 2026-11-22, one commit +per phase (`ccc439b2` to the commit that adds this header), plus one test commit in Phase 8. +Behind `ExperimentalFeatures.groupInbox`, on in development builds and off in release. +jvmTest 1,706, all passing; `m3Audit`, `brandAudit` and `walletAudit` at their budgets; +`compileDebugKotlinAndroid` builds. The phases are kept as written, because they are the +reasoning. Where the build chose differently: + +| what the plan said | what it turned out to be | +|---|---| +| D3: candidate kinds 30390–30396 | **30410–30416**. quartz 2.20.1 has 30392–30395 (experimental trusted lists); Phase 0 found the collision | +| Phase 3: a `GroupInboxOutbound` table for wraps | `GroupInboxPublication`, one table for everything owed to relays: the 10044 and 10050 (D7) and the reply wraps (D10). Phase 5 folded `InboxSigning` (a reply's manifest and a refusal's reason, kept past arrival) and `InboxKeyCeremony.announceRelays` into schema 45, which has not shipped | +| Phase 4: `InboxKeyRitualScreen` | the settings screen's ceremony card (Phase 7): who it waits on, and Abandon | +| Phase 4: transcript lines that say what each step does | three lines a ceremony (started, made, ended). Nobody is asked anything in it, so a ladder per step names nobody whose door to knock on; the ceremony card names them when it stalls | +| (not in the plan) | **an announcement that arrives before this device has finished the same ceremony waits** instead of being declined as a key nobody made. The coordinator asks for the signature the moment its own copy is made, which is routinely before anyone else's; `FrostSigningManager.resumeInboxAnnouncements` looks again when the ceremony finishes here | +| (not in the plan) | **a member who only watches the ceremony learns the key**, by running the coordinator's two aggregations over the public messages, which need no secret. That is what lets a share-holder who is not an admin check a 10044 before signing it | +| Phase 6: catch-up from the newest wrap less two days | no `since`, as the personal inbox has none, and no negentropy pass: the live subscription's `limit` covers reconnection. A device away longer than that window misses mail; the same is true of the personal inbox today | +| Phase 6: the subscription asks for `#p` = the group's npub | and for `#p` = each inbox key this device holds, routing a wrap by its key when it is not tagged with the group. An app that knows only the announcement, and builds its wrap with quartz's `GiftWrapEvent.create`, tags the key it encrypts to | +| Phase 6: `indexNostrEvent` skips a wrap tagged with a group | not needed: the personal subscription asks only for `#p` = the identity, so a group's mail never reaches `storeNostrEvent` | +| Phase 6: the wipe | in `MarmotInboundManager.processGroupMembershipChanges`, and it deletes the inbox's messages and ledger too, with a transcript line said once | +| D10: any admin can **Send again** | offered on the proposer's device, the only one that knows a relay never took the wrap. `InboxReplies.sendAgain` works on any device holding the session's manifest; nothing else offers it yet | +| Phase 8: `FrostSigningScreen` shows the decrypted reply | through the notes the confederation already used, renamed `proposalNotes` (`FrostSigningRepository`, `FrostSigningUIState.notes`). `ProposedEvent` says only "A private reply from the group's inbox", since it has no key to read with | +| Phase 9: `GovernanceFollowThrough` owes an inbox rotation after each change | a rule every device reads off what it holds, `InboxRotation.isOwed`: the newest key was made over admins the room no longer has. The admin whose key sorts first starts it. Run from the governance follow-through and the sweep | +| (not in the plan) | **crossing ceremonies**: two admins who start one at once end in the one whose session id sorts first, on every device, the other ended out loud. A proposal for a generation a device already has is dropped | +| Phase 9: a test that no inbox ceremony starts during a share rotation | the refusal reads `RotationHold` as planned, but the inbox harness runs no share refresh, so it is not tested | +| Phase 0, check 4 in `SignedGroupKeyStateTest` | moved: Phase 8 made a seal nobody can read a decline, so that test now pins the decline, and `InboxReplyJvmTest` checks the premise end to end | +| (not in the plan) | the worktree's build needed `lightning-kmp-app` and its nested submodules initialised from the main checkout's copies, with their `local.properties` and the prebuilt native secp256k1 | + +**Not done:** Phase 10's device run. Nothing here has run on a device or a desktop client: no +inbox has been set up across real devices, no stranger's NIP-17 client has written to one, and no +reply has been opened by a client that follows nostr-protocol/nips#2361 -- or by one that does +not, which is the case D13 warns about and nobody has watched happen. + +Written against `5ac4c053`, on 2026-11-22. Paths starting `K/` are under +`composeApp/src/commonMain/kotlin/mobi/giza/compose/`. ---