diff --git a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/41.json b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/41.json
new file mode 100644
index 00000000..e73bdae8
--- /dev/null
+++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/41.json
@@ -0,0 +1,5337 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 41,
+ "identityHash": "bf310eb98e414f3f739c04a89780af16",
+ "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": "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, `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": "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, `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": "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, 'bf310eb98e414f3f739c04a89780af16')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/42.json b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/42.json
new file mode 100644
index 00000000..18939899
--- /dev/null
+++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/42.json
@@ -0,0 +1,5352 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 42,
+ "identityHash": "ca900fd23a959e4ec66c5ccc50b3c0fd",
+ "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": "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, 'ca900fd23a959e4ec66c5ccc50b3c0fd')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index e248e046..f350245c 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -104,6 +104,39 @@
Key recovery
Learn more
Leave group
+ Couldn't leave the group
+ Member actions
+ Holds a share
+ Make admin
+ Make %1$s an admin?
+ They'll be able to add and remove members, including you, change who the admins are, and disband the group.
+ Remove as admin
+ Remove %1$s as admin?
+ They stay in the group as a member.
+ Step down as admin
+ Step down as admin?
+ You stay in the group as a member. Only an admin can make you one again.
+ Step down
+ Sent; it takes effect once a relay accepts it
+ Leave the group?
+ You're an admin, so you'll step down first, then leave once a relay accepts it.
+ Step down and leave
+ You're the only admin. Pick someone to make an admin before you leave.
+ Make admin and leave
+ Disband group instead
+ Changes to who is in this group need the group's signature. It always keeps at least %1$d admins.
+ Require the group's signature for changes
+ From then on, adding or removing a member, or changing who the admins are, is proposed and has to be signed by the group before it happens.
+ Before changes can need the group's signature, %1$s need to update Giza.
+ They'll be asked to accept, then the group signs it, and they'll hold a share of the group's key and be asked to approve its changes.
+ Once the group signs it, they stay in the group as a member and their share of the group's key is rotated away.
+ Asked; they become an admin once they accept and the group signs it
+ %1$s asked you to become an admin. You'll hold a share of the group's key, and be asked to approve its changes.
+ Accept
+ Accepted; the group signs it next
+ Proposed; it happens once the group signs it
+ Sent; changes will need the group's signature once a relay accepts it
+ Stepping down; you'll leave once a relay accepts it
Remove from group
Disband group
This group was disbanded. Nothing more can be sent into it, and nobody can rejoin.
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 475a6321..f7e64661 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt
@@ -27,6 +27,7 @@ import mobi.giza.compose.database.dao.InReplyToRelationDao
import mobi.giza.compose.database.dao.KeyShareDao
import mobi.giza.compose.database.dao.ShareRefreshDao
import mobi.giza.compose.database.dao.ShareRepairDao
+import mobi.giza.compose.database.dao.GovernanceProposalDao
import mobi.giza.compose.database.dao.MarmotCommitResultDao
import mobi.giza.compose.database.dao.MarmotOutboundDao
import mobi.giza.compose.database.dao.MarmotGroupEventDao
@@ -75,6 +76,7 @@ import mobi.giza.compose.database.model.ShareRefreshMessage
import mobi.giza.compose.database.model.ShareRefreshSession
import mobi.giza.compose.database.model.ShareRepairMessage
import mobi.giza.compose.database.model.ShareRepairSession
+import mobi.giza.compose.database.model.GovernanceProposal
import mobi.giza.compose.database.model.GroupSignedEvent
import mobi.giza.compose.database.model.InReplyToRelation
import mobi.giza.compose.database.model.MarmotCommitResult
@@ -141,6 +143,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
ShareRefreshSession::class,
ShareRepairMessage::class,
ShareRepairSession::class,
+ GovernanceProposal::class,
InReplyToRelation::class,
MarmotCommitResult::class,
MarmotGroupEvent::class,
@@ -170,7 +173,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
UnsignedNostrEvent::class,
Zap::class
],
- version = 40,
+ version = 42,
autoMigrations = [
// v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can
// generate the migration itself — nothing existing changes shape.
@@ -427,6 +430,14 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
// ShareRepairSession and ShareRepairMessage tables, and the nullable
// GroupKeyState.memberBindings. Room generates it.
AutoMigration(from = 39, to = 40),
+ // v41 adds GovernanceProposal (docs/member-admin-promotion.md, Phase 5): a
+ // change this device proposed to a governed room, held while the group signs
+ // it. One new table, so Room generates it.
+ AutoMigration(from = 40, to = 41),
+ // v42 adds GovernanceProposal.thenRotateWithout and ShareRepairSession.nParticipants
+ // (docs/member-admin-promotion.md, Phases 8 and 9): two nullable columns, so
+ // Room generates it.
+ AutoMigration(from = 41, to = 42),
]
)
@ConstructedBy(GizaDatabaseConstructor::class)
@@ -464,6 +475,7 @@ abstract class GizaDatabase: RoomDatabase() {
abstract fun shareRefreshDao(): ShareRefreshDao
abstract fun shareRepairDao(): ShareRepairDao
+ abstract fun governanceProposalDao(): GovernanceProposalDao
abstract fun groupSignedEventDao(): GroupSignedEventDao
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GovernanceProposalDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GovernanceProposalDao.kt
new file mode 100644
index 00000000..2323e150
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GovernanceProposalDao.kt
@@ -0,0 +1,28 @@
+package mobi.giza.compose.database.dao
+
+import androidx.room3.Dao
+import androidx.room3.Query
+import androidx.room3.Upsert
+import mobi.giza.compose.database.model.GovernanceProposal
+
+/** Changes this device proposed to a governed room (docs/member-admin-promotion.md, Phase 5). */
+@Dao
+interface GovernanceProposalDao {
+ @Query("SELECT * FROM GovernanceProposal WHERE id = :id")
+ suspend fun getById(id: String): GovernanceProposal?
+
+ @Query("SELECT * FROM GovernanceProposal WHERE frostSigningSessionId = :sessionId")
+ suspend fun getBySession(sessionId: String): List
+
+ @Query("SELECT * FROM GovernanceProposal WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC")
+ suspend fun getForRoom(chatRoomId: String): List
+
+ @Upsert
+ suspend fun upsert(proposal: GovernanceProposal)
+
+ @Query("SELECT * FROM GovernanceProposal ORDER BY createdAt ASC")
+ fun observeAll(): kotlinx.coroutines.flow.Flow>
+
+ @Query("SELECT * FROM GovernanceProposal ORDER BY createdAt ASC")
+ suspend fun getAll(): List
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotInnerEventDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotInnerEventDao.kt
index 2a2dade6..5bf826e0 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotInnerEventDao.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotInnerEventDao.kt
@@ -69,6 +69,12 @@ interface MarmotInnerEventDao {
@Query("SELECT COUNT(*) FROM MarmotInnerEvent WHERE chatRoomId = :chatRoomId AND kind IN (:kinds)")
fun observeCountByChatRoomAndKinds(chatRoomId: String, kinds: List): Flow
+ @Query("SELECT * FROM MarmotInnerEvent WHERE kind IN (:kinds) ORDER BY createdAt ASC")
+ suspend fun getByKinds(kinds: List): List
+
+ @Query("SELECT COUNT(*) FROM MarmotInnerEvent WHERE kind IN (:kinds)")
+ fun observeCountByKinds(kinds: List): Flow
+
@Query("DELETE FROM MarmotInnerEvent WHERE id = :id")
suspend fun deleteById(id: String)
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt
index 9f98ea80..7f2378a7 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt
@@ -4,10 +4,13 @@ import androidx.room3.Dao
import androidx.room3.Transaction
import co.touchlab.kermit.Logger
import com.vitorpamplona.crypto.random.RandomInstance
+import com.vitorpamplona.marmot.appComponents.AdminPolicyV1
import com.vitorpamplona.marmot.appComponents.AppComponentIds
+import com.vitorpamplona.marmot.appComponents.GroupProfileV1
+import com.vitorpamplona.marmot.appComponents.GroupLifecycleV1
+import com.vitorpamplona.mls.components.ComponentsList
import com.vitorpamplona.marmot.foundation.appEvents.MarmotAppEvent
import com.vitorpamplona.marmot.groups.MlsGroupManager
-import com.vitorpamplona.marmot.appComponents.AdminPolicyV1
import com.vitorpamplona.marmot.groups.currentAdminIdentities
import com.vitorpamplona.marmot.groups.currentGroupState
import com.vitorpamplona.marmot.groups.isLocalAdmin
@@ -58,8 +61,18 @@ import mobi.giza.compose.exceptions.MarmotMissingChatGroupException
import mobi.giza.compose.extensions.exporterSecret
import mobi.giza.compose.extensions.shortened
import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.managers.AdminFlags
+import mobi.giza.compose.managers.AdminGovernance
+import mobi.giza.compose.managers.ShareRefreshManager
+import mobi.giza.compose.managers.PromotionManager
+import mobi.giza.compose.ExperimentalFeatures
+import mobi.giza.compose.managers.GovernanceGate
+import mobi.giza.compose.managers.GovernanceManager
+import mobi.giza.compose.managers.GovernanceMarker
+import mobi.giza.compose.managers.GovernanceSupport
import mobi.giza.compose.managers.ChronicleManager
import mobi.giza.compose.managers.MarmotGroupFactory
+import mobi.giza.compose.managers.MarmotInboundManager
import mobi.giza.compose.managers.MarmotInboundManager.EPOCH_RETENTION_WINDOW
import mobi.giza.compose.nostr.MarmotDelivery
import mobi.giza.compose.nostr.MarmotDirectMessage
@@ -138,6 +151,9 @@ abstract class MarmotOutboundDao(
)
)
)
+ // The creator administers the room from epoch 0, and this device learns that
+ // nowhere else. docs/member-admin-promotion.md, Phase 1.
+ AdminFlags.reconcile(database, chatRoom.id, mlsGroup)
// Invite peer. On the current profile the manager owns the group from the row
// just written, and the invite moves that instance rather than the one the
@@ -630,6 +646,18 @@ abstract class MarmotOutboundDao(
"An earlier change to this room is still waiting for a relay to accept it; try again in a moment"
)
}
+ // A governed room: proposed and signed by the group; the Welcome goes out
+ // once a relay accepts the carried commit, as it does for a bare one.
+ // docs/member-admin-promotion.md, Phase 5.
+ if (!isOneMemberInitialGroupCreation && GovernanceGate.isGoverned(mlsGroup)) {
+ val room = database.chatRoomDao().findChatRoomById(chatRoomId)
+ ?: throw MarmotMissingChatGroupException("No room $chatRoomId")
+ GovernanceManager.propose(
+ database, room, userPublicKey, peerKeyPackageEventId = peerKeyPackage.id,
+ propose = GovernanceManager.addition(peerKeyPackage.tlsEncodedMarmotKeyPackage),
+ )
+ return
+ }
engine.awaitSettled(routingId)
val staged = engine.groupManager.stageAddMember(routingId, peerKeyPackage.tlsEncodedMarmotKeyPackage)
if (isOneMemberInitialGroupCreation) {
@@ -838,6 +866,13 @@ abstract class MarmotOutboundDao(
if (!group.isLocalAdmin() || !engine.groupManager.hasPendingProposals(routingId)) return
if (!engine.gate.canPrepareLocalCommit(routingId)) return
+ // In a governed room a member's leave is committed inside this account's own
+ // envelope, not bare (docs/member-admin-promotion.md, D6).
+ if (GovernanceGate.isGoverned(group)) {
+ GovernanceManager.publishOwnCommit(database, localChatRoom)
+ return
+ }
+
publishGatedCommit(localChatRoom) { manager, id -> manager.stageCommit(id) }
}
@@ -849,20 +884,244 @@ abstract class MarmotOutboundDao(
* every other from the commit -- so every device says the same thing at the
* same point. The library's admin-depletion guard refuses a commit that would
* leave no admin in the tree.
+ *
+ * An admin is taken off the admin list first, by a commit of its own, and
+ * removed once that one is confirmed. A bare `Remove` left their key on the
+ * list, so inviting them back made them an admin again with nobody having
+ * said so -- and `AdminPolicyV1` says a commit removing an account's last leaf
+ * must drop its key. Two commits until the library can stage both proposals
+ * in one (docs/member-admin-promotion.md, Phase 0, step 5); if the second is
+ * lost to a restart, the member is left demoted, and removing them again is
+ * one commit.
*/
@Transaction
open suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) {
require(localChatRoom.chatRoom.marmotProfile() == MarmotProfile.CURRENT) { "Only a current-profile room can remove a member" }
- val group = database.marmotEngine.groupFor(localChatRoom.routingId)
+ val engine = database.marmotEngine
+ val group = engine.groupFor(localChatRoom.routingId)
?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}")
val leafIndex = group.members()
.firstOrNull { (_, leaf) -> (leaf.credential as? Credential.Basic)?.identity?.toHexKey() == memberPublicKey }
?.first
?: throw IllegalArgumentException("$memberPublicKey is not in the group")
+ // A robust group keeps at least three admins, and never fewer than its
+ // quorum: they are its share holders. docs/member-admin-promotion.md, R3.
+ val floor = AdminGovernance.adminFloor(database, localChatRoom.chatRoom.id, group)
+ if (!AdminGovernance.keepsFloor(group, memberPublicKey, floor)) {
+ throw IllegalStateException("A group with a shared key needs at least $floor admins, so ${memberName(memberPublicKey)} can't be removed")
+ }
+
+ // A governed room: one change, proposed and signed by the group -- the
+ // removal and, for an admin, their admin entry in the same commit, which a
+ // copy of the group can build where the manager cannot.
+ // docs/member-admin-promotion.md, Phase 5.
+ if (GovernanceGate.isGoverned(group)) {
+ val admins = group.currentAdminIdentities()
+ GovernanceManager.propose(
+ database, localChatRoom, localChatRoom.chatRoom.userPublicKey,
+ thenRotateWithout = memberPublicKey.takeIf { holdsLiveShare(localChatRoom, it) },
+ propose = GovernanceManager.removal(leafIndex, memberPublicKey, admins),
+ )
+ return
+ }
+
+ if (memberPublicKey in group.currentAdminIdentities()) {
+ thenAfterConfirmed(localChatRoom, publish = { publishAdmins(localChatRoom) { admins -> admins - memberPublicKey } }) {
+ database.chatRoomDao().findChatRoomById(localChatRoom.chatRoom.id)
+ ?.let { removeMember(it, memberPublicKey) }
+ }
+ return
+ }
+
publishGatedCommit(localChatRoom) { manager, id -> manager.stageRemoveMember(id, leafIndex) }
}
+ /**
+ * Makes [memberPublicKey] an admin of a room this device administers, by one
+ * commit through the publish gate. Nothing happens for someone who already is.
+ *
+ * Refused in a keyed room, whose admins change only with the group's signature
+ * and a share of its key (docs/member-admin-promotion.md, R1 and R2), and for
+ * someone who is not in the tree: an admin with no leaf is not valid state.
+ * The line saying so is written when the commit is applied, on every device.
+ * docs/member-admin-promotion.md, Phase 6.
+ */
+ @Transaction
+ open suspend fun promote(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) {
+ val group = governedGroup(localChatRoom)
+ if (memberPublicKey in group.currentAdminIdentities()) return
+ // A keyed room: an offer the member accepts, then the group signs the change
+ // and the key state that gives them a share (docs/member-admin-promotion.md,
+ // Phase 8).
+ if (AdminGovernance.isKeyedRoom(group)) {
+ check(AdminGovernance.keyedChangesAllowed(group)) { KEYED_ROOM_REFUSAL }
+ PromotionManager.offer(database, localChatRoom, localChatRoom.chatRoom.userPublicKey, memberPublicKey)
+ return
+ }
+ if (memberPublicKey !in AdminGovernance.members(group)) {
+ throw IllegalArgumentException("${memberName(memberPublicKey)} is not in the group any more")
+ }
+
+ publishAdmins(localChatRoom) { admins -> admins + memberPublicKey }
+ }
+
+ /**
+ * Makes [adminPublicKey] stop being an admin of a room this device administers,
+ * by one commit through the publish gate. Nothing happens for someone who is not
+ * one. [adminPublicKey] may be this device's own account, which is stepping down.
+ *
+ * Refused in a keyed room, as [promote] is, and where it would leave no admin
+ * among the members -- the commit every peer refuses as admin depletion, said
+ * here in words that name the fix. docs/member-admin-promotion.md, Phase 6.
+ */
+ @Transaction
+ open suspend fun demote(localChatRoom: LocalChatRoom, adminPublicKey: HexKey) {
+ val group = governedGroup(localChatRoom)
+ if (adminPublicKey !in group.currentAdminIdentities()) return
+
+ // A keyed room: proposed for the group's signature, and their share rotated
+ // away once it lands (docs/member-admin-promotion.md, Phase 9).
+ if (AdminGovernance.isKeyedRoom(group)) {
+ check(AdminGovernance.keyedChangesAllowed(group)) { KEYED_ROOM_REFUSAL }
+ check(adminPublicKey != localChatRoom.chatRoom.userPublicKey) {
+ "In a group with a shared key, another admin removes you as admin, so the group can rotate your share away"
+ }
+ val floor = AdminGovernance.adminFloor(database, localChatRoom.chatRoom.id, group)
+ if (!AdminGovernance.keepsFloor(group, adminPublicKey, floor)) {
+ throw IllegalStateException("A group with a shared key needs at least $floor admins. Make someone else an admin first")
+ }
+ val admins = group.currentAdminIdentities()
+ GovernanceManager.propose(
+ database, localChatRoom, localChatRoom.chatRoom.userPublicKey,
+ thenRotateWithout = adminPublicKey.takeIf { holdsLiveShare(localChatRoom, it) },
+ ) { copy ->
+ copy.proposeAppDataUpdate(AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(admins - adminPublicKey).encode())
+ }
+ return
+ }
+ if (!AdminGovernance.canDemote(group, localChatRoom.chatRoom.userPublicKey, adminPublicKey)) {
+ throw IllegalStateException(
+ if (adminPublicKey == localChatRoom.chatRoom.userPublicKey) "You're the only admin. Make someone else an admin first"
+ else "${memberName(adminPublicKey)} is the only admin. Make someone else an admin first"
+ )
+ }
+
+ publishAdmins(localChatRoom) { admins -> admins - adminPublicKey }
+ }
+
+ /**
+ * Leaves a convenient room this device administers, which an admin cannot do
+ * directly: the library refuses an admin's SelfRemove. Steps down first and
+ * leaves once that commit is accepted -- and, for the only admin, makes [heir]
+ * an admin before that, so the room is never left with nobody to govern it.
+ *
+ * The chain is held in memory ([MarmotEngine.afterConfirmed]). A restart part
+ * way through leaves this device a member that has not left, possibly no
+ * longer an admin, and **Leave group** finishes it. See
+ * docs/member-admin-promotion.md, Phase 10.
+ */
+ @Transaction
+ open suspend fun stepDownAndLeave(localChatRoom: LocalChatRoom, heir: HexKey?) {
+ val me = localChatRoom.chatRoom.userPublicKey
+ val roomId = localChatRoom.chatRoom.id
+ val group = database.marmotEngine.groupFor(localChatRoom.routingId)
+ ?: throw MarmotMissingChatGroupException("No live group for $roomId")
+ suspend fun fresh() = database.chatRoomDao().findChatRoomById(roomId)
+ val leaveOnceAccepted: suspend () -> Unit = { fresh()?.let { leave(it) } }
+ val admins = group.currentAdminIdentities()
+
+ when {
+ // Nothing to step down from: leave as any member does.
+ me !in admins -> leave(localChatRoom)
+
+ heir == null || heir in admins ->
+ thenAfterConfirmed(localChatRoom, publish = { demote(localChatRoom, me) }, step = leaveOnceAccepted)
+
+ else -> thenAfterConfirmed(localChatRoom, publish = { promote(localChatRoom, heir) }) {
+ fresh()?.let { room -> thenAfterConfirmed(room, publish = { demote(room, me) }, step = leaveOnceAccepted) }
+ }
+ }
+ }
+
+ /**
+ * Publishes a commit with [publish] and runs [step] once a relay accepts it. The
+ * step is registered first, so the acceptance cannot overtake it, and taken back
+ * if [publish] throws, so a refused change leaves nothing waiting.
+ */
+ private suspend fun thenAfterConfirmed(localChatRoom: LocalChatRoom, publish: suspend () -> Unit, step: suspend () -> Unit) {
+ val engine = database.marmotEngine
+ engine.afterConfirmed(localChatRoom.routingId, step)
+ try {
+ publish()
+ } catch (e: Throwable) {
+ engine.cancelFollowUp(localChatRoom.routingId)
+ throw e
+ }
+ }
+
+ /**
+ * Makes a keyed room's changes need the group's signature from the next epoch:
+ * one ordinary commit adding [GovernanceMarker]'s line to the profile
+ * description, with the floor the room's quorum sets. It is the room's last bare
+ * commit, and every device that applies it enforces the rule from the state it
+ * just applied. docs/member-admin-promotion.md, D4 and Phase 4b.
+ *
+ * Refused while any member has not said their device can follow signed commits
+ * -- they would be left in a different group by the first change -- and while
+ * the room has fewer admins than the floor it would set.
+ */
+ @Transaction
+ open suspend fun requireSignatures(localChatRoom: LocalChatRoom) {
+ val group = governedGroup(localChatRoom)
+ val roomId = localChatRoom.chatRoom.id
+ check(AdminGovernance.isKeyedRoom(group)) { "Only a group with a shared key can require its signature" }
+ if (GovernanceGate.isGoverned(group)) return
+ val missing = GovernanceSupport.missing(database, roomId, group)
+ if (missing.isNotEmpty()) {
+ throw IllegalStateException("Waiting for ${missing.map { memberName(it) }.sorted().joinToString()} to update Giza")
+ }
+ val floor = AdminGovernance.adminFloor(database, roomId, group)
+ val admins = group.currentAdminIdentities() intersect AdminGovernance.members(group)
+ check(admins.size >= floor) { "A group with a shared key needs at least $floor admins first" }
+
+ publishGatedCommit(localChatRoom) { manager, id ->
+ val live = manager.getGroup(id) ?: throw MarmotMissingChatGroupException("No live group for $id")
+ val profile = live.currentGroupState().profile ?: throw IllegalStateException("The group has no profile to record the rule in")
+ manager.stageAppDataUpdate(
+ id,
+ GroupProfileV1.COMPONENT_ID,
+ GroupProfileV1(profile.name, GovernanceMarker.describe(profile.description, floor)).encode(),
+ )
+ }
+ }
+
+ /** Whether [memberPublicKey] holds a live share of the room's key, with rotation on. */
+ private suspend fun holdsLiveShare(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): Boolean =
+ ExperimentalFeatures.shareRefresh &&
+ runCatching { ShareRefreshManager.liveIdOf(database, localChatRoom, memberPublicKey) != null }.getOrDefault(false)
+
+ /** The room's live group, when this device may change who administers it. */
+ private suspend fun governedGroup(localChatRoom: LocalChatRoom): MlsGroup {
+ require(localChatRoom.chatRoom.marmotProfile() == MarmotProfile.CURRENT) { "Only a current-profile room has admins to change" }
+ val group = database.marmotEngine.groupFor(localChatRoom.routingId)
+ ?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}")
+ check(group.isLocalAdmin()) { "Only an admin can change who the admins are" }
+ return group
+ }
+
+ /**
+ * Commits the room's admin list as [change] makes it from the list the group
+ * holds at the moment the commit is staged -- after any convergence pass has
+ * settled -- rather than from one read before the wait.
+ */
+ private suspend fun publishAdmins(localChatRoom: LocalChatRoom, change: (Set) -> Set) {
+ publishGatedCommit(localChatRoom) { manager, id ->
+ val live = manager.getGroup(id) ?: throw MarmotMissingChatGroupException("No live group for $id")
+ manager.stageAppDataUpdate(id, AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(change(live.currentAdminIdentities())).encode())
+ }
+ }
+
/**
* Adds [publicKeys] to a current-profile room's admin policy, as an admin.
*
@@ -882,6 +1141,17 @@ abstract class MarmotOutboundDao(
val added = publicKeys - current
if (added.isEmpty()) return
+ // A governed room's admins change only with the group's signature, so the
+ // repair is proposed rather than committed. The founders it adds took part
+ // in the ceremony and hold shares of the key, as R1 asks of every admin.
+ // docs/member-admin-promotion.md, Phase 5.
+ if (GovernanceGate.isGoverned(group)) {
+ GovernanceManager.propose(database, localChatRoom, localChatRoom.chatRoom.userPublicKey) { copy ->
+ copy.proposeAppDataUpdate(AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(current + added).encode())
+ }
+ return
+ }
+
val policy = AdminPolicyV1.ofHex(current + added).encode()
publishGatedCommit(localChatRoom) { manager, id ->
manager.stageAppDataUpdate(id, AdminPolicyV1.COMPONENT_ID, policy)
@@ -905,6 +1175,19 @@ abstract class MarmotOutboundDao(
val group = engine.groupFor(routingId)
?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}")
require(group.isLocalAdmin()) { "Only an admin can disband the group" }
+
+ // A governed room ends only with the group's signature. One that has not yet
+ // agreed it can be disbanded agrees to that first, as its own signed change.
+ if (GovernanceGate.isGoverned(group)) {
+ val me = localChatRoom.chatRoom.userPublicKey
+ if (group.currentGroupState().requires(AppComponentIds.GROUP_LIFECYCLE_V1)) {
+ GovernanceManager.propose(database, localChatRoom, me, propose = GovernanceManager.disbanding)
+ return
+ }
+ GovernanceManager.propose(database, localChatRoom, me, propose = GovernanceManager.enablingDisbanding)
+ throw IllegalStateException("The group first has to agree it can be disbanded, and that has been proposed. Disband again once the group has signed it")
+ }
+
if (!engine.gate.canPrepareLocalCommit(routingId)) {
throw MarmotCommitPendingException(
"An earlier change to this room is still waiting for a relay to accept it; try again in a moment"
@@ -1361,5 +1644,9 @@ abstract class MarmotOutboundDao(
companion object {
const val TAG = "MarmotOutboundDao"
+
+ /** Why a keyed room's admins cannot be changed by one admin's commit yet. */
+ const val KEYED_ROOM_REFUSAL =
+ "This group's admins hold shares of its key, so changing them needs the group's signature. That isn't built yet"
}
}
\ No newline at end of file
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 7facdce2..54941a19 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
@@ -5,6 +5,13 @@ import androidx.room3.Transaction
import co.touchlab.kermit.Logger
import com.vitorpamplona.marmot.GroupEventResult
import com.vitorpamplona.marmot.groups.MarmotGroupPolicy
+import com.vitorpamplona.marmot.groups.currentAdminIdentities
+import mobi.giza.compose.managers.GovernanceGate
+import mobi.giza.compose.managers.GovernanceSupport
+import mobi.giza.compose.nostr.frost.GovernanceSupportEvent
+import mobi.giza.compose.nostr.frost.GovernanceEvents
+import mobi.giza.compose.nostr.frost.GovernanceCarrierEvent
+import mobi.giza.compose.nostr.frost.OwnCommitEvent
import com.vitorpamplona.marmot.groups.currentGroupState
import com.vitorpamplona.marmot.groups.currentMarmotData
import com.vitorpamplona.marmot.groups.currentNostrGroupId
@@ -17,6 +24,7 @@ import com.vitorpamplona.quartz.marmot.mip00KeyPackages.KeyPackageRelayListEvent
import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent
import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent
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.metadata.MetadataEvent
@@ -78,6 +86,7 @@ import mobi.giza.compose.managers.roomId
import mobi.giza.compose.managers.roomName
import mobi.giza.compose.managers.routingId
import mobi.giza.compose.nostr.MarmotProfile
+import mobi.giza.compose.extensions.exporterSecret
import mobi.giza.compose.nostr.Relays
import mobi.giza.compose.nostr.dkg.DkgRitualEvents
import mobi.giza.compose.nostr.frost.ShareRefreshEvents
@@ -1412,10 +1421,15 @@ abstract class NostrDao(
}
}
+ /**
+ * @param authorized true for a commit [GovernanceGate.admit] has let through out
+ * of its envelope, which the bare-commit check below must not then drop.
+ */
private suspend fun indexCurrentProfileGroupEvent(
groupEvent: GroupEvent,
localChatRoom: LocalChatRoom,
activeKeyPair: KeyPair,
+ authorized: Boolean = false,
) {
val chatRoomId = localChatRoom.chatRoom.id
val routingId = groupEvent.groupId()
@@ -1428,8 +1442,27 @@ abstract class NostrDao(
throw MarmotNotMemberOfChatGroupException("We are not a member of the chat room $chatRoomId")
}
+ // In a room whose state says its changes need the group's signature, a
+ // commit sent bare is dropped before the engine sees it: only one that came
+ // out of a checked envelope is applied. docs/member-admin-promotion.md, R2.
+ if (!authorized && GovernanceGate.isGoverned(mlsGroup)) {
+ val outerKeys = listOf(mlsGroup.exporterSecret()) + engine.groupManager.retainedExporterSecrets(routingId)
+ if (GovernanceGate.isBareCommit(groupEvent, outerKeys)) {
+ logger.w("Dropped an unsigned commit ${groupEvent.id.take(8)}… into governed room ${chatRoomId.take(8)}…")
+ // Filed, so its line is replaced rather than repeated when a relay
+ // hands it over again.
+ upsertMarmotGroupEvent(groupEvent, chatRoomId, activeKeyPair)
+ announceChangeNotApplied(chatRoomId, activeKeyPair, groupEvent.id, "A change arrived without the group's signature, so it was not applied")
+ return
+ }
+ }
+
upsertMarmotGroupEvent(groupEvent, chatRoomId, activeKeyPair)
+ // Who administered the room before this event, for the captions a commit's
+ // change to it earns. A copy, taken before the engine moves the group.
+ val priorAdmins = mlsGroup.currentAdminIdentities()
+
// Through the engine, not the processor: an application message is the one
// result that moves state the library writes nothing for, and the engine is
// where that write is. The processor names the group by its address; every
@@ -1444,6 +1477,7 @@ abstract class NostrDao(
activeKeyPair = activeKeyPair,
// The live group the manager holds, which the commit just moved.
mlsGroup = engine.groupManager.getGroup(routingId) ?: mlsGroup,
+ priorAdmins = priorAdmins,
)
// A commit that forked the group opened a pass, and a quiet group has
@@ -1488,6 +1522,8 @@ abstract class NostrDao(
if (memberPubkeys.contains(activeKeyPair.pubKey.toHex())) {
upsertMarmotGroupEvent(groupEvent, chatRoomId, activeKeyPair)
+ // Before processing moves this very instance.
+ val priorAdmins = mlsGroup.currentAdminIdentities()
MarmotInboundManager.processGroupEvent(
database = database,
activeKeyPair = activeKeyPair,
@@ -1503,6 +1539,7 @@ abstract class NostrDao(
groupEventResult = groupEventResult,
activeKeyPair = activeKeyPair,
mlsGroup = mlsGroup,
+ priorAdmins = priorAdmins,
)
}
} else {
@@ -1551,13 +1588,15 @@ abstract class NostrDao(
groupEventResult: GroupEventResult,
activeKeyPair: KeyPair,
mlsGroup: MlsGroup,
+ priorAdmins: Set? = null,
) {
when(groupEventResult) {
is GroupEventResult.CommitProcessed -> {
MarmotInboundManager.processGroupMembershipChanges(
database = database,
mlsGroup = mlsGroup,
- localChatRoom = localChatRoom
+ localChatRoom = localChatRoom,
+ priorAdmins = priorAdmins,
)
}
// A member's standalone proposal -- their SelfRemove -- sits in the
@@ -1654,6 +1693,25 @@ abstract class NostrDao(
nostrPrivateKey = activeKeyPair.privKey!!
)
+ // A change to a governed room, inside the group's signature or,
+ // for a member's own leave, its committer's. Checked, and its
+ // commit applied, only here (docs/member-admin-promotion.md).
+ // Another member says their device follows signed commits:
+ // this one says so back, once, so that a member who never
+ // opens the room's screen is still counted (Phase 4b).
+ innerEvent.kind == GovernanceSupportEvent.KIND ->
+ if (localChatRoom.chatRoom.marmotProfile() == MarmotProfile.CURRENT) {
+ database.marmotEngine.groupFor(localChatRoom.routingId)?.let { group ->
+ GovernanceSupport.announce(database, localChatRoom.chatRoom.id, group, activeKeyPair.pubKey.toHex())
+ }
+ }
+
+ innerEvent.kind == OwnCommitEvent.KIND ->
+ admitEnvelopedCommit(localChatRoom, innerEvent, activeKeyPair)
+ innerEvent.kind == GovernanceCarrierEvent.KIND ->
+ GovernanceCarrierEvent.statementOf(innerEvent)
+ ?.let { admitEnvelopedCommit(localChatRoom, it, activeKeyPair) }
+
// Nothing for the group Lightning wallet's kinds: Giza takes no
// part in it, so a Bennu member's ceremony, co-signing and node
// traffic are filed and ignored. docs/giza-wallet-removal.md.
@@ -1662,6 +1720,72 @@ abstract class NostrDao(
}
}
+ /**
+ * Applies the commit [envelope] carries, if [GovernanceGate.admit] says the room
+ * may; otherwise says in the room why not. The commit is handed to the engine as
+ * the event it is -- the proposer's own kind:445, byte for byte -- so every device
+ * applies the same event with the same id.
+ *
+ * Nothing for an envelope around this device's own commit: the proposer installs
+ * its staged state when a relay accepts the envelope, and cannot process its own
+ * commit in any case.
+ */
+ private suspend fun admitEnvelopedCommit(localChatRoom: LocalChatRoom, envelope: Event, activeKeyPair: KeyPair) {
+ if (localChatRoom.chatRoom.marmotProfile() != MarmotProfile.CURRENT) return
+ val engine = database.marmotEngine
+ val group = engine.groupFor(localChatRoom.routingId) ?: return
+ if (!GovernanceGate.isGoverned(group)) return
+ val inner = GovernanceEvents.innerCommitOf(envelope)
+ // This device's own commit, or one already applied: the same envelope can
+ // arrive twice -- carried by two members, or repeated by a relay -- and the
+ // second is not news, nor a refusal.
+ if (inner != null && database.marmotCommitResultDao().getMarmotCommitRequestById(inner.id) != null) return
+ if (inner != null && database.marmotGroupEventDao().getMarmotGroupEventById(inner.id) != null) return
+
+ GovernanceGate.admit(group, localChatRoom.chatRoom.id, envelope).fold(
+ onSuccess = { commit ->
+ val fresh = database.chatRoomDao().findChatRoomById(localChatRoom.chatRoom.id) ?: return
+ // Stored as the event it is, as if a relay had handed it over: the
+ // room's group events are kept against their nostr rows.
+ database.nostrEventDao().upsert(
+ NostrEvent(
+ id = commit.id,
+ createdAt = Instant.fromEpochSeconds(commit.createdAt),
+ content = commit.content,
+ sig = commit.sig,
+ tags = commit.tags,
+ kind = commit.kind,
+ pubKey = commit.pubKey,
+ )
+ )
+ indexCurrentProfileGroupEvent(commit, fresh, activeKeyPair, authorized = true)
+ },
+ onFailure = { refusal ->
+ logger.w("Refused envelope ${envelope.id.take(8)}…: ${refusal.message}")
+ announceChangeNotApplied(localChatRoom.chatRoom.id, activeKeyPair, null, "A change was not applied: ${refusal.message}")
+ },
+ )
+ }
+
+ /**
+ * A line saying a change to the room was refused -- once per group event, when
+ * [eventId] names the one that carried it.
+ */
+ private suspend fun announceChangeNotApplied(chatRoomId: String, activeKeyPair: KeyPair, eventId: HexKey?, content: String) {
+ persistMarmotChatMessage(
+ ChatMessage(
+ content = content,
+ messageType = ChatMessage.TYPE_CHANGE_NOT_APPLIED,
+ chatRoomId = chatRoomId,
+ senderPublicKey = activeKeyPair.pubKey.toHex(),
+ isUserMessage = true,
+ giftWrapPayloadId = null,
+ marmotGroupEventId = eventId,
+ marmotInnerEventId = null,
+ )
+ )
+ }
+
/**
* Files the chat line a kind:445 produced, replacing the line that event
* already has rather than adding a second one. The rule for which of the two
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 ef1c736b..9eba3761 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
@@ -38,6 +38,7 @@ import mobi.giza.compose.nostr.MarmotDirectMessage
import mobi.giza.compose.nostr.chronicle.ChronicleEvent
import mobi.giza.compose.nostr.chronicle.ChronicleRequestEvent
import mobi.giza.compose.nostr.dkg.DkgRitualEvents
+import mobi.giza.compose.nostr.frost.GovernanceEvents
import mobi.giza.compose.nostr.frost.ShareRefreshEvents
import mobi.giza.compose.nostr.frost.ShareRepairEvents
import mobi.giza.compose.nostr.frost.FrostSigningEvents
@@ -570,6 +571,28 @@ data class ChatMessage(
const val TYPE_MEMBER_LEFT = "memberLeft"
const val TYPE_GROUP_DISBANDED = "groupDisbanded"
+ /**
+ * A member became an admin, or stopped being one -- derived like the lines
+ * above, from the group's admin set before and after a commit, on every
+ * device that applies it. docs/member-admin-promotion.md, Phase 2.
+ */
+ const val TYPE_ADMIN_ADDED = "adminAdded"
+ const val TYPE_ADMIN_REMOVED = "adminRemoved"
+
+ /**
+ * An offer to make a member an admin of a keyed room, or their answer to one:
+ * this device's own account of what it asked or said, before the group signs
+ * anything. docs/member-admin-promotion.md, Phase 8.
+ */
+ const val TYPE_ADMIN_OFFERED = "adminOffered"
+
+ /**
+ * A change to a governed room that this device refused: a commit sent bare,
+ * or an envelope whose check failed. Every device refuses the same ones,
+ * so every device says so. docs/member-admin-promotion.md, Phase 4a.
+ */
+ const val TYPE_CHANGE_NOT_APPLIED = "changeNotApplied"
+
/**
* A change this device asked for that every relay refused, so the line
* written when it was asked for -- a removal, a disband -- did not come
@@ -598,6 +621,10 @@ data class ChatMessage(
TYPE_MEMBER_ADDED,
TYPE_MEMBER_LEFT,
TYPE_GROUP_DISBANDED,
+ TYPE_ADMIN_ADDED,
+ TYPE_ADMIN_REMOVED,
+ TYPE_ADMIN_OFFERED,
+ TYPE_CHANGE_NOT_APPLIED,
TYPE_CHANGE_REJECTED,
TYPE_FOUNDING_ADMINS_MISSING,
)
@@ -894,7 +921,8 @@ data class ChatMessage(
event.kind in DkgRitualEvents.ALL ||
event.kind in FrostSigningEvents.ALL ||
event.kind in ShareRefreshEvents.ALL ||
- event.kind in ShareRepairEvents.ALL
+ event.kind in ShareRepairEvents.ALL ||
+ event.kind in GovernanceEvents.ALL
)
database.marmotInnerEventDao().upsert(
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GovernanceProposal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GovernanceProposal.kt
new file mode 100644
index 00000000..02735680
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GovernanceProposal.kt
@@ -0,0 +1,85 @@
+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 kotlin.time.Clock
+import kotlin.time.Instant
+import mobi.giza.compose.database.model.traits.LocalStoreEntity
+import mobi.giza.compose.database.model.traits.TimestampedEntity
+
+/**
+ * A change this device proposed to a governed room, held while the group signs it.
+ * docs/member-admin-promotion.md, Phase 5.
+ *
+ * The commit is built when the change is proposed -- the group signs the very
+ * kind:445 that carries it -- and this device cannot process its own commit, so the
+ * state the commit leads to has to be kept from then until a relay accepts it.
+ * Signing outlasts a session, so it is kept here rather than in memory.
+ *
+ * Only the proposer's device has one; every other device learns of the change from
+ * the signing session and applies it from the carried envelope.
+ */
+@Entity(
+ foreignKeys = [
+ ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE)
+ ],
+ indices = [Index("chatRoomId"), Index("frostSigningSessionId"), Index("commitEventId")],
+)
+data class GovernanceProposal(
+ /** The unsigned statement's id: what the group signs. */
+ @PrimaryKey
+ val id: HexKey,
+ val chatRoomId: String,
+ val routingId: HexKey,
+ /** The epoch the commit is built at, and the only one it can land at. */
+ val epoch: Long,
+ val frostSigningSessionId: String,
+ /** The kind:445 that carries the commit, as JSON, exactly as it was built. */
+ val commitEventId: HexKey,
+ val commitEventJson: String,
+ /**
+ * The invitee's key package event, for an add, so the Welcome goes to the right
+ * package. The commit's own parts -- its bytes, its Welcome, its outer key -- are
+ * in the `MarmotCommitResult` filed under [commitEventId].
+ */
+ val peerKeyPackageEventId: HexKey? = null,
+ /** The group's state before and after the commit, TLS-encoded hex. */
+ val priorStateHex: String,
+ val pendingStateHex: String,
+ val stage: GovernanceProposalStage = GovernanceProposalStage.SIGNING,
+ /**
+ * A member whose live share has to be rotated away once this change lands: one
+ * it demotes or removes (docs/member-admin-promotion.md, Phase 9). Persisted,
+ * because the change can land long after it was proposed, across a restart.
+ */
+ val thenRotateWithout: HexKey? = null,
+ /**
+ * The promotion offer this change answers, for a promotion in a keyed room: once
+ * it lands, the new admin is handed what they need to be enrolled into the key
+ * (docs/member-admin-promotion.md, Phase 8).
+ */
+ val promotionOfferId: HexKey? = null,
+ override val createdAt: Instant = Clock.System.now(),
+ override val updatedAt: Instant = createdAt,
+ override val savedAt: Instant = createdAt,
+) : TimestampedEntity, LocalStoreEntity
+
+enum class GovernanceProposalStage {
+ /** Waiting for the group's signature. */
+ SIGNING,
+
+ /** Signed and sent; waiting for a relay to accept it. */
+ PUBLISHED,
+
+ /** The group moved past its epoch before it was signed or sent; nothing can land it now. */
+ STALE,
+
+ /** A relay accepted it, so the change is the group's. */
+ APPLIED,
+
+ /** Applied, and what had to follow it -- a rotation without a demoted member -- has been started. */
+ DONE,
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRepairSession.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRepairSession.kt
index f8b12700..2e7983f7 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRepairSession.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRepairSession.kt
@@ -45,6 +45,13 @@ data class ShareRepairSession(
val helpApprovedAt: Instant? = null,
val approvalRequested: Boolean = false,
val failureReason: String? = null,
+ /**
+ * The `n` the reduced enrollment runs with, when it is not the key's: for an
+ * enrollment at a new id it is that id -- the table had n entries before the
+ * new member's public share was added (docs/member-admin-promotion.md, Phase 8).
+ * Null for a repair, which uses the current table's size.
+ */
+ val nParticipants: Int? = null,
override val createdAt: Instant = Clock.System.now(),
override val updatedAt: Instant = createdAt,
override val savedAt: Instant = createdAt,
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 30dc919f..d1bd0264 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
@@ -10,6 +10,12 @@ import com.vitorpamplona.quartz.nip01Core.core.Kind
import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import mobi.giza.compose.managers.AdminGovernance
+import mobi.giza.compose.managers.GovernanceGate
+import mobi.giza.compose.managers.PromotionManager
+import mobi.giza.compose.managers.GovernanceFollowThrough
+import mobi.giza.compose.managers.GovernanceSupport
+import mobi.giza.compose.managers.MarmotInboundManager
import mobi.giza.compose.managers.AdminFlags
import mobi.giza.compose.managers.FoundingAdmins
import mobi.giza.compose.managers.SharedKeyDerivation
@@ -28,6 +34,7 @@ import com.vitorpamplona.quartz.utils.TimeUtils
import kotlin.time.Clock
import kotlin.time.Instant
import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@@ -50,6 +57,7 @@ import mobi.giza.compose.database.model.types.MarmotReindexReport
import mobi.giza.compose.identity.Identity
import mobi.giza.compose.identity.toKeyPair
import mobi.giza.compose.managers.ShareRefreshManager
+import mobi.giza.compose.ui.view.state.GovernanceStatus
import mobi.giza.compose.managers.RotationHold
import mobi.giza.compose.ui.view.state.SharesSummary
import mobi.giza.compose.ui.view.state.RotationPreview
@@ -137,8 +145,14 @@ class DatabaseChatRepository(
override suspend fun reconcileAdminFlags(): Int = AdminFlags.reconcileAll(database)
- override suspend fun followThroughCeremonies(keyPair: KeyPair) =
- CeremonyFollowThrough.observe(database = database, chatRepository = this, keyPair = keyPair)
+ override suspend fun followThroughCeremonies(keyPair: KeyPair) = kotlinx.coroutines.coroutineScope {
+ launch { CeremonyFollowThrough.observe(database = database, chatRepository = this@DatabaseChatRepository, keyPair = keyPair) }
+ // What a governed room's signed changes need after they land: a rotation
+ // without a demoted member, a promotion's next steps.
+ // docs/member-admin-promotion.md, Phases 8 and 9.
+ launch { GovernanceFollowThrough.observe(database = database, keyPair = keyPair) }
+ Unit
+ }
override suspend fun observeChatRoomListByPublicKey(publicKey: String): Flow> {
return database.chatRoomDao().observeChatRoomListByUserPublicKey(publicKey)
@@ -686,6 +700,60 @@ class DatabaseChatRepository(
onCompletion.invoke()
}
+ override suspend fun reconcileAdmins(chatRoomId: String): Boolean {
+ val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return false
+ // A row whose state this build cannot read has no admin set to agree with.
+ val group = runCatching { room.chatRoom.toMlsGroup() }.getOrNull() ?: return false
+ return AdminFlags.reconcile(database, chatRoomId, group) > 0
+ }
+
+ override suspend fun adminFloor(chatRoomId: String): Int {
+ val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return 1
+ val group = runCatching { room.chatRoom.toMlsGroup() }.getOrNull() ?: return 1
+ return AdminGovernance.adminFloor(database, chatRoomId, group)
+ }
+
+ override suspend fun governanceStatus(chatRoomId: String): GovernanceStatus? {
+ val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return null
+ if (room.chatRoom.marmotProfile() != MarmotProfile.CURRENT) return null
+ val group = database.marmotEngine.groupFor(room.routingId) ?: return null
+ if (!AdminGovernance.isKeyedRoom(group)) return null
+ GovernanceGate.minimumAdmins(group)?.let { return GovernanceStatus.Governed(it) }
+ if (room.chatRoom.leftGroupAt == null) GovernanceSupport.announce(database, chatRoomId, group, room.chatRoom.userPublicKey)
+ val missing = GovernanceSupport.missing(database, chatRoomId, group)
+ return if (missing.isEmpty()) GovernanceStatus.Ready(AdminGovernance.adminFloor(database, chatRoomId, group))
+ else GovernanceStatus.Waiting(missing)
+ }
+
+ override suspend fun requireSignatures(localChatRoom: LocalChatRoom) {
+ database.marmotOutboundDao().requireSignatures(localChatRoom)
+ }
+
+ override suspend fun promoteMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) {
+ database.marmotOutboundDao().promote(localChatRoom, memberPublicKey)
+ }
+
+ override suspend fun demoteMember(localChatRoom: LocalChatRoom, adminPublicKey: HexKey) {
+ database.marmotOutboundDao().demote(localChatRoom, adminPublicKey)
+ }
+
+ override suspend fun pendingPromotion(chatRoomId: String): PromotionManager.Offer? {
+ val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return null
+ return PromotionManager.pendingOffer(database, chatRoomId, room.chatRoom.userPublicKey)
+ }
+
+ override suspend fun acceptPromotion(localChatRoom: LocalChatRoom, offerId: HexKey): String? {
+ val identity = activeIdentity.value ?: return "No identity is signed in"
+ val nostrPrivateKey = identity.toKeyPair().privKey ?: return "This identity cannot sign"
+ return runCatching {
+ PromotionManager.accept(database, localChatRoom, identity.nostrPublicKey, nostrPrivateKey, offerId)
+ }.exceptionOrNull()?.let { it.message ?: it::class.simpleName ?: "Unknown error" }
+ }
+
+ override suspend fun stepDownAndLeave(localChatRoom: LocalChatRoom, heir: HexKey?) {
+ database.marmotOutboundDao().stepDownAndLeave(localChatRoom, heir)
+ }
+
override suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) {
database.marmotOutboundDao().removeMember(localChatRoom, memberPublicKey)
}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt
new file mode 100644
index 00000000..5529384c
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt
@@ -0,0 +1,130 @@
+package mobi.giza.compose.managers
+
+import com.vitorpamplona.marmot.groups.MarmotGroupPermissions
+import com.vitorpamplona.marmot.groups.currentAdminIdentities
+import com.vitorpamplona.mls.group.MlsGroup
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import mobi.giza.compose.ExperimentalFeatures
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.model.types.DkgRitualStage
+import mobi.giza.compose.ui.view.state.AdminLeave
+import mobi.giza.compose.ui.view.state.MemberAction
+
+/**
+ * Who may change who governs a room, in one place, so the screen that offers an
+ * action and the code that commits it cannot disagree. See
+ * docs/member-admin-promotion.md.
+ *
+ * Every answer is read off the group's state -- its admin set and its tree --
+ * never off `Participant.adminAt`, which is a cache of it (D1). The permission
+ * itself is the library's, [MarmotGroupPermissions], which is what every peer
+ * enforces on a commit; this adds the two things it leaves to the application.
+ */
+object AdminGovernance {
+
+ /**
+ * A room around a group's threshold key: the admin room a robust group opens,
+ * or a subgroup's. Its description records the path the key was walked to
+ * ([SharedKeyDerivation.parsePath]), which a convenient room or a direct
+ * message never has.
+ *
+ * Such a room's admins change only with the group's signature on the change,
+ * and only alongside a share of the key (R1, R2), neither of which is built.
+ * Until it is, a keyed room's admin list is changed by nothing here.
+ */
+ fun isKeyedRoom(group: MlsGroup): Boolean = SharedKeyDerivation.parsePath(group.roomDescription()) != null
+
+ /**
+ * The fewest admins [chatRoomId] may be left with: one in a convenient room,
+ * where the library's depletion guard is the whole rule, and
+ * [Quorum.minimumAdmins] of the room's quorum in a keyed one (R3). The
+ * quorum is the completed ceremony's; a device that holds none -- a member
+ * welcomed after the founding -- applies the size floor alone.
+ */
+ suspend fun adminFloor(database: GizaDatabase, chatRoomId: String, group: MlsGroup): Int {
+ if (!isKeyedRoom(group)) return 1
+ val key = GroupKeyStateManager.keyStateFor(database, chatRoomId)?.dkgSessionId
+ ?.let { database.dkgSessionDao().getSessionById(it) }
+ ?.takeIf { it.stage == DkgRitualStage.COMPLETE }
+ ?: FrostSigningManager.completedKey(database, chatRoomId)
+ return Quorum.minimumAdmins(key?.threshold)
+ }
+
+ /**
+ * Whether taking [target]'s admin rights away -- by demotion or by removing
+ * them -- leaves [group] at least [floor] admins among its members. True for
+ * someone who is not an admin, whose going changes nothing.
+ */
+ fun keepsFloor(group: MlsGroup, target: HexKey, floor: Int): Boolean {
+ val activeAdmins = group.currentAdminIdentities() intersect members(group)
+ return target !in activeAdmins || activeAdmins.size - 1 >= floor
+ }
+
+ /** The accounts holding a leaf in [group] now. */
+ fun members(group: MlsGroup): Set = group.currentMemberIdentities()
+
+ /**
+ * Whether [actor] may make [target] an admin of [group] by a single commit.
+ *
+ * The library's rule, plus that [target] holds a leaf: `canPromote` does not
+ * ask, and an admin entry for an account with no leaf is the state
+ * `AdminPolicyV1` says is never valid.
+ */
+ fun canPromote(group: MlsGroup, actor: HexKey, target: HexKey): Boolean =
+ (!isKeyedRoom(group) || keyedChangesAllowed(group)) &&
+ target in members(group) &&
+ MarmotGroupPermissions.canPromote(group.currentAdminIdentities(), actor, target)
+
+ /**
+ * Whether [actor] may make [target] stop being an admin of [group] by a single
+ * commit. The library's rule, which already refuses a demotion that would
+ * leave no admin among the members; [actor] and [target] may be the same
+ * account, which is stepping down.
+ */
+ fun canDemote(group: MlsGroup, actor: HexKey, target: HexKey): Boolean =
+ (!isKeyedRoom(group) || (keyedChangesAllowed(group) && actor != target)) &&
+ MarmotGroupPermissions.canDemote(group.currentAdminIdentities(), members(group), actor, target)
+
+ /**
+ * Whether a keyed room's admins can be changed at all from this build: the room
+ * has to need the group's signature for its changes (R2), and share rotation and
+ * enrollment have to be on, since every admin change moves a share (R1). Even
+ * then an admin does not step down on their own in a keyed room: the rotation
+ * that has to follow is the remaining holders', so another admin proposes it.
+ * docs/member-admin-promotion.md, Phases 8 and 9.
+ */
+ fun keyedChangesAllowed(group: MlsGroup): Boolean =
+ isKeyedRoom(group) && GovernanceGate.isGoverned(group) && ExperimentalFeatures.shareRefresh
+
+ /**
+ * What [me] may do to each member of [group], for the member rows' menus. Empty
+ * when [me] does not govern the room. Removal stays offered in a keyed room,
+ * where it always was, unless it would take the room below [floor] admins
+ * ([adminFloor]); promotion and demotion are not, for [isKeyedRoom]'s reason.
+ */
+ fun memberActions(group: MlsGroup, me: HexKey, floor: Int = 1): Map> {
+ if (!MarmotGroupPermissions.canManage(group.currentAdminIdentities(), me)) return emptyMap()
+ return members(group).associateWith { member ->
+ buildSet {
+ if (member == me) {
+ if (canDemote(group, me, me)) add(MemberAction.STEP_DOWN)
+ } else {
+ if (canPromote(group, me, member)) add(MemberAction.MAKE_ADMIN)
+ if (canDemote(group, me, member) && keepsFloor(group, member, floor)) add(MemberAction.REMOVE_AS_ADMIN)
+ if (MarmotGroupPermissions.canRemove(group.currentAdminIdentities(), me, member) && keepsFloor(group, member, floor)) {
+ add(MemberAction.REMOVE_FROM_GROUP)
+ }
+ }
+ }
+ }.filterValues { it.isNotEmpty() }
+ }
+
+ /** How **Leave group** goes for [me] in [group]: null when [me] is not an admin. */
+ fun adminLeave(group: MlsGroup, me: HexKey): AdminLeave? = when {
+ me !in group.currentAdminIdentities() -> null
+ isKeyedRoom(group) -> AdminLeave.CANNOT
+ canDemote(group, me, me) -> AdminLeave.STEP_DOWN_FIRST
+ (members(group) - me).isEmpty() -> AdminLeave.CANNOT
+ else -> AdminLeave.PICK_HEIR
+ }
+}
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 a3a9095e..f4d4e7cc 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.frost.GovernanceStatementEvent
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
/**
@@ -356,7 +357,9 @@ object FrostSigningManager {
userPublicKey = userPublicKey,
dkgSessionId = ceremony.id,
threshold = ceremony.threshold,
- participantCount = ceremony.participantCount,
+ // The table's size, not the ceremony's: an enrollment adds an id
+ // (docs/member-admin-promotion.md, Phase 8).
+ participantCount = shares.publicShares?.size ?: ceremony.participantCount,
signerId = signerId,
derivationPath = path?.let(SharedKeyDerivation::formatPath),
generation = shares.generation,
@@ -515,7 +518,8 @@ object FrostSigningManager {
key: DkgSession,
signerId: Int,
path: List?,
- generation: Int = 0
+ generation: Int = 0,
+ participantCount: Int = key.participantCount,
) = FrostSigningSession(
id = sessionId,
chatRoomId = localChatRoom.chatRoom.id,
@@ -526,7 +530,7 @@ object FrostSigningManager {
userPublicKey = userPublicKey,
dkgSessionId = key.id,
threshold = key.threshold,
- participantCount = key.participantCount,
+ participantCount = participantCount,
signerId = signerId,
derivationPath = path?.let(SharedKeyDerivation::formatPath),
generation = generation
@@ -610,6 +614,9 @@ object FrostSigningManager {
// could choose the key the group signs as, and every signer would put
// their share behind an author none of them checked.
val path = signingPath(database, localChatRoom, key)
+ // `n` is the generation's table, which an enrollment grows
+ // (docs/member-admin-promotion.md, Phase 8); the ceremony's count otherwise.
+ val n = generation?.let { ShareGenerations.at(database, key, it) }?.publicShares?.size ?: key.participantCount
val unsignedEvents = proposed.map { event ->
unsignedEventOf(
key = key,
@@ -643,7 +650,7 @@ object FrostSigningManager {
// docs/giza-wallet-removal.md, Phase 1.
WalletRefusal.of(unsignedEvents)?.let { why ->
logger.w("Signing proposal $sessionId $why; declining")
- val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0)
+ 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))
@@ -651,6 +658,22 @@ object FrostSigningManager {
return declined
}
+ // A change to a governed room whose commit does not say what its statement
+ // says -- or that the group's door would refuse anyway -- is declined before
+ // anybody is asked, for the wallet's reason: a device that signs what it
+ // cannot stand behind is a rubber stamp. docs/member-admin-promotion.md, Phase 5.
+ unsignedEvents.firstOrNull { it.kind == GovernanceStatementEvent.KIND }?.let { statement ->
+ GovernanceManager.refusalOf(database, localChatRoom, statement)?.let { why ->
+ logger.w("Signing proposal $sessionId carries a change that is refused: $why; declining")
+ val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0, participantCount = n)
+ .copy(signDeclinedAt = Clock.System.now())
+ database.frostSigningSessionDao().upsert(declined)
+ database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents))
+ announceStarted(database, declined)
+ return declined
+ }
+ }
+
// A 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
@@ -674,7 +697,7 @@ object FrostSigningManager {
)
// An unreadable tag is filed as -1: no generation, so nothing reads it as a
// share this device holds, and the decline says why.
- val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: -1)
+ val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: -1, participantCount = n)
.copy(signDeclinedAt = Clock.System.now())
database.frostSigningSessionDao().upsert(declined)
database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents))
@@ -690,7 +713,7 @@ object FrostSigningManager {
}
}
- val session = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0)
+ val session = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0, participantCount = n)
database.frostSigningSessionDao().upsert(session)
database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents))
announceStarted(database, session)
@@ -1309,6 +1332,14 @@ object FrostSigningManager {
// signature off.
signedEvents.forEach { applySignedEvent(database, session, it, recorded) }
+ // A change to a governed room this device proposed: now it can be sent.
+ // Swallowed like the rest -- the signature is made either way.
+ try {
+ GovernanceManager.onSigned(database, signedEvents)
+ } catch (e: Throwable) {
+ logger.e("Signed session ${session.id} but could not publish its change", e)
+ }
+
announce(
database = database,
session = session,
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt
new file mode 100644
index 00000000..9bdf87a7
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceFollowThrough.kt
@@ -0,0 +1,152 @@
+package mobi.giza.compose.managers
+
+import co.touchlab.kermit.Logger
+import com.vitorpamplona.marmot.groups.currentAdminIdentities
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.core.toHexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import kotlin.time.Clock
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.conflate
+import mobi.giza.compose.ExperimentalFeatures
+import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
+import mobi.giza.compose.nostr.frost.PromotionEvents
+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.GovernanceProposal
+import mobi.giza.compose.database.model.GovernanceProposalStage
+
+/**
+ * What a governed room's signed changes need after they land, taken by the device
+ * that proposed them, which holds the key pair those steps need.
+ * docs/member-admin-promotion.md, Phases 8 and 9.
+ *
+ * Runs beside `CeremonyFollowThrough`, for the same reason: it needs the active key
+ * pair and stops with it. Each pass reads everything again from the database, so a
+ * step interrupted halfway, or a change that landed while the app was closed, is
+ * taken on the next one.
+ */
+object GovernanceFollowThrough {
+ private val logger = Logger.withTag("GovernanceFollowThrough")
+ private val mutex = Mutex()
+
+ /** Follows this device's proposals until cancelled. */
+ suspend fun observe(database: GizaDatabase, keyPair: KeyPair) {
+ combine(
+ database.governanceProposalDao().observeAll(),
+ database.marmotInnerEventDao().observeCountByKinds(listOf(PromotionEvents.OFFER, PromotionEvents.ACCEPT, PromotionEvents.HANDOVER)),
+ database.groupSignedEventDao().observeByKind(GroupKeyStateEvent.KIND),
+ ) { _, _, _ -> Unit }
+ .conflate()
+ .collect {
+ try {
+ pass(database, keyPair)
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Throwable) {
+ logger.e("A governance follow-through pass failed", e)
+ }
+ }
+ }
+
+ /** One pass over everything owed. */
+ suspend fun pass(database: GizaDatabase, keyPair: KeyPair) = mutex.withLock {
+ rotationsOwed(database).forEach { proposal -> rotateAway(database, keyPair, proposal) }
+ if (!ExperimentalFeatures.shareRefresh) return@withLock
+ val me = keyPair.pubKey.toHexKey()
+ val privateKey = keyPair.privKey ?: return@withLock
+
+ // Phase 8, the device that offered: an accepted offer is proposed for the
+ // group's signature, once; a promotion that landed is handed over.
+ PromotionManager.acceptedOffers(database, me).forEach { (offer, acceptance) ->
+ if (offer.id in failedOffers) return@forEach
+ val room = database.chatRoomDao().findChatRoomById(offer.chatRoomId) ?: return@forEach
+ runCatching { PromotionManager.propose(database, room, me, offer, acceptance) }.onFailure {
+ if (it is CancellationException) throw it
+ failedOffers += offer.id
+ logger.w("Couldn't propose the promotion ${offer.id.take(8)}…: ${it.message}")
+ announce(database, offer.chatRoomId, me, "Couldn't ask the group to make them an admin: ${it.message}")
+ }
+ }
+ PromotionManager.handoversOwed(database).forEach { proposal ->
+ runCatching { PromotionManager.handover(database, proposal, me) }.onFailure {
+ if (it is CancellationException) throw it
+ logger.w("Couldn't hand over ${proposal.id.take(8)}…: ${it.message}")
+ }
+ }
+
+ // Phase 8, the new admin's device: a handover is checked and taken.
+ PromotionManager.handoversToMe(database, me).forEach { handover ->
+ if (handover.id in failedHandovers) return@forEach
+ val room = database.chatRoomDao().findChatRoomById(handover.chatRoomId) ?: return@forEach
+ runCatching { PromotionManager.takeHandover(database, room, me, privateKey, handover) }.onFailure {
+ if (it is CancellationException) throw it
+ failedHandovers += handover.id
+ logger.w("Couldn't take the handover ${handover.id.take(8)}…: ${it.message}")
+ }
+ }
+ }
+
+ /** Offers and handovers that failed once in this process: not retried on every pass. */
+ private val failedOffers = mutableSetOf()
+ private val failedHandovers = mutableSetOf()
+
+ /**
+ * This device's changes that have landed and owe a rotation without a member
+ * they demoted or removed (Phase 9). Landed means a relay accepted it -- marked
+ * [GovernanceProposalStage.APPLIED] -- or, for one confirmed while this device
+ * was not watching, that the group is past its epoch and no longer names the
+ * member an admin, or no longer holds them at all.
+ */
+ suspend fun rotationsOwed(database: GizaDatabase): List =
+ database.governanceProposalDao().getAll().filter { proposal ->
+ val member = proposal.thenRotateWithout ?: return@filter false
+ when (proposal.stage) {
+ GovernanceProposalStage.APPLIED -> true
+ GovernanceProposalStage.PUBLISHED -> {
+ val group = database.marmotEngine.groupFor(proposal.routingId) ?: return@filter false
+ group.epoch > proposal.epoch &&
+ (member !in group.currentAdminIdentities() || member !in group.currentMemberIdentities())
+ }
+ else -> false
+ }
+ }
+
+ /**
+ * Starts the rotation without [proposal]'s member, and marks it done either way:
+ * a rotation that could not start -- one already running, a holder this device
+ * cannot reach -- is said in the room, and the Shares section offers it from
+ * there, as it does after any removal.
+ */
+ private suspend fun rotateAway(database: GizaDatabase, keyPair: KeyPair, proposal: GovernanceProposal) {
+ val member = proposal.thenRotateWithout ?: return
+ val room = database.chatRoomDao().findChatRoomById(proposal.chatRoomId) ?: return
+ val me = keyPair.pubKey.toHexKey()
+ val privateKey = keyPair.privKey ?: return
+ val failure = runCatching { ShareRefreshManager.proposeWithout(database, room, me, privateKey, member) }.exceptionOrNull()
+ if (failure is CancellationException) throw failure
+ database.governanceProposalDao().upsert(proposal.copy(stage = GovernanceProposalStage.DONE, updatedAt = Clock.System.now()))
+ if (failure != null) {
+ logger.w("Could not rotate ${member.take(8)}… away after ${proposal.id.take(8)}…: ${failure.message}")
+ announce(database, proposal.chatRoomId, me, "Couldn't start rotating the shares without a member who is no longer an admin: ${failure.message}. Rotate them from the Shares section")
+ }
+ }
+
+ private suspend fun announce(database: GizaDatabase, chatRoomId: String, me: HexKey, content: String) {
+ database.chatMessageDao().upsert(
+ ChatMessage(
+ content = content,
+ messageType = ChatMessage.TYPE_CHANGE_NOT_APPLIED,
+ chatRoomId = chatRoomId,
+ senderPublicKey = me,
+ isUserMessage = true,
+ giftWrapPayloadId = null,
+ marmotGroupEventId = null,
+ marmotInnerEventId = null,
+ )
+ )
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceGate.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceGate.kt
new file mode 100644
index 00000000..70056556
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceGate.kt
@@ -0,0 +1,168 @@
+package mobi.giza.compose.managers
+
+import com.vitorpamplona.marmot.groups.MarmotGroupPolicy
+import com.vitorpamplona.marmot.groups.currentAdminIdentities
+import com.vitorpamplona.marmot.groups.currentGroupState
+import com.vitorpamplona.marmot.mip03GroupMessages.GroupEventEncryption
+import com.vitorpamplona.mls.codec.TlsReader
+import com.vitorpamplona.mls.framing.ContentType
+import com.vitorpamplona.mls.framing.MlsMessage
+import com.vitorpamplona.mls.framing.PrivateMessage
+import com.vitorpamplona.mls.framing.PublicMessage
+import com.vitorpamplona.mls.framing.WireFormat
+import com.vitorpamplona.mls.group.GroupView
+import com.vitorpamplona.mls.group.MlsGroup
+import com.vitorpamplona.mls.group.MlsGroupPolicy
+import com.vitorpamplona.mls.group.PendingProposal
+import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import mobi.giza.compose.extensions.exporterSecret
+import mobi.giza.compose.nostr.frost.GovernanceChange
+import mobi.giza.compose.nostr.frost.GovernanceEvents
+import mobi.giza.compose.nostr.frost.GovernanceStatementEvent
+import mobi.giza.compose.nostr.frost.OwnCommitEvent
+
+/**
+ * The door every commit into a governed room comes through. docs/member-admin-promotion.md,
+ * R2, the headline and Phase 4a.
+ *
+ * A room is governed when its state says so ([GovernanceMarker]). In one, a commit
+ * sent bare is dropped before the engine sees it ([isBareCommit]), and a commit
+ * arrives only inside an envelope ([admit]): the group's signature on a statement of
+ * what it does, or -- for the commits that need nobody's (D6) -- its committer's own.
+ *
+ * Every verdict here is a function of the bytes and the group's state, nothing a
+ * device happens to have seen, so every device reaches the same one. That is the
+ * property the rule cannot do without: a device that applied a commit another
+ * refused would be in a different group from then on.
+ */
+object GovernanceGate {
+
+ /** The floor a governed room's state sets, or null when the room is not governed. */
+ fun minimumAdmins(group: MlsGroup): Int? =
+ if (AdminGovernance.isKeyedRoom(group)) GovernanceMarker.minimumAdmins(group.roomDescription()) else null
+
+ fun isGoverned(group: MlsGroup): Boolean = minimumAdmins(group) != null
+
+ /**
+ * Whether [event] is a commit sent bare, read without processing it: the outer
+ * layer peeled with any of [outerKeys] -- the current epoch's, then the retained
+ * ones, because convergence can adopt a commit for an epoch already passed -- and
+ * the MLS content type read from the header. An event no key opens is not
+ * judged here; the engine cannot apply it either.
+ */
+ fun isBareCommit(event: GroupEvent, outerKeys: List): Boolean {
+ val mlsBytes = outerKeys.firstNotNullOfOrNull { key ->
+ runCatching { GroupEventEncryption.decrypt(event.encryptedContent(), key) }.getOrNull()
+ } ?: return false
+ return runCatching {
+ val message = MlsMessage.decodeTls(TlsReader(mlsBytes))
+ when (message.wireFormat) {
+ WireFormat.PUBLIC_MESSAGE -> PublicMessage.decodeTls(TlsReader(message.payload)).contentType == ContentType.COMMIT
+ WireFormat.PRIVATE_MESSAGE -> PrivateMessage.decodeTls(TlsReader(message.payload)).contentType == ContentType.COMMIT
+ else -> false
+ }
+ }.getOrDefault(false)
+ }
+
+ /** What an envelope's commit turned out to be, run on a copy of the group. */
+ class Inspection(
+ val before: GroupView,
+ val proposals: List,
+ val committer: HexKey?,
+ val after: MlsGroup,
+ )
+
+ /**
+ * Runs [inner]'s commit on a throwaway copy of [group] and says what it did, or
+ * null when the copy refuses it. The copy is given a policy that delegates to
+ * Marmot's and records what it is shown, which is the commit's real list of
+ * proposals and its committer. Only at the group's current epoch: an envelope
+ * is good there or nowhere (D5).
+ */
+ fun inspect(group: MlsGroup, inner: GroupEvent): Inspection? = runCatching {
+ val mlsBytes = GroupEventEncryption.decrypt(inner.encryptedContent(), group.exporterSecret())
+ val recorder = RecordingPolicy()
+ val copy = MlsGroup.restore(group.saveState(), recorder)
+ copy.processFramedCommit(mlsBytes)
+ val seen = recorder.seen ?: return null
+ // Identities from the group as it stood before the commit, which [group]
+ // still is: the copy's view can already have a removed leaf blank.
+ val before = group.view()
+ Inspection(before, seen.second, before.memberIdentityHex(seen.third), copy)
+ }.getOrNull()
+
+ /** Why an envelope was refused, in words for the room. */
+ class Refused(val reason: String)
+
+ /**
+ * The kind:445 [envelope] carries, when [group] -- the room [chatRoomId] -- may
+ * apply it; otherwise why not.
+ *
+ * A statement (30370) has to be the room's own signature, at the group's
+ * current epoch, on exactly what the commit does, and the commit has to leave at
+ * least the room's floor of admins (R3). An own commit (30371) has to be one of
+ * D6's two kinds, sent by the account whose leaf committed it.
+ */
+ fun admit(group: MlsGroup, chatRoomId: HexKey, envelope: Event): Result =
+ check(group, chatRoomId, envelope, requireSignature = true)
+
+ /**
+ * [admit]'s checks, with the room's signature on a statement optional: a member's
+ * device runs them on a statement still being asked for, before it signs
+ * (`GovernanceManager.refusalOf`). Everything else is the same, so nobody signs
+ * what the door would then refuse.
+ */
+ fun check(group: MlsGroup, chatRoomId: HexKey, envelope: Event, requireSignature: Boolean): Result {
+ fun refuse(reason: String) = Result.failure(IllegalStateException(reason))
+
+ val inner = GovernanceEvents.innerCommitOf(envelope) ?: return refuse("it carries no commit")
+ if (GovernanceEvents.roomOf(envelope)?.equals(chatRoomId, ignoreCase = true) != true) return refuse("it is for another group")
+ if (GovernanceEvents.epochOf(envelope) != group.epoch) return refuse("it was signed for another moment in the group's history")
+ val inspection = inspect(group, inner) ?: return refuse("its change is not one this group can make")
+
+ when (envelope.kind) {
+ GovernanceStatementEvent.KIND -> {
+ val change = GovernanceChange.of(inspection.before, inspection.proposals)
+ ?: return refuse("its change cannot be described, so nobody could have approved it")
+ val statement = GovernanceStatementEvent.parse(envelope) ?: return refuse("its statement cannot be read")
+ if (statement.change != change) return refuse("it does not say what its commit does")
+ if (requireSignature && !GovernanceStatementEvent.authorises(envelope, chatRoomId, group.epoch, change)) {
+ return refuse("the group's signature is not on this change")
+ }
+ // A disband ends the group, so no floor applies to what it leaves.
+ if (!inspection.after.currentGroupState().isDisbanded) {
+ val floor = minimumAdmins(group) ?: 1
+ val admins = inspection.after.currentAdminIdentities() intersect inspection.after.currentMemberIdentities()
+ if (admins.size < floor) return refuse("it would leave fewer than $floor admins")
+ }
+ }
+ OwnCommitEvent.KIND -> {
+ if (!GovernanceChange.isExempt(inspection.proposals)) return refuse("only the group can sign a change like this one")
+ // Its author is its sender, which MLS has already authenticated: the
+ // inbound path holds every application message to its sender's leaf
+ // (MIP-03). So the one thing left to ask is that the sender made it.
+ if (!envelope.pubKey.equals(inspection.committer, ignoreCase = true)) {
+ return refuse("it was not sent by the member who made it")
+ }
+ }
+ else -> return refuse("it is not a commit envelope")
+ }
+ return Result.success(inner)
+ }
+
+ /**
+ * Marmot's policy, recording the first commit it is asked about. The copy is
+ * thrown away; this is how the app is told what a commit does without the
+ * library being changed to say.
+ */
+ internal class RecordingPolicy : MlsGroupPolicy by MarmotGroupPolicy {
+ var seen: Triple, Int>? = null
+
+ override fun authorizeCommit(group: GroupView, proposals: List, committerLeafIndex: Int) {
+ MarmotGroupPolicy.authorizeCommit(group, proposals, committerLeafIndex)
+ if (seen == null) seen = Triple(group, proposals, committerLeafIndex)
+ }
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceManager.kt
new file mode 100644
index 00000000..0fa0f5d8
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceManager.kt
@@ -0,0 +1,450 @@
+package mobi.giza.compose.managers
+
+import co.touchlab.kermit.Logger
+import com.vitorpamplona.marmot.foundation.appEvents.MarmotAppEvent
+import com.vitorpamplona.marmot.groups.MlsGroupManager
+import com.vitorpamplona.marmot.mip03GroupMessages.GroupEventEncryption
+import com.vitorpamplona.mls.group.MlsGroup
+import com.vitorpamplona.mls.group.MlsGroupState
+import com.vitorpamplona.mls.messages.CommitResult
+import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent
+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.KeyPair
+import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate
+import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal
+import kotlin.time.Clock
+import kotlin.time.Instant
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.model.BroadcastNostrEventRequest
+import mobi.giza.compose.database.model.ChatMessage
+import mobi.giza.compose.database.model.GovernanceProposal
+import mobi.giza.compose.database.model.GovernanceProposalStage
+import mobi.giza.compose.database.model.MarmotCommitResult
+import mobi.giza.compose.database.model.MarmotGroupEvent
+import mobi.giza.compose.database.model.NostrEvent
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+import mobi.giza.compose.exceptions.MarmotCommitPendingException
+import mobi.giza.compose.exceptions.MarmotMissingChatGroupException
+import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.nostr.Relays
+import mobi.giza.compose.nostr.frost.GovernanceCarrierEvent
+import mobi.giza.compose.nostr.frost.GovernanceChange
+import mobi.giza.compose.nostr.frost.GovernanceStatementEvent
+import mobi.giza.compose.nostr.frost.OwnCommitEvent
+import com.vitorpamplona.marmot.appComponents.GroupLifecycleV1
+import com.vitorpamplona.marmot.appComponents.AdminPolicyV1
+import com.vitorpamplona.mls.components.ComponentsList
+
+/**
+ * How a change to a governed room becomes a commit: built, signed by the group, then
+ * published inside that signature. docs/member-admin-promotion.md, R2 and Phase 5.
+ *
+ * 1. [propose]: the commit is built on a copy of the group -- the copy's policy
+ * records the proposals, so the statement is read off the very commit -- and the
+ * kind:445 that carries it is built and *not* published. The group is asked to
+ * sign a statement whose content is that kind:445, and the staged state is kept
+ * in a [GovernanceProposal], because this device cannot process its own commit.
+ * 2. The quorum signs, through the room's ordinary signing sessions. A member's
+ * device declines a statement whose commit does not say what its tags say
+ * ([refusalOf]), before its owner is asked.
+ * 3. [onSigned]: the proposer's device sends the signed statement in a carrier and
+ * raises the publish gate with the kept state. A relay's OK on the carrier
+ * installs it, as any commit's would.
+ */
+object GovernanceManager {
+ private val logger = Logger.withTag("GovernanceManager")
+
+ /** A commit built on a copy, with what it does. */
+ class Prepared(
+ val staged: MlsGroupManager.StagedCommit,
+ val change: GovernanceChange,
+ val commitEvent: GroupEvent,
+ val epoch: Long,
+ )
+
+ /**
+ * Builds the commit [propose] describes on a copy of [live], and the kind:445 that
+ * would carry it to [routingId]. [propose] calls the copy's `propose…` functions;
+ * a member's leave already pooled rides along (D6). The copy's policy is Marmot's,
+ * so a commit every peer would refuse is refused here.
+ */
+ suspend fun prepare(live: MlsGroup, routingId: HexKey, propose: (MlsGroup) -> Unit): Prepared {
+ val prior = live.saveState()
+ val recorder = GovernanceGate.RecordingPolicy()
+ val copy = MlsGroup.restore(prior, recorder)
+ propose(copy)
+ val result = copy.commit()
+ val (_, proposals, _) = checkNotNull(recorder.seen) { "The commit was built without being checked" }
+ // Who a Remove names is read off the group as it stood before the commit:
+ // the copy's own view can already have the removed leaf blank.
+ val change = checkNotNull(GovernanceChange.of(live.view(), proposals)) {
+ "This change cannot be described, so the group could not approve it: " +
+ proposals.joinToString { it.proposal::class.simpleName.orEmpty() }
+ }
+ val commitEvent: GroupEvent = NostrSignerInternal(KeyPair()).sign(
+ GroupEvent.build(
+ encryptedContentBase64 = GroupEventEncryption.encrypt(result.framedCommitBytes, result.preCommitExporterSecret),
+ nostrGroupId = routingId,
+ )
+ )
+ return Prepared(MlsGroupManager.StagedCommit(result, prior, copy.saveState()), change, commitEvent, live.epoch)
+ }
+
+ /**
+ * Proposes [propose]'s change to a governed room, as [userPublicKey]: builds it,
+ * asks the group to sign it, and keeps what is needed to publish it. Returns the
+ * signing session. Throws, in words a person can act on, when it cannot.
+ */
+ suspend fun propose(
+ database: GizaDatabase,
+ localChatRoom: LocalChatRoom,
+ userPublicKey: HexKey,
+ peerKeyPackageEventId: HexKey? = null,
+ thenRotateWithout: HexKey? = null,
+ promotionOfferId: HexKey? = null,
+ alsoSign: List> = emptyList(),
+ propose: (MlsGroup) -> Unit,
+ ): String {
+ val engine = database.marmotEngine
+ val routingId = localChatRoom.routingId
+ val roomId = localChatRoom.chatRoom.id
+ engine.awaitSettled(routingId)
+ val live = engine.groupFor(routingId) ?: throw MarmotMissingChatGroupException("No live group for $roomId")
+ check(GovernanceGate.isGoverned(live)) { "This group's changes do not need its signature" }
+ if (!engine.gate.canPrepareLocalCommit(routingId)) {
+ throw MarmotCommitPendingException("An earlier change to this room is still waiting for a relay to accept it; try again in a moment")
+ }
+
+ val prepared = prepare(live, routingId, propose)
+ // A disband ends the group, so no floor applies to what it leaves behind.
+ val disbands = GroupLifecycleV1.COMPONENT_ID in prepared.change.components
+ GovernanceGate.minimumAdmins(live)?.takeUnless { disbands }?.let { floor ->
+ val admins = prepared.change.admins ?: live.currentAdminIdentitiesSet()
+ val remaining = admins - prepared.change.removes
+ check(remaining.size >= floor) { "A group with a shared key needs at least $floor admins. Make someone else an admin first" }
+ }
+
+ // The statement leads; anything signed with it -- a promotion's key state --
+ // is one decision by one quorum, so it is one batch.
+ val statement = EventTemplate(
+ Clock.System.now().epochSeconds,
+ GovernanceStatementEvent.KIND,
+ GovernanceStatementEvent.assembleTags(roomId, prepared.epoch, prepared.change, userPublicKey),
+ prepared.commitEvent.toJson(),
+ )
+ val session = FrostSigningManager.proposeSigningBatch(
+ database = database,
+ localChatRoom = localChatRoom,
+ userPublicKey = userPublicKey,
+ events = listOf(statement) + alsoSign,
+ )
+ val statementId = database.frostSigningSessionDao().getItems(session.id)
+ .first { Event.fromJsonOrNull(it.unsignedEventJson)?.kind == GovernanceStatementEvent.KIND }
+ .eventId
+ record(database, localChatRoom, userPublicKey, prepared, statementId, session.id, peerKeyPackageEventId, thenRotateWithout, promotionOfferId)
+ return session.id
+ }
+
+ /**
+ * Keeps what publishing [prepared] will need once the group has signed the
+ * statement [statementId]: the commit's parts, under the id of the event that
+ * carries it -- which is also how the inbound path knows a carried commit is this
+ * device's own -- and the states either side of it.
+ */
+ internal suspend fun record(
+ database: GizaDatabase,
+ localChatRoom: LocalChatRoom,
+ userPublicKey: HexKey,
+ prepared: Prepared,
+ statementId: HexKey,
+ sessionId: String,
+ peerKeyPackageEventId: HexKey? = null,
+ thenRotateWithout: HexKey? = null,
+ promotionOfferId: HexKey? = null,
+ ): GovernanceProposal {
+ val roomId = localChatRoom.chatRoom.id
+ database.marmotCommitResultDao().upsert(
+ MarmotCommitResult.from(
+ commitEventId = prepared.commitEvent.id,
+ commitResult = prepared.staged.result,
+ chatRoomId = roomId,
+ userPublicKey = userPublicKey,
+ peerKeyPackageEventId = peerKeyPackageEventId ?: MarmotCommitResult.NO_INVITEE,
+ isOneMemberInitialGroupCreation = false,
+ createdAt = Instant.fromEpochSeconds(prepared.commitEvent.createdAt),
+ )
+ )
+ val proposal = GovernanceProposal(
+ id = statementId,
+ chatRoomId = roomId,
+ routingId = localChatRoom.routingId,
+ epoch = prepared.epoch,
+ frostSigningSessionId = sessionId,
+ commitEventId = prepared.commitEvent.id,
+ commitEventJson = prepared.commitEvent.toJson(),
+ peerKeyPackageEventId = peerKeyPackageEventId,
+ priorStateHex = prepared.staged.priorState.encodeTls().toHex(),
+ pendingStateHex = prepared.staged.pendingState.encodeTls().toHex(),
+ thenRotateWithout = thenRotateWithout,
+ promotionOfferId = promotionOfferId,
+ )
+ database.governanceProposalDao().upsert(proposal)
+ return proposal
+ }
+
+ /**
+ * Why this device will not put its share to [statement], or null when it may.
+ * Run on a statement still being asked for -- unsigned -- by every member's device
+ * before its owner is asked: the same check the door will make, but for the
+ * signature, so nobody signs a commit that does not say what it does. The
+ * proposer's own is not checked here: it built it, and cannot process its own
+ * commit to look.
+ */
+ suspend fun refusalOf(database: GizaDatabase, localChatRoom: LocalChatRoom, statement: Event): String? {
+ if (database.governanceProposalDao().getById(statement.id) != null) return null
+ val group = database.marmotEngine.groupFor(localChatRoom.routingId) ?: return "this device holds no state for the group"
+ return GovernanceGate.check(group, localChatRoom.chatRoom.id, statement, requireSignature = false).exceptionOrNull()?.message
+ }
+
+ /**
+ * The group signed [signedEvents]: for each that is a statement this device
+ * proposed, publish it. Called on every device that completes a signing session;
+ * only the proposer's holds a [GovernanceProposal] for it.
+ */
+ suspend fun onSigned(database: GizaDatabase, signedEvents: List) {
+ signedEvents.filter { it.kind == GovernanceStatementEvent.KIND }.forEach { signed ->
+ val proposal = database.governanceProposalDao().getById(signed.id) ?: return@forEach
+ if (proposal.stage != GovernanceProposalStage.SIGNING) return@forEach
+ runCatching { publish(database, proposal, signed) }
+ .onFailure { logger.e("Signed ${signed.id.take(8)}… but could not publish it", it) }
+ }
+ }
+
+ /**
+ * Sends [signed] in a carrier and raises the publish gate with the state
+ * [proposal] kept; a relay's OK on the carrier installs it. A proposal the group
+ * has moved past is marked stale and said so: its commit can no longer land.
+ */
+ suspend fun publish(
+ database: GizaDatabase,
+ proposal: GovernanceProposal,
+ signed: Event,
+ relays: List = Relays.DefaultDMRelayList.map { it.url },
+ ) {
+ val engine = database.marmotEngine
+ val routingId = proposal.routingId
+ val room = database.chatRoomDao().findChatRoomById(proposal.chatRoomId) ?: return
+ val me = room.chatRoom.userPublicKey
+ engine.awaitSettled(routingId)
+ val live = engine.groupFor(routingId) ?: return
+ if (live.epoch != proposal.epoch || !engine.gate.canPrepareLocalCommit(routingId)) {
+ database.governanceProposalDao().upsert(proposal.copy(stage = GovernanceProposalStage.STALE, updatedAt = Clock.System.now()))
+ announce(database, proposal.chatRoomId, me, "A change the group signed was overtaken by another before it could be sent. Propose it again")
+ return
+ }
+
+ val commitRow = checkNotNull(database.marmotCommitResultDao().getMarmotCommitRequestById(proposal.commitEventId)) {
+ "The proposed commit's parts are missing"
+ }
+ val result = CommitResult(
+ commitBytes = commitRow.commitBytes,
+ welcomeBytes = commitRow.welcomeBytes,
+ groupInfoBytes = commitRow.groupInfoBytes,
+ framedCommitBytes = commitRow.framedCommitBytes,
+ preCommitExporterSecret = commitRow.preCommitExporterSecret,
+ )
+ val staged = MlsGroupManager.StagedCommit(
+ result,
+ MlsGroupState.decodeTls(proposal.priorStateHex.hexToByteArray()),
+ MlsGroupState.decodeTls(proposal.pendingStateHex.hexToByteArray()),
+ )
+
+ val commitEvent = Event.fromJson(proposal.commitEventJson).let {
+ GroupEvent(it.id, it.pubKey, it.createdAt, it.tags, it.content, it.sig)
+ }
+ // When a relay accepts it, the change is the group's: what has to follow it
+ // -- a rotation without a member it demoted -- reads that off the row
+ // (GovernanceFollowThrough). Registered before the gate is raised, so the
+ // acceptance cannot overtake it; a restart in between is caught there too.
+ engine.afterConfirmed(routingId) {
+ database.governanceProposalDao().getById(proposal.id)?.let { current ->
+ if (current.stage == GovernanceProposalStage.PUBLISHED) {
+ database.governanceProposalDao().upsert(current.copy(stage = GovernanceProposalStage.APPLIED, updatedAt = Clock.System.now()))
+ }
+ }
+ }
+ try {
+ sendEnvelope(
+ database = database,
+ chatRoomId = proposal.chatRoomId,
+ routingId = routingId,
+ me = me,
+ staged = staged,
+ commitEvent = commitEvent,
+ commitRow = commitRow,
+ carrierKind = GovernanceCarrierEvent.KIND,
+ carrierContent = signed.toJson(),
+ carrierTags = GovernanceCarrierEvent.assembleTags(proposal.chatRoomId),
+ relays = relays,
+ )
+ } catch (e: Throwable) {
+ engine.cancelFollowUp(routingId)
+ throw e
+ }
+ database.governanceProposalDao().upsert(proposal.copy(stage = GovernanceProposalStage.PUBLISHED, updatedAt = Clock.System.now()))
+ }
+
+ /**
+ * Commits whatever members' own leaves are waiting in a governed room's pool, as
+ * an admin's device does on receipt -- inside this account's own envelope (D6),
+ * not bare. Nothing when nothing is waiting.
+ */
+ suspend fun publishOwnCommit(
+ database: GizaDatabase,
+ localChatRoom: LocalChatRoom,
+ relays: List = Relays.DefaultDMRelayList.map { it.url },
+ ) {
+ val engine = database.marmotEngine
+ val routingId = localChatRoom.routingId
+ val me = localChatRoom.chatRoom.userPublicKey
+ if (!engine.groupManager.hasPendingProposals(routingId) || !engine.gate.canPrepareLocalCommit(routingId)) return
+ engine.awaitSettled(routingId)
+ val live = engine.groupFor(routingId) ?: return
+ val prepared = prepare(live, routingId) { }
+ // Only members' own leaves are ever pooled (MIP-03), and they need nobody's
+ // signature; anything else would not be this envelope's to carry.
+ check(prepared.change == GovernanceChange()) { "Only a member's own leave can be committed without the group's signature" }
+ val commitRow = MarmotCommitResult.from(
+ commitEventId = prepared.commitEvent.id,
+ commitResult = prepared.staged.result,
+ chatRoomId = localChatRoom.chatRoom.id,
+ userPublicKey = me,
+ peerKeyPackageEventId = MarmotCommitResult.NO_INVITEE,
+ isOneMemberInitialGroupCreation = false,
+ createdAt = Instant.fromEpochSeconds(prepared.commitEvent.createdAt),
+ )
+ database.marmotCommitResultDao().upsert(commitRow)
+ sendEnvelope(
+ database = database,
+ chatRoomId = localChatRoom.chatRoom.id,
+ routingId = routingId,
+ me = me,
+ staged = prepared.staged,
+ commitEvent = prepared.commitEvent,
+ commitRow = commitRow,
+ carrierKind = OwnCommitEvent.KIND,
+ carrierContent = prepared.commitEvent.toJson(),
+ carrierTags = OwnCommitEvent.assembleTags(localChatRoom.chatRoom.id, prepared.epoch),
+ relays = relays,
+ )
+ }
+
+ /**
+ * Puts a commit on the wire inside an envelope: the envelope as an application
+ * message at the commit's epoch, then the publish gate raised with the staged
+ * state, the commit filed as the event it is -- so the envelope coming back is
+ * known for this device's own -- and the relay's OK on the envelope made the
+ * commit's confirmation, as `publishCommit` does for a bare one.
+ */
+ private suspend fun sendEnvelope(
+ database: GizaDatabase,
+ chatRoomId: String,
+ routingId: HexKey,
+ me: HexKey,
+ staged: MlsGroupManager.StagedCommit,
+ commitEvent: GroupEvent,
+ commitRow: MarmotCommitResult,
+ carrierKind: Int,
+ carrierContent: String,
+ carrierTags: Array>,
+ relays: List,
+ ) {
+ val engine = database.marmotEngine
+ val payload = MarmotAppEvent.build(
+ pubKey = me,
+ kind = carrierKind,
+ content = carrierContent,
+ createdAt = Clock.System.now().epochSeconds,
+ tags = carrierTags,
+ ).encodeToPayload()
+ val carrier = engine.outbound.buildGroupEventFromBytes(routingId, payload).signedEvent
+ val obligation = engine.gate.prepare(
+ groupId = routingId,
+ staged = staged,
+ outboundBytes = staged.result.framedCommitBytes,
+ recipientScope = relays,
+ )
+
+ listOf(commitEvent, carrier).forEach { event ->
+ database.nostrEventDao().upsert(
+ NostrEvent(
+ id = event.id, createdAt = Instant.fromEpochSeconds(event.createdAt), content = event.content,
+ sig = event.sig, tags = event.tags, kind = event.kind, pubKey = event.pubKey,
+ )
+ )
+ database.marmotGroupEventDao().upsert(
+ MarmotGroupEvent(
+ id = event.id, createdAt = Instant.fromEpochSeconds(event.createdAt), encryptedContent = event.encryptedContent(),
+ publicKey = event.pubKey, userPublicKey = me, expiresAt = null, chatRoomId = chatRoomId, signature = event.sig,
+ )
+ )
+ }
+ database.marmotCommitResultDao().upsert(
+ commitRow.copy(id = carrier.id, obligationId = obligation.obligationId, createdAt = Instant.fromEpochSeconds(carrier.createdAt))
+ )
+ database.broadcastNostrEventRequestDao().insert(relays.map { BroadcastNostrEventRequest(nostrEventId = carrier.id, relayURL = it) })
+ }
+
+ // --- The changes, as the proposals a copy of the group is given ----------------
+
+ /** Removing the member at [leafIndex], and their admin entry in the same commit when [admins] names [member]. */
+ fun removal(leafIndex: Int, member: HexKey, admins: Set): (MlsGroup) -> Unit = { copy ->
+ copy.proposeRemove(leafIndex)
+ if (member in admins) {
+ copy.proposeAppDataUpdate(AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(admins - member).encode())
+ }
+ }
+
+ /** Adding the holder of [keyPackageBytes]. */
+ fun addition(keyPackageBytes: ByteArray): (MlsGroup) -> Unit = { copy -> copy.proposeAdd(keyPackageBytes) }
+
+ /** Ending the group, as the library's own disband does: everyone else removed, this device its last admin. */
+ val disbanding: (MlsGroup) -> Unit = { copy ->
+ copy.proposeAppDataUpdate(GroupLifecycleV1.COMPONENT_ID, GroupLifecycleV1.DISBANDED.encode())
+ copy.proposeAppDataUpdate(AdminPolicyV1.COMPONENT_ID, AdminPolicyV1(listOf(checkNotNull(copy.memberIdentity(copy.leafIndex)))).encode())
+ for ((leafIndex, _) in copy.members()) {
+ if (leafIndex != copy.leafIndex) copy.proposeRemove(leafIndex)
+ }
+ }
+
+ /** Agreeing the group can be disbanded, as the library's enablement does: the lifecycle component required, and active. */
+ val enablingDisbanding: (MlsGroup) -> Unit = { copy ->
+ val dictionary = copy.appDataDictionary()
+ val required = ComponentsList.supportedOrRequired(dictionary).toMutableSet()
+ required.add(GroupLifecycleV1.COMPONENT_ID)
+ copy.proposeAppDataUpdate(ComponentsList.APP_COMPONENTS_ID, ComponentsList.encode(required))
+ if (dictionary[GroupLifecycleV1.COMPONENT_ID] == null) {
+ copy.proposeAppDataUpdate(GroupLifecycleV1.COMPONENT_ID, GroupLifecycleV1.ACTIVE.encode())
+ }
+ }
+
+ private suspend fun announce(database: GizaDatabase, chatRoomId: String, me: HexKey, content: String) {
+ database.chatMessageDao().upsert(
+ ChatMessage(
+ content = content,
+ messageType = ChatMessage.TYPE_CHANGE_NOT_APPLIED,
+ chatRoomId = chatRoomId,
+ senderPublicKey = me,
+ isUserMessage = true,
+ giftWrapPayloadId = null,
+ marmotGroupEventId = null,
+ marmotInnerEventId = null,
+ )
+ )
+ }
+
+ private fun MlsGroup.currentAdminIdentitiesSet(): Set =
+ com.vitorpamplona.marmot.groups.MarmotGroupPolicy.adminIdentitiesIn(extensions)
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceMarker.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceMarker.kt
new file mode 100644
index 00000000..90453b3a
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceMarker.kt
@@ -0,0 +1,32 @@
+package mobi.giza.compose.managers
+
+/**
+ * The line in a keyed room's profile description that says its changes need the
+ * group's signature, and how few admins it may ever have. docs/member-admin-promotion.md,
+ * D4 and D8.
+ *
+ * In the group's state, so every device that applies the commit adding it enforces
+ * the rule from the same epoch, and reads the same floor: a floor each device worked
+ * out for itself from the ceremony it happens to hold would differ between a founder
+ * and a member welcomed later, and the two would disagree about a commit. The
+ * description is the one free text the current profile offers, which is why
+ * [MarmotRoomIdentity] and [SharedKeyDerivation.describe] put their lines there too.
+ */
+object GovernanceMarker {
+ private const val PREFIX = "Changes need the group's signature; at least "
+ private const val SUFFIX = " admins."
+ private val LINE = Regex("^" + Regex.escape(PREFIX) + "(\\d{1,3})" + Regex.escape(SUFFIX) + "$")
+
+ /** The floor [description] sets, or null when it does not carry the line. */
+ fun minimumAdmins(description: String?): Int? =
+ description?.lineSequence()
+ ?.firstNotNullOfOrNull { LINE.find(it.trim())?.groupValues?.get(1)?.toIntOrNull() }
+ ?.takeIf { it >= 1 }
+
+ /** [description] with the line set to [minimumAdmins], replacing any it already had. */
+ fun describe(description: String?, minimumAdmins: Int): String {
+ val kept = description.orEmpty().lines().filterNot { LINE.matches(it.trim()) }.joinToString("\n").trimEnd()
+ val line = "$PREFIX$minimumAdmins$SUFFIX"
+ return if (kept.isBlank()) line else "$kept\n\n$line"
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt
new file mode 100644
index 00000000..88b4469e
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GovernanceSupport.kt
@@ -0,0 +1,62 @@
+package mobi.giza.compose.managers
+
+import com.vitorpamplona.mls.group.MlsGroup
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
+import kotlin.time.Clock
+import kotlin.time.Instant
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.model.MarmotInnerEvent
+import mobi.giza.compose.nostr.frost.GovernanceSupportEvent
+
+/**
+ * Who in a keyed room has said their device follows signed commits, and this
+ * device saying it. docs/member-admin-promotion.md, D4 and Phase 4b.
+ *
+ * The rule cannot be switched on while anybody in the room would be left behind
+ * by it: a device that does not know it applies the bare commits Giza drops and
+ * reads none of the envelopes, and is in a different group from the first change.
+ * So each device says, once per room, that it can follow -- and says it back when
+ * it hears another say it, which is how a member who never opens the room's screen
+ * still gets counted.
+ */
+object GovernanceSupport {
+
+ /** The accounts that have said, in [chatRoomId], that they follow signed commits. */
+ suspend fun supporters(database: GizaDatabase, chatRoomId: String): Set =
+ database.marmotInnerEventDao().getByChatRoomAndKinds(chatRoomId, listOf(GovernanceSupportEvent.KIND))
+ .filter { row -> row.tags.any { it.size >= 2 && it[0] == GovernanceSupportEvent.VERSION_TAG && it[1] == GovernanceSupportEvent.VERSION } }
+ .map { it.publicKey }
+ .toSet()
+
+ /** The members of [group] who have not said it yet. */
+ suspend fun missing(database: GizaDatabase, chatRoomId: String, group: MlsGroup): Set =
+ AdminGovernance.members(group) - supporters(database, chatRoomId)
+
+ /**
+ * Says, for [me], that this device follows signed commits in [chatRoomId] -- once:
+ * nothing happens when it already has. Only in a keyed room, which is the only
+ * kind the rule can be switched on in. Returns whether it said it now.
+ */
+ suspend fun announce(database: GizaDatabase, chatRoomId: String, group: MlsGroup, me: HexKey): Boolean {
+ if (!AdminGovernance.isKeyedRoom(group)) return false
+ if (me in supporters(database, chatRoomId)) return false
+ val tags = GovernanceSupportEvent.assembleTags(chatRoomId)
+ val createdAt = Clock.System.now().epochSeconds
+ val id = EventHasher.hashId(pubKey = me, createdAt = createdAt, kind = GovernanceSupportEvent.KIND, tags = tags, content = "")
+ // Unsent: the outbound worker puts an inner event with no group event behind
+ // it into the room, as it does for every manager's messages.
+ database.marmotInnerEventDao().upsert(
+ MarmotInnerEvent(
+ id = id,
+ publicKey = me,
+ kind = GovernanceSupportEvent.KIND,
+ createdAt = Instant.fromEpochSeconds(createdAt),
+ tags = tags,
+ content = "",
+ chatRoomId = chatRoomId,
+ )
+ )
+ return true
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt
index 60c82131..6403b019 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt
@@ -4,6 +4,8 @@ import co.touchlab.kermit.Logger
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlin.time.Clock
+import fr.acinq.bitcoin.PublicKey
+import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate
import kotlin.time.Instant
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.DkgSession
@@ -219,8 +221,10 @@ object GroupKeyStateManager {
val filed = database.groupKeyStateDao().replace(state)
// `replace` re-stamps what it files, so the row is compared on what it says.
if (filed.generation == state.generation && filed.announcedAt == state.announcedAt) {
- retireOlderShares(database, state)
+ // Bindings first: one that enrolls a new id extends the table, and the
+ // table has to be the one the group signed before older shares go.
applyBindings(database, state)
+ retireOlderShares(database, state)
}
return filed
}
@@ -261,6 +265,9 @@ object GroupKeyStateManager {
val generation = state.generation ?: return
val bindings = GroupKeyStateEvent.MemberBinding.decodeAll(state.memberBindings)
if (bindings.isEmpty()) return
+ // A binding of the next id is an enrollment: the id joins the table first
+ // (docs/member-admin-promotion.md, Phase 8).
+ bindings.forEach { binding -> PromotionManager.enrollNewId(database, state, binding) }
val members = database.keyShareDao().getMembers(state.dkgSessionId, generation)
val changed = bindings.mapNotNull { binding ->
val row = members.firstOrNull { it.participantId == binding.participantId } ?: return@mapNotNull null
@@ -316,50 +323,71 @@ object GroupKeyStateManager {
refreshId: String?,
newBinding: GroupKeyStateEvent.MemberBinding? = null,
): FrostSigningSession {
+ val template = generationTemplate(database, localChatRoom, key, refreshId, newBinding)
+ return FrostSigningManager.proposeSigning(
+ database = database,
+ localChatRoom = localChatRoom,
+ userPublicKey = userPublicKey,
+ kind = template.kind,
+ tags = template.tags,
+ content = template.content,
+ key = key,
+ createdAt = template.createdAt,
+ )
+ }
+
+ /**
+ * The key state [proposeGeneration] asks the group to sign, unsigned, for a caller
+ * that signs it alongside something else -- a promotion signs it with the change
+ * it makes (docs/member-admin-promotion.md, Phase 8). [publicShares], when given,
+ * is the table the state names instead of this device's: the current one with a
+ * new member's public share appended.
+ */
+ suspend fun generationTemplate(
+ database: GizaDatabase,
+ localChatRoom: LocalChatRoom,
+ key: DkgSession,
+ refreshId: String?,
+ newBinding: GroupKeyStateEvent.MemberBinding? = null,
+ publicShares: List? = null,
+ ): EventTemplate {
val shares = ShareGenerations.active(database, key)
check(shares.generation >= 1) { "Generation 0 is the ceremony's, and needs no new key state" }
- val publicShares = requireNotNull(shares.publicShares) { "Generation ${shares.generation} has no public shares" }
+ val table = publicShares ?: requireNotNull(shares.publicShares) { "Generation ${shares.generation} has no public shares" }
val current = keyStateFor(database, localChatRoom.chatRoom.id)
val path = current?.pathIndices() ?: SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH
val parent = current?.parentChatRoomId?.let { parentId ->
current.birthCertificateJson?.let { Event.fromJsonOrNull(it) }?.let { SubgroupParentage(parentId, it) }
}
val thresholdPublicKey = requireNotNull(key.thresholdPublicKey)
- return FrostSigningManager.proposeSigning(
- database = database,
- localChatRoom = localChatRoom,
- userPublicKey = userPublicKey,
- kind = GroupKeyStateEvent.KIND,
- tags = GroupKeyStateEvent.assembleTags(
- chatRoomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey, path),
- dkgSessionId = key.id,
- path = path,
- parent = parent,
- generation = GroupKeyStateEvent.ShareGenerationTags(
- generation = shares.generation,
- publicSharesHash = ShareGenerations.publicSharesHash(publicShares),
- refreshId = refreshId,
- retiredIds = shares.roster.filter { it.standing == ShareStanding.RETIRED }.map { it.participantId },
- // Bindings already in force at this generation stay said, so a
- // later state does not quietly undo them; a new one replaces any
- // earlier binding of the same id.
- bindings = (
- GroupKeyStateEvent.MemberBinding.decodeAll(current?.takeIf { it.generation == shares.generation }?.memberBindings)
- .filter { it.participantId != newBinding?.participantId } + listOfNotNull(newBinding)
- ),
- ),
- ),
- content = thresholdPublicKey,
- key = key,
- // Later than the state it amends, by a second if it must be. Two states
- // at one generation are told apart by their time alone, and a rebind
- // stamped in the same second as the state it adds to would tie with it
- // -- and the binding could be the one that loses.
- createdAt = maxOf(
- Clock.System.now().epochSeconds,
- (current?.takeIf { (it.generation ?: 0) == shares.generation }?.announcedAt?.epochSeconds ?: 0L) + 1
+ val tags = GroupKeyStateEvent.assembleTags(
+ chatRoomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey, path),
+ dkgSessionId = key.id,
+ path = path,
+ parent = parent,
+ generation = GroupKeyStateEvent.ShareGenerationTags(
+ generation = shares.generation,
+ publicSharesHash = ShareGenerations.publicSharesHash(table),
+ refreshId = refreshId,
+ retiredIds = shares.roster.filter { it.standing == ShareStanding.RETIRED }.map { it.participantId },
+ // Bindings already in force at this generation stay said, so a
+ // later state does not quietly undo them; a new one replaces any
+ // earlier binding of the same id.
+ bindings = (
+ GroupKeyStateEvent.MemberBinding.decodeAll(current?.takeIf { it.generation == shares.generation }?.memberBindings)
+ .filter { it.participantId != newBinding?.participantId } + listOfNotNull(newBinding)
+ ),
),
)
+ // Later than the state it amends, by a second if it must be. Two states
+ // at one generation are told apart by their time alone, and a rebind
+ // stamped in the same second as the state it adds to would tie with it
+ // -- and the binding could be the one that loses.
+ val createdAt = maxOf(
+ Clock.System.now().epochSeconds,
+ (current?.takeIf { (it.generation ?: 0) == shares.generation }?.announcedAt?.epochSeconds ?: 0L) + 1
+ )
+ return EventTemplate(createdAt, GroupKeyStateEvent.KIND, tags, thresholdPublicKey)
}
/**
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotEngine.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotEngine.kt
index 1d4a1db8..94892fa9 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotEngine.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotEngine.kt
@@ -90,6 +90,38 @@ class MarmotEngine(
val gate = MarmotPublishGate(groupManager, RoomPublishObligationStore(database))
private val restoreMutex = Mutex()
+
+ /**
+ * The next step of a two-commit change, by the group whose commit it waits on:
+ * removing an admin is a demotion and then the removal, and leaving as an admin
+ * is a step-down and then the leave. Run when that group's commit is confirmed,
+ * dropped when every relay refuses it.
+ *
+ * Keyed by group because the gate allows one commit in flight per group, so the
+ * next confirmation for it is the one this waits on. In memory on purpose: a
+ * restart between the two leaves a demoted member who has not been removed, or
+ * an ex-admin who has not left, and either can be finished with one tap.
+ * docs/member-admin-promotion.md, Phases 6 and 10.
+ */
+ private val followUps = mutableMapOf Unit>()
+ private val followUpsMutex = Mutex()
+
+ /**
+ * Runs [step] once [routingId]'s next commit is confirmed. Registered *before*
+ * that commit is published, so a relay's OK cannot arrive ahead of it; a caller
+ * whose publish then fails takes it back with [cancelFollowUp].
+ */
+ suspend fun afterConfirmed(routingId: HexKey, step: suspend () -> Unit) {
+ followUpsMutex.withLock { followUps[routingId] = step }
+ }
+
+ /** Drops the step [afterConfirmed] registered for [routingId], if any. */
+ suspend fun cancelFollowUp(routingId: HexKey) {
+ takeFollowUp(routingId)
+ }
+
+ private suspend fun takeFollowUp(routingId: HexKey): (suspend () -> Unit)? =
+ followUpsMutex.withLock { followUps.remove(routingId) }
private var restored = false
/**
@@ -224,8 +256,14 @@ class MarmotEngine(
val chatRoomId = database.marmotRoutingDao().chatRoomIdFor(obligation.groupId)
val localChatRoom = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return
val group = groupManager.getGroup(obligation.groupId) ?: return
- MarmotInboundManager.processGroupMembershipChanges(database, localChatRoom, group, announceAdditions = false)
+ MarmotInboundManager.processGroupMembershipChanges(
+ database, localChatRoom, group, announceAdditions = false,
+ priorAdmins = MarmotGroupPolicy.adminIdentitiesIn(obligation.priorState.groupContext.extensions),
+ )
database.marmotOutboundDao().continueDisband(localChatRoom)
+ takeFollowUp(obligation.groupId)?.let { step ->
+ runCatching { step() }.onFailure { logger.w("The step after ${obligation.groupId.take(8)}…'s commit failed: ${it.message}") }
+ }
}
/**
@@ -241,6 +279,7 @@ class MarmotEngine(
ensureRestored()
val obligation = gate.allPending().firstOrNull { it.obligationId == obligationId } ?: return false
gate.resolve(obligationId, PublishOutcome.FAILED)
+ takeFollowUp(obligation.groupId)
logger.w("Commit ${obligationId.take(8)}… discarded; ${obligation.groupId.take(8)}… stays at epoch ${obligation.priorState.groupContext.epoch}")
return true
}
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 e10d30d6..6360103e 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt
@@ -3,6 +3,7 @@ package mobi.giza.compose.managers
import co.touchlab.kermit.Logger
import com.vitorpamplona.marmot.GroupEventResult
import com.vitorpamplona.marmot.foundation.appEvents.MarmotAppEvent
+import com.vitorpamplona.marmot.groups.currentAdminIdentities
import com.vitorpamplona.marmot.groups.currentGroupState
import com.vitorpamplona.marmot.mip03GroupMessages.GroupEventEncryption
import com.vitorpamplona.mls.codec.TlsReader
@@ -127,12 +128,18 @@ object MarmotInboundManager {
* the room out. Both are a terminal state on the other side too -- a removed
* member cannot decrypt the next epoch, and a disbanded group refuses every
* later event -- so nothing is lost by closing here.
+ *
+ * [priorAdmins] is the group's admin set before the commit, read off the
+ * group's state by the caller. With it, promotions and demotions are captioned
+ * too; without it, the flags are corrected and nothing is said about them. See
+ * docs/member-admin-promotion.md, Phase 2.
*/
suspend fun processGroupMembershipChanges(
database: GizaDatabase,
localChatRoom: LocalChatRoom,
mlsGroup: MlsGroup,
announceAdditions: Boolean = true,
+ priorAdmins: Set? = null,
) {
logger.d("processGroupMembershipChanges")
@@ -245,6 +252,25 @@ object MarmotInboundManager {
"${memberName(database, participant.participantPublicKey)} left the group")
}
+ // Who governs the room, from the group's admin set before and after this
+ // commit -- never from the `adminAt` flags, which a room made before
+ // Phase 1 could have wrong. Only for accounts still in the tree: one that
+ // left took its admin rights with it, and "left the group" says so already.
+ if (priorAdmins != null && !disbanded && !removedUs) {
+ val adminPublicKeys = mlsGroup.currentAdminIdentities()
+ val members = committedGroupMembersPublicKeys.toSet()
+ (priorAdmins - adminPublicKeys).filter { it in members }.sorted().forEach { demoted ->
+ announceLine(database, localChatRoom, ChatMessage.TYPE_ADMIN_REMOVED,
+ if (demoted == userPublicKey) "You are no longer an admin"
+ else "${memberName(database, demoted)} is no longer an admin")
+ }
+ (adminPublicKeys - priorAdmins).filter { it in members }.sorted().forEach { promoted ->
+ announceLine(database, localChatRoom, ChatMessage.TYPE_ADMIN_ADDED,
+ if (promoted == userPublicKey) "You are now an admin"
+ else "${memberName(database, promoted)} is now an admin")
+ }
+ }
+
when {
disbanded -> announceLine(database, localChatRoom, ChatMessage.TYPE_GROUP_DISBANDED, "The group was disbanded")
removedUs -> announceLine(database, localChatRoom, ChatMessage.TYPE_MEMBER_LEFT, "You were removed from the group")
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/PromotionManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/PromotionManager.kt
new file mode 100644
index 00000000..5fb0c155
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/PromotionManager.kt
@@ -0,0 +1,386 @@
+package mobi.giza.compose.managers
+
+import co.touchlab.kermit.Logger
+import com.vitorpamplona.marmot.appComponents.AdminPolicyV1
+import com.vitorpamplona.marmot.groups.currentAdminIdentities
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
+import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
+import fr.acinq.bitcoin.ByteVector
+import fr.acinq.bitcoin.PublicKey
+import fr.acinq.bitcoin.crypto.frost.FrostEnrollment
+import kotlin.time.Clock
+import kotlin.time.Instant
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.buildJsonArray
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.int
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.put
+import mobi.giza.compose.ExperimentalFeatures
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.model.ChatMessage
+import mobi.giza.compose.database.model.DkgSession
+import mobi.giza.compose.database.model.GovernanceProposal
+import mobi.giza.compose.database.model.GovernanceProposalStage
+import mobi.giza.compose.database.model.GroupKeyState
+import mobi.giza.compose.database.model.KeyShareGeneration
+import mobi.giza.compose.database.model.KeyShareMember
+import mobi.giza.compose.database.model.MarmotInnerEvent
+import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
+import mobi.giza.compose.database.model.types.DkgRitualStage
+import mobi.giza.compose.database.model.types.ShareGenerationState
+import mobi.giza.compose.database.model.types.ShareStanding
+import mobi.giza.compose.exceptions.MarmotMissingChatGroupException
+import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
+import mobi.giza.compose.nostr.frost.PromotionEvents
+
+/**
+ * Making a member an admin of a keyed room, which makes them a holder of its key
+ * too (R1). docs/member-admin-promotion.md, Phase 8; the steps are on
+ * [PromotionEvents].
+ *
+ * The new member is enrolled at the next participant id, `n`, by reduced FROST
+ * enrollment -- the repair protocol run with `newId = n` and the `n` before it
+ * (`ShareRepairManager`). Every device puts the id in its table the same way: its
+ * public share is derived from the table it already has ([publicShareFor]) and
+ * accepted only when the extended table hashes to what the group signed
+ * ([enrollNewId]). So nothing about the new id is anybody's say-so.
+ *
+ * Only from a key past its ceremony's generation: generation 0 lives in the
+ * ceremony's own record, which has no room for an id the ceremony did not make.
+ */
+object PromotionManager {
+ private val logger = Logger.withTag("PromotionManager")
+
+ // ---- the new id's public share, the same on every device -------------------------------------------------------
+
+ /**
+ * The public share of participant [newId] on the polynomial [table] lies on, by
+ * interpolation in the exponent from its first [threshold] entries. Any t entries
+ * give the same point, so every device that holds the same table gets the same one.
+ */
+ fun publicShareFor(table: List, threshold: Int, newId: Int): PublicKey {
+ val helperIds = (0 until threshold).map { it.toUInt() }
+ val derived = FrostEnrollment.derivePublicShare(table.take(threshold), helperIds, newId.toUInt(), newId, threshold)
+ return derived.right ?: throw IllegalStateException("Couldn't derive id $newId's public share: ${derived.left?.message}")
+ }
+
+ /** [table] with the next id's public share appended. */
+ fun extended(table: List, threshold: Int): List = table + publicShareFor(table, threshold, table.size)
+
+ /**
+ * Puts the next id in this device's table at [state]'s generation, when [binding]
+ * names it and the table extended by its derived public share is the one the
+ * group signed. Called with a signed key state's bindings, before they are
+ * applied; anything else -- an id already there, a table that would hash
+ * differently -- is left alone.
+ */
+ suspend fun enrollNewId(database: GizaDatabase, state: GroupKeyState, binding: GroupKeyStateEvent.MemberBinding) {
+ val generation = state.generation ?: return
+ val key = database.dkgSessionDao().getSessionById(state.dkgSessionId) ?: return
+ val row = database.keyShareDao().getGeneration(key.id, generation) ?: return
+ val table = row.publicShareList() ?: return
+ if (binding.participantId != table.size) return
+ if (database.keyShareDao().getMembers(key.id, generation).any { it.participantId == binding.participantId }) return
+
+ val withNewId = extended(table, key.threshold)
+ if (ShareGenerations.publicSharesHash(withNewId) != state.publicSharesHash) {
+ logger.w("A key state enrolls id ${binding.participantId} of ${key.id} with a table this device's does not extend to; leaving it")
+ return
+ }
+ val now = Clock.System.now()
+ database.keyShareDao().upsert(row.copy(publicShares = withNewId.joinToString(",") { it.value.toHex() }, updatedAt = now))
+ database.keyShareDao().upsert(
+ listOf(
+ KeyShareMember(
+ dkgSessionId = key.id,
+ generation = generation,
+ participantId = binding.participantId,
+ memberPublicKey = binding.memberPublicKey,
+ hostPublicKey = binding.hostPublicKey,
+ standing = ShareStanding.STALE,
+ )
+ )
+ )
+ logger.i("Id ${binding.participantId} of ${key.id} added for ${binding.memberPublicKey.take(8)}…, to be enrolled")
+ }
+
+ // ---- 1. the offer --------------------------------------------------------------------------------------------
+
+ /**
+ * Offers [target] the role of admin in [localChatRoom], as [me]. Refused, in words
+ * a person can act on, where the room or its key cannot take a new admin.
+ */
+ suspend fun offer(database: GizaDatabase, localChatRoom: LocalChatRoom, me: HexKey, target: HexKey): HexKey {
+ val group = database.marmotEngine.groupFor(localChatRoom.routingId)
+ ?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}")
+ check(AdminGovernance.keyedChangesAllowed(group)) { "This group's admins can't be changed from this device" }
+ check(me in group.currentAdminIdentities()) { "Only an admin can make someone else one" }
+ require(target in AdminGovernance.members(group)) { "They are not in the group any more" }
+ if (target in group.currentAdminIdentities()) return ""
+ val key = FrostSigningManager.completedKey(database, localChatRoom.chatRoom.id)
+ ?: throw IllegalStateException("This device holds no share of the group's key")
+ check(ShareGenerations.active(database, key).generation >= 1) {
+ "Rotate the group's shares once before adding an admin: the key's first generation is its ceremony's, and has no room for a new member"
+ }
+ val id = send(database, localChatRoom.chatRoom.id, me, PromotionEvents.OFFER, "", PromotionEvents.offerTags(localChatRoom.chatRoom.id, target))
+ announce(database, localChatRoom.chatRoom.id, me, ChatMessage.TYPE_ADMIN_OFFERED, "Asked ${nameOf(database, target)} to become an admin")
+ return id
+ }
+
+ /** An offer to [me] in [chatRoomId] that has not been answered, if there is one. */
+ data class Offer(val id: HexKey, val from: HexKey)
+
+ suspend fun pendingOffer(database: GizaDatabase, chatRoomId: String, me: HexKey): Offer? {
+ val events = database.marmotInnerEventDao().getByChatRoomAndKinds(chatRoomId, listOf(PromotionEvents.OFFER, PromotionEvents.ACCEPT))
+ val answered = events.filter { it.kind == PromotionEvents.ACCEPT && it.publicKey == me }
+ .mapNotNull { PromotionEvents.value(it.tags, PromotionEvents.OFFER_TAG) }
+ .toSet()
+ val offer = events.lastOrNull {
+ it.kind == PromotionEvents.OFFER && PromotionEvents.value(it.tags, PromotionEvents.TARGET_TAG) == me && it.id !in answered
+ } ?: return null
+ return Offer(offer.id, offer.publicKey)
+ }
+
+ // ---- 2. the acceptance ---------------------------------------------------------------------------------------
+
+ /**
+ * Accepts [offerId], as [me], naming the ChillDKG host key that shares sent to
+ * this device will be sealed to: derived from the account key, as a ceremony's is.
+ */
+ suspend fun accept(database: GizaDatabase, localChatRoom: LocalChatRoom, me: HexKey, nostrPrivateKey: ByteArray, offerId: HexKey) {
+ check(ExperimentalFeatures.shareRefresh) { "This build does not take part in enrollment" }
+ val host = ChillDkgRitualManager.deriveHostPublicKey(nostrPrivateKey).value.toHex()
+ send(database, localChatRoom.chatRoom.id, me, PromotionEvents.ACCEPT, "", PromotionEvents.acceptTags(localChatRoom.chatRoom.id, offerId, host))
+ announce(database, localChatRoom.chatRoom.id, me, ChatMessage.TYPE_ADMIN_OFFERED, "You accepted becoming an admin. The group signs it next")
+ }
+
+ // ---- 3. the proposal, by the device that offered ---------------------------------------------------------------
+
+ /** This device's offers that have been accepted and not yet proposed, with their acceptance. */
+ suspend fun acceptedOffers(database: GizaDatabase, me: HexKey): List> {
+ val events = database.marmotInnerEventDao().getByKinds(listOf(PromotionEvents.OFFER, PromotionEvents.ACCEPT))
+ val proposed = database.governanceProposalDao().getAll()
+ .filter { it.stage != GovernanceProposalStage.STALE }
+ .mapNotNull { it.promotionOfferId }
+ .toSet()
+ return events.filter { it.kind == PromotionEvents.OFFER && it.publicKey == me && it.id !in proposed }.mapNotNull { offer ->
+ val target = PromotionEvents.value(offer.tags, PromotionEvents.TARGET_TAG) ?: return@mapNotNull null
+ val acceptance = events.lastOrNull {
+ it.kind == PromotionEvents.ACCEPT && it.publicKey == target &&
+ PromotionEvents.value(it.tags, PromotionEvents.OFFER_TAG) == offer.id
+ } ?: return@mapNotNull null
+ offer to acceptance
+ }
+ }
+
+ /**
+ * Proposes the promotion [offer] and [acceptance] agreed: one batch for the group
+ * to sign, the change that makes the member an admin and the key state that binds
+ * the next participant id to them, with that id's public share in the table.
+ */
+ suspend fun propose(
+ database: GizaDatabase,
+ localChatRoom: LocalChatRoom,
+ me: HexKey,
+ offer: MarmotInnerEvent,
+ acceptance: MarmotInnerEvent,
+ ): String {
+ val target = requireNotNull(PromotionEvents.value(offer.tags, PromotionEvents.TARGET_TAG))
+ val host = requireNotNull(PromotionEvents.value(acceptance.tags, PromotionEvents.HOST_KEY_TAG)?.lowercase()?.takeIf { it.length == 66 }) {
+ "The acceptance names no host key"
+ }
+ val group = database.marmotEngine.groupFor(localChatRoom.routingId)
+ ?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}")
+ val key = FrostSigningManager.completedKey(database, localChatRoom.chatRoom.id)
+ ?: throw IllegalStateException("This device holds no share of the group's key")
+ val shares = ShareGenerations.active(database, key)
+ val table = requireNotNull(shares.publicShares) { "Generation ${shares.generation} has no public shares" }
+ val binding = GroupKeyStateEvent.MemberBinding(table.size, target, host)
+ val keyState = GroupKeyStateManager.generationTemplate(
+ database, localChatRoom, key, refreshId = null, newBinding = binding, publicShares = extended(table, key.threshold),
+ )
+ val admins = group.currentAdminIdentities()
+ return GovernanceManager.propose(
+ database, localChatRoom, me,
+ promotionOfferId = offer.id,
+ alsoSign = listOf(keyState),
+ ) { copy ->
+ copy.proposeAppDataUpdate(AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(admins + target).encode())
+ }
+ }
+
+ // ---- 4. the handover, once the change lands --------------------------------------------------------------------
+
+ /** This device's promotions that have landed and not yet been handed over. */
+ suspend fun handoversOwed(database: GizaDatabase): List =
+ database.governanceProposalDao().getAll().filter { proposal ->
+ proposal.promotionOfferId != null && (
+ proposal.stage == GovernanceProposalStage.APPLIED ||
+ (proposal.stage == GovernanceProposalStage.PUBLISHED && (database.marmotEngine.groupFor(proposal.routingId)?.epoch ?: 0) > proposal.epoch)
+ )
+ }
+
+ /**
+ * Hands the new admin what they need to be enrolled: the table and roster of the
+ * generation the group signs with, and the key state that binds their id, as the
+ * group signed it. Marks [proposal] done.
+ */
+ suspend fun handover(database: GizaDatabase, proposal: GovernanceProposal, me: HexKey) {
+ val offer = database.marmotInnerEventDao().getById(proposal.promotionOfferId ?: return) ?: return
+ val target = PromotionEvents.value(offer.tags, PromotionEvents.TARGET_TAG) ?: return
+ val content = handoverContent(database, proposal.chatRoomId) ?: return
+ send(database, proposal.chatRoomId, me, PromotionEvents.HANDOVER, content, PromotionEvents.handoverTags(proposal.chatRoomId, target))
+ database.governanceProposalDao().upsert(proposal.copy(stage = GovernanceProposalStage.DONE, updatedAt = Clock.System.now()))
+ }
+
+ /**
+ * What a handover says about [chatRoomId]'s key, from this device: the table and
+ * roster of the generation the group signs with, and the key state as the group
+ * signed it. Null when this device holds no key for the room or no signed state.
+ */
+ suspend fun handoverContent(database: GizaDatabase, chatRoomId: String): String? {
+ val key = FrostSigningManager.completedKey(database, chatRoomId) ?: return null
+ val shares = ShareGenerations.active(database, key)
+ val table = shares.publicShares ?: return null
+ val signedState = GroupKeyStateManager.signedEventFor(database, chatRoomId)?.toEvent() ?: return null
+ return buildJsonObject {
+ put("key", key.id)
+ put("generation", shares.generation)
+ put("threshold", key.threshold)
+ put("thresholdPublicKey", requireNotNull(key.thresholdPublicKey))
+ put("publicShares", buildJsonArray { table.forEach { add(JsonPrimitive(it.value.toHex())) } })
+ put("roster", buildJsonArray {
+ shares.roster.forEach { entry ->
+ add(buildJsonArray {
+ add(JsonPrimitive(entry.participantId)); add(JsonPrimitive(entry.memberPublicKey))
+ add(JsonPrimitive(entry.hostPublicKey)); add(JsonPrimitive(entry.standing.name))
+ })
+ }
+ })
+ put("keyState", signedState.toJson())
+ }.toString()
+ }
+
+ // ---- 5. the new admin's device ----------------------------------------------------------------------------------
+
+ /** Handovers to [me] this device has not acted on: no enrollment of its own for the key yet. */
+ suspend fun handoversToMe(database: GizaDatabase, me: HexKey): List =
+ database.marmotInnerEventDao().getByKinds(listOf(PromotionEvents.HANDOVER)).filter { handover ->
+ PromotionEvents.value(handover.tags, PromotionEvents.TARGET_TAG) == me && handover.publicKey != me &&
+ runCatching { Json.parseToJsonElement(handover.content).jsonObject["key"]!!.jsonPrimitive.content }.getOrNull()
+ ?.let { keyId -> database.shareRepairDao().getSessionsForKey(keyId).none { it.targetPublicKey == me } } == true
+ }
+
+ /**
+ * Takes [handover] as the new admin: checks it against the room's own signature,
+ * files what it says -- this device's record of the key, its table and roster,
+ * and the signed key state -- and asks to be enrolled at its id. Nothing in it is
+ * taken on the sender's word: the key state has to be one the room signed and
+ * that derives the room, the table has to hash to what it names, and it has to
+ * bind the next id to this account under this device's host key.
+ */
+ suspend fun takeHandover(database: GizaDatabase, localChatRoom: LocalChatRoom, me: HexKey, nostrPrivateKey: ByteArray, handover: MarmotInnerEvent) {
+ val json = Json.parseToJsonElement(handover.content).jsonObject
+ val keyId = json["key"]!!.jsonPrimitive.content
+ val generation = json["generation"]!!.jsonPrimitive.int
+ val threshold = json["threshold"]!!.jsonPrimitive.int
+ val thresholdPublicKey = json["thresholdPublicKey"]!!.jsonPrimitive.content
+ val table = json["publicShares"]!!.jsonArray.map { PublicKey(ByteVector(it.jsonPrimitive.content.hexToByteArray())) }
+ val roster = (json["roster"] as JsonArray).map { row ->
+ val cells = row.jsonArray
+ KeyShareMember(
+ dkgSessionId = keyId,
+ generation = generation,
+ participantId = cells[0].jsonPrimitive.int,
+ memberPublicKey = cells[1].jsonPrimitive.content,
+ hostPublicKey = cells[2].jsonPrimitive.content.lowercase(),
+ standing = ShareStanding.valueOf(cells[3].jsonPrimitive.content),
+ )
+ }
+ val keyStateEvent = Event.fromJson(json["keyState"]!!.jsonPrimitive.content)
+ val myHost = ChillDkgRitualManager.deriveHostPublicKey(nostrPrivateKey).value.toHex()
+ val newId = table.size - 1
+
+ val state = GroupKeyStateManager.stateFrom(localChatRoom.chatRoom.id, keyStateEvent)
+ val binding = GroupKeyStateEvent.MemberBinding.decodeAll(state?.memberBindings).firstOrNull { it.participantId == newId }
+ val refusal = when {
+ state == null -> "its key state is not one this room signed"
+ state.dkgSessionId != keyId || state.generation != generation -> "its key state is for another key or generation"
+ !state.thresholdPublicKey.equals(thresholdPublicKey, ignoreCase = true) -> "its key is not the room's"
+ ShareGenerations.publicSharesHash(table) != state.publicSharesHash -> "its table is not the one the group signed"
+ binding == null || binding.memberPublicKey != me || !binding.hostPublicKey.equals(myHost, ignoreCase = true) -> "the group did not bind the new id to this device"
+ roster.map { it.participantId } != table.indices.toList() -> "its roster does not match its table"
+ else -> null
+ }
+ if (refusal != null) {
+ logger.w("Refusing a handover in ${localChatRoom.chatRoom.id}: $refusal")
+ announce(database, localChatRoom.chatRoom.id, me, ChatMessage.TYPE_CHANGE_NOT_APPLIED, "Couldn't take a share of the group's key: $refusal")
+ return
+ }
+
+ val now = Clock.System.now()
+ val key = database.dkgSessionDao().getSessionById(keyId) ?: DkgSession(
+ id = keyId,
+ chatRoomId = localChatRoom.chatRoom.id,
+ coordinatorPublicKey = handover.publicKey,
+ userPublicKey = me,
+ threshold = threshold,
+ participantCount = newId,
+ stage = DkgRitualStage.COMPLETE,
+ hostPublicKey = myHost,
+ round1Random = "00".repeat(32),
+ round2AuxRandom = "00".repeat(32),
+ thresholdPublicKey = thresholdPublicKey,
+ ).also { database.dkgSessionDao().upsert(it) }
+ if (database.keyShareDao().getGeneration(keyId, generation) == null) {
+ database.keyShareDao().upsert(
+ KeyShareGeneration(
+ dkgSessionId = keyId,
+ generation = generation,
+ secretShare = null,
+ publicShares = table.joinToString(",") { it.value.toHex() },
+ state = ShareGenerationState.ACTIVE,
+ activatedAt = now,
+ )
+ )
+ database.keyShareDao().upsert(roster)
+ }
+ GroupKeyStateManager.record(database, localChatRoom.chatRoom.id, keyStateEvent)
+ ShareRepairManager.requestRepair(database, localChatRoom, me, nostrPrivateKey, key, targetId = newId, nParticipants = newId)
+ }
+
+ // ---- plumbing ----------------------------------------------------------------------------------------------------
+
+ /** Puts an inner event on the outbound queue, as every manager's messages go. Returns its id. */
+ private suspend fun send(database: GizaDatabase, chatRoomId: String, me: HexKey, kind: Int, content: String, tags: Array>): HexKey {
+ val createdAt = Clock.System.now().epochSeconds
+ val id = EventHasher.hashId(pubKey = me, createdAt = createdAt, kind = kind, tags = tags, content = content)
+ database.marmotInnerEventDao().upsert(
+ MarmotInnerEvent(
+ id = id, publicKey = me, kind = kind, createdAt = Instant.fromEpochSeconds(createdAt),
+ tags = tags, content = content, chatRoomId = chatRoomId,
+ )
+ )
+ return id
+ }
+
+ private suspend fun announce(database: GizaDatabase, chatRoomId: String, me: HexKey, type: String, content: String) {
+ database.chatMessageDao().upsert(
+ ChatMessage(
+ content = content, messageType = type, chatRoomId = chatRoomId, senderPublicKey = me,
+ isUserMessage = true, giftWrapPayloadId = null, marmotGroupEventId = null, marmotInnerEventId = null,
+ )
+ )
+ }
+
+ private suspend fun nameOf(database: GizaDatabase, publicKey: HexKey): String =
+ database.profileDao().getProfileByPublicKey(publicKey)?.humanReadableNameOrPubkey() ?: publicKey.take(8)
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/Quorum.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/Quorum.kt
index f0759d2f..4655154c 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/Quorum.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/Quorum.kt
@@ -41,4 +41,14 @@ object Quorum {
/** Whether a group of [memberCount] people, its creator included, can be made. */
fun isPossible(memberCount: Int): Boolean = memberCount >= MINIMUM_GROUP_SIZE
+
+ /**
+ * The fewest admins a group may ever have: [MINIMUM_GROUP_SIZE], or its quorum
+ * [threshold] when that is higher. In a group around a key the admins are its
+ * share holders, so fewer than [threshold] of them is a key that can never sign
+ * again -- and nothing about the group could change after that. Null [threshold]
+ * means this device does not know it, and the size floor alone applies.
+ * docs/member-admin-promotion.md, R3 and D8.
+ */
+ fun minimumAdmins(threshold: Int?): Int = maxOf(MINIMUM_GROUP_SIZE, threshold ?: 0)
}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRepairManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRepairManager.kt
index 41dcaa31..fa76952a 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRepairManager.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRepairManager.kt
@@ -71,6 +71,7 @@ object ShareRepairManager {
nostrPrivateKey: ByteArray,
key: DkgSession,
targetId: Int? = null,
+ nParticipants: Int? = null,
): ShareRepairSession {
check(ExperimentalFeatures.shareRefresh) { "This build does not repair shares" }
require(key.stage == DkgRitualStage.COMPLETE) { "Ceremony ${key.id} has not produced a key" }
@@ -95,9 +96,14 @@ object ShareRepairManager {
userPublicKey = userPublicKey,
stage = if (isBound(entry, userPublicKey, hostPublicKey)) ShareRepairStage.COLLECTING else ShareRepairStage.AWAITING_BINDING,
sessionRandom = RandomInstance.bytes(32).toHex(),
+ nParticipants = nParticipants,
)
database.shareRepairDao().upsert(session)
- announce(database, session, ChatMessage.TYPE_SHARE_REPAIR_REQUESTED, "asked to be brought back into the group's signing.", userPublicKey)
+ announce(
+ database, session, ChatMessage.TYPE_SHARE_REPAIR_REQUESTED,
+ if (nParticipants != null) "asked to be given a share of the group's key." else "asked to be brought back into the group's signing.",
+ userPublicKey,
+ )
broadcast(
database, localChatRoom, userPublicKey, ShareRepairEvents.REQUEST, "",
arrayOf(
@@ -107,7 +113,7 @@ object ShareRepairManager {
arrayOf(ShareRepairEvents.TARGET_TAG, id.toString()),
arrayOf(ShareRepairEvents.HELPERS_TAG, session.helperIds),
arrayOf(ShareRepairEvents.HOST_KEY_TAG, hostPublicKey),
- )
+ ) + listOfNotNull(nParticipants?.let { arrayOf(ShareRepairEvents.N_TAG, it.toString()) })
)
return session
}
@@ -146,8 +152,15 @@ object ShareRepairManager {
val helpers = tag(ShareRepairEvents.HELPERS_TAG)?.split(",")?.map { it.trim().toIntOrNull() ?: return null } ?: return null
val shares = ShareGenerations.active(database, key)
val entry = shares.roster.firstOrNull { it.participantId == targetId }
+ // An enrollment at a new id names the n it runs with, which has to be that
+ // id: one past the table the group had before the new member's public share
+ // was added to it (docs/member-admin-promotion.md, Phase 8).
+ val nParticipants = tag(ShareRepairEvents.N_TAG)?.let { it.toIntOrNull() ?: return null }
+ val tableSize = shares.publicShares?.size ?: return null
val reason = when {
+ nParticipants != null && (nParticipants != targetId || tableSize != targetId + 1) ->
+ "it enrolls id $targetId with n = $nParticipants, and this device's table has $tableSize entries"
shares.generation != generation -> "it repairs into generation $generation, and this device is at ${shares.generation}"
entry == null -> "id $targetId is not in the key"
entry.standing != ShareStanding.STALE -> "id $targetId is ${entry.standing.name.lowercase()}"
@@ -173,11 +186,14 @@ object ShareRepairManager {
userPublicKey = userPublicKey,
stage = if (isBound(entry!!, event.pubKey, hostKey)) ShareRepairStage.COLLECTING else ShareRepairStage.AWAITING_BINDING,
sessionRandom = RandomInstance.bytes(32).toHex(),
+ nParticipants = nParticipants,
)
database.shareRepairDao().upsert(session)
announce(
database, session, ChatMessage.TYPE_SHARE_REPAIR_REQUESTED,
- if (session.stage == ShareRepairStage.AWAITING_BINDING) {
+ if (nParticipants != null) {
+ "asked to be given a share of the group's key, as the group agreed."
+ } else if (session.stage == ShareRepairStage.AWAITING_BINDING) {
"asked to be brought back into the group's signing under a new identity. The group has to bind them to the id first."
} else {
"asked to be brought back into the group's signing."
@@ -236,7 +252,9 @@ object ShareRepairManager {
val thresholdPublicKey = PublicKey(ByteVector(requireNotNull(key.thresholdPublicKey).hexToByteArray()))
val helpers = session.helperIdList()
val helperIds = helpers.map { it.toUInt() }
- val n = key.participantCount
+ // The table's size, not the ceremony's count: an enrollment grows it. An
+ // enrollment runs with the n before it, which its session names.
+ val n = session.nParticipants ?: table.size
val t = key.threshold
val sid = ByteVector32(session.id)
val hostSecretKey = ChillDkgRitualManager.deriveHostSecretKey(nostrPrivateKey)
@@ -251,13 +269,16 @@ object ShareRepairManager {
throw IllegalStateException("the repaired member's proof does not match the group's public share")
}
markLive(database, key, session)
- complete(database, session, "was brought back into the group's signing.", session.targetPublicKey)
+ complete(database, session, completedLine(session), session.targetPublicKey)
return
}
// ---- a helper ----
if (myId != null && myId in helpers && session.userPublicKey != session.targetPublicKey) {
- if (session.helpApprovedAt == null) {
+ // An enrollment needs no approval of its own: the group signed the
+ // binding that makes the new member the holder of this id, and that
+ // signature was every helper's chance to say no.
+ if (session.helpApprovedAt == null && session.nParticipants == null) {
if (!session.approvalRequested) {
update(database, session) { it.copy(approvalRequested = true) }
announce(database, session, ChatMessage.TYPE_SHARE_REPAIR_APPROVAL_NEEDED, "Your approval is needed to help bring a member back into the group's signing.", session.userPublicKey)
@@ -316,7 +337,7 @@ object ShareRepairManager {
val proof = Crypto.signSchnorr(sid, share, null)
broadcast(database, localChatRoom, session.userPublicKey, ShareRepairEvents.DONE, proof.toHex(), arrayOf(arrayOf(ShareRepairEvents.SESSION_TAG, session.id)))
markLive(database, key, session)
- complete(database, session, "was brought back into the group's signing.", session.targetPublicKey)
+ complete(database, session, completedLine(session), session.targetPublicKey)
}
} catch (e: CancellationException) {
throw e
@@ -327,6 +348,9 @@ object ShareRepairManager {
}
}
+ private fun completedLine(session: ShareRepairSession): String =
+ if (session.nParticipants != null) "now holds a share of the group's key." else "was brought back into the group's signing."
+
/** Approves helping with a repair, and moves on. */
suspend fun approve(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) {
val session = database.shareRepairDao().getSessionById(sessionId) ?: return
@@ -337,7 +361,7 @@ object ShareRepairManager {
/** Whether this device's owner is being asked to help with [session]. */
suspend fun isAwaitingApproval(database: GizaDatabase, session: ShareRepairSession): Boolean {
- if (session.stage != ShareRepairStage.COLLECTING || session.helpApprovedAt != null) return false
+ if (session.stage != ShareRepairStage.COLLECTING || session.helpApprovedAt != null || session.nParticipants != null) return false
val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return false
val shares = ShareGenerations.at(database, key, session.generation) ?: return false
val myId = shares.roster.firstOrNull { it.memberPublicKey == session.userPublicKey && it.standing == ShareStanding.LIVE }?.participantId
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceEvents.kt
new file mode 100644
index 00000000..f3b6dae0
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceEvents.kt
@@ -0,0 +1,139 @@
+package mobi.giza.compose.nostr.frost
+
+import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.verify
+import com.vitorpamplona.quartz.nip01Core.core.Kind
+import com.vitorpamplona.quartz.nip01Core.tags.dTag.DTag
+
+/**
+ * The envelopes a governed room's commits travel in. docs/member-admin-promotion.md,
+ * the headline and Phase 4.
+ *
+ * In a room whose state says changes need the group's signature, no commit is sent
+ * bare. A change goes inside the group's signature ([GovernanceStatementEvent],
+ * 30370); a commit that needs nobody's signature -- a member's own leave folded in,
+ * a committer's own key update (D6) -- goes inside its committer's ([OwnCommitEvent],
+ * 30371). Either way the envelope's content is the complete kind:445 event that
+ * carries the commit, exactly as it would have been published, so every device hands
+ * the engine the same event with the same id.
+ *
+ * They travel as application messages inside the group, which no relay can open,
+ * and none is a chat line. A statement is signed by the room, not by whoever sends
+ * it, and the inbound path holds every application message to its sender's own key
+ * (MIP-03) -- so a statement goes inside a [GovernanceCarrierEvent] signed by the
+ * member who sends it. An own commit is already its sender's and needs no carrier.
+ */
+object GovernanceEvents {
+ val ALL: Set = setOf(
+ GovernanceStatementEvent.KIND, OwnCommitEvent.KIND, GovernanceSupportEvent.KIND, GovernanceCarrierEvent.KIND,
+ PromotionEvents.OFFER, PromotionEvents.ACCEPT, PromotionEvents.HANDOVER,
+ )
+
+ /** The epoch tag every envelope names: the epoch its commit is built at. */
+ const val EPOCH_TAG = "epoch"
+
+ /**
+ * The kind:445 an envelope carries, or null when its content is not one. Its id
+ * is checked against its fields -- the envelope's signature covers the content,
+ * not the inner event's own consistency.
+ */
+ fun innerCommitOf(envelope: Event): GroupEvent? = runCatching {
+ val inner = Event.fromJson(envelope.content)
+ if (inner.kind != GroupEvent.KIND || !inner.verify()) return null
+ GroupEvent(inner.id, inner.pubKey, inner.createdAt, inner.tags, inner.content, inner.sig)
+ }.getOrNull()
+
+ /** The room an envelope names, by its `d` tag. */
+ fun roomOf(envelope: Event): HexKey? = envelope.tags.firstOrNull { it.size >= 2 && it[0] == "d" }?.get(1)
+
+ /** The epoch an envelope names. */
+ fun epochOf(envelope: Event): Long? =
+ envelope.tags.firstOrNull { it.size >= 2 && it[0] == EPOCH_TAG }?.get(1)?.toLongOrNull()
+}
+
+/**
+ * A commit that needs nobody's signature (D6), signed by the account that made it:
+ * a member's own leave, folded in by an admin's device, or a committer's own key
+ * update. Accepted only when running it shows it really is one of those and its
+ * sender -- whom MLS authenticates -- is the account whose leaf committed it.
+ */
+object OwnCommitEvent {
+ val KIND: Kind = 30371
+
+ fun assembleTags(chatRoomId: HexKey, epoch: Long): Array> =
+ arrayOf(DTag.assemble(chatRoomId), arrayOf(GovernanceEvents.EPOCH_TAG, epoch.toString()))
+}
+
+/**
+ * A member's word that their device applies signed commits, said once per room so
+ * the room can tell when the rule can be switched on without leaving anybody behind.
+ * Signed by the member's account. docs/member-admin-promotion.md, Phase 4b.
+ */
+object GovernanceSupportEvent {
+ val KIND: Kind = 30372
+
+ const val VERSION_TAG = "governance"
+ const val VERSION = "signed-commits/v1"
+
+ fun assembleTags(chatRoomId: HexKey): Array> =
+ arrayOf(DTag.assemble(chatRoomId), arrayOf(VERSION_TAG, VERSION))
+
+ fun supports(event: Event): Boolean =
+ event.kind == KIND && event.tags.any { it.size >= 2 && it[0] == VERSION_TAG && it[1] == VERSION }
+}
+
+/**
+ * A member sending the group's signed statement into the room: its content is the
+ * statement, as signed. The carrier vouches for nothing -- the statement inside is
+ * checked on its own signature -- it only gets the statement past the rule that an
+ * application message is its sender's (MIP-03).
+ */
+object GovernanceCarrierEvent {
+ val KIND: Kind = 30373
+
+ fun assembleTags(chatRoomId: HexKey): Array> = arrayOf(DTag.assemble(chatRoomId))
+
+ /** The statement [carrier] carries, or null when it carries none. */
+ fun statementOf(carrier: Event): Event? = runCatching {
+ Event.fromJson(carrier.content).takeIf { it.kind == GovernanceStatementEvent.KIND }
+ }.getOrNull()
+}
+
+/**
+ * Making a member an admin of a keyed room, which also makes them a holder of its
+ * key (R1). docs/member-admin-promotion.md, Phase 8.
+ *
+ * 1. An admin offers ([OFFER]) -- a request, carrying no authority.
+ * 2. The member accepts ([ACCEPT]), naming the ChillDKG host key the shares sent
+ * to them will be sealed to. This is the one decision only they can make.
+ * 3. The group signs the promotion and the key state that binds the next
+ * participant id to them, in one batch, and the commit lands.
+ * 4. The proposer hands over ([HANDOVER]) what the new member needs to take part:
+ * the share table, the roster and the signed key state. Nothing in it is
+ * trusted on the proposer's word -- the table has to hash to what the group
+ * signed, and the state has to be the room's own signature.
+ * 5. The member asks to be enrolled at the new id, and t holders run reduced
+ * FROST enrollment for them, as they would a repair.
+ */
+object PromotionEvents {
+ val OFFER: Kind = 30374
+ val ACCEPT: Kind = 30375
+ val HANDOVER: Kind = 30376
+
+ const val TARGET_TAG = "target"
+ const val OFFER_TAG = "offer"
+ const val HOST_KEY_TAG = "host"
+
+ fun offerTags(chatRoomId: HexKey, target: HexKey): Array> =
+ arrayOf(DTag.assemble(chatRoomId), arrayOf(TARGET_TAG, target))
+
+ fun acceptTags(chatRoomId: HexKey, offerId: HexKey, hostPublicKey: HexKey): Array> =
+ arrayOf(DTag.assemble(chatRoomId), arrayOf(OFFER_TAG, offerId), arrayOf(HOST_KEY_TAG, hostPublicKey))
+
+ fun handoverTags(chatRoomId: HexKey, target: HexKey): Array> =
+ arrayOf(DTag.assemble(chatRoomId), arrayOf(TARGET_TAG, target))
+
+ fun value(tags: Array>, name: String): String? = tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1)
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceStatementEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceStatementEvent.kt
new file mode 100644
index 00000000..5c576a0b
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GovernanceStatementEvent.kt
@@ -0,0 +1,176 @@
+package mobi.giza.compose.nostr.frost
+
+import com.vitorpamplona.crypto.sha2.sha256
+import com.vitorpamplona.marmot.appComponents.AdminPolicyV1
+import com.vitorpamplona.mls.group.GroupView
+import com.vitorpamplona.mls.group.PendingProposal
+import com.vitorpamplona.mls.messages.Proposal
+import com.vitorpamplona.mls.tree.Credential
+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.toHexKey
+import com.vitorpamplona.quartz.nip01Core.tags.dTag.DTag
+import mobi.giza.compose.extensions.toHex
+
+/**
+ * What a keyed room's quorum signs before anything about the room may change: one
+ * statement, naming one epoch, saying exactly what the commit made at that epoch
+ * will do. docs/member-admin-promotion.md, R2 and Phase 3.
+ *
+ * ```
+ * ["d", ]
+ * ["epoch", ] -- the epoch the commit is built at
+ * ["add", , ] -- one per member added
+ * ["remove", ] -- one per member removed
+ * ["admins", , ...] -- the whole admin list after, when it changes
+ * ["component", , | "remove"] -- any other GroupContext component
+ * ["proposer", ]
+ * ```
+ *
+ * Readable on its face, because a member approving it is approving those lines:
+ * "make Bob an admin", not a hash of a commit. Bound to one epoch, because a
+ * statement good at any epoch could be replayed -- a demotion signed once and
+ * applied could be applied again after the member was promoted back. And the
+ * whole change, not a summary of it: [authorises] holds a commit to *exactly*
+ * these lines, so an extra Add folded in beside a signed promotion is refused.
+ *
+ * Signed by the room itself. A keyed room's id is the group's key walked to the
+ * room's path, so the key that must have signed is the room's id and nothing has
+ * to be looked up -- [GroupKeyStateEvent.isSignedByRoom].
+ *
+ * Kind 30370: past the last of the wallet kinds Giza retired
+ * (`RetiredKinds.GROUP_LIGHTNING`). Like every kind in the signing family it only ever travels
+ * inside an encryption a relay cannot open.
+ */
+object GovernanceStatementEvent {
+ val KIND: Kind = 30370
+
+ const val EPOCH_TAG = "epoch"
+ const val ADD_TAG = "add"
+ const val REMOVE_TAG = "remove"
+ const val ADMINS_TAG = "admins"
+ const val COMPONENT_TAG = "component"
+ const val PROPOSER_TAG = "proposer"
+ const val REMOVED = "remove"
+
+ fun isGovernanceStatementKind(kind: Kind): Boolean = kind == KIND
+
+ /** The tags of a statement that [change] be made to [chatRoomId] at [epoch]. */
+ fun assembleTags(chatRoomId: HexKey, epoch: Long, change: GovernanceChange, proposer: HexKey): Array> =
+ arrayOf(DTag.assemble(chatRoomId), arrayOf(EPOCH_TAG, epoch.toString())) +
+ change.adds.sortedBy { it.account }.map { arrayOf(ADD_TAG, it.account, it.keyPackageRef) } +
+ change.removes.sorted().map { arrayOf(REMOVE_TAG, it) } +
+ listOfNotNull(change.admins?.let { arrayOf(ADMINS_TAG, *it.sorted().toTypedArray()) }) +
+ change.components.toSortedMap().map { (id, digest) -> arrayOf(COMPONENT_TAG, id.toString(), digest) } +
+ arrayOf(arrayOf(PROPOSER_TAG, proposer))
+
+ /** A statement as its tags say it, or null when they do not make one. */
+ fun parse(event: Event): GovernanceStatement? = runCatching {
+ if (event.kind != KIND) return null
+ val tags = event.tags
+ val room = tags.firstOrNull { it.size >= 2 && it[0] == "d" }?.get(1) ?: return null
+ val epoch = tags.single { it.size == 2 && it[0] == EPOCH_TAG }[1].toLong()
+ val adminTags = tags.filter { it.isNotEmpty() && it[0] == ADMINS_TAG }
+ if (adminTags.size > 1) return null
+ GovernanceStatement(
+ chatRoomId = room,
+ epoch = epoch,
+ proposer = tags.firstOrNull { it.size >= 2 && it[0] == PROPOSER_TAG }?.get(1),
+ change = GovernanceChange(
+ adds = tags.filter { it.isNotEmpty() && it[0] == ADD_TAG }.map { AddedMember(it[1], it[2]) }.toSet(),
+ removes = tags.filter { it.isNotEmpty() && it[0] == REMOVE_TAG }.map { it[1] }.toSet(),
+ admins = adminTags.singleOrNull()?.drop(1)?.toSet(),
+ components = tags.filter { it.isNotEmpty() && it[0] == COMPONENT_TAG }.associate { it[1].toInt() to it[2] },
+ ),
+ )
+ }.getOrNull()
+
+ /**
+ * Whether [event] is the room's own signature on [change] at [epoch]: its kind,
+ * the room's signature on it, the room and epoch it names, and a change equal to
+ * [change] -- nothing more and nothing less. Every input is off the wire, so
+ * anything malformed is a no.
+ */
+ fun authorises(event: Event, chatRoomId: HexKey, epoch: Long, change: GovernanceChange): Boolean {
+ val statement = parse(event) ?: return false
+ return statement.chatRoomId.equals(chatRoomId, ignoreCase = true) &&
+ statement.epoch == epoch &&
+ statement.change == change &&
+ GroupKeyStateEvent.isSignedByRoom(event, chatRoomId)
+ }
+}
+
+/** A member a commit adds: their account, and the exact KeyPackage that adds them. */
+data class AddedMember(val account: HexKey, val keyPackageRef: HexKey)
+
+/** A signed statement, read. */
+data class GovernanceStatement(
+ val chatRoomId: HexKey,
+ val epoch: Long,
+ val proposer: HexKey?,
+ val change: GovernanceChange,
+)
+
+/**
+ * What a commit does to a room, in a statement's terms: who it adds and removes,
+ * the admin list it leaves (null when it leaves it alone), and every other
+ * component it changes, by id and the hash of the new value (or [GovernanceStatementEvent.REMOVED]).
+ *
+ * A member's own leave rides along without appearing here; it needs nobody's
+ * signature (D6), so [of] leaves it out rather than refusing it.
+ */
+data class GovernanceChange(
+ val adds: Set = emptySet(),
+ val removes: Set = emptySet(),
+ val admins: Set? = null,
+ val components: Map = emptyMap(),
+) {
+ companion object {
+ /**
+ * What [proposals] would do to [group], or null when they do something a
+ * statement cannot describe -- another member's Update, a GroupContext
+ * rewrite, a pre-shared key, a re-init -- which is therefore never
+ * authorised. [proposals] is the commit's whole list, exempt ones included.
+ */
+ fun of(group: GroupView, proposals: List): GovernanceChange? {
+ val adds = mutableSetOf()
+ val removes = mutableSetOf()
+ var admins: Set? = null
+ val components = mutableMapOf()
+ for (pending in proposals) {
+ when (val proposal = pending.proposal) {
+ is Proposal.SelfRemove -> Unit
+ is Proposal.Add -> {
+ val account = (proposal.keyPackage.leafNode.credential as? Credential.Basic)?.identity?.toHexKey() ?: return null
+ adds += AddedMember(account, proposal.keyPackage.reference().toHex())
+ }
+ is Proposal.Remove -> removes += group.memberIdentityHex(proposal.removedLeafIndex) ?: return null
+ is Proposal.AppDataUpdate -> {
+ val operation = proposal.operation
+ if (proposal.componentId == AdminPolicyV1.COMPONENT_ID) {
+ if (operation !is Proposal.AppDataUpdate.Operation.Update) return null
+ admins = AdminPolicyV1.decode(operation.data).adminHexKeys.toSet()
+ } else {
+ components[proposal.componentId] = when (operation) {
+ is Proposal.AppDataUpdate.Operation.Update -> sha256(operation.data).toHex()
+ Proposal.AppDataUpdate.Operation.Remove -> GovernanceStatementEvent.REMOVED
+ }
+ }
+ }
+ else -> return null
+ }
+ }
+ return GovernanceChange(adds, removes, admins, components)
+ }
+
+ /**
+ * Whether a commit needs nobody's signature (D6): one made only of members'
+ * own SelfRemoves, or a committer's own key update with no proposals at all.
+ * MIP-03 lets any member make exactly these, and neither changes who governs
+ * the room or who is in it beyond the leaver.
+ */
+ fun isExempt(proposals: List): Boolean =
+ proposals.all { it.proposal is Proposal.SelfRemove }
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/ShareRepairEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/ShareRepairEvents.kt
index f09ee84a..ec26d60c 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/ShareRepairEvents.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/ShareRepairEvents.kt
@@ -37,6 +37,13 @@ object ShareRepairEvents {
const val KEY_TAG = "frost_key"
const val GENERATION_TAG = "frost_generation"
+ /**
+ * The `n` an enrollment at a new id runs with: that id, since the table held n
+ * entries before it (docs/member-admin-promotion.md, Phase 8). Absent on a
+ * repair, which uses the table it has.
+ */
+ const val N_TAG = "repair_n"
+
fun value(tags: Array>, name: String): String? = tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1)
fun parseSessionId(tags: Array>): String? = value(tags, SESSION_TAG)?.takeIf { it.length == 64 }
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 6447ccfd..e2eb7a0e 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt
@@ -23,6 +23,8 @@ import mobi.giza.compose.managers.FoundingAdmins
import mobi.giza.compose.managers.MarmotGroupCreation
import mobi.giza.compose.managers.SubgroupManager
import mobi.giza.compose.nostr.MarmotProfile
+import mobi.giza.compose.managers.PromotionManager
+import mobi.giza.compose.ui.view.state.GovernanceStatus
import mobi.giza.compose.ui.view.state.SharesSummary
import mobi.giza.compose.ui.view.state.RotationPreview
@@ -296,6 +298,29 @@ interface ChatRepository {
onCompletion: () -> Unit
)
+ /**
+ * Brings the room's admin flags into line with its group's admin set, without a
+ * caption. Returns whether any changed. See docs/member-admin-promotion.md, Phase 1.
+ */
+ suspend fun reconcileAdmins(chatRoomId: String): Boolean
+
+ /**
+ * The fewest admins the room may be left with: one in a convenient room, at
+ * least three -- and never fewer than its quorum -- in a keyed one.
+ * docs/member-admin-promotion.md, R3.
+ */
+ suspend fun adminFloor(chatRoomId: String): Int
+
+ /**
+ * Where a keyed room stands on needing the group's signature, or null for any
+ * other room. Says, for this device, that it follows signed commits, if it has
+ * not yet. docs/member-admin-promotion.md, Phase 4b.
+ */
+ suspend fun governanceStatus(chatRoomId: String): GovernanceStatus?
+
+ /** Makes a keyed room's changes need the group's signature. Throws with words a person can act on. */
+ suspend fun requireSignatures(localChatRoom: LocalChatRoom)
+
/**
* Removes [memberPublicKey] from a current-profile room this device administers:
* a commit through the publish gate, applied when a relay accepts it. See
@@ -303,6 +328,37 @@ interface ChatRepository {
*/
suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey)
+ /**
+ * Makes [memberPublicKey] an admin of a convenient room this device
+ * administers: one commit through the publish gate, captioned when it is
+ * applied. Throws with words a person can act on when it cannot be done. See
+ * docs/member-admin-promotion.md, Phase 6.
+ */
+ suspend fun promoteMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey)
+
+ /**
+ * Makes [adminPublicKey] stop being an admin of a convenient room this device
+ * administers -- this device's own account included, which is stepping down.
+ * Throws with words a person can act on when it cannot be done.
+ */
+ suspend fun demoteMember(localChatRoom: LocalChatRoom, adminPublicKey: HexKey)
+
+ /**
+ * Leaves a convenient room this device administers: steps down -- making
+ * [heir] an admin first, when this device is the only one -- and leaves once
+ * that is accepted. docs/member-admin-promotion.md, Phase 10.
+ */
+ suspend fun stepDownAndLeave(localChatRoom: LocalChatRoom, heir: HexKey?)
+
+ /**
+ * An offer to this device's account to become an admin of a keyed room that it
+ * has not answered, or null. docs/member-admin-promotion.md, Phase 8.
+ */
+ suspend fun pendingPromotion(chatRoomId: String): PromotionManager.Offer?
+
+ /** Accepts [offerId]. Returns null when the acceptance went out, or why it could not. */
+ suspend fun acceptPromotion(localChatRoom: LocalChatRoom, offerId: HexKey): String?
+
/**
* Adds [publicKeys] to a current-profile room's admin policy, as an admin of
* it: one commit through the publish gate, additions only. The repair for a
@@ -564,6 +620,24 @@ interface ChatRepository {
TODO("Not yet implemented")
}
+ override suspend fun reconcileAdmins(chatRoomId: String): Boolean = false
+
+ override suspend fun adminFloor(chatRoomId: String): Int = 1
+
+ override suspend fun governanceStatus(chatRoomId: String): GovernanceStatus? = null
+
+ override suspend fun requireSignatures(localChatRoom: LocalChatRoom) = Unit
+
+ override suspend fun promoteMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) = Unit
+
+ override suspend fun demoteMember(localChatRoom: LocalChatRoom, adminPublicKey: HexKey) = Unit
+
+ override suspend fun stepDownAndLeave(localChatRoom: LocalChatRoom, heir: HexKey?) = Unit
+
+ override suspend fun pendingPromotion(chatRoomId: String): PromotionManager.Offer? = null
+
+ override suspend fun acceptPromotion(localChatRoom: LocalChatRoom, offerId: HexKey): String? = null
+
override suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) = Unit
override suspend fun addAdmins(localChatRoom: LocalChatRoom, publicKeys: Set) = 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 8e8c39de..7b668a88 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt
@@ -5,6 +5,7 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey
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.frost.GroupKeyStateEvent
import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent
@@ -69,6 +70,24 @@ object ProposedEvent {
).joinToString(" · ")
)
+ // A change to the room itself, which no single admin may make: who is in
+ // it and who governs it, said in names, because a member approving it is
+ // approving those lines and not a hash. docs/member-admin-promotion.md,
+ // Phase 3.
+ GovernanceStatementEvent.KIND -> GovernanceStatementEvent.parse(event)?.let { statement ->
+ val name = { key: HexKey -> nameOf(key) ?: key.take(8) }
+ val change = statement.change
+ Summary(
+ label = "A change to who is in this group",
+ detail = listOfNotNull(
+ change.adds.takeIf { it.isNotEmpty() }?.joinToString(prefix = "Adds ") { name(it.account) },
+ change.removes.takeIf { it.isNotEmpty() }?.joinToString(prefix = "Removes ") { name(it) },
+ change.admins?.joinToString(prefix = "Admins afterwards: ") { name(it) },
+ "Changes its settings".takeIf { change.components.isNotEmpty() },
+ ).joinToString(" · ")
+ )
+ } ?: Summary(label = "A change to this group that cannot be read", detail = "")
+
// A Bennu wallet's: declined on arrival, and said as what it is rather than
// as a number. docs/giza-wallet-removal.md.
in RetiredKinds.WALLET, in RetiredKinds.GROUP_LIGHTNING -> WALLET
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 5e6fc129..bd8af3ab 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
@@ -47,6 +47,7 @@ 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.saveable.rememberSaveable
import androidx.compose.runtime.setValue
@@ -84,6 +85,17 @@ import mobi.giza.compose.ui.view.model.ChatRoomDetailViewModel
import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import mobi.giza.compose.ui.theme.spacing
+import mobi.giza.compose.resources.couldn_t_leave_the_group
+import mobi.giza.compose.resources.admin_change_requested
+import mobi.giza.compose.resources.stepping_down_to_leave
+import mobi.giza.compose.resources.require_signatures_sent
+import mobi.giza.compose.resources.change_proposed
+import mobi.giza.compose.resources.admin_offer_sent
+import mobi.giza.compose.resources.promotion_accepted
+import mobi.giza.compose.ui.view.state.GovernanceStatus
+import mobi.giza.compose.resources.holds_a_share
+import mobi.giza.compose.ui.view.state.AdminLeave
+import mobi.giza.compose.ui.view.state.MemberAction
import mobi.giza.compose.resources.every_member_of_this_group_administers_it_there
import mobi.giza.compose.resources.admin_room
import mobi.giza.compose.resources.run_by_alone
@@ -229,6 +241,15 @@ fun ChatRoomDetailScreen(
// composable, and a lambda passed to onClick is not.
val notify = rememberNotifier(rememberCoroutineScope())
val removalRequested = stringResource(Res.string.member_removal_requested)
+ val couldNotLeave = stringResource(Res.string.couldn_t_leave_the_group)
+ val adminChangeRequested = stringResource(Res.string.admin_change_requested)
+ val steppingDownToLeave = stringResource(Res.string.stepping_down_to_leave)
+ val requireSignaturesSent = stringResource(Res.string.require_signatures_sent)
+ val changeProposed = stringResource(Res.string.change_proposed)
+ val adminOfferSent = stringResource(Res.string.admin_offer_sent)
+ val promotionAccepted = stringResource(Res.string.promotion_accepted)
+ val adminLabel = stringResource(Res.string.admin)
+ val shareLabel = stringResource(Res.string.holds_a_share)
val rotationRequested = stringResource(Res.string.share_rotation_requested)
val sharesActionSent = stringResource(Res.string.shares_action_sent)
val noKeyToRotate = stringResource(Res.string.rotation_no_key)
@@ -347,6 +368,76 @@ fun ChatRoomDetailScreen(
}
}
is ChatRoomDetailUIState.Loaded -> {
+ // The change a member row's menu asked for, while its dialog asks first.
+ var confirmingAdminChange by remember { mutableStateOf?>(null) }
+ var isLeavingAsAdmin by remember { mutableStateOf(false) }
+ val nameOf = { publicKey: HexKey ->
+ chatRoomDetailUIState.localChatRoom.localParticipants
+ .firstOrNull { it.participant.participantPublicKey == publicKey }
+ ?.profile?.humanReadableNameOrPubkey()
+ ?: publicKey.take(8)
+ }
+
+ confirmingAdminChange?.let { (action, memberPublicKey) ->
+ ConfirmAdminChangeDialog(
+ action = action,
+ memberName = nameOf(memberPublicKey),
+ keyed = chatRoomDetailUIState.governance is GovernanceStatus.Governed,
+ onDismiss = { confirmingAdminChange = null },
+ onConfirm = {
+ confirmingAdminChange = null
+ val room = chatRoomDetailUIState.localChatRoom
+ val governed = chatRoomDetailUIState.governance is GovernanceStatus.Governed
+ val onDone = { failure: String? ->
+ notify(
+ failure ?: when {
+ governed && action == MemberAction.MAKE_ADMIN -> adminOfferSent
+ governed -> changeProposed
+ else -> adminChangeRequested
+ }
+ )
+ }
+ when (action) {
+ MemberAction.MAKE_ADMIN -> chatRoomDetailViewModel.makeAdmin(room, memberPublicKey, onDone)
+ MemberAction.REMOVE_AS_ADMIN, MemberAction.STEP_DOWN ->
+ chatRoomDetailViewModel.removeAsAdmin(room, memberPublicKey, onDone)
+ MemberAction.REMOVE_FROM_GROUP -> Unit
+ }
+ },
+ )
+ }
+
+ chatRoomDetailUIState.adminLeave?.takeIf { isLeavingAsAdmin }?.let { adminLeave ->
+ LeaveAsAdminDialog(
+ adminLeave = adminLeave,
+ candidates = chatRoomDetailUIState.localChatRoom.localParticipants
+ .map { it.participant.participantPublicKey }
+ .filter { it != chatRoomDetailUIState.localChatRoom.chatRoom.userPublicKey }
+ .map { it to nameOf(it) },
+ onDismiss = { isLeavingAsAdmin = false },
+ onDisband = {
+ isLeavingAsAdmin = false
+ chatRoomDetailViewModel.disbandGroup(
+ localChatRoom = chatRoomDetailUIState.localChatRoom,
+ onPopBackToRoute = onPopBackToRoute,
+ onFailed = { failure -> notify(failure ?: couldNotLeave) },
+ )
+ },
+ onStepDownAndLeave = { heir ->
+ isLeavingAsAdmin = false
+ chatRoomDetailViewModel.stepDownAndLeave(
+ localChatRoom = chatRoomDetailUIState.localChatRoom,
+ heir = heir,
+ onPopBackToRoute = { route ->
+ notify(steppingDownToLeave)
+ onPopBackToRoute(route)
+ },
+ onFailed = { failure -> notify(failure ?: couldNotLeave) },
+ )
+ },
+ )
+ }
+
Scaffold(
snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
topBar = {
@@ -1000,24 +1091,33 @@ fun ChatRoomDetailScreen(
},
trailingContent = {
val memberPublicKey = localParticipant.participant.participantPublicKey
- if (chatRoomDetailUIState.canGovern && memberPublicKey != activeUserPublicKey) {
- // An admin's removal of a member: a commit through the
- // publish gate, applied when a relay accepts it, which is
- // why the row stays until then. See docs/marmot-v2.md, Phase 7.
- IconButton(
- onClick = {
+ val actions = chatRoomDetailUIState.memberActions[memberPublicKey].orEmpty()
+ if (actions.isNotEmpty()) {
+ // What this device may do to this member, decided by the
+ // view model from the group's state. Every one is a commit
+ // through the publish gate, applied when a relay accepts
+ // it, which is why the row stays as it is until then. See
+ // docs/member-admin-promotion.md, Phase 11.
+ MemberActionsMenu(actions = actions) { action ->
+ if (action == MemberAction.REMOVE_FROM_GROUP) {
chatRoomDetailViewModel.removeMember(
localChatRoom = chatRoomDetailUIState.localChatRoom,
memberPublicKey = memberPublicKey,
) { failure, rotationHeld ->
- notify(failure ?: if (rotationHeld) rotationHeldAfterRemoval else removalRequested)
+ // In a governed room the removal is a proposal
+ // the group still has to sign.
+ val governed = chatRoomDetailUIState.governance is GovernanceStatus.Governed
+ notify(
+ failure ?: when {
+ governed -> changeProposed
+ rotationHeld -> rotationHeldAfterRemoval
+ else -> removalRequested
+ }
+ )
}
+ } else {
+ confirmingAdminChange = action to memberPublicKey
}
- ) {
- Icon(
- Icons.Default.PersonRemove,
- contentDescription = stringResource(Res.string.remove_from_group)
- )
}
} else {
Icon(
@@ -1032,12 +1132,20 @@ fun ChatRoomDetailScreen(
)
},
supportingContent = {
+ // Two facts, shown apart: when they disagree, a share is
+ // still owed or still to be rotated away
+ // (docs/member-admin-promotion.md, D2). Admin from the
+ // group's policy, through `AdminFlags` --
+ // docs/robust-group-admins.md.
+ val memberPublicKey = localParticipant.participant.participantPublicKey
+ val roles = listOfNotNull(
+ adminLabel.takeIf { localParticipant.participant.adminAt != null },
+ shareLabel.takeIf { memberPublicKey in chatRoomDetailUIState.shareHolders },
+ )
Column {
- // From the group's admin policy, through
- // `AdminFlags` -- docs/robust-group-admins.md.
- if (localParticipant.participant.adminAt != null) {
+ if (roles.isNotEmpty()) {
Text(
- text = stringResource(Res.string.admin),
+ text = roles.joinToString(" · "),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)
@@ -1060,6 +1168,35 @@ fun ChatRoomDetailScreen(
HorizontalDivider()
}
+ // Whether the room's changes need the group's signature, and the
+ // switch that makes them. docs/member-admin-promotion.md, Phase 4b.
+ // An offer to this account to become an admin, with its one
+ // decision. docs/member-admin-promotion.md, Phase 8.
+ chatRoomDetailUIState.promotionOffer?.let { (offerId, from) ->
+ item {
+ PromotionOfferCard(fromName = nameOf(from)) {
+ chatRoomDetailViewModel.acceptPromotion(chatRoomDetailUIState.localChatRoom, offerId) { failure ->
+ notify(failure ?: promotionAccepted)
+ }
+ }
+ }
+ }
+
+ chatRoomDetailUIState.governance?.let { governance ->
+ item {
+ GovernanceSection(
+ governance = governance,
+ canGovern = chatRoomDetailUIState.canGovern,
+ nameOf = nameOf,
+ onRequireSignatures = {
+ chatRoomDetailViewModel.requireSignatures(chatRoomDetailUIState.localChatRoom) { failure ->
+ notify(failure ?: requireSignaturesSent)
+ }
+ },
+ )
+ }
+ }
+
if (chatRoomDetailUIState.isDisbanded) {
item {
Text(
@@ -1122,10 +1259,17 @@ fun ChatRoomDetailScreen(
// Disabled after we leave, and after the group ends.
enabled = chatRoomDetailUIState.localChatRoom.chatRoom.leftGroupAt == null && !chatRoomDetailUIState.isDisbanded,
onClick = {
- chatRoomDetailViewModel.leaveGroup(
- localChatRoom = chatRoomDetailUIState.localChatRoom,
- onPopBackToRoute = onPopBackToRoute
- )
+ // An admin cannot simply leave; they step down first, and
+ // the only admin hands over. A keyed room's admin has no way
+ // to yet, and is told so by the refusal leaveGroup reports.
+ when (chatRoomDetailUIState.adminLeave) {
+ AdminLeave.STEP_DOWN_FIRST, AdminLeave.PICK_HEIR -> isLeavingAsAdmin = true
+ else -> chatRoomDetailViewModel.leaveGroup(
+ localChatRoom = chatRoomDetailUIState.localChatRoom,
+ onPopBackToRoute = onPopBackToRoute,
+ onFailed = { failure -> notify(failure ?: couldNotLeave) },
+ )
+ }
}
) {
Icon(
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt
new file mode 100644
index 00000000..0a15f180
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt
@@ -0,0 +1,270 @@
+package mobi.giza.compose.ui.composable
+
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.selection.selectable
+import androidx.compose.foundation.selection.selectableGroup
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.MoreVert
+import androidx.compose.material.icons.filled.Verified
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.DropdownMenu
+import androidx.compose.material3.DropdownMenuItem
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.RadioButton
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.minimumInteractiveComponentSize
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.semantics.Role
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+import mobi.giza.compose.resources.Res
+import mobi.giza.compose.resources.cancel
+import mobi.giza.compose.resources.disband_group_instead
+import mobi.giza.compose.resources.governance_on
+import mobi.giza.compose.resources.governance_waiting
+import mobi.giza.compose.resources.require_signatures
+import mobi.giza.compose.resources.require_signatures_explainer
+import mobi.giza.compose.resources.make_admin
+import mobi.giza.compose.resources.make_admin_and_leave
+import mobi.giza.compose.resources.make_admin_body
+import mobi.giza.compose.resources.make_admin_body_keyed
+import mobi.giza.compose.resources.remove_as_admin_body_keyed
+import mobi.giza.compose.resources.promotion_offer_body
+import mobi.giza.compose.resources.accept
+import mobi.giza.compose.resources.make_admin_title
+import mobi.giza.compose.resources.member_actions
+import mobi.giza.compose.resources.pick_heir_body
+import mobi.giza.compose.resources.leave_as_admin_title
+import mobi.giza.compose.resources.remove_as_admin
+import mobi.giza.compose.resources.remove_as_admin_body
+import mobi.giza.compose.resources.remove_as_admin_title
+import mobi.giza.compose.resources.remove_from_group
+import mobi.giza.compose.resources.step_down
+import mobi.giza.compose.resources.step_down_and_leave
+import mobi.giza.compose.resources.step_down_and_leave_body
+import mobi.giza.compose.resources.step_down_as_admin
+import mobi.giza.compose.resources.step_down_body
+import mobi.giza.compose.resources.step_down_title
+import mobi.giza.compose.ui.theme.spacing
+import mobi.giza.compose.ui.composable.widgets.Decorative
+import mobi.giza.compose.ui.view.state.AdminLeave
+import mobi.giza.compose.ui.view.state.GovernanceStatus
+import mobi.giza.compose.ui.view.state.MemberAction
+import org.jetbrains.compose.resources.stringResource
+
+/**
+ * The member row's overflow menu: the actions [actions] allows, and nothing else.
+ * The view model decides them; this only lays them out. A 48dp `IconButton`, as
+ * every target is. See docs/member-admin-promotion.md, Phase 11.
+ */
+@Composable
+internal fun MemberActionsMenu(
+ actions: Set,
+ onAction: (MemberAction) -> Unit,
+) {
+ var expanded by remember { mutableStateOf(false) }
+ Box {
+ IconButton(onClick = { expanded = true }) {
+ Icon(Icons.Default.MoreVert, contentDescription = stringResource(Res.string.member_actions))
+ }
+ DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
+ // In a fixed order, whatever order the set holds them in.
+ MemberAction.entries.filter { it in actions }.forEach { action ->
+ DropdownMenuItem(
+ text = { Text(stringResource(action.label())) },
+ onClick = {
+ expanded = false
+ onAction(action)
+ },
+ )
+ }
+ }
+ }
+}
+
+private fun MemberAction.label() = when (this) {
+ MemberAction.MAKE_ADMIN -> Res.string.make_admin
+ MemberAction.REMOVE_AS_ADMIN -> Res.string.remove_as_admin
+ MemberAction.STEP_DOWN -> Res.string.step_down_as_admin
+ MemberAction.REMOVE_FROM_GROUP -> Res.string.remove_from_group
+}
+
+/**
+ * Asks before a change to who administers the room. Promotion says what it gives
+ * away -- the power to remove the person granting it, and to disband the group --
+ * because that is the part nobody thinks of in the moment. [memberName] is the
+ * member's display name; it is unused for [MemberAction.STEP_DOWN].
+ */
+@Composable
+internal fun ConfirmAdminChangeDialog(
+ action: MemberAction,
+ memberName: String,
+ keyed: Boolean = false,
+ onConfirm: () -> Unit,
+ onDismiss: () -> Unit,
+) {
+ val (title, body, confirm) = when (action) {
+ MemberAction.MAKE_ADMIN -> Triple(
+ stringResource(Res.string.make_admin_title, memberName),
+ stringResource(if (keyed) Res.string.make_admin_body_keyed else Res.string.make_admin_body),
+ stringResource(Res.string.make_admin),
+ )
+ MemberAction.REMOVE_AS_ADMIN -> Triple(
+ stringResource(Res.string.remove_as_admin_title, memberName),
+ stringResource(if (keyed) Res.string.remove_as_admin_body_keyed else Res.string.remove_as_admin_body),
+ stringResource(Res.string.remove_as_admin),
+ )
+ MemberAction.STEP_DOWN -> Triple(
+ stringResource(Res.string.step_down_title),
+ stringResource(Res.string.step_down_body),
+ stringResource(Res.string.step_down),
+ )
+ // Removal keeps the immediate action it always had.
+ MemberAction.REMOVE_FROM_GROUP -> return
+ }
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text(title) },
+ text = { Text(body) },
+ confirmButton = { TextButton(onClick = onConfirm) { Text(confirm) } },
+ dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.cancel)) } },
+ )
+}
+
+/**
+ * **Leave group**, pressed by an admin, who cannot simply leave. Another admin
+ * remaining: step down, then leave. The only admin: pick who takes over, or
+ * disband instead -- the choice of who governs the group afterwards is the
+ * person's, not the device's. docs/member-admin-promotion.md, Phase 10.
+ *
+ * [candidates] are the other members, by public key and display name, for the
+ * [AdminLeave.PICK_HEIR] case.
+ */
+@Composable
+internal fun LeaveAsAdminDialog(
+ adminLeave: AdminLeave,
+ candidates: List>,
+ onStepDownAndLeave: (heir: HexKey?) -> Unit,
+ onDisband: () -> Unit,
+ onDismiss: () -> Unit,
+) {
+ var heir by remember { mutableStateOf(null) }
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text(stringResource(Res.string.leave_as_admin_title)) },
+ text = {
+ when (adminLeave) {
+ AdminLeave.PICK_HEIR -> Column(modifier = Modifier.selectableGroup()) {
+ Text(stringResource(Res.string.pick_heir_body))
+ candidates.forEach { (publicKey, name) ->
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .selectable(selected = heir == publicKey, onClick = { heir = publicKey }, role = Role.RadioButton)
+ .minimumInteractiveComponentSize()
+ .padding(vertical = MaterialTheme.spacing.compactPadding),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ // The row is the target; the button only shows the state.
+ RadioButton(selected = heir == publicKey, onClick = null)
+ Text(name, modifier = Modifier.padding(start = MaterialTheme.spacing.relatedGap))
+ }
+ }
+ TextButton(onClick = onDisband) { Text(stringResource(Res.string.disband_group_instead)) }
+ }
+ else -> Text(stringResource(Res.string.step_down_and_leave_body))
+ }
+ },
+ confirmButton = {
+ when (adminLeave) {
+ AdminLeave.PICK_HEIR -> TextButton(onClick = { onStepDownAndLeave(heir) }, enabled = heir != null) {
+ Text(stringResource(Res.string.make_admin_and_leave))
+ }
+ else -> TextButton(onClick = { onStepDownAndLeave(null) }) {
+ Text(stringResource(Res.string.step_down_and_leave))
+ }
+ }
+ },
+ dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.cancel)) } },
+ )
+}
+
+/**
+ * Whether a keyed room's changes need the group's signature. Once they do, a line
+ * saying so; before, for an admin, the switch -- or who it is still waiting on,
+ * since switching it on with a member whose device cannot follow would leave them
+ * in a different group from the first change. docs/member-admin-promotion.md, Phase 4b.
+ */
+@Composable
+internal fun GovernanceSection(
+ governance: GovernanceStatus,
+ canGovern: Boolean,
+ nameOf: (HexKey) -> String,
+ onRequireSignatures: () -> Unit,
+) {
+ val explainer = Modifier.padding(
+ horizontal = MaterialTheme.spacing.containerPadding,
+ vertical = MaterialTheme.spacing.compactPadding,
+ )
+ Column(modifier = Modifier.fillMaxWidth()) {
+ when (governance) {
+ is GovernanceStatus.Governed -> Text(
+ text = stringResource(Res.string.governance_on, governance.minimumAdmins),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = explainer,
+ )
+ is GovernanceStatus.Ready -> if (canGovern) {
+ TextButton(onClick = onRequireSignatures) {
+ Icon(Icons.Default.Verified, contentDescription = Decorative)
+ Text(stringResource(Res.string.require_signatures), modifier = Modifier.padding(start = MaterialTheme.spacing.relatedGap))
+ }
+ Text(
+ text = stringResource(Res.string.require_signatures_explainer),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = explainer,
+ )
+ }
+ is GovernanceStatus.Waiting -> if (canGovern) {
+ Text(
+ text = stringResource(Res.string.governance_waiting, governance.missing.map(nameOf).sorted().joinToString()),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = explainer,
+ )
+ }
+ }
+ }
+}
+
+/**
+ * An offer to this account to become an admin of a keyed room, with the one
+ * decision only its owner can make: accepting puts them in the group's signing
+ * quorum. docs/member-admin-promotion.md, D3 and Phase 8.
+ */
+@Composable
+internal fun PromotionOfferCard(fromName: String, onAccept: () -> Unit) {
+ Column(modifier = Modifier.fillMaxWidth().padding(horizontal = MaterialTheme.spacing.containerPadding, vertical = MaterialTheme.spacing.compactPadding)) {
+ Text(
+ text = stringResource(Res.string.promotion_offer_body, fromName),
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ TextButton(onClick = onAccept) {
+ Icon(Icons.Default.Verified, contentDescription = Decorative)
+ Text(stringResource(Res.string.accept), modifier = Modifier.padding(start = MaterialTheme.spacing.relatedGap))
+ }
+ }
+}
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 89ffdb36..cc4cfb42 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
@@ -34,6 +34,8 @@ import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.ChevronRight
import androidx.compose.material.icons.filled.ErrorOutline
+import androidx.compose.material.icons.filled.AdminPanelSettings
+import androidx.compose.material.icons.filled.RemoveModerator
import androidx.compose.material.icons.filled.CallMerge
import androidx.compose.material.icons.filled.Campaign
import androidx.compose.material.icons.filled.FactCheck
@@ -880,6 +882,10 @@ private fun RitualNotice(
ChatMessage.TYPE_MEMBER_INVITE_SENT -> Icons.Default.Upload
ChatMessage.TYPE_MEMBER_INVITE_FAILED -> Icons.Default.ErrorOutline
ChatMessage.TYPE_CHANGE_REJECTED -> Icons.Default.ErrorOutline
+ ChatMessage.TYPE_ADMIN_ADDED -> Icons.Default.AdminPanelSettings
+ ChatMessage.TYPE_ADMIN_REMOVED -> Icons.Default.RemoveModerator
+ ChatMessage.TYPE_ADMIN_OFFERED -> Icons.Default.AdminPanelSettings
+ ChatMessage.TYPE_CHANGE_NOT_APPLIED -> Icons.Default.Block
else -> Icons.Default.PanTool
@@ -901,7 +907,8 @@ private fun RitualNotice(
chatMessage.messageType == ChatMessage.TYPE_DKG_FAILED ||
chatMessage.messageType == ChatMessage.TYPE_FROST_FAILED ||
chatMessage.messageType == ChatMessage.TYPE_MEMBER_INVITE_FAILED ||
- chatMessage.messageType == ChatMessage.TYPE_CHANGE_REJECTED ->
+ chatMessage.messageType == ChatMessage.TYPE_CHANGE_REJECTED ||
+ chatMessage.messageType == ChatMessage.TYPE_CHANGE_NOT_APPLIED ->
MaterialTheme.colorScheme.error
isRequest -> MaterialTheme.colorScheme.primary
else -> MaterialTheme.colorScheme.onSurfaceVariant
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 56842304..21fc93d2 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
@@ -26,6 +26,9 @@ import mobi.giza.compose.managers.FoundingAdmins
import mobi.giza.compose.managers.MarmotGroupCreation
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.database.model.types.MarmotReindexReport
+import mobi.giza.compose.ExperimentalFeatures
+import mobi.giza.compose.database.model.types.ShareStanding
+import mobi.giza.compose.managers.AdminGovernance
import mobi.giza.compose.managers.WalletRefusal
import mobi.giza.compose.nostr.MarmotProfile
import mobi.giza.compose.repository.ChatRepository
@@ -33,6 +36,7 @@ import mobi.giza.compose.repository.NostrRepository
import mobi.giza.compose.ui.composable.navigation.routes.HomeRoute
import mobi.giza.compose.ui.composable.navigation.routes.Route
import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState
+import mobi.giza.compose.ui.view.state.GovernanceStatus
import mobi.giza.compose.ui.view.state.SharesSummary
import mobi.giza.compose.ui.view.state.RotationPreview
@@ -78,6 +82,11 @@ class ChatRoomDetailViewModel(
logger.d("compressed (most likely chat room): $chatRoomId")
// Get ChatRoomById
viewModelScope.launch(Dispatchers.IO) {
+ // A room made before its creator's flag was written at creation reads as
+ // having no admins until a commit arrives; caught up here, silently, before
+ // anything reads it. docs/member-admin-promotion.md, Phase 1.
+ runCatching { chatRepository.reconcileAdmins(chatRoomId) }
+ .onFailure { if (it is CancellationException) throw it else logger.w(throwable = it) { "Couldn't reconcile $chatRoomId's admins" } }
val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId)
logger.d("localChatRoom: $localChatRoom")
@@ -104,6 +113,12 @@ class ChatRoomDetailViewModel(
?.let { Event.fromJsonOrNull(it) }
?.let(WalletRefusal::isGuarded) == true
+ val shares = chatRepository.sharesSummary(localChatRoom)
+ // Who governs, and what this device may do about it, from the group's
+ // state through the same rules the commits are made by.
+ // docs/member-admin-promotion.md, Phase 11.
+ val me = localChatRoom.chatRoom.userPublicKey
+ val roomIsOpen = !isDisbanded && localChatRoom.chatRoom.leftGroupAt == null
// The founding members, against what the ceremony that made the
// room's key said: who the policy leaves out, and who the founding
// invite never reached. docs/robust-group-admins.md, Phases 3 and 4.
@@ -128,7 +143,22 @@ class ChatRoomDetailViewModel(
!isDisbanded &&
localChatRoom.chatRoom.leftGroupAt == null,
isDisbanded = isDisbanded,
- shares = chatRepository.sharesSummary(localChatRoom),
+ shares = shares,
+ adminPublicKeys = group?.currentAdminIdentities().orEmpty(),
+ shareHolders = if (ExperimentalFeatures.shareRefresh) {
+ shares?.members.orEmpty().filter { it.standing == ShareStanding.LIVE }.map { it.publicKey }.toSet()
+ } else {
+ emptySet()
+ },
+ memberActions = group?.takeIf { canGovern }?.let { AdminGovernance.memberActions(it, me, chatRepository.adminFloor(chatRoomId)) }.orEmpty(),
+ adminLeave = group?.takeIf { roomIsOpen }?.let { AdminGovernance.adminLeave(it, me) },
+ governance = runCatching { chatRepository.governanceStatus(chatRoomId) }
+ .onFailure { if (it is CancellationException) throw it }
+ .getOrNull(),
+ promotionOffer = runCatching { chatRepository.pendingPromotion(chatRoomId) }
+ .onFailure { if (it is CancellationException) throw it }
+ .getOrNull()
+ ?.let { it.id to it.from },
missingFoundingAdmins = missingFoundingAdmins,
uninvitedFounders = uninvitedFounders,
founderNames = (missingFoundingAdmins + uninvitedFounders).associateWith { publicKey ->
@@ -213,7 +243,61 @@ class ChatRoomDetailViewModel(
// can still help sign until the shares are rotated without them.
// A second act, offered rather than folded in -- it needs every
// remaining holder (docs/frost-share-refresh.md, Phase 9).
- if (rotation == SharesSummary.Rotation.Available) rotationOffer = RotationOffer(localChatRoom, memberPublicKey, preview)
+ // Not for a removal the group has yet to sign: they are still in the
+ // room, and the offer would come before the fact it is about.
+ val proposed = (chatRoomDetailUIState as? ChatRoomDetailUIState.Loaded)?.governance is GovernanceStatus.Governed
+ if (rotation == SharesSummary.Rotation.Available && !proposed) rotationOffer = RotationOffer(localChatRoom, memberPublicKey, preview)
+ }
+ }
+ }
+
+ /**
+ * Runs one change to who administers the room, reloads the screen, and
+ * reports: null when the commit went out, or why it could not. The change
+ * itself lands when a relay accepts it, and the room says so then.
+ * docs/member-admin-promotion.md, Phase 11.
+ */
+ private fun adminAction(onDone: (String?) -> Unit, action: suspend () -> Unit) {
+ viewModelScope.launch(Dispatchers.IO) {
+ val failure = runCatching { action() }.exceptionOrNull()
+ if (failure is CancellationException) throw failure
+ initiateChatRoomDetail()
+ viewModelScope.launch(Dispatchers.Main) { onDone(failure?.let { it.message ?: "Couldn't make that change" }) }
+ }
+ }
+
+ /** Makes the room's changes need the group's signature. docs/member-admin-promotion.md, Phase 4b. */
+ fun requireSignatures(localChatRoom: LocalChatRoom, onDone: (String?) -> Unit) =
+ adminAction(onDone) { chatRepository.requireSignatures(localChatRoom) }
+
+ /** Accepts becoming an admin of a keyed room. docs/member-admin-promotion.md, Phase 8. */
+ fun acceptPromotion(localChatRoom: LocalChatRoom, offerId: HexKey, onDone: (String?) -> Unit) =
+ adminAction(onDone) { chatRepository.acceptPromotion(localChatRoom, offerId)?.let { throw IllegalStateException(it) } }
+
+ fun makeAdmin(localChatRoom: LocalChatRoom, memberPublicKey: HexKey, onDone: (String?) -> Unit) =
+ adminAction(onDone) { chatRepository.promoteMember(localChatRoom, memberPublicKey) }
+
+ /** Removes [adminPublicKey] as an admin; this device's own account is stepping down. */
+ fun removeAsAdmin(localChatRoom: LocalChatRoom, adminPublicKey: HexKey, onDone: (String?) -> Unit) =
+ adminAction(onDone) { chatRepository.demoteMember(localChatRoom, adminPublicKey) }
+
+ /**
+ * Leaves as an admin: steps down, after making [heir] an admin when this device
+ * is the only one, and leaves once that is accepted. Leaves the screen as soon
+ * as the first step is sent; a refusal stays on it and goes to [onFailed].
+ */
+ fun stepDownAndLeave(
+ localChatRoom: LocalChatRoom,
+ heir: HexKey?,
+ onPopBackToRoute: (Route) -> Unit,
+ onFailed: (String?) -> Unit,
+ ) {
+ viewModelScope.launch(Dispatchers.IO) {
+ val failure = runCatching { chatRepository.stepDownAndLeave(localChatRoom, heir) }.exceptionOrNull()
+ if (failure is CancellationException) throw failure
+ viewModelScope.launch(Dispatchers.Main) {
+ if (failure == null) onPopBackToRoute(HomeRoute(activeUserPublicKey = activeUserPublicKey))
+ else onFailed(failure.message)
}
}
}
@@ -356,23 +440,37 @@ class ChatRoomDetailViewModel(
}
}
+ /**
+ * Leaves the group, then leaves the screen. A refusal -- an admin, who has to
+ * hand over admin first -- goes to [onFailed] in the words the refusal used, and
+ * the screen stays. It used to escape the coroutine, which nobody saw and which
+ * on Android is a crash. See docs/member-admin-promotion.md, Phase 10.
+ */
fun leaveGroup(
localChatRoom: LocalChatRoom,
- onPopBackToRoute: (Route) -> Unit
+ onPopBackToRoute: (Route) -> Unit,
+ onFailed: (String?) -> Unit = {},
) {
viewModelScope.launch(Dispatchers.IO) {
- chatRepository.leaveChatRoom(
- localChatRoom,
- onCompletion = {
- viewModelScope.launch(Dispatchers.Main) {
- onPopBackToRoute.invoke(
- HomeRoute(
- activeUserPublicKey = activeUserPublicKey,
+ val failure = runCatching {
+ chatRepository.leaveChatRoom(
+ localChatRoom,
+ onCompletion = {
+ viewModelScope.launch(Dispatchers.Main) {
+ onPopBackToRoute.invoke(
+ HomeRoute(
+ activeUserPublicKey = activeUserPublicKey,
+ )
)
- )
+ }
}
- }
- )
+ )
+ }.exceptionOrNull()
+ if (failure is CancellationException) throw failure
+ if (failure != null) {
+ logger.w(throwable = failure) { "Couldn't leave $chatRoomId" }
+ viewModelScope.launch(Dispatchers.Main) { onFailed(failure.message) }
+ }
}
}
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 ca658017..916e6703 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
@@ -91,6 +91,31 @@ sealed interface ChatRoomDetailUIState {
* room has no key (docs/frost-share-refresh.md, Phase 11).
*/
val shares: SharesSummary? = null,
+ /**
+ * Who administers the room, read off the group's state rather than the
+ * participants' `adminAt` flags. Labels each member row **Admin**.
+ * docs/member-admin-promotion.md, D1 and Phase 11.
+ */
+ val adminPublicKeys: Set = emptySet(),
+ /**
+ * Who holds a live share of the room's key, for the **Holds a share**
+ * label. Shown apart from [adminPublicKeys] on purpose: when the two
+ * disagree, an enrollment or a rotation is still owed. Empty while share
+ * rotation is behind its flag.
+ */
+ val shareHolders: Set = emptySet(),
+ /** What this device may do to each member, by public key; absent means nothing. */
+ val memberActions: Map> = emptyMap(),
+ /** How **Leave group** goes when this device is an admin; null when it is not. */
+ val adminLeave: AdminLeave? = null,
+ /** Where a keyed room stands on needing the group's signature; null for any other room. */
+ val governance: GovernanceStatus? = null,
+ /**
+ * An offer to this device's account to become an admin of this keyed room,
+ * by public key of the offer and of who made it; null when there is none.
+ * docs/member-admin-promotion.md, Phase 8.
+ */
+ val promotionOffer: Pair? = null,
/**
* Members of the ceremony that made this room's key whom its admin policy
* does not name -- empty when it names them all, and when this device has
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GovernanceStatus.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GovernanceStatus.kt
new file mode 100644
index 00000000..cc6f0897
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GovernanceStatus.kt
@@ -0,0 +1,18 @@
+package mobi.giza.compose.ui.view.state
+
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
+
+/**
+ * Where a keyed room stands on needing the group's signature for its changes.
+ * docs/member-admin-promotion.md, R2 and Phase 4b.
+ */
+sealed interface GovernanceStatus {
+ /** It does: every change is proposed, signed by the group, and only then applied. */
+ data class Governed(val minimumAdmins: Int) : GovernanceStatus
+
+ /** It does not yet, and every member's device could follow if it were switched on. */
+ data class Ready(val minimumAdmins: Int) : GovernanceStatus
+
+ /** It does not yet, and these members have not said their device could follow. */
+ data class Waiting(val missing: Set) : GovernanceStatus
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberAction.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberAction.kt
new file mode 100644
index 00000000..2f6f4a7f
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberAction.kt
@@ -0,0 +1,33 @@
+package mobi.giza.compose.ui.view.state
+
+/**
+ * What this device may do to one member of a room, as the member row's menu offers
+ * it. Computed by the view model from the group's state and
+ * `mobi.giza.compose.managers.AdminGovernance`, so the screen never decides an
+ * action itself. See docs/member-admin-promotion.md, Phase 11.
+ */
+enum class MemberAction {
+ MAKE_ADMIN,
+ REMOVE_AS_ADMIN,
+ /** Removing yourself as an admin, on your own row. */
+ STEP_DOWN,
+ REMOVE_FROM_GROUP,
+}
+
+/**
+ * How **Leave group** goes for an admin, who cannot simply leave: the library
+ * refuses an admin's SelfRemove. docs/member-admin-promotion.md, Phase 10.
+ */
+enum class AdminLeave {
+ /** Another admin remains: step down, then leave once that is accepted. */
+ STEP_DOWN_FIRST,
+
+ /** The only admin: make someone else an admin first, or disband instead. */
+ PICK_HEIR,
+
+ /**
+ * Nothing this build can do: a keyed room, whose admins change only with the
+ * group's signature, or a room with nobody else in it to hand over to.
+ */
+ CANNOT,
+}
diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/frost/GovernanceStatementEventTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/frost/GovernanceStatementEventTest.kt
new file mode 100644
index 00000000..4bcbcb0c
--- /dev/null
+++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/frost/GovernanceStatementEventTest.kt
@@ -0,0 +1,160 @@
+package mobi.giza.compose.nostr.frost
+
+import com.vitorpamplona.marmot.appComponents.AdminPolicyV1
+import com.vitorpamplona.marmot.appComponents.CurrentProfileGroupFactory
+import com.vitorpamplona.mls.group.GroupView
+import com.vitorpamplona.mls.group.PendingProposal
+import com.vitorpamplona.mls.messages.Proposal
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.toHexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal
+import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
+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.test.runTest
+import mobi.giza.compose.extensions.toHex
+
+/**
+ * The statement a keyed room's quorum signs before its commit, and the one
+ * function that holds a commit to it. docs/member-admin-promotion.md, Phase 3.
+ */
+class GovernanceStatementEventTest {
+
+ private val room = KeyPair()
+ private val roomId = room.pubKey.toHexKey()
+ private val alice = "a1".repeat(32)
+ private val bob = "b2".repeat(32)
+ private val carol = "c3".repeat(32)
+ private val epoch = 7L
+
+ /** A tree of Alice, Bob and Carol at leaves 0, 1 and 2. */
+ private val group = GroupView(
+ extensions = emptyList(),
+ leafCount = 3,
+ myLeafIndex = 0,
+ identityAt = { listOf(alice, bob, carol).getOrNull(it) },
+ capabilitiesAt = { null },
+ )
+
+ private fun pending(proposal: Proposal, from: Int = 0) = PendingProposal(proposal, senderLeafIndex = from)
+
+ private fun adminsUpdate(vararg admins: String) = Proposal.AppDataUpdate(
+ AdminPolicyV1.COMPONENT_ID,
+ Proposal.AppDataUpdate.Operation.Update(AdminPolicyV1.ofHex(admins.toList()).encode()),
+ )
+
+ private fun statement(change: GovernanceChange, at: Long = epoch, signer: KeyPair = room, about: String = roomId): Event =
+ NostrSignerSync(signer).signNormal(
+ createdAt = 1_700_000_000,
+ kind = GovernanceStatementEvent.KIND,
+ tags = GovernanceStatementEvent.assembleTags(about, at, change, proposer = alice),
+ content = "",
+ )
+
+ @Test
+ fun `a statement reads back as the change it was written from`() {
+ val change = GovernanceChange(
+ adds = setOf(AddedMember(carol, "ff".repeat(32))),
+ removes = setOf(bob),
+ admins = setOf(alice, carol),
+ components = mapOf(0x800c to "ee".repeat(32)),
+ )
+
+ val read = assertNotNull(GovernanceStatementEvent.parse(statement(change)))
+
+ assertEquals(GovernanceStatement(roomId, epoch, alice, change), read)
+ }
+
+ @Test
+ fun `a promotion commit is exactly what its statement says`() {
+ val proposals = listOf(pending(adminsUpdate(alice, bob, carol)))
+ val change = assertNotNull(GovernanceChange.of(group, proposals))
+
+ assertEquals(GovernanceChange(admins = setOf(alice, bob, carol)), change)
+ assertTrue(GovernanceStatementEvent.authorises(statement(change), roomId, epoch, change))
+ }
+
+ @Test
+ fun `a removal names the account, not the leaf`() {
+ val change = assertNotNull(GovernanceChange.of(group, listOf(pending(Proposal.Remove(2)), pending(adminsUpdate(alice, bob)))))
+
+ assertEquals(GovernanceChange(removes = setOf(carol), admins = setOf(alice, bob)), change)
+ }
+
+ @Test
+ fun `an add is pinned to the exact key package`() = runTest {
+ val dave = KeyPair()
+ val keyPackage = CurrentProfileGroupFactory.createKeyPackage(NostrSignerInternal(dave)).keyPackage
+ val change = assertNotNull(GovernanceChange.of(group, listOf(pending(Proposal.Add(keyPackage)))))
+
+ assertEquals(setOf(AddedMember(dave.pubKey.toHexKey(), keyPackage.reference().toHex())), change.adds)
+
+ // Another of Dave's packages is another add, and the statement does not cover it.
+ val other = CurrentProfileGroupFactory.createKeyPackage(NostrSignerInternal(dave)).keyPackage
+ val otherChange = assertNotNull(GovernanceChange.of(group, listOf(pending(Proposal.Add(other)))))
+ assertFalse(GovernanceStatementEvent.authorises(statement(change), roomId, epoch, otherChange))
+ }
+
+ @Test
+ fun `nothing more and nothing less`() {
+ val signed = GovernanceChange(admins = setOf(alice, bob, carol))
+ val event = statement(signed)
+
+ // An extra removal folded in beside the signed promotion.
+ assertFalse(GovernanceStatementEvent.authorises(event, roomId, epoch, signed.copy(removes = setOf(bob))))
+ // The admin list off by one.
+ assertFalse(GovernanceStatementEvent.authorises(event, roomId, epoch, signed.copy(admins = setOf(alice, bob))))
+ }
+
+ @Test
+ fun `a statement is good at its own epoch only`() {
+ val change = GovernanceChange(admins = setOf(alice, bob))
+
+ assertFalse(GovernanceStatementEvent.authorises(statement(change, at = epoch), roomId, epoch + 1, change))
+ }
+
+ @Test
+ fun `only the room itself can sign for the room`() {
+ val change = GovernanceChange(admins = setOf(alice, bob))
+
+ // Signed by one member's own key.
+ assertFalse(GovernanceStatementEvent.authorises(statement(change, signer = KeyPair()), roomId, epoch, change))
+ // Signed by another room, about this one.
+ val otherRoom = KeyPair()
+ assertFalse(GovernanceStatementEvent.authorises(statement(change, signer = otherRoom), roomId, epoch, change))
+ // This room's signature, about another room.
+ assertFalse(GovernanceStatementEvent.authorises(statement(change, about = otherRoom.pubKey.toHexKey()), roomId, epoch, change))
+ }
+
+ @Test
+ fun `a member's own leave needs no signature, and rides along with one that does`() {
+ val leave = pending(Proposal.SelfRemove(), from = 1)
+
+ assertTrue(GovernanceChange.isExempt(listOf(leave)))
+ assertTrue(GovernanceChange.isExempt(emptyList()), "a committer's own key update needed a signature")
+ assertFalse(GovernanceChange.isExempt(listOf(leave, pending(adminsUpdate(alice)))))
+ assertEquals(GovernanceChange(admins = setOf(alice)), GovernanceChange.of(group, listOf(leave, pending(adminsUpdate(alice)))))
+ }
+
+ @Test
+ fun `a change a statement cannot describe is never authorised`() {
+ assertNull(GovernanceChange.of(group, listOf(pending(Proposal.GroupContextExtensions(emptyList())))))
+ }
+
+ @Test
+ fun `malformed tags make no statement`() {
+ val event = NostrSignerSync(room).signNormal(
+ createdAt = 1_700_000_000,
+ kind = GovernanceStatementEvent.KIND,
+ tags = arrayOf(arrayOf("d", roomId), arrayOf("epoch", "seven")),
+ content = "",
+ )
+
+ assertNull(GovernanceStatementEvent.parse(event))
+ }
+}
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 24920847..ab6ff389 100644
--- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt
+++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt
@@ -2,6 +2,8 @@ package mobi.giza.compose.text
import fr.acinq.bitcoin.PrivateKey
import fr.acinq.bitcoin.ByteVector32
+import mobi.giza.compose.nostr.frost.GovernanceChange
+import mobi.giza.compose.nostr.frost.GovernanceStatementEvent
import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent
@@ -51,6 +53,25 @@ class ProposedEventTest {
)
}
+ /** docs/member-admin-promotion.md, Phase 3: a member approves names, not a hash. */
+ @Test
+ fun `a change to the group says who, in names`() {
+ val bob = "b".repeat(64)
+ val carol = "c".repeat(64)
+ val tags = GovernanceStatementEvent.assembleTags(
+ chatRoomId = "1".repeat(64),
+ epoch = 4,
+ change = GovernanceChange(removes = setOf(carol), admins = setOf(bob)),
+ proposer = bob,
+ )
+ val names = mapOf(bob to "Bob", carol to "Carol")
+
+ val summary = ProposedEvent.summarize(event(GovernanceStatementEvent.KIND, tags = tags), nameOf = names::get)
+
+ assertEquals("A change to who is in this group", summary.label)
+ assertEquals("Removes Carol · Admins afterwards: Bob", summary.detail)
+ }
+
@Test
fun `a wallet's kind is said as one, not as a number`() {
listOf(30331, 30334, 30337, 30355, 30363).forEach { kind ->
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 d4b988d7..27cfdc5c 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
@@ -64,10 +64,11 @@ class ShippedProfileUpgradeJvmTest {
/**
* The schema version this branch builds: 38 for share generations, 39 for share
* refresh and 40 for share repair (docs/frost-share-refresh.md, Phases 6, 7 and
- * 10), so the upgrade crosses four generated migrations and the file has to come
- * out at the last.
+ * 10), 41 for governance proposals and 42 for what follows them
+ * (docs/member-admin-promotion.md, Phases 5, 8 and 9), so the upgrade crosses six
+ * generated migrations and the file has to come out at the last.
*/
- private val current = 40
+ private val current = 42
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/AdminCaptionsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminCaptionsJvmTest.kt
new file mode 100644
index 00000000..ac06c0cf
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminCaptionsJvmTest.kt
@@ -0,0 +1,116 @@
+package mobi.giza.compose.managers
+
+import androidx.room3.Room
+import com.vitorpamplona.marmot.appComponents.AdminPolicyV1
+import com.vitorpamplona.marmot.appComponents.CurrentProfileGroupFactory
+import com.vitorpamplona.quartz.nip01Core.core.toHexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal
+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.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.runBlocking
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.builder.getRoomDatabase
+import mobi.giza.compose.database.model.ChatMessage
+import mobi.giza.compose.database.repository.DatabaseMarmotRepository
+
+/**
+ * The lines a room gets when who governs it changes. docs/member-admin-promotion.md,
+ * Phase 2.
+ *
+ * Another member administers the room and changes its admin list over the wire;
+ * the app applies each commit and is checked for what it says. The lines come from
+ * the group's admin set before and after the commit -- not from the participants'
+ * `adminAt` flags -- so they are the same on every device that applies it.
+ */
+class AdminCaptionsJvmTest {
+
+ private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder())
+ private val marmotRepository = DatabaseMarmotRepository(db, CoroutineScope(Dispatchers.Default))
+
+ @AfterTest
+ fun closeDb() = db.close()
+
+ private val user = KeyPair()
+ private val userHex = user.pubKey.toHexKey()
+ private val dana = MarmotStandIn()
+
+ /** Dana's room with the app in it; Dana is its only admin. Returns the room id. */
+ private suspend fun danasRoom(): String {
+ MarmotStandIn.seedProfile(db, userHex, "us")
+ MarmotStandIn.seedProfile(db, dana.hex, "Dana")
+ val routingId = dana.createGroup("Dana's")
+ return dana.inviteApp(db, marmotRepository, user, routingId)
+ }
+
+ /** Dana commits [admins] as the room's admin list, and the app receives it. */
+ private suspend fun danaSetsAdmins(routingId: String, admins: List) {
+ val commit = dana.commitLocally(routingId) {
+ val staged = dana.manager.stageAppDataUpdate(routingId, AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(admins).encode())
+ dana.manager.installState(routingId, staged.pendingState)
+ staged.result
+ }
+ MarmotStandIn.storeInApp(db, user, dana.outbound.buildCommitEvent(routingId, commit.framedCommitBytes, commit.preCommitExporterSecret).signedEvent)
+ }
+
+ /**
+ * The admin lines, in no particular order: two written in the same second
+ * cannot be told apart by time, so the tests look for each by its type.
+ */
+ private suspend fun adminLines(roomId: String) =
+ db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage }
+ .filter { it.messageType == ChatMessage.TYPE_ADMIN_ADDED || it.messageType == ChatMessage.TYPE_ADMIN_REMOVED }
+
+ @Test
+ fun `made an admin, and then not, the app says so in its own words`() = runBlocking {
+ val roomId = danasRoom()
+
+ danaSetsAdmins(roomId, listOf(dana.hex, userHex))
+ assertEquals(listOf(ChatMessage.TYPE_ADMIN_ADDED to "You are now an admin"), adminLines(roomId).map { it.messageType to it.content })
+ assertNotNull(db.chatRoomDao().findChatRoomById(roomId)!!.localParticipants.single { it.participant.participantPublicKey == userHex }.participant.adminAt)
+
+ danaSetsAdmins(roomId, listOf(dana.hex))
+ assertEquals(
+ listOf("You are no longer an admin"),
+ adminLines(roomId).filter { it.messageType == ChatMessage.TYPE_ADMIN_REMOVED }.map { it.content },
+ )
+ assertEquals(2, adminLines(roomId).size, "the demotion repeated the promotion's line")
+ assertNull(db.chatRoomDao().findChatRoomById(roomId)!!.localParticipants.single { it.participant.participantPublicKey == userHex }.participant.adminAt)
+ }
+
+ @Test
+ fun `another member made an admin is named`() = runBlocking {
+ val roomId = danasRoom()
+ val erin = KeyPair()
+ MarmotStandIn.seedProfile(db, erin.pubKey.toHexKey(), "Erin")
+ val add = dana.commitLocally(roomId) {
+ dana.manager.addMember(roomId, CurrentProfileGroupFactory.createKeyPackage(NostrSignerInternal(erin)).keyPackage.toTlsBytes())
+ }
+ MarmotStandIn.storeInApp(db, user, dana.outbound.buildCommitEvent(roomId, add.framedCommitBytes, add.preCommitExporterSecret).signedEvent)
+
+ danaSetsAdmins(roomId, listOf(dana.hex, erin.pubKey.toHexKey()))
+
+ assertEquals(listOf("Erin is now an admin"), adminLines(roomId).map { it.content })
+ }
+
+ @Test
+ fun `a commit that changes nobody's rights says nothing about them`() = runBlocking {
+ val roomId = danasRoom()
+ val erin = KeyPair()
+ MarmotStandIn.seedProfile(db, erin.pubKey.toHexKey(), "Erin")
+
+ val add = dana.commitLocally(roomId) {
+ dana.manager.addMember(roomId, CurrentProfileGroupFactory.createKeyPackage(NostrSignerInternal(erin)).keyPackage.toTlsBytes())
+ }
+ MarmotStandIn.storeInApp(db, user, dana.outbound.buildCommitEvent(roomId, add.framedCommitBytes, add.preCommitExporterSecret).signedEvent)
+
+ assertTrue(db.chatMessageDao().getChatMessagesByChatRoomId(roomId).any { it.chatMessage.messageType == ChatMessage.TYPE_MEMBER_ADDED })
+ assertTrue(adminLines(roomId).isEmpty(), "an add wrote an admin line")
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt
new file mode 100644
index 00000000..9d0c2aaf
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt
@@ -0,0 +1,323 @@
+package mobi.giza.compose.managers
+
+import androidx.room3.Room
+import com.vitorpamplona.marmot.GroupEventResult
+import com.vitorpamplona.marmot.appComponents.AdminPolicyV1
+import com.vitorpamplona.marmot.groups.currentAdminIdentities
+import com.vitorpamplona.marmot.groups.isLocalAdmin
+import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent
+import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent
+import com.vitorpamplona.quartz.nip01Core.core.toHexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import kotlin.io.encoding.Base64
+import kotlin.test.AfterTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFailsWith
+import kotlin.test.assertFalse
+import kotlin.test.assertIs
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+import kotlin.time.Instant
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.runBlocking
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.builder.getRoomDatabase
+import mobi.giza.compose.database.model.ChatMessage
+import mobi.giza.compose.database.model.MarmotKeyPackage
+import mobi.giza.compose.database.model.NostrEvent
+import mobi.giza.compose.database.model.Profile
+import mobi.giza.compose.database.repository.DatabaseChatRepository
+import mobi.giza.compose.database.repository.DatabaseNostrRepository
+import mobi.giza.compose.exceptions.MarmotCommitPendingException
+import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.nostr.MarmotProfile
+import mobi.giza.compose.nostr.Relays
+import mobi.giza.compose.ui.view.state.AdminLeave
+import mobi.giza.compose.ui.view.state.MemberAction
+
+/**
+ * Promoting and demoting in a convenient room, which has no key to sign with and
+ * so is governed by one admin's commit. docs/member-admin-promotion.md, Phase 6.
+ *
+ * The app creates the room the way the room-type screen does and administers it;
+ * a stand-in is the other member. Every commit goes through the publish gate and
+ * the relay's OK is played by hand, as in GroupLifecycleJvmTest.
+ */
+class AdminChangesJvmTest {
+
+ private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder())
+ private val scope = CoroutineScope(Dispatchers.Default)
+ private val chatRepository = DatabaseChatRepository(db, scope)
+ private val nostrRepository = DatabaseNostrRepository(db, scope)
+
+ @AfterTest
+ fun closeDb() = db.close()
+
+ private val keyPair = KeyPair()
+ private val user = keyPair.pubKey.toHexKey()
+ private val roomId = KeyPair().pubKey.toHexKey()
+ private val member = MarmotStandIn()
+ private lateinit var routingId: String
+
+ private suspend fun seedProfile(publicKey: String, name: String) {
+ val eventId = publicKey.take(32).padEnd(64, 'f')
+ db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)))
+ db.profileDao().upsert(Profile(publicKey = publicKey, userName = name, nostrEventId = eventId))
+ }
+
+ private suspend fun room() = db.chatRoomDao().findChatRoomById(roomId)!!
+ private suspend fun adminLines() = db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage }
+ .filter { it.messageType == ChatMessage.TYPE_ADMIN_ADDED || it.messageType == ChatMessage.TYPE_ADMIN_REMOVED }
+ private suspend fun appGroup() = db.marmotEngine.groupManager.getGroup(routingId)!!
+
+ /**
+ * A convenient room, as Giza made one before every group was robust and a Bennu
+ * peer still does (docs/remove-convenient-groups.md), with the stand-in in it.
+ */
+ private suspend fun convenientRoomWithMember() {
+ seedProfile(user, "us")
+ seedProfile(member.hex, "Dana")
+ val created = MarmotGroupFactory.create(
+ creator = keyPair, roomId = roomId, name = "#room", description = null,
+ adminPublicKeys = listOf(user), relays = Relays.DefaultDMRelayList.map { it.url },
+ profile = MarmotProfile.CURRENT,
+ )
+ routingId = created.routingId
+ assertNotNull(
+ chatRepository.getOrCreateChatRoom(
+ chatRoomId = roomId, activeUserPublicKey = user, relayHint = null, defaultSubject = "#room",
+ description = null, mlsGroupState = created.group.saveState().encodeTls().toHex(),
+ )
+ )
+ chatRepository.recordMarmotRouting(chatRoomId = roomId, routingId = routingId)
+ chatRepository.reconcileAdmins(roomId)
+ invite()
+ }
+
+ /** Invites the stand-in with a fresh key package and has it join from the Welcome. */
+ private suspend fun invite() {
+ val earlier = db.giftWrapPayloadDao().getAllGiftWrapUnsigned().map { it.id }.toSet()
+ member.makeBundle()
+ chatRepository.inviteMember(
+ room(), member.hex,
+ MarmotKeyPackage(
+ id = member.hex + db.giftWrapPayloadDao().getAllGiftWrapUnsigned().size, publicKey = member.hex,
+ tlsEncodedMarmotKeyPackage = member.bundle.keyPackage.toTlsBytes(), profile = MarmotProfile.CURRENT.wireName,
+ ),
+ )
+ val welcome = db.giftWrapPayloadDao().getAllGiftWrapUnsigned().single { it.kind == WelcomeEvent.KIND && it.id !in earlier }
+ val welcomeEvent = WelcomeEvent(id = welcome.id, pubKey = user, createdAt = welcome.createdAt.epochSeconds, tags = welcome.tags, content = welcome.content, sig = "")
+ member.manager.processWelcome(Base64.decode(welcomeEvent.welcomeBase64()), member.bundle)
+ member.inbound.trackGroup(routingId)
+ }
+
+ /** The relay's OK on the newest commit this device put on the wire, which the stand-in then applies. */
+ private suspend fun okTheLatestCommit(): GroupEvent {
+ val event = db.nostrEventDao().getMLSGroupEvents(since = Instant.fromEpochSeconds(0), limit = 50)
+ .filter { it.kind == GroupEvent.KIND }
+ .filter { db.marmotCommitResultDao().getMarmotCommitRequestById(it.id) != null }
+ .first { db.broadcastNostrEventRequestDao().getFirstBroadcastNostrEventRequestByNostrEventId(it.id)?.status == "pending" }
+ val request = db.broadcastNostrEventRequestDao().getFirstBroadcastNostrEventRequestByNostrEventId(event.id)!!
+ nostrRepository.broadcastProcessed(request, "published")
+ val groupEvent = event.toGroupEvent(user)!!
+ if (member.manager.isMember(routingId)) member.inbound.processGroupEvent(groupEvent)
+ return groupEvent
+ }
+
+ @Test
+ fun `an admin makes a member an admin, every device agrees, and the room says it once`() = runBlocking {
+ convenientRoomWithMember()
+
+ chatRepository.promoteMember(room(), member.hex)
+ assertFalse(member.hex in appGroup().currentAdminIdentities(), "applied before any relay accepted it")
+ val commit = okTheLatestCommit()
+
+ assertTrue(member.hex in appGroup().currentAdminIdentities())
+ assertTrue(member.manager.getGroup(routingId)!!.isLocalAdmin(), "the promotion did not reach the member")
+ assertEquals(listOf("Dana is now an admin"), adminLines().map { it.content })
+
+ // The relay hands the app its own commit back: nothing more is said.
+ MarmotStandIn.storeInApp(db, keyPair, commit)
+ assertEquals(1, adminLines().size, "the echo of our own commit captioned it again")
+ }
+
+ @Test
+ fun `a promoted member can govern, and a demoted one cannot`() = runBlocking {
+ convenientRoomWithMember()
+ chatRepository.promoteMember(room(), member.hex)
+ okTheLatestCommit()
+
+ chatRepository.demoteMember(room(), member.hex)
+ okTheLatestCommit()
+
+ assertEquals(setOf(user), appGroup().currentAdminIdentities())
+ assertFalse(member.manager.getGroup(routingId)!!.isLocalAdmin())
+ assertFailsWith("a demoted member's own library let it change the admin list") {
+ member.manager.stageAppDataUpdate(routingId, AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(listOf(member.hex)).encode())
+ }
+ assertTrue(adminLines().any { it.messageType == ChatMessage.TYPE_ADMIN_REMOVED && it.content == "Dana is no longer an admin" })
+ }
+
+ @Test
+ fun `the only admin cannot step down, and is told what to do instead`() = runBlocking {
+ convenientRoomWithMember()
+
+ val refusal = assertFailsWith { chatRepository.demoteMember(room(), user) }
+
+ assertEquals("You're the only admin. Make someone else an admin first", refusal.message)
+ assertTrue(db.marmotPublishObligationDao().getAll().isEmpty(), "a refused change still raised an obligation")
+ }
+
+ @Test
+ fun `with another admin, an admin can step down`() = runBlocking {
+ convenientRoomWithMember()
+ chatRepository.promoteMember(room(), member.hex)
+ okTheLatestCommit()
+
+ chatRepository.demoteMember(room(), user)
+ okTheLatestCommit()
+
+ assertEquals(setOf(member.hex), appGroup().currentAdminIdentities())
+ assertFalse(appGroup().isLocalAdmin())
+ assertTrue(adminLines().any { it.content == "You are no longer an admin" })
+ }
+
+ @Test
+ fun `a change while another is waiting for a relay is refused in words`() = runBlocking {
+ convenientRoomWithMember()
+ chatRepository.promoteMember(room(), member.hex)
+
+ // Asked again before the first is accepted: the gate holds one commit at a time.
+ assertFailsWith { chatRepository.promoteMember(room(), member.hex) }
+ }
+
+ /**
+ * The hole this phase closes. A bare Remove left the admin's key on the list,
+ * so inviting them back made them an admin again with nobody having said so.
+ */
+ @Test
+ fun `a removed admin who is invited back is not an admin`() = runBlocking {
+ convenientRoomWithMember()
+ chatRepository.promoteMember(room(), member.hex)
+ okTheLatestCommit()
+
+ chatRepository.removeMember(room(), member.hex)
+ okTheLatestCommit() // the demotion; its confirmation stages the removal
+ assertEquals(setOf(user), appGroup().currentAdminIdentities(), "the admin list still names them")
+ okTheLatestCommit() // the removal
+ assertFalse(member.hex in appGroup().currentMemberIdentities(), "the removal did not follow the demotion")
+
+ invite()
+ assertTrue(member.hex in appGroup().currentMemberIdentities())
+ assertEquals(setOf(user), appGroup().currentAdminIdentities(), "re-invited, and an admin again")
+ }
+
+ @Test
+ fun `the member rows offer what the group would accept, and leaving says how it will go`() = runBlocking {
+ convenientRoomWithMember()
+
+ assertEquals(mapOf(member.hex to setOf(MemberAction.MAKE_ADMIN, MemberAction.REMOVE_FROM_GROUP)), AdminGovernance.memberActions(appGroup(), user))
+ assertEquals(AdminLeave.PICK_HEIR, AdminGovernance.adminLeave(appGroup(), user))
+ assertEquals(emptyMap(), AdminGovernance.memberActions(member.manager.getGroup(routingId)!!, member.hex), "a member who is not an admin was offered something")
+
+ chatRepository.promoteMember(room(), member.hex)
+ okTheLatestCommit()
+
+ assertEquals(
+ mapOf(user to setOf(MemberAction.STEP_DOWN), member.hex to setOf(MemberAction.REMOVE_AS_ADMIN, MemberAction.REMOVE_FROM_GROUP)),
+ AdminGovernance.memberActions(appGroup(), user),
+ )
+ assertEquals(AdminLeave.STEP_DOWN_FIRST, AdminGovernance.adminLeave(appGroup(), user))
+ }
+
+ @Test
+ fun `an admin with another admin beside them steps down, then leaves`() = runBlocking {
+ convenientRoomWithMember()
+ chatRepository.promoteMember(room(), member.hex)
+ okTheLatestCommit()
+
+ chatRepository.stepDownAndLeave(room(), heir = null)
+ assertEquals(null, room().chatRoom.leftGroupAt, "left before the step-down was accepted")
+ okTheLatestCommit() // the step-down; its acceptance sends the leave
+
+ assertNotNull(room().chatRoom.leftGroupAt, "the leave did not follow the step-down")
+ assertEquals(setOf(member.hex), member.manager.getGroup(routingId)!!.currentAdminIdentities())
+ }
+
+ @Test
+ fun `the only admin hands over to the member they pick, then leaves`() = runBlocking {
+ convenientRoomWithMember()
+
+ chatRepository.stepDownAndLeave(room(), heir = member.hex)
+ okTheLatestCommit() // the promotion
+ assertNull(room().chatRoom.leftGroupAt)
+ okTheLatestCommit() // the step-down
+
+ assertNotNull(room().chatRoom.leftGroupAt, "the leave did not follow the hand-over")
+ assertEquals(setOf(member.hex), member.manager.getGroup(routingId)!!.currentAdminIdentities())
+ assertTrue(member.manager.getGroup(routingId)!!.isLocalAdmin())
+ }
+
+ @Test
+ fun `the only admin who names nobody is refused, and nothing waits`() = runBlocking {
+ convenientRoomWithMember()
+
+ assertFailsWith { chatRepository.stepDownAndLeave(room(), heir = null) }
+
+ assertNull(room().chatRoom.leftGroupAt)
+ assertTrue(db.marmotPublishObligationDao().getAll().isEmpty())
+ }
+
+ @Test
+ fun `a robust group keeps at least three admins, and never fewer than its quorum`() {
+ assertEquals(3, Quorum.minimumAdmins(threshold = null))
+ assertEquals(3, Quorum.minimumAdmins(threshold = 2))
+ assertEquals(4, Quorum.minimumAdmins(threshold = 4))
+ }
+
+ @Test
+ fun `a keyed room's floor comes from its own ceremony, a convenient room's is one`() = runBlocking {
+ val keyed = GroupFixtures.signingRoom(db, GroupFixtures.keyMaterial("f1001" + "0".repeat(57) + "f6"), members = listOf("a1".repeat(32), "b2".repeat(32)))
+ assertEquals(3, AdminGovernance.adminFloor(db, keyed.chatRoom.id, keyed.chatRoom.toMlsGroup()!!))
+
+ convenientRoomWithMember()
+ assertEquals(1, AdminGovernance.adminFloor(db, roomId, appGroup()))
+ }
+
+ @Test
+ fun `removing an admin is not offered, or allowed, where it would break the floor`() = runBlocking {
+ convenientRoomWithMember()
+ chatRepository.promoteMember(room(), member.hex)
+ okTheLatestCommit()
+
+ assertTrue(AdminGovernance.keepsFloor(appGroup(), member.hex, floor = 1))
+ assertFalse(AdminGovernance.keepsFloor(appGroup(), member.hex, floor = 2), "two admins down to one kept a floor of two")
+ assertFalse(
+ MemberAction.REMOVE_FROM_GROUP in AdminGovernance.memberActions(appGroup(), user, floor = 2)[member.hex].orEmpty(),
+ "the menu offered a removal the floor forbids",
+ )
+ }
+
+ @Test
+ fun `a keyed room's admins are not changed by one admin's commit`() = runBlocking {
+ seedProfile(user, "us")
+ val keyedRoomId = SharedKeyDerivation.marmotGroupId("02" + KeyPair().pubKey.toHexKey())
+ assertIs(
+ MarmotGroupCreation.create(
+ database = db, chatRepository = chatRepository, groupId = keyedRoomId, name = "#keyed",
+ purpose = "Admins.", adminPublicKeys = setOf(user), userPublicKey = user, keyPair = keyPair,
+ profile = MarmotProfile.CURRENT,
+ )
+ )
+ val keyedRoom = db.chatRoomDao().findChatRoomById(keyedRoomId)!!
+
+ val refusal = assertFailsWith { chatRepository.demoteMember(keyedRoom, user) }
+ assertEquals(mobi.giza.compose.database.dao.MarmotOutboundDao.KEYED_ROOM_REFUSAL, refusal.message)
+ assertTrue(db.marmotPublishObligationDao().getAll().isEmpty())
+ val keyedGroup = db.marmotEngine.groupFor(keyedRoom.routingId)!!
+ assertEquals(AdminLeave.CANNOT, AdminGovernance.adminLeave(keyedGroup, user))
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminFlagsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminFlagsJvmTest.kt
new file mode 100644
index 00000000..cca6eb41
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminFlagsJvmTest.kt
@@ -0,0 +1,97 @@
+package mobi.giza.compose.managers
+
+import androidx.room3.Room
+import com.vitorpamplona.quartz.nip01Core.core.toHexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import kotlin.test.AfterTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+import kotlin.time.Instant
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.runBlocking
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.builder.getRoomDatabase
+import mobi.giza.compose.database.model.MarmotKeyPackage
+import mobi.giza.compose.database.model.NostrEvent
+import mobi.giza.compose.database.model.Profile
+import mobi.giza.compose.database.repository.DatabaseChatRepository
+import mobi.giza.compose.nostr.MarmotProfile
+
+/**
+ * `Participant.adminAt` made true where rooms are made and when a room is opened,
+ * so that nothing reads a stale flag as news. docs/member-admin-promotion.md,
+ * Phase 1.
+ *
+ * Before, the flag was written only when a commit arrived, so on the device that
+ * created a convenient room or a direct message nobody was an admin until somebody
+ * else committed. With admin captions derived from changes, that would have put
+ * "You are now an admin" on the creator's screen at their first invite.
+ */
+class AdminFlagsJvmTest {
+
+ private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder())
+ private val chatRepository = DatabaseChatRepository(db, CoroutineScope(Dispatchers.Default))
+
+ @AfterTest
+ fun closeDb() = db.close()
+
+ private val keyPair = KeyPair()
+ private val user = keyPair.pubKey.toHexKey()
+ private val member = MarmotStandIn()
+
+ private suspend fun seedProfile(publicKey: String) {
+ val eventId = publicKey.take(32).padEnd(64, 'f')
+ db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)))
+ db.profileDao().upsert(Profile(publicKey = publicKey, userName = publicKey.take(8), nostrEventId = eventId))
+ }
+
+ private suspend fun directMessage(): String {
+ seedProfile(user)
+ seedProfile(member.hex)
+ member.makeBundle()
+ return db.marmotOutboundDao().createMlsDirectMessageChatRoom(
+ creator = keyPair,
+ peerPublicKey = member.hex,
+ peerKeyPackage = MarmotKeyPackage(
+ id = member.hex, publicKey = member.hex,
+ tlsEncodedMarmotKeyPackage = member.bundle.keyPackage.toTlsBytes(),
+ profile = MarmotProfile.CURRENT.wireName,
+ ),
+ profile = MarmotProfile.CURRENT,
+ )
+ }
+
+ private suspend fun flags(roomId: String): Map =
+ db.chatRoomDao().findChatRoomById(roomId)!!.localParticipants
+ .associate { it.participant.participantPublicKey to it.participant.adminAt }
+
+ @Test
+ fun `the creator of a direct message is its admin from the start, and the peer is not`() = runBlocking {
+ val roomId = directMessage()
+
+ val flags = flags(roomId)
+ assertNotNull(flags[user], "the creator was not flagged before any commit arrived")
+ assertNull(flags[member.hex])
+ }
+
+ @Test
+ fun `opening a room whose flags went stale catches them up and says nothing`() = runBlocking {
+ val roomId = directMessage()
+ // A room made before this build: the creator's row never flagged.
+ val creatorRow = db.chatRoomDao().findChatRoomById(roomId)!!.localParticipants
+ .single { it.participant.participantPublicKey == user }.participant
+ db.participantDao().upsert(listOf(creatorRow.copy(adminAt = null)))
+ val linesBefore = db.chatMessageDao().getChatMessagesByChatRoomId(roomId).size
+
+ assertTrue(chatRepository.reconcileAdmins(roomId))
+
+ assertNotNull(flags(roomId)[user])
+ assertEquals(linesBefore, db.chatMessageDao().getChatMessagesByChatRoomId(roomId).size, "a reconcile wrote a line")
+ assertFalse(chatRepository.reconcileAdmins(roomId), "a second reconcile found something to change")
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt
new file mode 100644
index 00000000..6117e5ef
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GovernanceGateJvmTest.kt
@@ -0,0 +1,567 @@
+package mobi.giza.compose.managers
+
+import androidx.room3.Room
+import com.vitorpamplona.marmot.appComponents.AdminPolicyV1
+import com.vitorpamplona.marmot.foundation.appEvents.MarmotAppEvent
+import com.vitorpamplona.marmot.groups.currentAdminIdentities
+import com.vitorpamplona.marmot.groups.isLocalAdmin
+import com.vitorpamplona.mls.messages.CommitResult
+import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import com.vitorpamplona.quartz.nip01Core.core.toHexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
+import kotlin.test.AfterTest
+import mobi.giza.compose.extensions.toHex
+import mobi.giza.compose.ui.view.state.GovernanceStatus
+import mobi.giza.compose.nostr.frost.GovernanceSupportEvent
+import mobi.giza.compose.database.repository.DatabaseNostrRepository
+import mobi.giza.compose.database.repository.DatabaseChatRepository
+import kotlin.test.assertIs
+import kotlin.test.assertFailsWith
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertNotNull
+import kotlin.test.assertTrue
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.runBlocking
+import mobi.giza.compose.database.GizaDatabase
+import mobi.giza.compose.database.builder.getRoomDatabase
+import mobi.giza.compose.database.model.ChatMessage
+import mobi.giza.compose.database.repository.DatabaseMarmotRepository
+import mobi.giza.compose.nostr.frost.GovernanceCarrierEvent
+import mobi.giza.compose.nostr.frost.GovernanceChange
+import mobi.giza.compose.nostr.frost.GovernanceStatementEvent
+import mobi.giza.compose.nostr.frost.OwnCommitEvent
+
+/**
+ * The door a governed room's commits come through. docs/member-admin-promotion.md,
+ * R2 and Phase 4a.
+ *
+ * Dana runs a keyed room whose state says its changes need the group's signature;
+ * the app is the other member. The group's key is played by an ordinary key pair
+ * whose public half is the room's id -- which is all a FROST signature by the room is,
+ * once aggregated -- so these tests are about the door, not about the signing.
+ */
+class GovernanceGateJvmTest {
+
+ private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder())
+ private val marmotRepository = DatabaseMarmotRepository(db, CoroutineScope(Dispatchers.Default))
+ private val chatRepository = DatabaseChatRepository(db, CoroutineScope(Dispatchers.Default))
+ private val nostrRepository = DatabaseNostrRepository(db, CoroutineScope(Dispatchers.Default))
+
+ @AfterTest
+ fun closeDb() = db.close()
+
+ private val user = KeyPair()
+ private val userHex = user.pubKey.toHexKey()
+ private val dana = MarmotStandIn()
+ private val roomKey = KeyPair()
+ private val roomId = roomKey.pubKey.toHexKey()
+ private lateinit var routingId: String
+
+ /** Dana's keyed room, governed from its first epoch, with the app in it. */
+ private suspend fun governedRoom(governed: Boolean = true) {
+ MarmotStandIn.seedProfile(db, userHex, "us")
+ MarmotStandIn.seedProfile(db, dana.hex, "Dana")
+ val keyed = MarmotRoomIdentity.describe(SharedKeyDerivation.describe("Admins."), roomId)
+ routingId = dana.createGroup("#keyed", if (governed) GovernanceMarker.describe(keyed, minimumAdmins = 1) else keyed)
+ dana.inviteApp(db, marmotRepository, user, routingId, roomId = roomId)
+ assertEquals(governed, GovernanceGate.isGoverned(appGroup()))
+ }
+
+ private suspend fun appGroup() = db.marmotEngine.groupFor(routingId)!!
+
+ private suspend fun lines(type: String) =
+ db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage }.filter { it.messageType == type }
+
+ /** Dana's commit making the app an admin, staged and not yet installed on her side. */
+ private suspend fun stagedPromotion() =
+ dana.manager.stageAppDataUpdate(routingId, AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(listOf(dana.hex, userHex)).encode())
+
+ private suspend fun commitEvent(result: CommitResult): GroupEvent =
+ dana.outbound.buildCommitEvent(routingId, result.framedCommitBytes, result.preCommitExporterSecret).signedEvent
+
+ /** The statement [change] at [epoch], signed by [signer], carrying [commit]. */
+ private fun statement(commit: GroupEvent, change: GovernanceChange, epoch: Long, signer: KeyPair = roomKey): Event =
+ NostrSignerSync(signer).signNormal(
+ createdAt = 1_700_000_000,
+ kind = GovernanceStatementEvent.KIND,
+ tags = GovernanceStatementEvent.assembleTags(roomId, epoch, change, proposer = dana.hex),
+ content = commit.toJson(),
+ )
+
+ /** Dana sends [kind] with [content] into the room as an application message. */
+ private suspend fun danaSays(kind: Int, content: String, tags: Array>) {
+ val payload = MarmotAppEvent.build(pubKey = dana.hex, kind = kind, content = content, createdAt = 1_700_000_001, tags = tags).encodeToPayload()
+ MarmotStandIn.storeInApp(db, user, dana.outbound.buildGroupEventFromBytes(routingId, payload).signedEvent)
+ }
+
+ private suspend fun danaCarries(statement: Event) =
+ danaSays(GovernanceCarrierEvent.KIND, statement.toJson(), GovernanceCarrierEvent.assembleTags(roomId))
+
+ @Test
+ fun `a commit sent bare into a governed room is dropped, and the room says so`() = runBlocking {
+ governedRoom()
+ val epoch = appGroup().epoch
+
+ val bare = dana.commitLocally(routingId) {
+ val staged = stagedPromotion()
+ dana.manager.installState(routingId, staged.pendingState)
+ staged.result
+ }
+ MarmotStandIn.storeInApp(db, user, commitEvent(bare))
+
+ assertEquals(epoch, appGroup().epoch, "the unsigned commit was applied")
+ assertFalse(appGroup().isLocalAdmin())
+ assertEquals(1, lines(ChatMessage.TYPE_CHANGE_NOT_APPLIED).size)
+ }
+
+ @Test
+ fun `a commit inside the group's signature lands, as the very event the proposer built`() = runBlocking {
+ governedRoom()
+ val epoch = appGroup().epoch
+ val staged = stagedPromotion()
+ val commit = commitEvent(staged.result)
+
+ danaCarries(statement(commit, GovernanceChange(admins = setOf(dana.hex, userHex)), epoch))
+ dana.manager.installState(routingId, staged.pendingState)
+
+ assertEquals(epoch + 1, appGroup().epoch, "the signed commit was not applied")
+ assertTrue(appGroup().isLocalAdmin())
+ assertNotNull(db.marmotGroupEventDao().getMarmotGroupEventById(commit.id), "applied as some other event than the proposer's")
+ assertEquals(listOf("You are now an admin"), lines(ChatMessage.TYPE_ADMIN_ADDED).map { it.content })
+ assertTrue(lines(ChatMessage.TYPE_CHANGE_NOT_APPLIED).isEmpty())
+
+ // Carried again by somebody else, or repeated by a relay: not news, and not a refusal.
+ danaCarries(statement(commit, GovernanceChange(admins = setOf(dana.hex, userHex)), epoch))
+ assertTrue(lines(ChatMessage.TYPE_CHANGE_NOT_APPLIED).isEmpty())
+ }
+
+ @Test
+ fun `a signature by anyone but the room is refused`() = runBlocking {
+ governedRoom()
+ val epoch = appGroup().epoch
+ val commit = commitEvent(stagedPromotion().result)
+
+ danaCarries(statement(commit, GovernanceChange(admins = setOf(dana.hex, userHex)), epoch, signer = dana.keyPair))
+
+ assertEquals(epoch, appGroup().epoch)
+ assertEquals(1, lines(ChatMessage.TYPE_CHANGE_NOT_APPLIED).size)
+ }
+
+ @Test
+ fun `a statement that does not say what its commit does is refused`() = runBlocking {
+ governedRoom()
+ val epoch = appGroup().epoch
+ val commit = commitEvent(stagedPromotion().result)
+
+ // The group signed "Dana stays the only admin"; the commit makes the app one.
+ danaCarries(statement(commit, GovernanceChange(admins = setOf(dana.hex)), epoch))
+
+ assertEquals(epoch, appGroup().epoch)
+ assertFalse(appGroup().isLocalAdmin())
+ }
+
+ @Test
+ fun `a statement signed for another epoch is refused`() = runBlocking {
+ governedRoom()
+ val epoch = appGroup().epoch
+ val commit = commitEvent(stagedPromotion().result)
+
+ danaCarries(statement(commit, GovernanceChange(admins = setOf(dana.hex, userHex)), epoch + 1))
+
+ assertEquals(epoch, appGroup().epoch)
+ }
+
+ @Test
+ fun `a member's own key update needs nobody's signature, and lands in its own envelope`() = runBlocking {
+ governedRoom()
+ val epoch = appGroup().epoch
+ val update = dana.manager.stageCommit(routingId)
+
+ danaSays(OwnCommitEvent.KIND, commitEvent(update.result).toJson(), OwnCommitEvent.assembleTags(roomId, epoch))
+ dana.manager.installState(routingId, update.pendingState)
+
+ assertEquals(epoch + 1, appGroup().epoch, "an own key update was not applied")
+ assertTrue(lines(ChatMessage.TYPE_CHANGE_NOT_APPLIED).isEmpty())
+ }
+
+ @Test
+ fun `a change to the room cannot pass as a member's own commit`() = runBlocking {
+ governedRoom()
+ val epoch = appGroup().epoch
+
+ danaSays(OwnCommitEvent.KIND, commitEvent(stagedPromotion().result).toJson(), OwnCommitEvent.assembleTags(roomId, epoch))
+
+ assertEquals(epoch, appGroup().epoch)
+ assertFalse(appGroup().isLocalAdmin())
+ assertEquals(1, lines(ChatMessage.TYPE_CHANGE_NOT_APPLIED).size)
+ }
+
+ @Test
+ fun `a keyed room whose state does not say so takes commits as it always did`() = runBlocking {
+ governedRoom(governed = false)
+ val epoch = appGroup().epoch
+
+ val bare = dana.commitLocally(routingId) {
+ val staged = stagedPromotion()
+ dana.manager.installState(routingId, staged.pendingState)
+ staged.result
+ }
+ MarmotStandIn.storeInApp(db, user, commitEvent(bare))
+
+ assertEquals(epoch + 1, appGroup().epoch)
+ assertEquals(setOf(dana.hex, userHex), appGroup().currentAdminIdentities())
+ }
+
+ // --- Phase 4b: who can follow, and the switch ---------------------------------
+
+ private val erin = MarmotStandIn()
+
+ /** Erin joins Dana's room, by Dana's bare commit; the app applies it. */
+ private suspend fun erinJoins() {
+ MarmotStandIn.seedProfile(db, erin.hex, "Erin")
+ erin.makeBundle()
+ val add = dana.commitLocally(routingId) { dana.manager.addMember(routingId, erin.bundle.keyPackage.toTlsBytes()) }
+ erin.manager.processWelcome(assertNotNull(add.welcomeBytes), erin.bundle)
+ erin.inbound.trackGroup(routingId)
+ MarmotStandIn.storeInApp(db, user, commitEvent(add))
+ }
+
+ /** Dana makes [admins] the admin list by a bare commit, which Erin and the app apply. */
+ private suspend fun danaSetsAdminsBare(admins: List) {
+ val commit = dana.commitLocally(routingId) {
+ val staged = dana.manager.stageAppDataUpdate(routingId, AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(admins).encode())
+ dana.manager.installState(routingId, staged.pendingState)
+ staged.result
+ }
+ val event = commitEvent(commit)
+ erin.inbound.processGroupEvent(event)
+ MarmotStandIn.storeInApp(db, user, event)
+ }
+
+ /** [member] says, in the room, that their device follows signed commits. */
+ private suspend fun says(member: MarmotStandIn) {
+ val payload = MarmotAppEvent.build(
+ pubKey = member.hex, kind = GovernanceSupportEvent.KIND, content = "", createdAt = 1_700_000_002,
+ tags = GovernanceSupportEvent.assembleTags(roomId),
+ ).encodeToPayload()
+ MarmotStandIn.storeInApp(db, user, member.outbound.buildGroupEventFromBytes(routingId, payload).signedEvent)
+ }
+
+ private suspend fun room() = db.chatRoomDao().findChatRoomById(roomId)!!
+
+ /** The relay's OK on the newest commit this device put on the wire. */
+ private suspend fun okTheLatestCommit(): GroupEvent {
+ val event = db.nostrEventDao().getMLSGroupEvents(since = kotlin.time.Instant.fromEpochSeconds(0), limit = 50)
+ .filter { it.kind == GroupEvent.KIND }
+ .filter { db.marmotCommitResultDao().getMarmotCommitRequestById(it.id) != null }
+ .first { db.broadcastNostrEventRequestDao().getFirstBroadcastNostrEventRequestByNostrEventId(it.id)?.status == "pending" }
+ nostrRepository.broadcastProcessed(db.broadcastNostrEventRequestDao().getFirstBroadcastNostrEventRequestByNostrEventId(event.id)!!, "published")
+ return event.toGroupEvent(userHex)!!
+ }
+
+ @Test
+ fun `hearing another member say it, this device says it back`() = runBlocking {
+ governedRoom(governed = false)
+ assertFalse(userHex in GovernanceSupport.supporters(db, roomId))
+
+ says(dana)
+
+ assertTrue(userHex in GovernanceSupport.supporters(db, roomId), "the app did not answer")
+ assertTrue(dana.hex in GovernanceSupport.supporters(db, roomId))
+ }
+
+ @Test
+ fun `the switch waits for every member, then turns the rule on for everyone`() = runBlocking {
+ governedRoom(governed = false)
+ erinJoins()
+ danaSetsAdminsBare(listOf(dana.hex, userHex, erin.hex))
+ says(dana)
+
+ val waiting = assertIs(chatRepository.governanceStatus(roomId))
+ assertEquals(setOf(erin.hex), waiting.missing)
+ val refusal = assertFailsWith { chatRepository.requireSignatures(room()) }
+ assertTrue("Erin" in refusal.message.orEmpty(), refusal.message)
+
+ says(erin)
+ assertEquals(GovernanceStatus.Ready(minimumAdmins = 3), chatRepository.governanceStatus(roomId))
+
+ chatRepository.requireSignatures(room())
+ val switch = okTheLatestCommit()
+
+ assertEquals(3, GovernanceGate.minimumAdmins(appGroup()), "the rule is not on here")
+ dana.inbound.processGroupEvent(switch)
+ assertEquals(3, GovernanceMarker.minimumAdmins(dana.manager.getGroup(routingId)!!.roomDescription()), "the rule did not reach Dana")
+ assertEquals(GovernanceStatus.Governed(3), chatRepository.governanceStatus(roomId))
+
+ // And from here, Dana's bare commit is refused.
+ val epoch = appGroup().epoch
+ val bare = dana.commitLocally(routingId) {
+ val staged = dana.manager.stageAppDataUpdate(routingId, AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(listOf(dana.hex, userHex)).encode())
+ dana.manager.installState(routingId, staged.pendingState)
+ staged.result
+ }
+ MarmotStandIn.storeInApp(db, user, commitEvent(bare))
+ assertEquals(epoch, appGroup().epoch, "a bare commit landed after the switch")
+ }
+
+ // --- Phase 5: this device proposes, the group signs, this device publishes ------
+
+ /** The app made an admin beside Dana, inside the group's signature. */
+ private suspend fun appIsAdmin() {
+ val epoch = appGroup().epoch
+ val staged = stagedPromotion()
+ danaCarries(statement(commitEvent(staged.result), GovernanceChange(admins = setOf(dana.hex, userHex)), epoch))
+ dana.manager.installState(routingId, staged.pendingState)
+ assertTrue(appGroup().isLocalAdmin())
+ }
+
+ /** The app's change, built and kept as `propose` keeps it, and the group's signature on it. */
+ private suspend fun appProposes(propose: (com.vitorpamplona.mls.group.MlsGroup) -> Unit): Pair {
+ val prepared = GovernanceManager.prepare(appGroup(), routingId, propose)
+ val signed = statement(prepared.commitEvent, prepared.change, prepared.epoch)
+ val proposal = GovernanceManager.record(db, room(), userHex, prepared, statementId = signed.id, sessionId = "session-" + signed.id.take(8))
+ return proposal to signed
+ }
+
+ private fun demoteDana(group: com.vitorpamplona.mls.group.MlsGroup) {
+ group.proposeAppDataUpdate(AdminPolicyV1.COMPONENT_ID, AdminPolicyV1.ofHex(listOf(userHex)).encode())
+ }
+
+ /** The carrier this device put on the wire last, as the room's other members receive it. */
+ private suspend fun lastCarrier(): GroupEvent = okTheLatestCommit()
+
+ @Test
+ fun `this device proposes, the group signs, and the change lands here and at Dana's alike`() = runBlocking {
+ governedRoom()
+ appIsAdmin()
+ val epoch = appGroup().epoch
+
+ val (proposal, signed) = appProposes(::demoteDana)
+ assertEquals(epoch, appGroup().epoch, "the commit was applied before it was signed")
+
+ GovernanceManager.publish(db, proposal, signed)
+ assertEquals(epoch, appGroup().epoch, "the commit was applied before a relay accepted it")
+ val carrier = lastCarrier()
+
+ assertEquals(epoch + 1, appGroup().epoch)
+ assertEquals(setOf(userHex), appGroup().currentAdminIdentities())
+ assertTrue(lines(ChatMessage.TYPE_ADMIN_REMOVED).any { it.content == "Dana is no longer an admin" })
+
+ // Dana reads the carrier and applies the commit inside it, as the gate would.
+ val carried = assertIs(dana.inbound.processGroupEvent(carrier))
+ val statement = assertNotNull(GovernanceCarrierEvent.statementOf(Event.fromJson(carried.innerEventJson)))
+ assertEquals(signed.id, statement.id)
+ dana.inbound.processGroupEvent(assertNotNull(mobi.giza.compose.nostr.frost.GovernanceEvents.innerCommitOf(statement)))
+ assertEquals(setOf(userHex), dana.manager.getGroup(routingId)!!.currentAdminIdentities(), "Dana is in another group")
+
+ // The carrier coming back to this device is not news.
+ MarmotStandIn.storeInApp(db, user, carrier)
+ assertEquals(epoch + 1, appGroup().epoch)
+ assertTrue(lines(ChatMessage.TYPE_CHANGE_NOT_APPLIED).isEmpty())
+ }
+
+ @Test
+ fun `a signed change the group moved past is marked stale, and says so`() = runBlocking {
+ governedRoom()
+ appIsAdmin()
+ val (proposal, signed) = appProposes(::demoteDana)
+
+ // Dana's own key update lands first.
+ val update = dana.manager.stageCommit(routingId)
+ danaSays(OwnCommitEvent.KIND, commitEvent(update.result).toJson(), OwnCommitEvent.assembleTags(roomId, appGroup().epoch))
+ dana.manager.installState(routingId, update.pendingState)
+
+ GovernanceManager.publish(db, proposal, signed)
+
+ assertEquals(
+ mobi.giza.compose.database.model.GovernanceProposalStage.STALE,
+ db.governanceProposalDao().getById(proposal.id)!!.stage,
+ )
+ assertEquals(1, lines(ChatMessage.TYPE_CHANGE_NOT_APPLIED).size)
+ assertEquals(setOf(dana.hex, userHex), appGroup().currentAdminIdentities())
+ }
+
+ @Test
+ fun `a member's device declines to sign a statement that does not say what its commit does`() = runBlocking {
+ governedRoom()
+ val epoch = appGroup().epoch
+ val commit = commitEvent(stagedPromotion().result)
+ val unsigned = { change: GovernanceChange ->
+ Event(
+ id = "0".repeat(64), pubKey = roomId, createdAt = 1_700_000_000, kind = GovernanceStatementEvent.KIND,
+ tags = GovernanceStatementEvent.assembleTags(roomId, epoch, change, proposer = dana.hex), content = commit.toJson(), sig = "",
+ )
+ }
+
+ assertEquals(null, GovernanceManager.refusalOf(db, room(), unsigned(GovernanceChange(admins = setOf(dana.hex, userHex)))))
+ assertNotNull(GovernanceManager.refusalOf(db, room(), unsigned(GovernanceChange(admins = setOf(dana.hex)))))
+ }
+
+ // --- Phase 5b: the room's ordinary changes, governed --------------------------
+
+ /** Erin added by Dana inside the group's signature, joined from the Welcome. */
+ private suspend fun erinAddedSigned() {
+ MarmotStandIn.seedProfile(db, erin.hex, "Erin")
+ erin.makeBundle()
+ val epoch = appGroup().epoch
+ val staged = dana.manager.stageAddMember(routingId, erin.bundle.keyPackage.toTlsBytes())
+ val added = mobi.giza.compose.nostr.frost.AddedMember(erin.hex, erin.bundle.keyPackage.reference().toHex())
+ danaCarries(statement(commitEvent(staged.result), GovernanceChange(adds = setOf(added)), epoch))
+ dana.manager.installState(routingId, staged.pendingState)
+ erin.manager.processWelcome(assertNotNull(staged.result.welcomeBytes), erin.bundle)
+ erin.inbound.trackGroup(routingId)
+ assertTrue(erin.hex in appGroup().currentMemberIdentities(), "Erin's signed add did not land")
+ }
+
+ /** Dana applies the commit inside the carrier this device sent. */
+ private suspend fun danaFollows(carrier: GroupEvent) {
+ val carried = assertIs(dana.inbound.processGroupEvent(carrier))
+ val envelope = Event.fromJson(carried.innerEventJson)
+ val statement = GovernanceCarrierEvent.statementOf(envelope) ?: envelope
+ dana.inbound.processGroupEvent(assertNotNull(mobi.giza.compose.nostr.frost.GovernanceEvents.innerCommitOf(statement)))
+ }
+
+ @Test
+ fun `a member's leave is committed by an admin's device inside its own envelope`() = runBlocking {
+ governedRoom()
+ appIsAdmin()
+ erinAddedSigned()
+ val epoch = appGroup().epoch
+
+ val (framed, exporter) = erin.manager.leaveGroup(routingId)
+ val leave = com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal(KeyPair()).sign(
+ GroupEvent.build(encryptedContentBase64 = com.vitorpamplona.marmot.mip03GroupMessages.GroupEventEncryption.encrypt(framed, exporter), nostrGroupId = routingId)
+ )
+ // Every member pools the proposal; the commit only refers to it.
+ dana.inbound.processGroupEvent(leave)
+ MarmotStandIn.storeInApp(db, user, leave)
+ val carrier = okTheLatestCommit()
+
+ assertEquals(epoch + 1, appGroup().epoch)
+ assertFalse(erin.hex in appGroup().currentMemberIdentities(), "Erin is still in the tree")
+ danaFollows(carrier)
+ assertFalse(erin.hex in dana.manager.getGroup(routingId)!!.currentMemberIdentities(), "Dana is in another group")
+ }
+
+ @Test
+ fun `removing an admin is one signed commit that takes their admin entry with them`() = runBlocking {
+ governedRoom()
+ appIsAdmin()
+ val epoch = appGroup().epoch
+ val danaLeaf = appGroup().members().first { (_, leaf) ->
+ (leaf.credential as com.vitorpamplona.mls.tree.Credential.Basic).identity.toHexKey() == dana.hex
+ }.first
+
+ val prepared = GovernanceManager.prepare(appGroup(), routingId, GovernanceManager.removal(danaLeaf, dana.hex, appGroup().currentAdminIdentities()))
+ val signed = statement(prepared.commitEvent, prepared.change, prepared.epoch)
+ assertEquals(GovernanceChange(removes = setOf(dana.hex), admins = setOf(userHex)), prepared.change)
+ GovernanceManager.publish(db, GovernanceManager.record(db, room(), userHex, prepared, signed.id, "s"), signed)
+ okTheLatestCommit()
+
+ assertEquals(epoch + 1, appGroup().epoch, "the removal took more than one commit")
+ assertEquals(setOf(userHex), appGroup().currentAdminIdentities())
+ assertFalse(dana.hex in appGroup().currentMemberIdentities())
+ assertTrue(lines(ChatMessage.TYPE_ADMIN_REMOVED).isEmpty(), "a departure was captioned twice")
+ }
+
+ @Test
+ fun `an invite signed by the group sends its Welcome once the carrier is accepted`() = runBlocking {
+ governedRoom()
+ appIsAdmin()
+ MarmotStandIn.seedProfile(db, erin.hex, "Erin")
+ erin.makeBundle()
+ val welcomesBefore = db.giftWrapPayloadDao().getAllGiftWrapUnsigned().count { it.kind == com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent.KIND }
+ val packageRow = mobi.giza.compose.database.model.MarmotKeyPackage(
+ id = erin.hex, publicKey = erin.hex,
+ tlsEncodedMarmotKeyPackage = erin.bundle.keyPackage.toTlsBytes(), profile = mobi.giza.compose.nostr.MarmotProfile.CURRENT.wireName,
+ )
+ db.participantDao().upsert(listOf(mobi.giza.compose.database.model.Participant(participantPublicKey = erin.hex, chatRoomId = roomId, relayHint = null)))
+
+ val prepared = GovernanceManager.prepare(appGroup(), routingId, GovernanceManager.addition(packageRow.tlsEncodedMarmotKeyPackage))
+ val signed = statement(prepared.commitEvent, prepared.change, prepared.epoch)
+ GovernanceManager.publish(db, GovernanceManager.record(db, room(), userHex, prepared, signed.id, "s", peerKeyPackageEventId = packageRow.id), signed)
+ assertEquals(welcomesBefore, db.giftWrapPayloadDao().getAllGiftWrapUnsigned().count { it.kind == com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent.KIND }, "the Welcome went before the commit was accepted")
+
+ okTheLatestCommit()
+
+ assertTrue(erin.hex in appGroup().currentMemberIdentities())
+ assertEquals(welcomesBefore + 1, db.giftWrapPayloadDao().getAllGiftWrapUnsigned().count { it.kind == com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent.KIND }, "no Welcome for Erin")
+ }
+
+ @Test
+ fun `a removal signed by the group, from another member, lands here`() = runBlocking {
+ governedRoom()
+ erinAddedSigned()
+ val epoch = appGroup().epoch
+ val erinLeaf = dana.manager.getGroup(routingId)!!.members().first { (_, leaf) ->
+ (leaf.credential as com.vitorpamplona.mls.tree.Credential.Basic).identity.toHexKey() == erin.hex
+ }.first
+
+ val staged = dana.manager.stageRemoveMember(routingId, erinLeaf)
+ danaCarries(statement(commitEvent(staged.result), GovernanceChange(removes = setOf(erin.hex)), epoch))
+
+ assertEquals(epoch + 1, appGroup().epoch, "a signed removal was refused at the door")
+ assertFalse(erin.hex in appGroup().currentMemberIdentities())
+ assertTrue(lines(ChatMessage.TYPE_CHANGE_NOT_APPLIED).isEmpty())
+ }
+
+ // --- Phase 9: demotion and removal in a keyed room, then a rotation ------------
+
+ @Test
+ fun `in a governed keyed room an admin is offered demoting another, never stepping down`() = runBlocking {
+ governedRoom()
+ appIsAdmin()
+ mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = true
+ try {
+ val actions = AdminGovernance.memberActions(appGroup(), userHex, floor = 1)
+ assertTrue(mobi.giza.compose.ui.view.state.MemberAction.REMOVE_AS_ADMIN in actions[dana.hex].orEmpty())
+ assertFalse(mobi.giza.compose.ui.view.state.MemberAction.STEP_DOWN in actions[userHex].orEmpty(), "an admin was offered stepping down from a keyed room")
+ assertFalse(mobi.giza.compose.ui.view.state.MemberAction.REMOVE_AS_ADMIN in AdminGovernance.memberActions(appGroup(), userHex, floor = 2)[dana.hex].orEmpty(), "the floor was ignored")
+ } finally {
+ mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = null
+ }
+ }
+
+ @Test
+ fun `a signed demotion that lands owes a rotation without the member, and asks for one`() = runBlocking {
+ governedRoom()
+ appIsAdmin()
+ val prepared = GovernanceManager.prepare(appGroup(), routingId, ::demoteDana)
+ val signed = statement(prepared.commitEvent, prepared.change, prepared.epoch)
+ val proposal = GovernanceManager.record(db, room(), userHex, prepared, signed.id, "s", thenRotateWithout = dana.hex)
+
+ GovernanceManager.publish(db, proposal, signed)
+ assertTrue(GovernanceFollowThrough.rotationsOwed(db).isEmpty(), "a rotation was owed before the change landed")
+ okTheLatestCommit()
+
+ assertEquals(mobi.giza.compose.database.model.GovernanceProposalStage.APPLIED, db.governanceProposalDao().getById(proposal.id)!!.stage)
+ assertEquals(listOf(proposal.id), GovernanceFollowThrough.rotationsOwed(db).map { it.id })
+
+ // This room has no ceremony behind it, so the rotation cannot start: the
+ // room says so, and the change is not asked about again.
+ GovernanceFollowThrough.pass(db, user)
+ assertEquals(mobi.giza.compose.database.model.GovernanceProposalStage.DONE, db.governanceProposalDao().getById(proposal.id)!!.stage)
+ assertTrue(lines(ChatMessage.TYPE_CHANGE_NOT_APPLIED).any { "Shares section" in it.content })
+ assertTrue(GovernanceFollowThrough.rotationsOwed(db).isEmpty())
+ }
+
+ @Test
+ fun `a demotion that landed while nobody watched still owes its rotation`() = runBlocking {
+ governedRoom()
+ appIsAdmin()
+ val prepared = GovernanceManager.prepare(appGroup(), routingId, ::demoteDana)
+ val signed = statement(prepared.commitEvent, prepared.change, prepared.epoch)
+ val proposal = GovernanceManager.record(db, room(), userHex, prepared, signed.id, "s", thenRotateWithout = dana.hex)
+ GovernanceManager.publish(db, proposal, signed)
+ okTheLatestCommit()
+ // A restart between the OK and the row being marked.
+ db.governanceProposalDao().upsert(db.governanceProposalDao().getById(proposal.id)!!.copy(stage = mobi.giza.compose.database.model.GovernanceProposalStage.PUBLISHED))
+
+ assertEquals(listOf(proposal.id), GovernanceFollowThrough.rotationsOwed(db).map { it.id })
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotStandIn.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotStandIn.kt
index 276f9d79..aca1287d 100644
--- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotStandIn.kt
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotStandIn.kt
@@ -85,13 +85,13 @@ internal class MarmotStandIn(val keyPair: KeyPair = KeyPair()) {
CurrentProfileGroupFactory.createKeyPackage(signer).also { bundle = it }
/** A current-profile group of this client's own, tracked. Returns its routing id. */
- suspend fun createGroup(name: String): String {
+ suspend fun createGroup(name: String, description: String = ""): String {
val routingId = RandomInstance.bytes(32)
val group = CurrentProfileGroupFactory.createGroup(
signer = signer,
nostrGroupId = routingId,
relays = Relays.DefaultDMRelayList.map { it.url },
- profile = GroupProfileV1(name = name, description = ""),
+ profile = GroupProfileV1(name = name, description = description),
)
val hex = routingId.toHexKey()
manager.adoptGroup(hex, group)
@@ -105,7 +105,7 @@ internal class MarmotStandIn(val keyPair: KeyPair = KeyPair()) {
* throwaway key and p-tagged to the app, through the sync funnel. The app's
* current-profile package is published first. Returns the app's room id.
*/
- suspend fun inviteApp(db: GizaDatabase, marmotRepository: DatabaseMarmotRepository, user: KeyPair, routingId: String): String {
+ suspend fun inviteApp(db: GizaDatabase, marmotRepository: DatabaseMarmotRepository, user: KeyPair, routingId: String, roomId: String = routingId): String {
val userHex = user.pubKey.toHexKey()
marmotRepository.publishMarmotKeyPackageBundle(user, setOf(MarmotProfile.CURRENT))
val unsigned = db.unsignedNostrEventDao().getAllUnprocessedUnsignedNostrEvents()
@@ -130,8 +130,8 @@ internal class MarmotStandIn(val keyPair: KeyPair = KeyPair()) {
)
val wrap = GiftWrapEvent.create(event = seal, recipientPubKey = userHex, createdAt = rumor.createdAt)
storeInApp(db, user, wrap)
- assertNotNull(db.chatRoomDao().findChatRoomById(routingId), "the app did not join")
- return routingId
+ assertNotNull(db.chatRoomDao().findChatRoomById(roomId), "the app did not join")
+ return roomId
}
companion object {
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/PromotionOffersJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/PromotionOffersJvmTest.kt
new file mode 100644
index 00000000..39ddb87e
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/PromotionOffersJvmTest.kt
@@ -0,0 +1,87 @@
+package mobi.giza.compose.managers
+
+import androidx.room3.Room
+import com.vitorpamplona.quartz.nip01Core.core.toHexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import kotlin.test.AfterTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+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.GovernanceProposal
+import mobi.giza.compose.database.model.GovernanceProposalStage
+import mobi.giza.compose.database.model.MarmotInnerEvent
+import mobi.giza.compose.nostr.frost.PromotionEvents
+
+/**
+ * Which promotion offers are waiting on whom. docs/member-admin-promotion.md,
+ * Phase 8: an offer waits on the member until they accept it, and an accepted
+ * offer waits on the device that made it until it is proposed -- once.
+ */
+class PromotionOffersJvmTest {
+
+ private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder())
+
+ @AfterTest
+ fun closeDb() = db.close()
+
+ private val roomId = "1".repeat(64)
+ private val alice = KeyPair().pubKey.toHexKey()
+ private val erin = KeyPair().pubKey.toHexKey()
+
+ private suspend fun room() {
+ MarmotStandIn.seedProfile(db, alice, "Alice")
+ MarmotStandIn.seedProfile(db, erin, "Erin")
+ db.chatRoomDao().upsert(ChatRoom(id = roomId, userPublicKey = erin, subject = "#keyed", description = null, mlsGroupState = null))
+ }
+
+ private suspend fun said(id: Char, by: String, kind: Int, tags: Array>, at: Long) =
+ db.marmotInnerEventDao().upsert(
+ MarmotInnerEvent(id = id.toString().repeat(64), publicKey = by, kind = kind, tags = tags, content = "", chatRoomId = roomId, createdAt = Instant.fromEpochSeconds(at))
+ )
+
+ @Test
+ fun `an offer waits on the member until they accept it`() = runBlocking {
+ room()
+ said('a', alice, PromotionEvents.OFFER, PromotionEvents.offerTags(roomId, erin), 1)
+
+ assertEquals(PromotionManager.Offer("a".repeat(64), alice), PromotionManager.pendingOffer(db, roomId, erin))
+ assertNull(PromotionManager.pendingOffer(db, roomId, alice), "an offer to Erin was shown to Alice")
+
+ said('b', erin, PromotionEvents.ACCEPT, PromotionEvents.acceptTags(roomId, "a".repeat(64), "02" + "c".repeat(64)), 2)
+ assertNull(PromotionManager.pendingOffer(db, roomId, erin), "an accepted offer still asked")
+ }
+
+ @Test
+ fun `an accepted offer is the offerer's to propose, once`() = runBlocking {
+ room()
+ said('a', alice, PromotionEvents.OFFER, PromotionEvents.offerTags(roomId, erin), 1)
+ assertTrue(PromotionManager.acceptedOffers(db, alice).isEmpty(), "proposed before it was accepted")
+
+ // Accepted by somebody else first: not an acceptance.
+ said('c', alice, PromotionEvents.ACCEPT, PromotionEvents.acceptTags(roomId, "a".repeat(64), "02" + "c".repeat(64)), 2)
+ assertTrue(PromotionManager.acceptedOffers(db, alice).isEmpty(), "the offerer accepted on the member's behalf")
+
+ said('b', erin, PromotionEvents.ACCEPT, PromotionEvents.acceptTags(roomId, "a".repeat(64), "02" + "c".repeat(64)), 3)
+ assertEquals(listOf("a".repeat(64)), PromotionManager.acceptedOffers(db, alice).map { it.first.id })
+ assertTrue(PromotionManager.acceptedOffers(db, erin).isEmpty(), "the member was asked to propose their own promotion")
+
+ db.governanceProposalDao().upsert(
+ GovernanceProposal(
+ id = "d".repeat(64), chatRoomId = roomId, routingId = roomId, epoch = 1, frostSigningSessionId = "s",
+ commitEventId = "e".repeat(64), commitEventJson = "{}", priorStateHex = "", pendingStateHex = "",
+ promotionOfferId = "a".repeat(64),
+ )
+ )
+ assertTrue(PromotionManager.acceptedOffers(db, alice).isEmpty(), "proposed twice")
+
+ // A proposal the group moved past frees the offer to be proposed again.
+ db.governanceProposalDao().upsert(db.governanceProposalDao().getById("d".repeat(64))!!.copy(stage = GovernanceProposalStage.STALE))
+ assertEquals(1, PromotionManager.acceptedOffers(db, alice).size)
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt
index 6ae97ea3..6b415c79 100644
--- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt
@@ -13,6 +13,8 @@ import fr.acinq.bitcoin.crypto.frost.Frost
import fr.acinq.bitcoin.crypto.frost.KeyMaterial
import kotlin.test.AfterTest
import kotlin.test.Test
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonArray
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotEquals
@@ -1358,6 +1360,138 @@ class ShareRefreshRitualJvmTest {
return Device(group, -1, db, LocalChatRoom(chatRoom = chatRoom), keyPair).also { devices += it }
}
+ // ---- member-admin-promotion, Phase 8: enrollment at a new id -----------------------------------------------
+
+ /** A 3-member 2-of-3 group that has rotated once, everyone included, with its key state signed. */
+ private suspend fun rotatedOnce(): Pair> {
+ val group = Group(3, 2)
+ val all = devicesFor(group)
+ val refresh = propose(all[0])
+ pump(all)
+ approveAll(all, refresh.id)
+ approveSigning(all)
+ return group to all
+ }
+
+ /** A device for [keyPair] holding nothing of the key at all: the room, the members' profiles, no ceremony. */
+ private suspend fun stranger(group: Group, keyPair: KeyPair): Device {
+ val db = getRoomDatabase(Room.inMemoryDatabaseBuilder())
+ val publicKey = keyPair.pubKey.toHexKey()
+ (group.members + publicKey).forEach { member ->
+ val nostrEventId = "e$member".take(64)
+ db.nostrEventDao().upsert(NostrEvent(id = nostrEventId, pubKey = member, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)))
+ db.profileDao().upsert(Profile(publicKey = member, nostrEventId = nostrEventId))
+ }
+ val chatRoom = ChatRoom(id = group.roomId, userPublicKey = publicKey, subject = "#Ekklesia", description = SharedKeyDerivation.describe("Admins."), mlsGroupState = "00")
+ db.chatRoomDao().upsert(chatRoom)
+ return Device(group, -1, db, LocalChatRoom(chatRoom = chatRoom), keyPair).also { devices += it }
+ }
+
+ /** The group signs the key state binding the next id to [member] under [host], with that id's public share added. */
+ private suspend fun bindNextId(all: List, member: HexKey, host: HexKey) {
+ val alice = all[0]
+ val table = alice.active().publicShares!!
+ val binding = mobi.giza.compose.nostr.frost.GroupKeyStateEvent.MemberBinding(table.size, member, host)
+ val template = GroupKeyStateManager.generationTemplate(
+ alice.db, alice.room, alice.key(), refreshId = null, newBinding = binding,
+ publicShares = PromotionManager.extended(table, alice.key().threshold),
+ )
+ FrostSigningManager.proposeSigning(alice.db, alice.room, alice.publicKey, template.kind, template.tags, template.content, alice.key(), template.createdAt)
+ pump(all)
+ approveSigning(all)
+ pump(all)
+ }
+
+ /** The handover the proposer's device would send, as Erin's device receives it. */
+ private suspend fun handoverFrom(from: Device, to: HexKey): MarmotInnerEvent =
+ MarmotInnerEvent(
+ id = "f".repeat(64), publicKey = from.publicKey, kind = mobi.giza.compose.nostr.frost.PromotionEvents.HANDOVER,
+ tags = mobi.giza.compose.nostr.frost.PromotionEvents.handoverTags(from.group.roomId, to),
+ content = assertNotNull(PromotionManager.handoverContent(from.db, from.group.roomId)),
+ chatRoomId = from.group.roomId,
+ )
+
+ /**
+ * A member who never took part in the ceremony is enrolled at id 3 of a 2-of-3
+ * key: every device adds the id from the key state the group signed, the new
+ * member checks what they are handed against it, two holders run reduced
+ * enrollment with nobody asked, and the new share signs.
+ */
+ @Test
+ fun `a new member is enrolled at the next id, and signs with the group`() = runBlocking {
+ mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = true
+ val (_, all) = rotatedOnce()
+ val (alice, bob, carol) = all
+ val erinKeys = KeyPair()
+ val erinHost = ChillDkgRitualManager.deriveHostPublicKey(erinKeys.privKey!!).value.toHex()
+ val erin = stranger(all[0].group, erinKeys)
+
+ bindNextId(all, erin.publicKey, erinHost)
+ all.forEach { device ->
+ assertEquals(4, device.active().publicShares!!.size, "the table on device ${device.index}")
+ val entry = device.active().roster.single { it.participantId == 3 }
+ assertEquals(erin.publicKey, entry.memberPublicKey)
+ assertEquals(ShareStanding.STALE, entry.standing, "id 3 waits for its share")
+ }
+
+ PromotionManager.takeHandover(erin.db, erin.room, erin.publicKey, erin.privateKey, handoverFrom(alice, erin.publicKey))
+ val everyone = all + erin
+ pump(everyone)
+
+ val share = assertNotNull(erin.active().secretShare, "Erin must hold a share of id 3")
+ assertEquals(alice.active().publicShares!![3], share.publicKey(), "a share on the group's polynomial")
+ everyone.forEach { device ->
+ assertEquals(ShareStanding.LIVE, device.active().roster.single { it.participantId == 3 }.standing, "id 3 on device ${device.index}")
+ }
+
+ // Erin signs, with Alice; Bob and Carol stay out.
+ val session = FrostSigningManager.proposeSigning(alice.db, alice.room, alice.publicKey, kind = 1, tags = arrayOf(), content = "Erin signs")
+ assertEquals(4, session.participantCount, "n is the table's, which grew")
+ pump(everyone)
+ FrostSigningManager.approve(erin.db, erin.room, session.id)
+ pump(everyone)
+ assertEquals(FrostSigningStage.COMPLETE, alice.db.frostSigningSessionDao().getSessionById(session.id)?.stage)
+ assertTrue(alice.db.frostSigningSessionDao().getSessionById(session.id)!!.signerIdList()!!.contains(3))
+ listOf(bob, carol).forEach { assertNull(it.db.frostSigningSessionDao().getSessionById(session.id)?.signApprovedAt) }
+ }
+
+ /** A handover that does not match what the group signed is refused, and nothing is asked for. */
+ @Test
+ fun `a handover whose table the group did not sign is refused`() = runBlocking {
+ mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = true
+ val (_, all) = rotatedOnce()
+ val erinKeys = KeyPair()
+ val erin = stranger(all[0].group, erinKeys)
+ bindNextId(all, erin.publicKey, ChillDkgRitualManager.deriveHostPublicKey(erinKeys.privKey!!).value.toHex())
+
+ val honest = handoverFrom(all[0], erin.publicKey)
+ val json = kotlinx.serialization.json.Json.parseToJsonElement(honest.content).jsonObject
+ val shares = json["publicShares"]!!.jsonArray
+ val swapped = kotlinx.serialization.json.JsonArray(listOf(shares[1], shares[0]) + shares.drop(2))
+ val forged = honest.copy(content = kotlinx.serialization.json.JsonObject(json + ("publicShares" to swapped)).toString())
+
+ PromotionManager.takeHandover(erin.db, erin.room, erin.publicKey, erin.privateKey, forged)
+
+ assertNull(erin.db.dkgSessionDao().getSessionById(ceremonyId), "a key was filed from a forged handover")
+ assertTrue(erin.db.shareRepairDao().getSessionsForKey(ceremonyId).isEmpty())
+ }
+
+ /** A binding of the next id whose table this device cannot extend to is not applied. */
+ @Test
+ fun `an id enrolled with a table that does not extend this one is not added`() = runBlocking {
+ mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = true
+ val (_, all) = rotatedOnce()
+ val alice = all[0]
+ val table = alice.active().publicShares!!
+ val state = assertNotNull(GroupKeyStateManager.keyStateFor(alice.db, alice.group.roomId))
+ // The next id, but a hash over some other fourth share.
+ val wrong = state.copy(publicSharesHash = ShareGenerations.publicSharesHash(table + table[0]))
+ PromotionManager.enrollNewId(alice.db, wrong, mobi.giza.compose.nostr.frost.GroupKeyStateEvent.MemberBinding(3, "a".repeat(64), "02" + "b".repeat(64)))
+
+ assertEquals(3, alice.active().publicShares!!.size)
+ assertTrue(alice.active().roster.none { it.participantId == 3 })
+ }
+
// ---- Phase 12: restore ---------------------------------------------------------------------------------------
/**
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomMemberRowJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomMemberRowJvmTest.kt
index b14af204..cc1c4eae 100644
--- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomMemberRowJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomMemberRowJvmTest.kt
@@ -5,6 +5,9 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.ui.Modifier
import androidx.compose.ui.test.ComposeUiTest
import androidx.compose.ui.test.ExperimentalTestApi
+import androidx.compose.ui.test.assertCountEquals
+import androidx.compose.ui.test.onAllNodesWithContentDescription
+import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.runDesktopComposeUiTest
@@ -20,6 +23,7 @@ import mobi.giza.compose.ui.composable.navigation.routes.Route
import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost
import mobi.giza.compose.ui.theme.GizaTheme
import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState
+import mobi.giza.compose.ui.view.state.MemberAction
import kotlin.test.Test
import kotlin.test.assertEquals
@@ -66,6 +70,49 @@ class ChatRoomMemberRowJvmTest {
assertEquals(ProfilePreviewRoute(activeUserPublicKey, stillLoading), opened)
}
+ /**
+ * An admin's row menu offers what the view model decided, and promotion asks
+ * first, saying what it gives away. docs/member-admin-promotion.md, Phase 11.
+ */
+ @Test
+ fun `an admin makes a member an admin from the row's menu, after being told what it gives`() {
+ render(
+ onNavigateToRoute = {},
+ state = state().copy(
+ adminPublicKeys = setOf(activeUserPublicKey),
+ memberActions = mapOf(named to setOf(MemberAction.MAKE_ADMIN, MemberAction.REMOVE_FROM_GROUP)),
+ ),
+ ) {
+ onAllNodesWithContentDescription("Member actions").assertCountEquals(1)
+ onNodeWithContentDescription("Member actions").performClick()
+ onNodeWithText("Remove from group").assertExists()
+ onNodeWithText("Make admin").performClick()
+
+ onNodeWithText("Make Nomvula an admin?").assertExists()
+ onNodeWithText("including you", substring = true).assertExists()
+ }
+ }
+
+ @Test
+ fun `an admin's row says so, and a share holder's says that apart`() {
+ render(
+ onNavigateToRoute = {},
+ state = state().let { loaded ->
+ loaded.copy(
+ localChatRoom = loaded.localChatRoom.copy(
+ localParticipants = loaded.localChatRoom.localParticipants.map {
+ if (it.participant.participantPublicKey == named) it.copy(participant = it.participant.copy(adminAt = kotlin.time.Instant.fromEpochSeconds(1_700_000_000))) else it
+ },
+ ),
+ shareHolders = setOf(stillLoading),
+ )
+ },
+ ) {
+ onNodeWithText("Admin").assertExists()
+ onNodeWithText("Holds a share").assertExists()
+ }
+ }
+
private fun member(publicKey: String, profile: Profile?) = LocalParticipant(
participant = Participant(
participantPublicKey = publicKey,
@@ -98,6 +145,7 @@ class ChatRoomMemberRowJvmTest {
*/
private fun render(
onNavigateToRoute: (Route) -> Unit,
+ state: ChatRoomDetailUIState.Loaded = state(),
assertions: ComposeUiTest.() -> Unit,
) = runDesktopComposeUiTest(width = 400, height = 4000) {
setContent {
@@ -108,7 +156,7 @@ class ChatRoomMemberRowJvmTest {
activeUserPublicKey = activeUserPublicKey,
chatRoomId = chatRoomId,
relayHint = null,
- initialChatRoomDetailUIState = state(),
+ initialChatRoomDetailUIState = state,
nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY,
chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY,
onNavigateToRoute = onNavigateToRoute,
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModelJvmTest.kt
new file mode 100644
index 00000000..cdc80b66
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModelJvmTest.kt
@@ -0,0 +1,76 @@
+package mobi.giza.compose.ui.view.model
+
+import kotlin.test.AfterTest
+import kotlin.test.BeforeTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.test.UnconfinedTestDispatcher
+import kotlinx.coroutines.test.resetMain
+import kotlinx.coroutines.test.setMain
+import kotlinx.coroutines.withTimeout
+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.NostrRepository
+import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState
+
+/**
+ * The room detail screen's view model, where the repository's refusals have to
+ * become something the screen can say. See docs/member-admin-promotion.md.
+ */
+@OptIn(ExperimentalCoroutinesApi::class)
+class ChatRoomDetailViewModelJvmTest {
+
+ @BeforeTest
+ fun setUp() {
+ Dispatchers.setMain(UnconfinedTestDispatcher())
+ }
+
+ @AfterTest
+ fun tearDown() {
+ Dispatchers.resetMain()
+ }
+
+ private val room = LocalChatRoom(
+ chatRoom = ChatRoom(id = "room", userPublicKey = "me", subject = "A room", description = null, mlsGroupState = null),
+ localParticipants = emptyList(),
+ )
+
+ private fun viewModel(chatRepository: ChatRepository) = ChatRoomDetailViewModel(
+ chatRoomId = "room",
+ activeUserPublicKey = "me",
+ relayHint = null,
+ initialChatRoomDetailUIState = ChatRoomDetailUIState.Loading,
+ nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY,
+ chatRepository = chatRepository,
+ )
+
+ /**
+ * Phase 10's first step. The refusal used to be thrown inside the view model's
+ * coroutine and caught by nothing: never shown, and on Android a crash.
+ */
+ @Test
+ fun `an admin's refused leave reaches the screen in the refusal's own words`() = runBlocking {
+ val refusal = "An admin cannot leave; hand over admin first"
+ val repository = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY {
+ override suspend fun leaveChatRoom(localChatRoom: LocalChatRoom, onCompletion: () -> Unit) {
+ throw IllegalStateException(refusal)
+ }
+ }
+ val reported = CompletableDeferred()
+ var poppedBack = false
+
+ viewModel(repository).leaveGroup(
+ localChatRoom = room,
+ onPopBackToRoute = { poppedBack = true },
+ onFailed = { reported.complete(it) },
+ )
+
+ assertEquals(refusal, withTimeout(5_000) { reported.await() })
+ assertEquals(false, poppedBack, "the screen was left although nothing left the group")
+ }
+}
diff --git a/docs/README.md b/docs/README.md
index 098c1853..5e2d90d4 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -36,6 +36,7 @@ the [retired](./retired/) notes now.
| [marmot-v2.md](./marmot-v2.md) | bringing the group layer onto the Marmot current profile after the quartz 1.15.2 bump — the nine rules that reach this app, why the room's id and the routing id have to become two values, nine phases from reading both profiles to publishing before applying, and the one fork the library cannot yet settle |
| [marmot-kmp.md](./marmot-kmp.md) | moving the group layer off quartz's engine and onto marmot-kmp, mls-kmp and crypto-kmp — why staying on quartz 1.15.2 is staying on an engine that left, the 228 import lines and the one rule that places all but two of them, the group state on a device that must still open afterwards, nine phases that put the swap in one commit and the evidence around it, how often this app persists a group once a sent message no longer rewrites it, and the schema change that followed, opened from the version the app ships |
| [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 |
+| [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 |
| [giza-rebrand.md](./giza-rebrand.md) | forking Bennu as Giza under `mobi.giza` — what carries the name, what must not be renamed and why, why the desktop data directory changes first, and how the fork keeps merging from Bennu |
| [robust-group-admins.md](./robust-group-admins.md) | making every founding member of a robust group an admin of its room, on every device -- phased and built. Covers why the ceremony's participants are the founding set, the Welcome that flags no admins, the joiner's check against the ceremony it took part in, and finishing an invite that partly failed |
| [remove-convenient-groups.md](./remove-convenient-groups.md) | every group a member makes is robust -- phased and built. Covers why a one-to-one chat is not a group yet takes no new members, why the three-member floor moves to the member picker rather than down to 2-of-2, the quorum rules that outlive `ChatRoomType`, and why a Bennu peer's convenient group is still joined |
@@ -106,6 +107,14 @@ that phase, and its table of findings before any phase. Its second half
removes the nip30303 documents and leaves the member chronicle built but
carrying no kinds, so read it before building on the chronicle note.
+The member-admin-promotion note is a phased plan built but for a keyed room's admin
+leaving; its share work (Phases 8 and 9) is behind the experimental enrollment. It reads as
+the Marmot v2 note's Phase 7 finished, and as the share-refresh note put to work: a
+promotion is an enrollment and a demotion is a refresh. Read its three rules and its
+headline before any phase. Its headline is the one idea the keyed-room half stands
+on -- the commit travels inside the group's signature -- and its ship order says which
+half can go out before enrollment leaves experimental.
+
The wallet-removal note is a phased plan that has been built but for its Phase 7b.
It is how Giza came to keep no wallet: read its constraints and its decisions
before any phase, and its table of where the build chose differently before the
diff --git a/docs/member-admin-promotion.md b/docs/member-admin-promotion.md
new file mode 100644
index 00000000..9926cad8
--- /dev/null
+++ b/docs/member-admin-promotion.md
@@ -0,0 +1,795 @@
+# Making a member an admin, and back
+
+A plan for promoting a member of a group to admin and demoting an admin back to
+member. It also covers the jobs that need the same machinery: removing an admin, an
+admin stepping down, and an admin leaving.
+
+**A phased plan, built but for its keyed-room leave.** Written against the code as it stood at `fc437d05`, with
+marmot-kmp 2.2.1 and mls-kmp 1.3.0 as the catalogue pins them. The second draft adds
+three rules the first draft lacked; they are stated in the next section, and most of
+the plan follows from them.
+
+**Built**, one commit per phase on `claude/member-admin-promotion-plan-d9d716`: the
+first release's phases (10a, 1, 2, 6, and 10 and 11 for convenient rooms), Phases 3, 4a,
+4b, 5 and 5b, Phase 7 on both sides, and Phases 8 and 9 under the experimental FROST
+enrollment (`ExperimentalFeatures.shareRefresh`, off in release). The first draft's
+Phase 0 -- upstream work in mls-kmp and marmot-kmp -- was dropped when the commit moved
+inside the signature (the headline). **Not built:** Phase 10's keyed-room rows (an admin
+of a keyed room still cannot step down or leave) and Phase 12. **Not run:** nothing here
+has been on a device. The enrollment itself is tested end to end with real reduced FROST
+across in-memory devices (`ShareRefreshRitualJvmTest`): a member who never took part in
+the ceremony is enrolled at the next id and signs. What no test runs is the whole
+promotion in one go -- offer, acceptance, the signed batch through
+`GovernanceManager.propose`, the commit, then the enrollment -- since the governed-room
+tests stand a key pair in for the room's key and the enrollment tests run in a room
+that is not governed; each half is tested on its own.
+
+Where the build chose differently:
+
+| what the plan said | what it turned out to be |
+|---|---|
+| Phase 1's `reconcileAdmins` as the single writer of `adminAt` | `AdminFlags.reconcile`, from [robust-group-admins.md](./robust-group-admins.md), which was built at the same time for the same reason and also runs on the Welcome and once at start. Phase 1's own function was dropped when the two met; its creation-site calls now go through `AdminFlags` |
+| Phase 2's lines in the library's order: departures, arrivals, demotions, promotions | after the membership lines, which keep the order they had (arrivals, then departures); then demotions, then promotions |
+| Phase 3's statement has a `disband` line | a `component` line per GroupContext component the commit changes, by id and the hash of its new value. Disband, enabling disband and a rename are all that one rule, and a statement cannot sign off one component while the commit changes another |
+| Phase 3's kind "in the 303xx range" | 30370, past the last retired wallet kind. 30371 is the own-commit envelope, 30372 the support announcement, 30373 the carrier |
+| Phase 4a: the signed statement is published as an application message | inside a **carrier** (30373) sent by a member. The inbound path holds every application message to its sender's own key (MIP-03), and a statement is the room's, so it cannot travel as one -- which is also why `FrostSigningManager.complete` never publishes a group-signed event. The carrier vouches for nothing; the statement inside is checked on its own signature |
+| Phase 4a: an own commit (30371) is "signed by the committer's account key" | sent by it: the inner event is an unsigned rumor whose author MLS has already authenticated as its sender, so the check is that the sender is the committer |
+| D4: the marker is `giza-governance: threshold/v1` | `Changes need the group's signature; at least N admins.` -- it carries the **floor** too. A floor each device worked out from the ceremony it holds would differ between a founder and a member welcomed later, and the two would disagree about a commit |
+| Phase 4a's copy-check reads a commit's proposals off the copy | the proposals off the copy, and who a Remove names off the live group as it stood before the commit: the copy's view can already have the removed leaf blank. Found by the inbound removal test; without it every signed removal was refused at the door |
+| Phase 4b: an invite into a governed room is refused for an account that has not announced | not built. A joiner announces as soon as it hears another member say it, which every device does once per room; a joiner on a build that cannot follow is the open problem D4 names |
+| Phase 5: any other admin publishes a signed change after a short wait | only the proposer publishes. A proposer who goes quiet after the signature leaves the change waiting until it comes back |
+| Phase 5: a stale statement is proposed again automatically | it is marked stale and the room says so; proposing again is the person's |
+| Phase 5b: a removal of an admin is two signed commits | one: the proposer builds it on its own copy of the group, which can stage a Remove and the admin-list update together where the library's manager cannot |
+| Phase 5b: disband proposes each of its commits | in a room that has not agreed it can be disbanded, the first press proposes that agreement and says to disband again once it is signed |
+| D7: founding commits authorised by the key state | dropped: the rule is switched on after founding (Phase 4b), so founding needs nothing |
+| Phase 6's removal of an admin is "chained in memory" | through `MarmotEngine.afterConfirmed`, registered *before* the commit it waits on so a relay's OK cannot overtake it, and taken back if publishing throws. Leaving as an admin uses the same hook. In a governed room a removal is one signed commit instead |
+| Phase 7's floor is checked on demotion, removal and leaving | on removal and on every governed commit at the door; a keyed room offers no demotion and no leave for an admin until Phases 8 to 10 |
+| Phase 10's keyed-room rows: "above the floor" and "at the floor" | one row for now. A keyed room's admin who presses **Leave group** is told, as before, that an admin cannot leave; `AdminLeave.CANNOT` |
+| Phase 8: promotion from any keyed room | only from a key past its ceremony's generation. Generation 0 lives in the ceremony's own record, which has no room for an id the ceremony did not make; the first rotation makes the generation rows an enrollment extends. **Make admin** says so when it is refused |
+| Phase 8: offer and acceptance as "a new 303xx kind" | 30374 and 30375, and a third, 30376, for the **handover**: once the change lands, the offering device sends the new admin the table, roster and signed key state. The new member's device holds nothing of the key before that, and checks all of it against the room's own signature -- the state has to be one the room signed, the table has to hash to what it names, and it has to bind the new id to this account under this device's host key |
+| Phase 8: `P_n` "interpolated in the exponent from the existing table" | from the table's first `t` entries, with `FrostEnrollment.derivePublicShare`. Every device does it, and adds the id only when the extended table hashes to what the group signed |
+| Phase 8: enrollment as `ShareRepairManager` generalised | the repair protocol unchanged but for its `n`: a request names the `n` it runs with (the new id, the table's size before it), helpers check that against their own table, and an enrollment asks no helper for approval -- the signed binding was everyone's chance to say no |
+| Phase 8: `n` grows in "the stored key" | a signing session's and a repair's `n` is the generation's table size, which the enrollment grew; the ceremony's `participantCount` is left as the ceremony made it |
+| Phase 9: every remaining holder's deal and confirm made automatic | the rotation is started by the proposer's device once the change lands (`GovernanceFollowThrough`), and each holder is asked once to take part, as every rotation now asks (rotate-shares-single-approval). A rotation that cannot start is said in the room and offered from the Shares section |
+| Phase 9: an admin can step down in a keyed room | not offered. The rotation that has to follow is the remaining holders', so another admin proposes the demotion |
+| Phase 11's dialogs for every action | removal keeps the immediate action it had; promotion, demotion and stepping down ask first |
+
+Read [marmot-v2.md](./marmot-v2.md) Phase 7 first. Removing a member, disbanding and
+the derived membership captions all come from there. Read
+[frost-share-refresh.md](./frost-share-refresh.md) before Phases 8 and 9: a promotion
+is an enrollment and a demotion is a refresh. Read
+[frost-batch-signing.md](./frost-batch-signing.md) before Phase 5, because a
+governance change is signed as a batch.
+
+---
+
+## The three rules
+
+| | rule | what it means here |
+|---|---|---|
+| **R1** | **Every admin holds a share of the group's key** | Promotion includes enrolling the new admin into the key. Demotion includes rotating the shares without them. A member row still shows **Admin** and **Holds a share** as two separate labels, because between the commit and the share work they disagree, and that disagreement is how a person sees that an enrollment or a rotation is still owed. |
+| **R2** | **Every commit is first a proposal, and becomes a commit only once the group's threshold signature is on it**, except a member's own leave and a member's own key update (D6) | No single admin can change a keyed room. An admin builds the commit and proposes it, `t` share holders sign an event that carries it, and only that signed event is published. Every device refuses a bare commit. |
+| **R3** | **A robust group always has at least three admins** | The floor `ChatRoomType.MINIMUM_ROBUST_GROUP_SIZE` (now `Quorum.MINIMUM_GROUP_SIZE`) already sets at creation becomes an invariant. Demotion, removal and leaving are refused when they would break it, and so is anything that would leave fewer admins than the quorum `t`. |
+
+### Which rooms they apply to
+
+All three rules are about a group's **threshold key**, so they apply to *keyed
+rooms*. That means the Marmot room `MarmotGroupCreation` opens around a robust
+group's key, and every subgroup's room. In those rooms every member is an admin today
+(`ChatRoomType.ROBUST`: "Every member administers the room"). Promotion and demotion
+add a second kind of member: someone who is in the room but does not govern it.
+
+A **convenient room** has no key. Nothing can produce a threshold signature for it,
+so R2 cannot apply there. R1 has no share to give and R3 is a robust-group rule. A
+convenient room keeps the single-admin commit it has today, and this plan gives it
+promotion and demotion on those terms (Phase 6). **Direct messages** are unaffected.
+
+---
+
+## The headline: the signature carries the commit
+
+Changing who is an admin needs nothing new. In a current-profile group it is an
+`AppDataUpdate` on component `0x8003` (`marmot.group.admin-policy.v1`), and
+marmot-kmp 2.2.1 stages it (`MlsGroupManager.stageAppDataUpdate`), checks it
+(`MarmotGroupPermissions.canPromote` / `canDemote`), and refuses one that leaves no
+admin (`MarmotGroupPolicy.enforceNoAdminDepletion`). The app even receives one today:
+[ConvergenceForkJvmTest.kt:186](../composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConvergenceForkJvmTest.kt:186)
+has a stand-in member promote the app over the wire.
+
+R2 is the hard part: every device has to refuse a commit the group did not sign. The
+library cannot be told to -- its commit hook sees neither the commit's
+`authenticated_data` nor its epoch, and `MlsGroupManager` hard-codes Marmot's policy --
+so the first draft made that upstream work. It does not have to be. **The commit
+travels inside the group's signature instead of the signature inside the commit**:
+
+1. The proposer's device stages the commit on a copy and builds the kind:445 event that
+ carries it, exactly as it would publish it -- and does not publish it.
+2. The group signs one event whose content *is* that kind:445 event, with Phase 3's
+ statement as its tags. Each signer's device runs the commit on a throwaway copy of the
+ group and checks it does what the tags say before approving.
+3. The signed event goes out as an ordinary application message at the commit's epoch.
+4. Every device verifies it and hands the inner kind:445 to the engine as if it had
+ arrived from a relay. In a room where the rule is on, a kind:445 that is a bare
+ commit is dropped before the engine sees it.
+
+Everything that needs is public and already in the app's hands:
+
+| what the envelope needs | where it is |
+|---|---|
+| one place every inbound group event passes through, before the engine applies it | `NostrDao.indexCurrentProfileGroupEvent` calls `engine.processGroupEvent` and nothing else does ([NostrDao.kt:1419](../composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt:1419)) |
+| telling a commit from a message without processing it | after the Marmot outer layer, an MLS `PrivateMessage` or `PublicMessage` carries its `contentType` in the clear; `MarmotInboundManager.tryDecryptOuterLayer` already does the outer half |
+| running a commit without applying it | `MlsGroup.restore(state, policy)` and `processFramedCommit` are public, and a policy passed to the copy is handed the commit's real proposals |
+| applying a commit the app was handed rather than received | the inner kind:445 is a complete signed event; `engine.processGroupEvent` takes it like any other, and convergence sees it as it would any commit |
+| the proposer's own commit, which it cannot process | the staged state and the publish gate: `gate.prepare` with the state staged at proposal time, confirmed when a relay accepts the envelope |
+
+Because the inner kind:445 is the proposer's own event, byte for byte, every device
+hands the engine the same event with the same id -- which is what convergence needs to
+pick the same branch everywhere when two signed commits race.
+
+---
+
+## What the code does today
+
+| fact | where | why it matters here |
+|---|---|---|
+| The app has no control for promoting or demoting, but [MarmotOutboundDao.leave](../composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt:950) tells an admin who presses **Leave group** to "hand over admin first" or "make another member an admin, or disband the group" | — | an admin today can disband a group but cannot leave it |
+| That message is thrown inside `viewModelScope.launch` in [ChatRoomDetailViewModel.leaveGroup](../composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt:197), and nothing catches it | — | the person is never shown it, and on Android an uncaught coroutine exception is a crash. Fixed at the top of Phase 10 |
+| `Participant.adminAt` is a cache of the group's admin set, written on each applied commit and, for keyed rooms only, at creation | [MarmotInboundManager.kt:132](../composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt:132), [MarmotGroupCreation.kt:227](../composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt:227) | it is wrong on the creating device of every convenient room and DM until the first commit. Phase 1 |
+| Removing a member stages a bare `Remove`, so a removed admin's key stays in `0x8003` | [MarmotOutboundDao.kt:853](../composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt:853) | **a removed admin who is invited back is an admin again**, with no caption. `AdminPolicyV1` says the key must go in the same commit. Phases 6 and 9 |
+| Removal and disband are one admin's commit through the publish gate | `MarmotOutboundDao.removeMember`, `disband` | under R2 that changes in keyed rooms. Phase 5 |
+| Repair already runs `FrostReducedEnrollment` for an existing id (`newId < n`) | [ShareRepairManager.kt:268](../composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRepairManager.kt:268) | promotion is the same primitive at `newId = n`, which nothing builds yet ([frost-share-refresh.md](./frost-share-refresh.md) 10c; [submodule-refresh.md](./submodule-refresh.md) Phase 6). Phase 8 |
+| A refresh that withholds a removed member is built | `ChatRepository.rotateSharesWithout`, frost-share-refresh Phase 9 | demotion's share half. Phase 9 |
+| The group's key state carries the id-to-member table, `MemberBinding(participantId, memberPublicKey, hostPublicKey)`, signed by the group | [GroupKeyStateEvent.kt:163](../composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GroupKeyStateEvent.kt:163) | the authenticated table an enrollment reads its expected public share from |
+| Enrollment, refresh and repair sit behind `ExperimentalFeatures.shareRefresh`, off in release, until upstream drops "experimental" | frost-share-refresh D4 | **R1 cannot ship to release users before that.** R2 and R3 can. See *Ship order* |
+| `CommitProcessed` names the epoch and not the committer | marmot-kmp `MarmotInboundProcessor.kt:75` | captions are unattributed, as the membership lines are. A keyed room's lines can name the proposer instead, from the signed statement (Phase 2) |
+
+---
+
+## The decisions
+
+### D1. The admin set comes from the group's state, never from `adminAt`
+
+Every check that decides an action reads `currentAdminIdentities()` and the tree off
+the live group, as `SubgroupManager` already does
+([SubgroupManager.kt:107](../composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/SubgroupManager.kt:107)).
+`adminAt` is for display and caption diffs only. Phase 1 makes it accurate enough for
+those.
+
+### D2. Admin and share are kept in step, and shown apart (R1)
+
+In a keyed room, a member's two facts move together but cannot change in the same
+instant. The MLS commit is atomic, while an enrollment or a refresh is a multi-round
+protocol between devices. So the plan keeps them in step by sequence, and the member
+row shows each one on its own:
+
+| row shows | meaning | what the room offers |
+|---|---|---|
+| **Admin · Holds a share** | settled | — |
+| **Admin** only | promoted, enrollment still running or failed | **Retry enrollment** |
+| **Holds a share** only | demoted or removed, rotation not finished | **Rotate shares** (the existing offer) |
+| neither | a member who does not govern | — |
+
+The commit always goes **first**, for both directions:
+
+- **Promotion: commit, then enrollment.** An admin without a share can publish a
+ commit only once the group has signed it (R2), so they can do nothing alone. A
+ share without the admin role would be signing power with nobody having agreed to
+ give it. That is the worse half-state, so the order avoids it.
+- **Demotion: commit, then refresh.** The demoted member is out of governance at
+ once. Their share still counts towards `t` until the refresh finishes, so the
+ refresh starts automatically, not as an offer (Phase 9). D10 names the risk that
+ remains in the meantime.
+
+### D3. Admin rights are an offer the new admin accepts
+
+Holding a share "puts the member in a group's signing quorum for good, and nothing on
+the device can decide that for them"
+([automatic-key-ceremony.md](./automatic-key-ceremony.md)). A promotion in a keyed
+room is therefore an offer: the target accepts by publishing an enrollment host key,
+and only then does the quorum sign. That order is not a choice, because the key
+state that binds the new id to them needs their host key (`MemberBinding`). After
+that one acceptance, everything runs by itself, which is that note's rule: the
+device asks only for what it cannot decide.
+
+A convenient room has no share, so its promotion needs no acceptance, the same as
+being invited.
+
+### D4. The commit rides inside the signature, and the rule lives in the group's state (R2)
+
+Two choices here decide whether R2 holds at all.
+
+**The commit inside the signature, not beside it.** The group signs an event whose
+content is the complete kind:445 commit event. A signature published as a separate
+message would race the commit on relays that impose no order: a device that saw the
+commit first would refuse it, a device that saw the signature first would apply it, and
+the group would split into two epochs. With the commit inside the signed event, every
+device reaches the same verdict from the same bytes at the same moment.
+
+**The rule in the group's state, not in the app's settings.** Whether a room needs
+signed commits is a marker line in its profile description, read the way
+`MarmotRoomIdentity` reads the room id from the same place:
+`giza-governance: threshold/v1`. It is switched on by an ordinary commit -- the room's
+last bare one -- and from the next epoch every device that applies that commit enforces
+the rule, from the state it just applied. Taking the line out again is itself a change
+the group has to sign. A rule read from the state cannot be on for some members and off
+for others.
+
+What the marker cannot do is keep out a client that does not know it: Bennu, or an
+older Giza build, applies the bare commits Giza drops and reads none of the envelopes.
+So the switch is refused until every member's account has said, in the room, that it
+applies signed commits (Phase 4b). A member who joins later on such a client cannot
+follow the room, and the invite says so.
+
+*Rejected:* MLS proposals by reference. MIP-03 lets a member send only `SelfRemove` on
+its own (`MarmotGroupPolicy.authorizeProposal`). "Proposal" in R2 is a Giza signing
+proposal, the kind the room already uses for key states and subgroup certificates.
+*Rejected, from the first draft:* the signature in the commit's `authenticated_data`,
+which every device's library would have had to be changed to read.
+
+### D5. A statement is bound to one epoch, and names exactly what the commit does
+
+The quorum signs a statement that is readable on its face, as with
+[subgroups.md](./subgroups.md)'s informed consent:
+
+```
+room
+epoch -- the epoch the commit is built at
+add …
+remove …
+admins
+disband
+```
+
+On receipt, the policy checks the commit's non-exempt proposals realise *exactly*
+those lines at epoch `E`: every Add's KeyPackage matches a named event, every Remove's
+leaf belongs to a named account, and the `0x8003` update equals `admins`. Nothing
+more and nothing less.
+
+**Why one epoch:** a statement valid at any epoch could be replayed. "Demote B",
+signed once and applied, could be applied again after B has been promoted back. The
+exact epoch makes each statement single-use.
+
+**What it costs:** a statement whose epoch has passed is dead. Signing takes as long
+as the slowest of `t` members. Meanwhile an exempt commit (D6) or a rival statement
+can advance the epoch, and the proposer's device then re-proposes at the new epoch by
+itself (Phase 5). To keep exempt commits from killing statements needlessly, a
+pending member `SelfRemove` is folded *into* the governance commit when one is due,
+because exempt proposals may ride along with a signed commit.
+
+### D6. Two exemptions: a member's own leave, and a member's own key update
+
+**Decided, and the one place this plan narrows R2 as first stated.** MIP-03 lets any
+member make exactly two kinds of commit without being an admin:
+
+- a commit made only of `SelfRemove`s, which is someone leaving;
+- a single self-Update, which is a member refreshing their own leaf key.
+
+Neither changes who governs the room or who is in it, beyond the leaver themselves.
+Requiring the quorum's signature for them would mean:
+
+- **a member cannot leave without the group's permission.** Their leaf stays in the
+ tree and keeps decrypting everything until `t` others agree to let them out. That
+ is the opposite of what leaving is for, and it gives a quorum a way to hold someone
+ in a conversation;
+- **post-compromise recovery waits on a vote.** A member who suspects their device
+ was compromised cannot rotate their own leaf key until the quorum signs.
+
+So the policy exempts these two, and only these two. R2 with no exceptions was
+considered and turned down for the two reasons above. Taking the exemption out later
+would be one `if` in the policy, plus a signing step in Phase 10's leave flow for a
+member who is not an admin.
+
+### D7. A room's founding commits come before the rule
+
+A keyed room is founded by its coordinator's bare commits, which every member who joins
+from the Welcome never processes. The rule is switched on afterwards (D4), once every
+member has said it can follow it, so nothing at founding needs a signature. The first
+draft authorised founding commits by the key state; with the switch, that is not needed.
+
+### D8. Admins at least `max(3, t)` in a robust group (R3)
+
+Three is the floor `MINIMUM_ROBUST_GROUP_SIZE` already uses: below it, a majority is
+not a check. The second term matters as much. In a keyed room the admins *are* the
+share holders (R1), so a demotion that leaves fewer admins than `t` leaves a key that
+can never sign again, and nothing could ever change the room after that. The floor is
+checked in three places:
+
+- the view model, which hides an action that would break it and says why;
+- the outbound DAO, which refuses before a proposal is opened, because a statement
+ nobody can lawfully sign wastes everyone's approval;
+- the policy, which reads the floor from the component, so a commit that breaks it is
+ refused by every device even if the quorum signed it.
+
+`t` itself does not change here. A refresh keeps the polynomial's degree, so lowering
+the threshold is a different protocol and is out of scope.
+
+### D9. Current-profile rooms only
+
+The same rule removal and disband follow. A legacy room rewrites its whole `0xF2EE`
+blob on every admin change, and the app governs no legacy room today.
+
+### D10. What the room is exposed to between a demotion and its refresh
+
+Until the refresh completes, the demoted member's share still counts. They plus `t-1`
+others can still sign anything, including a statement that promotes them back. That
+is the window frost-share-refresh's headline describes, and this plan narrows it
+rather than closing it:
+
+- the refresh starts automatically, with the signed demotion as every holder's
+ approval (Phase 9);
+- the row reads **Holds a share** without **Admin** until it finishes, so the room
+ can see the window is open;
+- while it is open, the room shows a banner with the Shares section's **Rotate
+ shares**, for the case where the automatic refresh stalled on an offline holder.
+
+---
+
+## Phase 0 — none: the commit travels inside the signature
+
+The first draft's Phase 0 changed mls-kmp and marmot-kmp so that a device could refuse an
+unsigned commit. The headline shows the app can do it with the libraries as they are, so
+there is no upstream work. Two library changes would still be welcome and are not needed:
+`stageRemoveMember` dropping a removed account's admin entry in the same commit (the app
+does it in two, Phase 6), and a public way to stage several proposals in one commit (a
+promotion is one proposal; a removal of an admin is two commits until then).
+
+## Phase 1 — `adminAt` is true from the first moment
+
+**Half a day.** Unchanged from the first draft. Nothing a user sees, and every caption
+stands on it.
+
+1. One function, `MarmotInboundManager.reconcileAdmins(database, localChatRoom,
+ mlsGroup)`, writes `adminAt` from `currentAdminIdentities()` and captions nothing.
+2. Call it wherever a room is made: `SelectChatRoomTypeViewModel.createMarmotChatRoom`
+ (since removed with the convenient group, [remove-convenient-groups.md](./remove-convenient-groups.md)),
+ `MarmotOutboundDao.createMlsDirectMessageChatRoom`, and `MarmotGroupCreation`, in
+ place of `stampAdmins`.
+3. Call it once, silently, for rooms already on devices, from
+ `initiateChatRoomDetail`.
+4. Captions get their own prior admin set, never the cache. On a confirmed own commit
+ that is `obligation.priorState` in
+ [MarmotEngine.confirmPublished](../composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotEngine.kt:209).
+ On an inbound commit it is the live group's `currentAdminIdentities()`, copied
+ before `engine.processGroupEvent` at
+ [NostrDao.kt:1413](../composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt:1413).
+ It is passed in as `priorAdmins`. With no `priorAdmins`, there is no admin
+ caption.
+5. Fix the KDoc on `ChatRoomType.kt:8` (the enum has since gone, [remove-convenient-groups.md](./remove-convenient-groups.md)).
+ It says the admin list is "stamped into epoch 0", and it says a robust room's
+ every member administers it. After this plan neither is true.
+
+**Tests:** a fresh convenient room and a fresh DM flag the creator before any commit.
+An existing room with no flags is reconciled when opened, with no line written. The
+first invite in a convenient room writes "joined" and no admin line.
+
+## Phase 2 — the group says who became an admin
+
+**Half a day.**
+
+Add `TYPE_ADMIN_ADDED` and `TYPE_ADMIN_REMOVED` beside the membership lines in
+[ChatMessage.kt:569](../composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt:569).
+Add both to `MEMBERSHIP_TYPES`, since a type missing from it renders as a chat bubble.
+Give them an icon in `ChatTranscript`'s `when`
+([ChatTranscript.kt:882](../composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt:882)),
+or they fall through to `PanTool`, the icon for a request.
+
+They are written in `processGroupMembershipChanges` from the Phase 1 diff, in the
+library's order (`MarmotSystemRowDiff`): departures, arrivals, demotions, promotions.
+Every device writes them, including the committer. An account that left the tree gets
+"left the group" and no admin line.
+
+| change | line | on the subject's device |
+|---|---|---|
+| promoted | `{name} is now an admin` | `You are now an admin` |
+| demoted | `{name} is no longer an admin` | `You are no longer an admin` |
+| enrolled (Phase 8) | `{name} now holds a share of the group's key` | `You now hold a share of the group's key` |
+
+In a keyed room, the commit's statement names who proposed it. The line can then say
+`{proposer} made {name} an admin, with {k} of {n} signatures`, which is an attribution
+the convenient room cannot give. That is optional, and Phase 5 decides once the
+statement is parsed on the inbound path anyway.
+
+## Phase 3 — the governance statement
+
+**Two days.** Pure, and in `commonTest`.
+
+`GovernanceStatementEvent`, under `nostr/frost/` beside `GroupKeyStateEvent`. It is a
+new parameterised kind in the 303xx range, chosen against `RetiredKinds` so the wallet
+audit stays green. The content is D5's lines as tags (`epoch`, `add`, `remove`,
+`admins`, `disband`, `proposer`), with the room id as its `d` tag, the way the key
+state is self-addressing.
+
+Three pure functions carry the whole rule, so the policy, the signing approval and the
+tests share one definition:
+
+```kotlin
+/** What [proposals] at [epoch] would do to the room, in a statement's terms. */
+fun GovernanceChange.of(group: GroupView, epoch: Long, proposals: List): GovernanceChange
+
+/** The proposals that need no signature (D6): own SelfRemoves, a lone self-Update. */
+fun GovernanceChange.isExempt(group: GroupView, proposals: List, committer: Int): Boolean
+
+/** Whether [statement] authorises exactly [change], signed by [roomKey]. */
+fun GovernanceStatementEvent.authorises(change: GovernanceChange, roomKey: XOnlyKey): Boolean
+```
+
+`ProposedEvent.summaryOf` gets an arm for the new kind, so the signing approval reads
+"Make Bob an admin" and not a hash, as the subgroup notes insisted for certificates.
+
+**Tests:** statement round-trips; one test per refusal (wrong epoch, an extra Add, a
+missing Remove, an admin list off by one, a signature by another key, a statement for
+another room); `isExempt` for each MIP-03 case and for a SelfRemove riding in a signed
+commit.
+
+## Phase 4 — the envelope, the filter, and the switch
+
+**4a. The envelope and the filter. Three days.**
+
+`GovernanceStatementEvent` (Phase 3) gains its content: the complete signed kind:445
+commit event, as JSON. A second kind, `OwnCommitEvent` (30371), carries a commit that
+needs nobody's signature (D6) -- a member's own leave folded in by an admin's device, or a
+member's own key update -- signed by the committer's account key.
+
+`GovernanceGate`, one function the inbound path calls for a current-profile room:
+
+1. If the room's state does not carry the marker, do what is done today.
+2. Peel the outer layer. A bare `COMMIT` is dropped before the engine sees it, with a
+ line in the room saying a change arrived without the group's signature. A proposal or
+ an application message goes on as today.
+3. An application message whose inner event is a 30370 is checked: signed by the room,
+ at the group's current epoch, and its inner commit -- run on a throwaway copy with a
+ policy that captures the proposals -- does exactly what its tags say, and leaves at
+ least the floor of admins (R3). Then the inner kind:445 is handed to the engine.
+4. A 30371 is checked the same way, except that it must be exempt (D6) and signed by the
+ account whose leaf committed it.
+
+The copy is `MlsGroup.restore(liveState, policy)`; the policy delegates to
+`MarmotGroupPolicy` and records what `authorizeCommit` is given. A commit the copy
+refuses is refused.
+
+**Tests**, with the stand-in as the other member: an unsigned commit in a governed room is
+dropped and the room stays at its epoch; a signed one lands, on both sides, with the same
+event id; one signed for another epoch, by a member's own key, or carrying an extra
+proposal is refused; a member's leave in a 30371 lands; a governance change in a 30371
+does not; nothing changes in a room without the marker.
+
+**4b. Support, and the switch. Two days.**
+
+- Each device on this build says once per keyed room, as an application message signed by
+ its account (`GovernanceSupportEvent`, 30372), that it applies signed commits. The room
+ records who has said it.
+- **Require signatures for changes**, on a keyed room's detail screen, for an admin, once
+ every current member has said it. It is one bare commit adding the marker line to the
+ profile description. Until every member has, the screen names who has not.
+- An invite into a governed room is refused for an account that has not said it, with
+ words that say why, once it is in the room (it says so from its own device on joining).
+
+**Tests:** the switch is refused while a member has not said it; after it lands, both
+sides enforce from the next epoch; a member added later announces on joining.
+
+## Phase 5 — propose, sign, publish
+
+**Four days.**
+
+`GovernanceManager` turns a change in a governed room into a commit:
+
+1. **Propose.** The admin's device reads the live group (D1), checks the change against
+ `AdminGovernance` and the floor, stages it on a copy at the current epoch `E`, and builds
+ the kind:445 that carries it -- signed by a throwaway key, outer-encrypted, exactly as
+ `publishCommit` would publish it. Nothing is published. The staged state (prior and
+ pending), the commit event and any Welcome are stored in a `GovernanceProposal` row,
+ because signing outlasts a session. Then it opens a FROST signing session over the
+ unsigned 30370 whose tags are the statement and whose content is that kind:445.
+2. **Sign.** Members approve through the existing signing approval, which reads the
+ statement's summary. Before a device puts its share to it, it runs the inner commit on
+ a copy and checks the tags (as the gate will), so nobody signs a commit that does not
+ say what it does.
+3. **Publish.** When the signature completes, the proposer's device -- if its group is
+ still at `E` -- raises the publish gate with the stored staged state and publishes the
+ signed 30370 as an application message. A relay's OK confirms the obligation, which
+ installs the pending state, captions the change and sends any Welcome. Any other
+ admin's device that holds the signed event and is still at `E` may publish it instead
+ after a short wait, so a proposer who went quiet does not strand the change.
+
+**Stale statements.** If the group moves past `E` first, the proposal is dead: the
+proposer's device marks it and proposes again at the new epoch, which nobody's earlier
+approval covers.
+
+| today, in a keyed room | after the switch |
+|---|---|
+| `inviteMember` | propose an add |
+| `removeMember` | propose a remove (with the admin list, if they were one) |
+| `disband` | propose each of its commits |
+| `commitStagedProposals` (a member's leave) | the same commit, in a 30371 |
+| leaving as an admin | propose your own demotion; leave once it lands |
+
+**Tests** across devices with real FROST (`CeremonyNetwork`): a removal runs propose →
+sign → publish and lands on every device; a statement staled by a member leaving is
+proposed again and lands; a restart between signature and publish still publishes.
+
+## Phase 6 — convenient rooms: one admin's commit
+
+**One day.** No upstream dependency. Can land straight after Phase 2.
+
+This is the first draft's Phase 3, kept for the rooms R2 cannot reach.
+`MarmotOutboundDao.setAdmins(localChatRoom, admins)` stages
+`stageAppDataUpdate(0x8003, AdminPolicyV1.ofHex(admins))` through `publishGatedCommit`.
+`promote` and `demote` build the list from the live group, refusing a target not in the
+tree, a demotion that leaves no admin among the members (`canDemote`), and a commit
+while another is waiting.
+
+Removing an admin here needs the `Remove` and the list update together. Until the
+library can stage both in one commit (Phase 0), that is two commits chained in
+memory: demote, then remove when the
+first is confirmed. A restart in between leaves a demoted member, and **Remove** works
+in one commit after that. Once `stageProposals` exists, it becomes one commit.
+
+**Tests** (`GroupLifecycleJvmTest`): the app promotes the stand-in, which can then
+remove a member; demotion takes that ability away; the only admin cannot demote
+themselves; **a removed admin re-invited is not an admin**. That last test fails on
+today's code.
+
+## Phase 7 — the floor (R3)
+
+**One day.** Needs Phase 4 for the policy half. The UI and DAO halves can land
+earlier.
+
+- `ChatRoomType.minimumAdmins(t) = max(MINIMUM_ROBUST_GROUP_SIZE, t)` (now
+ `Quorum.minimumAdmins`), one function
+ for all three checks (D8).
+- `GovernanceManager` refuses a demotion, an admin's removal or an admin's leave that
+ would cross it, *before* proposing. The words name the fix: "A group needs at least
+ {floor} admins. Make someone else an admin first".
+- The view model hides **Remove as admin** and **Step down** on rows where it would
+ cross it, and says why on the dialog that would have offered it.
+- The policy checks it on receipt (Phase 4).
+
+Rooms made before this plan are at least three already: the robust picker and the
+subgroup picker both refuse fewer.
+
+**Tests:** a three-admin room cannot demote; a four-admin room with `t = 3` can demote
+one, and not a second.
+
+## Phase 8 — promotion in a keyed room: offer, sign, commit, enroll
+
+**Four days.** Needs Phases 0 (step 8), 4 and 5, and the enrollment primitive. Behind
+`ExperimentalFeatures.shareRefresh`.
+
+1. **Offer.** An admin taps **Make admin**. A promotion offer goes to the room, naming
+ the target (a new 303xx kind; it carries no authority, it is a request).
+2. **Accept.** The target's device asks them, once: "{name} wants to make you an admin
+ of {group}. You'll hold a share of the group's key, and you'll be asked to approve
+ its changes". If they accept, the device publishes an enrollment host key, in the
+ ceremony's format. This is D3's one approval.
+3. **Sign.** The proposer's device opens one batch with two events:
+ - the governance statement (`admins` with them added);
+ - the next key state, whose `MemberBinding`s add `n → (target, host key)` and whose
+ public-share table adds `P_n`, interpolated in the exponent from the existing
+ table. That gives the enrollment an expected public share from authenticated
+ state, never from the helpers ([submodule-refresh.md](./submodule-refresh.md)
+ Phase 6).
+4. **Commit**, as in Phase 5. The row now reads **Admin**.
+5. **Enroll.** `t` live holders run `FrostReducedEnrollment` at `targetId = n`, with no
+ further approval: the signed key state naming the target at `n` is the approval,
+ the same rule automatic-key-ceremony Phase 7 uses for a key state. This is
+ `ShareRepairManager` generalised from `targetId < n` to `targetId = n`. Its rounds,
+ pairwise sealing and persistence are already built, and `n` grows by one in the
+ stored key. When the target's share checks against `P_n`, the row reads **Admin ·
+ Holds a share**.
+
+If enrollment fails, the room shows **Retry enrollment** on the row (D2). The retry is
+a new enrollment session under the same signed key state. It needs no new governance
+signature, because nobody's role changes.
+
+**Tests** (beside the repair cases in `ShareRefreshRitualJvmTest`, on its fixtures,
+with real FROST):
+
+- a member accepts, the batch signs, the commit lands, the enrollment completes, and
+ the new admin's partial signature then helps sign an event;
+- a member declines, and nothing is signed;
+- enrollment with a helper who presents a table that disagrees with the signed one
+ fails before the share is stored.
+
+## Phase 9 — demotion and removal in a keyed room: sign, commit, refresh
+
+**Three days.** Needs Phases 4, 5 and 7, and the refresh. Behind the same flag.
+
+1. **Sign** a statement: `admins` without them, plus `remove` for a removal. One
+ statement covers both commits -- the demotion and then the removal -- so a removed admin
+never stays on the list.
+2. **Commit.** The row reads **Holds a share** only.
+3. **Refresh** without them, started automatically by the proposer's device. This is
+ `rotateSharesWithout`, from frost-share-refresh Phase 9, with each remaining
+ holder's deal and confirm made automatic when the refresh names a signed demotion
+ or removal of the member it withholds. The refresh still needs every remaining
+ holder (frost-share-refresh D8), so a stalled refresh is the case D10's banner is
+ for.
+
+The demoted member's own device drops nothing by itself: its share becomes worthless
+when the refresh completes, which is when frost-share-refresh's Phase 8 deletes the
+old generation everywhere.
+
+**Tests:** demote, and the demoted member can no longer help reach `t` after the
+refresh, but could before it; remove an admin, and they are off `0x8003` in the same
+commit; demote below the floor is refused before anything is proposed.
+
+## Phase 10 — leaving as an admin
+
+**Two days.**
+
+**First, the crash.** `leaveGroup` in the view model wraps the call in `runCatching`
+and reports the failure through the notifier, as `disbandGroup` does. Ship this alone
+if everything else slips.
+
+Then **Leave group**, pressed by an admin, opens a dialog in place of firing:
+
+| room | dialog | what happens |
+|---|---|---|
+| convenient, another admin remains | "You'll step down first, then leave" | one-admin step-down commit (Phase 6), then the `SelfRemove` when it is confirmed |
+| convenient, the only admin | pick a member to make admin, or **Disband group instead** | promote the pick, then step down and leave, chained |
+| keyed, above the floor | "You'll step down, the group signs it, then you leave" | Phase 9's demotion of yourself, then the exempt `SelfRemove` once it lands. The refresh without you runs after you are gone, on the others' devices |
+| keyed, at the floor | "A group needs at least {floor} admins. Make someone else an admin before you leave" | nothing until a promotion has landed |
+
+The chain from step-down to `SelfRemove` is held in memory. A restart leaves a
+non-admin member who has not left yet, which is safe, and a plain **Leave group** then
+works.
+
+**Tests:** each row of the table, and the existing `an admin cannot leave, and is told
+why` test changed to check that the message reaches the caller.
+
+## Phase 11 — the member row
+
+**Two days.**
+
+Under each member's name, the labels from D2 (**Admin**, **Holds a share**, joined with
+` · `), read from the group and from `SharesSummary.members` with
+`ShareStanding.LIVE`, and a third line while a change is pending ("Being made an
+admin: 1 of 2 signatures"). **Holds a share** follows the experimental flag, so a
+release build shows **Admin** only until R1 ships.
+
+An admin's trailing control becomes an overflow `IconButton` with a `DropdownMenu`.
+Its items come from a per-member `memberActions` the view model computes from the
+library's permissions, the floor and the room kind. The screen never decides an action
+itself.
+
+| row | items |
+|---|---|
+| a member | **Make admin**, **Remove from group** |
+| another admin | **Remove as admin** (above the floor), **Remove from group** |
+| an admin with no share | **Retry enrollment** |
+| a non-admin with a share | **Rotate shares** |
+| yourself, an admin | **Step down as admin** (above the floor) |
+
+The dialogs say what each act gives or takes:
+
+- **Make {name} an admin?** — in a convenient room: "They'll be able to add and remove
+ members, including you, and disband the group". In a keyed room: "They'll be asked
+ to accept, then hold a share of the group's key. This needs {t} of you to sign".
+- **Remove {name} as admin?** — "They stay in the group as a member". In a keyed room:
+ "Their share is rotated away once the group signs".
+- **Step down as admin?** — "You stay in the group. Only the group can make you an
+ admin again".
+
+All text comes from the catalogue, in sentence case. Outcomes go through
+`rememberNotifier`, read above the handler. The overflow button is a 48dp `IconButton`
+with a decided description. `./gradlew :composeApp:m3Audit` stays at its budgets.
+
+**Tests:** `memberActions` for every row above, in both room kinds, at and above the
+floor.
+
+## Phase 12 — across devices, and the docs
+
+**Two days.**
+
+- **Fork:** two admins' devices commit the same signed statement at once, and both end
+ in one state with one caption (Phase 5).
+- **Split check:** a stand-in using the bare `MarmotGroupPolicy` commits unsigned into
+ an enabled room. Every app device refuses it, and the stand-in is the one that
+ diverges. That is the case D4's required component exists to prevent, and this test
+ shows the component refusing to let such a leaf in at all.
+- **Restart:** with `PublishBeforeApplyJvmTest`'s pattern, through propose, sign and
+ commit.
+- Docs: this note's status line and a table of where the build chose differently, the
+ README entry, a pointer from marmot-v2's Phase 7 row about leaving, and a line in
+ [shared-key-ceremony.md](./shared-key-ceremony.md) noting that the group's key now
+ also governs its room.
+
+---
+
+## Ship order
+
+R2 is a security property for every keyed room and does not need enrollment. R1 does,
+and enrollment cannot reach release users until upstream drops "experimental". So:
+
+| release | phases | users get |
+|---|---|---|
+| first | 10 (the crash fix alone), 1, 2, 6 | convenient rooms: promote, demote, step down, leave as admin; the re-invite hole closed there |
+| second | 3, 4, 5, 7 | keyed rooms: every change is proposed and signed; the floor; no promotion yet, because R1 cannot be met |
+| third, when enrollment leaves experimental | 8, 9, the rest of 10, 11, 12 | keyed rooms: promotion with a share, demotion with a refresh |
+
+In the second release, a keyed room's **Make admin** is hidden, not offered without a
+share. That would break R1, and an admin without a share is exactly the half-state D2
+keeps temporary.
+
+## Checking the work
+
+```bash
+./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest
+```
+
+```bash
+./gradlew check
+```
+
+By hand, with three devices in a robust group and the experimental flag on:
+
+1. A proposes making D (a member) an admin. D accepts. B signs. The commit lands, then
+ D's row goes from **Admin** to **Admin · Holds a share**.
+2. D helps sign a message, and the signature verifies under the group's key.
+3. A tries to demote B in a group of three admins and is told the floor. A promotes
+ someone first, then demotes B. B's row reads **Holds a share** until the refresh
+ ends.
+4. A stand-in sends an unsigned removal. No device applies it.
+
+## Estimate
+
+| phase | size |
+|---|---|
+| 1 — `adminAt` | half a day |
+| 2 — captions | half a day |
+| 3 — the statement | two days |
+| 4 — the envelope, the filter and the switch | five days |
+| 5 — propose, sign, publish | four days |
+| 6 — convenient rooms | one day |
+| 7 — the floor | one day |
+| 8 — promotion with a share | four days |
+| 9 — demotion with a refresh | three days |
+| 10 — leaving as an admin | two days |
+| 11 — the member row | two days |
+| 12 — across devices, docs | two days |
+
+About five weeks of work, and none of it waits on another repository. The first
+release's phases need about three days and wait on nothing.
+
+## Out of scope
+
+- **Changing `t`.** A refresh keeps the polynomial's degree. Raising or lowering the
+ threshold is a resharing protocol of its own.
+- **Legacy-profile rooms** (D9) and **robust NIP-17 rooms**, which have no admins.
+- **R2 in convenient rooms.** There is no key to sign with. A convenient room that
+ wants R2 becomes a robust group by running a ceremony, which is a different act.
+- **Quorum-signed chat.** R2 is about commits. Application messages stay each member's
+ own.
+
+## Appendix — what was considered and rejected
+
+**Holding a commit until its signature arrives.** The verdict would depend on what a
+device has seen and when, which is how D4's split happens. The envelope avoids it by
+putting the commit and its signature in one event: every device decides from the same
+bytes. (The first draft also rejected checking a commit on a copy under the app's own
+policy, for the same reason; with the commit inside the envelope, the copy-check sees the
+same bytes everywhere and the objection falls away.)
+
+**The signature in the commit's `authenticated_data`, enforced by the library.** The
+first draft's Phase 0: a week of changes to two libraries this app does not own, for a
+rule the app can enforce at its one inbound door.
+
+**Signing the commit's bytes alone, without a statement.** It binds just as tightly,
+but signers would approve an opaque hash, which is what the subgroup notes spent a
+section removing. The envelope signs both: the statement as tags a person reads, and the
+commit as content their device checks against them.
+
+**A statement valid at any epoch, with a precondition ("admins are A").** It survives
+staleness, but it can be replayed whenever the room comes back round to `A`. D5.
+
+**Share first, then the admin commit.** It leaves a share holder who governs nothing
+but can sign, which is signing power nobody agreed to give. D2.
+
+**No exemptions.** It was considered and turned down: a member could not leave
+without the group's permission, and could not replace a compromised leaf key without
+a vote. D6.
+
+**The library's `MarmotManager.leave`.** It picks the heir by leaf order and publishes
+outside the gate.
+
+**Reading the admin set from `adminAt`.** It is wrong on the creating device. D1.
diff --git a/docs/remove-convenient-groups.md b/docs/remove-convenient-groups.md
index 72ad2c3f..7384ff09 100644
--- a/docs/remove-convenient-groups.md
+++ b/docs/remove-convenient-groups.md
@@ -118,6 +118,8 @@ so deleting it touches no stored row, no route argument and no event.
new `Quorum` object in `managers/`, next to `ChillDkgRitualManager`, which enforces them.
They move in a phase of their own (Phase 1), so the deletion in Phase 4 changes no
behaviour.
+`ChatRoomType.minimumAdmins`, which member-admin-promotion added while this was being
+built, followed them there as `Quorum.minimumAdmins`.
**D7. Only a room with a key behind it takes members after its founding.** Added
during the build, when D1's second reason turned out to be false. A Marmot room with