diff --git a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/51.json b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/51.json new file mode 100644 index 00000000..e19d1c2e --- /dev/null +++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/51.json @@ -0,0 +1,7501 @@ +{ + "formatVersion": 1, + "database": { + "version": 51, + "identityHash": "da12b7739329a72e6df7180df7bc72cc", + "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, `expiresAt` INTEGER, `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": "expiresAt", + "columnName": "expiresAt", + "affinity": "INTEGER" + }, + { + "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`)" + }, + { + "name": "index_ChatMessage_expiresAt", + "unique": false, + "columnNames": [ + "expiresAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ChatMessage_expiresAt` ON `${TABLE_NAME}` (`expiresAt`)" + } + ], + "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, `lastReadMessageId` INTEGER, `notifications` TEXT NOT NULL DEFAULT 'all', `disappearingMessageSecs` INTEGER, `disappearingNoticeShownAt` INTEGER, `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": "lastReadMessageId", + "columnName": "lastReadMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "notifications", + "columnName": "notifications", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'all'" + }, + { + "fieldPath": "disappearingMessageSecs", + "columnName": "disappearingMessageSecs", + "affinity": "INTEGER" + }, + { + "fieldPath": "disappearingNoticeShownAt", + "columnName": "disappearingNoticeShownAt", + "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": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "userPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "GiftWrapPayload", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "initialGiftWrapPayloadId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Confederation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `ceremonyId` TEXT NOT NULL, `name` TEXT NOT NULL, `roster` TEXT NOT NULL, `keyState` TEXT NOT NULL, `genesis` TEXT NOT NULL, `configSeq` INTEGER NOT NULL, `rosterHash` TEXT NOT NULL, `keyStateHash` TEXT NOT NULL, `recoveryPackages` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `roomCreator` TEXT, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ceremonyId", + "columnName": "ceremonyId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roster", + "columnName": "roster", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyState", + "columnName": "keyState", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "genesis", + "columnName": "genesis", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "configSeq", + "columnName": "configSeq", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rosterHash", + "columnName": "rosterHash", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyStateHash", + "columnName": "keyStateHash", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "recoveryPackages", + "columnName": "recoveryPackages", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "roomCreator", + "columnName": "roomCreator", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Confederation_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Confederation_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + } + ] + }, + { + "tableName": "DisappearingSetting", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`userPublicKey` TEXT NOT NULL, `defaultSeconds` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`userPublicKey`))", + "fields": [ + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "defaultSeconds", + "columnName": "defaultSeconds", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "userPublicKey" + ] + } + }, + { + "tableName": "ExpiredGiftWrap", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `dropAfter` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dropAfter", + "columnName": "dropAfter", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "ConfederationCeremony", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `basisJson` TEXT NOT NULL, `attempt` INTEGER NOT NULL DEFAULT 1, `attestationRef` TEXT, `seedContribution` TEXT, `stage` TEXT NOT NULL, `approvedAt` INTEGER, `dealerSeeds` TEXT, `recoveryNonces` TEXT, `keyState` TEXT, `transitionHash` TEXT, `genesis` TEXT, `recoveryPackages` TEXT, `confederationPublicKey` TEXT, `failureReason` TEXT, `culprit` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "basisJson", + "columnName": "basisJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "attempt", + "columnName": "attempt", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "attestationRef", + "columnName": "attestationRef", + "affinity": "TEXT" + }, + { + "fieldPath": "seedContribution", + "columnName": "seedContribution", + "affinity": "TEXT" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "approvedAt", + "columnName": "approvedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "dealerSeeds", + "columnName": "dealerSeeds", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryNonces", + "columnName": "recoveryNonces", + "affinity": "TEXT" + }, + { + "fieldPath": "keyState", + "columnName": "keyState", + "affinity": "TEXT" + }, + { + "fieldPath": "transitionHash", + "columnName": "transitionHash", + "affinity": "TEXT" + }, + { + "fieldPath": "genesis", + "columnName": "genesis", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryPackages", + "columnName": "recoveryPackages", + "affinity": "TEXT" + }, + { + "fieldPath": "confederationPublicKey", + "columnName": "confederationPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "culprit", + "columnName": "culprit", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ConfederationCeremony_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationCeremony_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_ConfederationCeremony_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationCeremony_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationMember", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`confederationId` TEXT NOT NULL, `groupPublicKey` TEXT NOT NULL, PRIMARY KEY(`confederationId`, `groupPublicKey`))", + "fields": [ + { + "fieldPath": "confederationId", + "columnName": "confederationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "groupPublicKey", + "columnName": "groupPublicKey", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "confederationId", + "groupPublicKey" + ] + }, + "indices": [ + { + "name": "index_ConfederationMember_groupPublicKey", + "unique": false, + "columnNames": [ + "groupPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationMember_groupPublicKey` ON `${TABLE_NAME}` (`groupPublicKey`)" + } + ] + }, + { + "tableName": "ConfederationSigningAttempt", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `confederationId` TEXT NOT NULL, `proposerPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `eventJson` TEXT NOT NULL, `stage` TEXT NOT NULL, `approvedAt` INTEGER, `declinedAt` INTEGER, `signedEventJson` TEXT, `failureReason` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`confederationId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "confederationId", + "columnName": "confederationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposerPublicKey", + "columnName": "proposerPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventJson", + "columnName": "eventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "approvedAt", + "columnName": "approvedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "declinedAt", + "columnName": "declinedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "signedEventJson", + "columnName": "signedEventJson", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ConfederationSigningAttempt_confederationId", + "unique": false, + "columnNames": [ + "confederationId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationSigningAttempt_confederationId` ON `${TABLE_NAME}` (`confederationId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "confederationId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationSigningMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`attemptId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`attemptId`, `senderPublicKey`, `kind`), FOREIGN KEY(`attemptId`) REFERENCES `ConfederationSigningAttempt`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "attemptId", + "columnName": "attemptId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "attemptId", + "senderPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "ConfederationSigningAttempt", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "attemptId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationCeremonyMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `senderPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `ConfederationCeremony`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "senderPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "ConfederationCeremony", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ConfederationEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `kind` INTEGER NOT NULL, `pubKey` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `eventCreatedAt` INTEGER NOT NULL, `eventJson` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, `ownSessionId` TEXT, `publishedAt` INTEGER, `sealJson` TEXT, `inboxRoomId` TEXT, `confederationId` TEXT, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventCreatedAt", + "columnName": "eventCreatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "eventJson", + "columnName": "eventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "ownSessionId", + "columnName": "ownSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "publishedAt", + "columnName": "publishedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "sealJson", + "columnName": "sealJson", + "affinity": "TEXT" + }, + { + "fieldPath": "inboxRoomId", + "columnName": "inboxRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "confederationId", + "columnName": "confederationId", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ConfederationEvent_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + }, + { + "name": "index_ConfederationEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_ConfederationEvent_publishedAt", + "unique": false, + "columnNames": [ + "publishedAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_publishedAt` ON `${TABLE_NAME}` (`publishedAt`)" + }, + { + "name": "index_ConfederationEvent_confederationId", + "unique": false, + "columnNames": [ + "confederationId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_confederationId` ON `${TABLE_NAME}` (`confederationId`)" + } + ] + }, + { + "tableName": "ConfederationInvitee", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`proposalId` TEXT NOT NULL, `groupPublicKey` TEXT NOT NULL, PRIMARY KEY(`proposalId`, `groupPublicKey`))", + "fields": [ + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "groupPublicKey", + "columnName": "groupPublicKey", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "proposalId", + "groupPublicKey" + ] + }, + "indices": [ + { + "name": "index_ConfederationInvitee_groupPublicKey", + "unique": false, + "columnNames": [ + "groupPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationInvitee_groupPublicKey` ON `${TABLE_NAME}` (`groupPublicKey`)" + } + ] + }, + { + "tableName": "ConfederationSigning", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `rumorJson` TEXT, `invitationJson` TEXT, `refusal` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "rumorJson", + "columnName": "rumorJson", + "affinity": "TEXT" + }, + { + "fieldPath": "invitationJson", + "columnName": "invitationJson", + "affinity": "TEXT" + }, + { + "fieldPath": "refusal", + "columnName": "refusal", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId" + ] + }, + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "DkgParticipantMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `participantPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `participantPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "participantPublicKey", + "kind" + ] + }, + "indices": [ + { + "name": "index_DkgParticipantMessage_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_DkgParticipantMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "DkgSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "DkgSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `threshold` INTEGER NOT NULL, `participantCount` INTEGER NOT NULL, `participantPublicKeys` TEXT, `subject` TEXT, `walletPolicy` TEXT, `stage` TEXT NOT NULL, `hostPublicKey` TEXT NOT NULL, `round1Random` TEXT NOT NULL, `round2AuxRandom` TEXT NOT NULL, `coordinatorRound1` TEXT, `certificate` TEXT, `thresholdPublicKey` TEXT, `secretShare` TEXT, `publicShares` TEXT, `recoveryData` TEXT, `failureReason` TEXT, `hostKeyApprovedAt` INTEGER, `round1ApprovedAt` INTEGER, `round2ApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `parentChatRoomId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "threshold", + "columnName": "threshold", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantCount", + "columnName": "participantCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantPublicKeys", + "columnName": "participantPublicKeys", + "affinity": "TEXT" + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT" + }, + { + "fieldPath": "walletPolicy", + "columnName": "walletPolicy", + "affinity": "TEXT" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "hostPublicKey", + "columnName": "hostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round1Random", + "columnName": "round1Random", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round2AuxRandom", + "columnName": "round2AuxRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorRound1", + "columnName": "coordinatorRound1", + "affinity": "TEXT" + }, + { + "fieldPath": "certificate", + "columnName": "certificate", + "affinity": "TEXT" + }, + { + "fieldPath": "thresholdPublicKey", + "columnName": "thresholdPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "secretShare", + "columnName": "secretShare", + "affinity": "TEXT" + }, + { + "fieldPath": "publicShares", + "columnName": "publicShares", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "hostKeyApprovedAt", + "columnName": "hostKeyApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "round1ApprovedAt", + "columnName": "round1ApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "round2ApprovedAt", + "columnName": "round2ApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedThrough", + "columnName": "approvalRequestedThrough", + "affinity": "TEXT" + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_DkgSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_DkgSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSignerMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `signerPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `signerPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signerPublicKey", + "columnName": "signerPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "signerPublicKey", + "kind" + ] + }, + "indices": [ + { + "name": "index_FrostSignerMessage_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSignerMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSigningItem", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `itemIndex` INTEGER NOT NULL, `unsignedEventJson` TEXT NOT NULL, `eventId` TEXT NOT NULL, `nonceRandom` TEXT NOT NULL, `aggregatedNonce` TEXT, `signature` TEXT, PRIMARY KEY(`sessionId`, `itemIndex`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "itemIndex", + "columnName": "itemIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "unsignedEventJson", + "columnName": "unsignedEventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventId", + "columnName": "eventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nonceRandom", + "columnName": "nonceRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "aggregatedNonce", + "columnName": "aggregatedNonce", + "affinity": "TEXT" + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "itemIndex" + ] + }, + "indices": [ + { + "name": "index_FrostSigningItem_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningItem_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSigningSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `threshold` INTEGER NOT NULL, `participantCount` INTEGER NOT NULL, `signerId` INTEGER NOT NULL, `derivationPath` TEXT, `generation` INTEGER, `stage` TEXT NOT NULL, `signerIds` TEXT, `failureReason` TEXT, `signApprovedAt` INTEGER, `signDeclinedAt` INTEGER, `approvalRequestedAt` INTEGER, `resentAt` INTEGER, `subject` TEXT NOT NULL DEFAULT 'EVENTS', `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "threshold", + "columnName": "threshold", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantCount", + "columnName": "participantCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "signerId", + "columnName": "signerId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT" + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signerIds", + "columnName": "signerIds", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "signApprovedAt", + "columnName": "signApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "signDeclinedAt", + "columnName": "signDeclinedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedAt", + "columnName": "approvalRequestedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "resentAt", + "columnName": "resentAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'EVENTS'" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_FrostSigningSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_FrostSigningSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `receiverPublicKey` TEXT NOT NULL, `receiverRelayHit` TEXT, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `giftWrapPayloadId` TEXT, `expiresAt` 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" + }, + { + "fieldPath": "giftWrapPayloadId", + "columnName": "giftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "expiresAt", + "columnName": "expiresAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GiftWrapMessage_giftWrapPayloadId", + "unique": false, + "columnNames": [ + "giftWrapPayloadId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GiftWrapMessage_giftWrapPayloadId` ON `${TABLE_NAME}` (`giftWrapPayloadId`)" + }, + { + "name": "index_GiftWrapMessage_expiresAt", + "unique": false, + "columnNames": [ + "expiresAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GiftWrapMessage_expiresAt` ON `${TABLE_NAME}` (`expiresAt`)" + } + ], + "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, `expiresAt` 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" + }, + { + "fieldPath": "expiresAt", + "columnName": "expiresAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GiftWrapPayload_expiresAt", + "unique": false, + "columnNames": [ + "expiresAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GiftWrapPayload_expiresAt` ON `${TABLE_NAME}` (`expiresAt`)" + } + ], + "foreignKeys": [ + { + "table": "GiftWrapSeal", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapSealId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupConversationKey", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `peer` TEXT NOT NULL, `conversationKey` TEXT NOT NULL, `roundId` TEXT NOT NULL, `computedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`, `peer`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "peer", + "columnName": "peer", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "conversationKey", + "columnName": "conversationKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roundId", + "columnName": "roundId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "computedAt", + "columnName": "computedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "peer" + ] + }, + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupDmMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`rumorId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `conversationId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `rumorJson` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `outgoing` INTEGER NOT NULL, `wrapId` TEXT, `signingSessionId` TEXT, `readAt` INTEGER, `filedAt` INTEGER NOT NULL, `expiresAt` INTEGER, PRIMARY KEY(`rumorId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "rumorId", + "columnName": "rumorId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "conversationId", + "columnName": "conversationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "rumorJson", + "columnName": "rumorJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "outgoing", + "columnName": "outgoing", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "wrapId", + "columnName": "wrapId", + "affinity": "TEXT" + }, + { + "fieldPath": "signingSessionId", + "columnName": "signingSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "readAt", + "columnName": "readAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "filedAt", + "columnName": "filedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "expiresAt", + "columnName": "expiresAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "rumorId" + ] + }, + "indices": [ + { + "name": "index_GroupDmMessage_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupDmMessage_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupDmMessage_conversationId", + "unique": false, + "columnNames": [ + "conversationId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupDmMessage_conversationId` ON `${TABLE_NAME}` (`conversationId`)" + }, + { + "name": "index_GroupDmMessage_expiresAt", + "unique": false, + "columnNames": [ + "expiresAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupDmMessage_expiresAt` ON `${TABLE_NAME}` (`expiresAt`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupDmOutbound", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`signingSessionId` TEXT NOT NULL, `sealId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `recipient` TEXT NOT NULL, `relays` TEXT NOT NULL, `wrapJson` TEXT, `publishedAt` INTEGER, `attempts` INTEGER NOT NULL, `nextAttemptAt` INTEGER, PRIMARY KEY(`signingSessionId`, `sealId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "signingSessionId", + "columnName": "signingSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sealId", + "columnName": "sealId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "recipient", + "columnName": "recipient", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relays", + "columnName": "relays", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapJson", + "columnName": "wrapJson", + "affinity": "TEXT" + }, + { + "fieldPath": "publishedAt", + "columnName": "publishedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "attempts", + "columnName": "attempts", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nextAttemptAt", + "columnName": "nextAttemptAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "signingSessionId", + "sealId" + ] + }, + "indices": [ + { + "name": "index_GroupDmOutbound_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupDmOutbound_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupDmWrap", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `wrapJson` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `state` TEXT NOT NULL, `sealJson` TEXT, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapJson", + "columnName": "wrapJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sealJson", + "columnName": "sealJson", + "affinity": "TEXT" + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GroupDmWrap_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupDmWrap_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupDmWrap_state", + "unique": false, + "columnNames": [ + "state" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupDmWrap_state` ON `${TABLE_NAME}` (`state`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupEcdhPartial", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`roundId` TEXT NOT NULL, `participantId` INTEGER NOT NULL, `senderPublicKey` TEXT NOT NULL, `partial` TEXT NOT NULL, `proof` TEXT NOT NULL, `verified` INTEGER NOT NULL, `blamedAt` INTEGER, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`roundId`, `participantId`), FOREIGN KEY(`roundId`) REFERENCES `GroupEcdhRound`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "roundId", + "columnName": "roundId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantId", + "columnName": "participantId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "partial", + "columnName": "partial", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proof", + "columnName": "proof", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "verified", + "columnName": "verified", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "blamedAt", + "columnName": "blamedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "roundId", + "participantId" + ] + }, + "foreignKeys": [ + { + "table": "GroupEcdhRound", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "roundId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupEcdhRound", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `point` TEXT NOT NULL, `purpose` TEXT NOT NULL, `ref` TEXT, `evidenceJson` TEXT, `state` TEXT NOT NULL, `partialSentAt` INTEGER, `openedAt` INTEGER NOT NULL, `combinedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "point", + "columnName": "point", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ref", + "columnName": "ref", + "affinity": "TEXT" + }, + { + "fieldPath": "evidenceJson", + "columnName": "evidenceJson", + "affinity": "TEXT" + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "partialSentAt", + "columnName": "partialSentAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "openedAt", + "columnName": "openedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "combinedAt", + "columnName": "combinedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GroupEcdhRound_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupEcdhRound_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupEcdhRound_point", + "unique": false, + "columnNames": [ + "point" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupEcdhRound_point` ON `${TABLE_NAME}` (`point`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupInboxMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `rumorId` TEXT NOT NULL, `wrapId` TEXT, `conversationId` TEXT NOT NULL, `participants` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `rumorJson` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `generation` INTEGER NOT NULL, `outgoing` INTEGER NOT NULL, `signingSessionId` TEXT, `readAt` INTEGER, `receivedAt` INTEGER NOT NULL, `expiresAt` INTEGER, PRIMARY KEY(`chatRoomId`, `rumorId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "rumorId", + "columnName": "rumorId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapId", + "columnName": "wrapId", + "affinity": "TEXT" + }, + { + "fieldPath": "conversationId", + "columnName": "conversationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participants", + "columnName": "participants", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rumorJson", + "columnName": "rumorJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "outgoing", + "columnName": "outgoing", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "signingSessionId", + "columnName": "signingSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "readAt", + "columnName": "readAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "expiresAt", + "columnName": "expiresAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "rumorId" + ] + }, + "indices": [ + { + "name": "index_GroupInboxMessage_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxMessage_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupInboxMessage_conversationId", + "unique": false, + "columnNames": [ + "conversationId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxMessage_conversationId` ON `${TABLE_NAME}` (`conversationId`)" + }, + { + "name": "index_GroupInboxMessage_expiresAt", + "unique": false, + "columnNames": [ + "expiresAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxMessage_expiresAt` ON `${TABLE_NAME}` (`expiresAt`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupInboxPublication", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`eventId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `eventJson` TEXT NOT NULL, `relays` TEXT NOT NULL, `signingSessionId` TEXT, `recipientPublicKey` TEXT, `attempts` INTEGER NOT NULL, `nextAttemptAt` INTEGER, `publishedAt` INTEGER, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`eventId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "eventId", + "columnName": "eventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "eventJson", + "columnName": "eventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relays", + "columnName": "relays", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signingSessionId", + "columnName": "signingSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "recipientPublicKey", + "columnName": "recipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "attempts", + "columnName": "attempts", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nextAttemptAt", + "columnName": "nextAttemptAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "publishedAt", + "columnName": "publishedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "eventId" + ] + }, + "indices": [ + { + "name": "index_GroupInboxPublication_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxPublication_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupInboxPublication_signingSessionId", + "unique": false, + "columnNames": [ + "signingSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxPublication_signingSessionId` ON `${TABLE_NAME}` (`signingSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupInboxWrap", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `wrapJson` TEXT NOT NULL, `wrapCreatedAt` INTEGER NOT NULL, `openedGeneration` INTEGER, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapJson", + "columnName": "wrapJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapCreatedAt", + "columnName": "wrapCreatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "openedGeneration", + "columnName": "openedGeneration", + "affinity": "INTEGER" + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GroupInboxWrap_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxWrap_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupKeyState", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `thresholdPublicKey` TEXT NOT NULL, `derivationPath` TEXT NOT NULL, `announcedBy` TEXT NOT NULL, `announcedAt` INTEGER NOT NULL, `parentChatRoomId` TEXT, `birthCertificateJson` TEXT, `generation` INTEGER, `publicSharesHash` TEXT, `memberBindings` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thresholdPublicKey", + "columnName": "thresholdPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcedBy", + "columnName": "announcedBy", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcedAt", + "columnName": "announcedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "birthCertificateJson", + "columnName": "birthCertificateJson", + "affinity": "TEXT" + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER" + }, + { + "fieldPath": "publicSharesHash", + "columnName": "publicSharesHash", + "affinity": "TEXT" + }, + { + "fieldPath": "memberBindings", + "columnName": "memberBindings", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId" + ] + }, + "indices": [ + { + "name": "index_GroupKeyState_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupKeyState_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupSignedEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `derivationPath` TEXT, `frostSigningSessionId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT" + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GroupSignedEvent_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupSignedEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_GroupSignedEvent_frostSigningSessionId", + "unique": false, + "columnNames": [ + "frostSigningSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_frostSigningSessionId` ON `${TABLE_NAME}` (`frostSigningSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InboxKey", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `generation` INTEGER NOT NULL, `publicKey` TEXT NOT NULL, `secretKey` TEXT, `recoveryData` TEXT, `ceremonyId` TEXT NOT NULL, `state` TEXT NOT NULL, `announcementEventId` TEXT, `createdAt` INTEGER NOT NULL, `announcedAt` INTEGER, `wipedAt` INTEGER, PRIMARY KEY(`chatRoomId`, `userPublicKey`, `generation`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "secretKey", + "columnName": "secretKey", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "ceremonyId", + "columnName": "ceremonyId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcementEventId", + "columnName": "announcementEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "announcedAt", + "columnName": "announcedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "wipedAt", + "columnName": "wipedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "userPublicKey", + "generation" + ] + }, + "indices": [ + { + "name": "index_InboxKey_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_InboxKey_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InboxKeyCeremony", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `participantPublicKeys` TEXT NOT NULL, `stage` TEXT NOT NULL, `hostPublicKey` TEXT, `round1Random` TEXT, `round2AuxRandom` TEXT, `announceRelays` TEXT, `inboxPublicKey` TEXT, `failureReason` TEXT, `culprit` TEXT, `lastMessageAt` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantPublicKeys", + "columnName": "participantPublicKeys", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "hostPublicKey", + "columnName": "hostPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "round1Random", + "columnName": "round1Random", + "affinity": "TEXT" + }, + { + "fieldPath": "round2AuxRandom", + "columnName": "round2AuxRandom", + "affinity": "TEXT" + }, + { + "fieldPath": "announceRelays", + "columnName": "announceRelays", + "affinity": "TEXT" + }, + { + "fieldPath": "inboxPublicKey", + "columnName": "inboxPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "culprit", + "columnName": "culprit", + "affinity": "TEXT" + }, + { + "fieldPath": "lastMessageAt", + "columnName": "lastMessageAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_InboxKeyCeremony_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_InboxKeyCeremony_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InboxKeyCeremonyMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `senderPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `InboxKeyCeremony`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "senderPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "InboxKeyCeremony", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InboxSigning", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `manifest` TEXT, `refusal` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "manifest", + "columnName": "manifest", + "affinity": "TEXT" + }, + { + "fieldPath": "refusal", + "columnName": "refusal", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId" + ] + }, + "indices": [ + { + "name": "index_InboxSigning_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_InboxSigning_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "KeyShareGeneration", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `secretShare` TEXT, `publicShares` TEXT NOT NULL, `state` TEXT NOT NULL, `refreshSessionId` TEXT, `recoveryData` TEXT, `activatedAt` INTEGER, `wipedAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `generation`), FOREIGN KEY(`dkgSessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "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": "NotificationLedger", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`userPublicKey` TEXT NOT NULL, `armedAt` INTEGER NOT NULL, `cursorMessageId` INTEGER NOT NULL, `lastBackgroundSyncAt` INTEGER, `lastBackgroundSyncOutcome` TEXT, `lastBackgroundSyncKind` TEXT, `enabled` INTEGER NOT NULL DEFAULT 1, `messages` INTEGER NOT NULL DEFAULT 1, `needsYou` INTEGER NOT NULL DEFAULT 1, `groupActivity` INTEGER NOT NULL DEFAULT 0, `showMessageText` INTEGER NOT NULL DEFAULT 1, PRIMARY KEY(`userPublicKey`))", + "fields": [ + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "armedAt", + "columnName": "armedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cursorMessageId", + "columnName": "cursorMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastBackgroundSyncAt", + "columnName": "lastBackgroundSyncAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "lastBackgroundSyncOutcome", + "columnName": "lastBackgroundSyncOutcome", + "affinity": "TEXT" + }, + { + "fieldPath": "lastBackgroundSyncKind", + "columnName": "lastBackgroundSyncKind", + "affinity": "TEXT" + }, + { + "fieldPath": "enabled", + "columnName": "enabled", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "messages", + "columnName": "messages", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "needsYou", + "columnName": "needsYou", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "groupActivity", + "columnName": "groupActivity", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "showMessageText", + "columnName": "showMessageText", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "userPublicKey" + ] + } + }, + { + "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, 'da12b7739329a72e6df7180df7bc72cc')" + ] + } +} \ 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 b5aad359..8e8e9436 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -771,6 +771,56 @@ This device holds no such request for the confederation to sign Propose the charter The charter is the confederation's public statement of the groups it is made of, signed with its own key. It is how members who are not admins hear of it. + + Member of %1$s + Profile + The confederation has signed no profile yet + %1$d admins hold its key + Profile changes + Only the group's admins see proposed changes. + No changes to its profile have been proposed + Edit profile + How it was formed + Open the confederation's room + This device knows nothing of that confederation + This device holds no record of the confederation + This group is not one of the confederation's + This group cannot sign from this device + Only one of the group's admins can propose a change + Set up the group's inbox first: a change is sent from it + %1$s has no inbox, so it cannot be asked + Open + Endorsed, being signed + Published + Replaced by a newer profile + Declined + Withdrawn + Expired + Endorsed by %1$d of the %2$d groups it needs + Edit the confederation's profile + What the confederation says about itself on nostr + Your group's quorum signs the change, and it goes to every other group's inbox. The confederation signs it once %1$d of its %2$d groups have endorsed it. + Propose from + Propose to the groups + Couldn't propose the change + Profile change + This device does not hold that change + Endorse + Object + Withdraw the change + Endorsing lets the confederation's admins sign this profile once enough groups have endorsed it. Nobody is asked again. + Proposed it + Endorsed + Objected + Was: %1$s + Becomes: %1$s + Nothing + This change edits no field shown here + Being signed. Waiting on %1$s + %1$s: %2$s + Admins who joined a group after %1$s formed are not here. + Open the confederation + The key ceremony for %1$s is complete. The confederation works in its own room now. Inbox Inbox settings 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 63ac7a88..e1e0e808 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt @@ -232,7 +232,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) UnsignedNostrEvent::class, Zap::class ], - version = 50, + version = 51, autoMigrations = [ // v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can // generate the migration itself — nothing existing changes shape. @@ -535,6 +535,12 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) // Room generates it. No data moves: an identity with no DisappearingSetting row reads as // the one-day default, which is D9's upgrade without a data step. AutoMigration(from = 49, to = 50), + // v51 adds the nullable ConfederationEvent.confederationId and its index, so a formed + // confederation's profile changes, their answers and vouchers, and the kind:0 it signs file + // beside the formation's statements (docs/confederation-profile.md, Phase 1; built as v50 + // beside disappearing messages' v50 and renumbered at the merge). Rows written before it read + // back null: none of them is about a formed confederation's profile. + AutoMigration(from = 50, to = 51), ] ) @ConstructedBy(GizaDatabaseConstructor::class) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationCeremonyDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationCeremonyDao.kt index 4cc4f94f..21aaeefd 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationCeremonyDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationCeremonyDao.kt @@ -57,6 +57,10 @@ interface ConfederationCeremonyDao { @Query("SELECT c.* FROM Confederation c JOIN ConfederationMember m ON m.confederationId = c.id WHERE m.groupPublicKey = :groupPublicKey ORDER BY c.createdAt DESC") fun observeConfederationsOf(groupPublicKey: HexKey): Flow> + /** The confederations this device holds a record of that [groupPublicKey] is a member of. */ + @Query("SELECT confederationId FROM ConfederationMember WHERE groupPublicKey = :groupPublicKey") + suspend fun getConfederationIdsOfGroup(groupPublicKey: HexKey): List + @Upsert suspend fun upsertConfederation(confederation: mobi.giza.compose.database.model.Confederation) @@ -72,6 +76,10 @@ interface ConfederationCeremonyDao { @Query("SELECT * FROM ConfederationSigningAttempt WHERE confederationId = :confederationId ORDER BY createdAt DESC") fun observeAttempts(confederationId: HexKey): Flow> + /** Every attempt [userPublicKey]'s device holds for [confederationId], oldest first. */ + @Query("SELECT * FROM ConfederationSigningAttempt WHERE confederationId = :confederationId AND userPublicKey = :userPublicKey ORDER BY createdAt ASC") + suspend fun getAttempts(confederationId: HexKey, userPublicKey: HexKey): List + @Query("SELECT * FROM ConfederationSigningAttempt WHERE userPublicKey = :userPublicKey AND stage NOT IN ('COMPLETE', 'FAILED')") suspend fun getRunningAttempts(userPublicKey: HexKey): List diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationDao.kt index b11f762d..6b412638 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationDao.kt @@ -80,6 +80,36 @@ abstract class ConfederationDao { @Query("UPDATE ConfederationEvent SET publishedAt = :at WHERE id = :id") abstract suspend fun markPublished(id: HexKey, at: kotlin.time.Instant) + /** Everything filed about [confederationId]'s profile: changes, answers, vouchers, signed kind:0s. */ + @Query("SELECT * FROM ConfederationEvent WHERE confederationId = :confederationId ORDER BY eventCreatedAt ASC, id ASC") + abstract suspend fun getEventsForConfederation(confederationId: HexKey): List + + @Query("SELECT * FROM ConfederationEvent WHERE confederationId = :confederationId ORDER BY eventCreatedAt ASC, id ASC") + abstract fun observeEventsForConfederation(confederationId: HexKey): Flow> + + @Query("DELETE FROM ConfederationEvent WHERE id = :id") + abstract suspend fun deleteEvent(id: HexKey) + + /** Every confederation that has signed a charter this device holds. */ + @Query("SELECT DISTINCT pubKey FROM ConfederationEvent WHERE kind = ${ConfederationKinds.CHARTER}") + abstract fun observeCharterAuthors(): Flow> + + /** The charters [confederationId] has signed that this device holds, newest first. */ + @Query("SELECT * FROM ConfederationEvent WHERE kind = ${ConfederationKinds.CHARTER} AND pubKey = :confederationId ORDER BY eventCreatedAt DESC, id DESC") + abstract suspend fun getCharters(confederationId: HexKey): List + + /** Every charter naming [groupPublicKey] among its groups that this device holds, newest first. */ + @Query( + "SELECT e.* FROM ConfederationEvent e JOIN ConfederationInvitee i ON i.proposalId = e.id " + + "WHERE i.groupPublicKey = :groupPublicKey AND e.kind = ${ConfederationKinds.CHARTER} " + + "ORDER BY e.eventCreatedAt DESC, e.id DESC" + ) + abstract suspend fun getChartersNaming(groupPublicKey: HexKey): List + + /** Every profile change this device holds, for the follow-through's sweep. */ + @Query("SELECT * FROM ConfederationEvent WHERE kind = ${ConfederationKinds.PROFILE_CHANGE} ORDER BY eventCreatedAt DESC, id DESC") + abstract suspend fun getProfileChanges(): List + @Query("SELECT * FROM ConfederationSigning WHERE sessionId = :sessionId") abstract suspend fun getSigning(sessionId: String): ConfederationSigning? 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 f1b2ab9d..6835c034 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 @@ -568,7 +568,26 @@ data class ChatMessage( const val TYPE_CONFEDERATION_SIGNING_PROPOSED = "confederationSigningProposed" const val TYPE_CONFEDERATION_SIGNING_FAILED = "confederationSigningFailed" - val CONFEDERATION_TYPES = setOf( + /** + * A formed confederation's profile, decided by its groups (docs/confederation-profile.md, D8): + * a group proposing a change, another endorsing or objecting to it, and the new profile once + * the confederation has signed it. Written by each device into its own member groups' rooms. + * [frostSigningSessionId] carries the change's id, or for a published profile the + * confederation's, so the line opens what it is about. + */ + const val TYPE_CONFEDERATION_PROFILE_PROPOSED = "confederationProfileProposed" + const val TYPE_CONFEDERATION_PROFILE_ENDORSED = "confederationProfileEndorsed" + const val TYPE_CONFEDERATION_PROFILE_OBJECTED = "confederationProfileObjected" + const val TYPE_CONFEDERATION_PROFILE_PUBLISHED = "confederationProfilePublished" + + val CONFEDERATION_PROFILE_TYPES = setOf( + TYPE_CONFEDERATION_PROFILE_PROPOSED, + TYPE_CONFEDERATION_PROFILE_ENDORSED, + TYPE_CONFEDERATION_PROFILE_OBJECTED, + TYPE_CONFEDERATION_PROFILE_PUBLISHED, + ) + + val CONFEDERATION_TYPES = CONFEDERATION_PROFILE_TYPES + setOf( TYPE_CONFEDERATION_PROPOSED, TYPE_CONFEDERATION_ACCEPTED, TYPE_CONFEDERATION_REJECTED, @@ -1540,6 +1559,9 @@ data class ChatMessage( // well as from a session here, so this arm writes nothing rather than a // raw-JSON bubble (docs/confederation.md, Phase 5). in ConfederationKinds.ALL -> null + // A profile change's voucher, signed beside its seals: carried into the + // confederation's room, and never a line (docs/confederation-profile.md, D5). + ConfederationKinds.VOUCHER -> null // Bennu's wallets, which a Bennu member can bring into a room this // device shares. What announces one is a line saying Giza takes no part; diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ConfederationEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ConfederationEvent.kt index ddaded3b..55b48d65 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ConfederationEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ConfederationEvent.kt @@ -13,7 +13,8 @@ import kotlin.time.Instant * A confederation statement this device holds: a proposal, or an answer to one, as a rumor one * of its groups' inboxes opened (docs/confederation-without-coordinator.md, D3 and Phase 5); or a * confederation's public charter, signed by the confederation's key (docs/confederation.md, - * Phase 15). + * Phase 15); or, for a formed confederation, a proposed change to its profile, an answer to one, a + * group's voucher, and the kind:0 it signed (docs/confederation-profile.md). * * A statement is filed only once the seal that carried it verified as its author's, and the seal * is kept beside it as the evidence: a rumor alone is unsigned. A charter is a signed event and @@ -28,7 +29,7 @@ import kotlin.time.Instant * (docs/subgroups.md). And never a `NostrEvent` row: that would put a group's confederation * event in the home feed and make it a `Profile` (docs/group-nostr-profile-and-posts.md, D7). */ -@Entity(indices = [Index("proposalId"), Index("kind"), Index("publishedAt")]) +@Entity(indices = [Index("proposalId"), Index("kind"), Index("publishedAt"), Index("confederationId")]) data class ConfederationEvent( @PrimaryKey val id: HexKey, @@ -56,6 +57,12 @@ data class ConfederationEvent( val sealJson: String? = null, /** Which of this device's groups' inboxes opened it, or signed it. Null for a charter. */ val inboxRoomId: String? = null, + /** + * The formed confederation a profile change, an answer to one, a voucher or the signed kind:0 + * is about (docs/confederation-profile.md): what its screen looks them up by. For those, + * [proposalId] is the change's rumor id. Null for the formation's statements and the charter. + */ + val confederationId: HexKey? = null, ) { fun toEvent(): Event = Event.fromJson(eventJson) } 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 64dac56f..6920da2c 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 @@ -208,6 +208,9 @@ class DatabaseChatRepository( // A formed confederation's room, made by its coordinator's device. // docs/confederation.md, Phase 13. launch { ConfederationFollowThrough.observe(database = database, chatRepository = this@DatabaseChatRepository, keyPair = keyPair) } + // A change to a formed confederation's profile its groups endorsed, signed by the + // confederation with nobody asked. docs/confederation-profile.md, D6. + launch { mobi.giza.compose.managers.ConfederationProfileFollowThrough.observe(database = database, keyPair = keyPair) } keyPair.privKey?.let { secret -> launch { runCatching { ConfederationRitualManager.resumeRunning(database, keyPair.pubKey.toHex(), secret) } @@ -367,6 +370,15 @@ class DatabaseChatRepository( override suspend fun confederationProposalCount(chatRoomId: String): Int = database.confederationDao().getProposalsNaming(chatRoomId).size + override suspend fun memberConfederations(chatRoomId: String): List> = try { + mobi.giza.compose.managers.ConfederationProfileManager.confederationsOf(database, chatRoomId).mapNotNull { id -> + mobi.giza.compose.managers.ConfederationProfileManager.membership(database, id)?.let { id to it.name } + } + } catch (e: Throwable) { + logger.e("Error reading the confederations of $chatRoomId", e) + emptyList() + } + override suspend fun canSignAsConfederation(chatRoomId: String): Boolean { if (!ExperimentalFeatures.confederation) return false val me = activeIdentity.value?.takeIf { it.canSign }?.nostrPublicKey ?: return false @@ -395,7 +407,36 @@ class DatabaseChatRepository( override suspend fun keyCeremonyOfRoom(chatRoomId: String): mobi.giza.compose.ui.view.state.KeyCeremonyLink? { val proposalId = ConfederationRitualManager.proposalOfRoom(database, chatRoomId) ?: return null val joined = database.confederationCeremonyDao().getLatestForProposal(proposalId)?.approvedAt != null - return mobi.giza.compose.ui.view.state.KeyCeremonyLink(proposalId = proposalId, joined = joined) + val formed = database.confederationCeremonyDao().getConfederationForProposal(proposalId) + ?.takeIf { ConfederationFormation.verifies(it) } + ?.let { confederation -> + mobi.giza.compose.ui.view.state.FormedConfederation(confederation.id, confederation.name, homeGroupOf(confederation.id)) + } + return mobi.giza.compose.ui.view.state.KeyCeremonyLink(proposalId = proposalId, joined = joined, formed = formed) + } + + /** A member group of [confederationId] this device holds the room of: where its screen is opened from. */ + private suspend fun homeGroupOf(confederationId: String): String? = + mobi.giza.compose.managers.ConfederationProfileManager.membership(database, confederationId)?.groups + ?.firstOrNull { database.chatRoomDao().findChatRoomById(it) != null } + + override suspend fun confederationRoomInfo(chatRoomId: String): mobi.giza.compose.ui.view.state.ConfederationRoomInfo? = try { + mobi.giza.compose.managers.ConfederationSigningManager.held(database, chatRoomId)?.let { held -> + val names = held.plan.groups.associateWith { mobi.giza.compose.managers.ConfederationManager.nameOf(database, it) } + val people = held.plan.people.associateWith { mobi.giza.compose.managers.ConfederationManager.nameOf(database, it) } + mobi.giza.compose.ui.view.state.ConfederationRoomInfo( + confederationId = chatRoomId, + name = held.confederation.name, + groups = held.plan.groups.map { group -> + names.getValue(group) to held.plan.seats.filter { it.group == group }.map { people.getValue(it.admin) } + }, + groupsOfMember = held.plan.people.associateWith { person -> held.plan.seatsOf(person).map { names.getValue(it.group) } }, + homeGroupId = homeGroupOf(chatRoomId), + ) + } + } catch (e: Throwable) { + logger.e("Error reading the confederation of $chatRoomId", e) + null } override suspend fun confederationOfRoom(chatRoomId: String): String? = diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt index d2fc0e33..d6e3a2f7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt @@ -11,6 +11,19 @@ import kotlinx.coroutines.flow.StateFlow import mobi.giza.compose.identity.Identity import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flowOf +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import mobi.giza.compose.managers.ConfederationProfileManager +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus +import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements +import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.managers.ConfederationProfileRefusal +import mobi.giza.compose.managers.FrostSigningManager +import mobi.giza.compose.managers.InboxReplies +import mobi.giza.compose.repository.ProfileChangeProblem +import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.Confederation import mobi.giza.compose.database.model.ConfederationCeremony @@ -110,6 +123,111 @@ class DatabaseConfederationRepository( ConfederationManager.statusOf(proposal, rows) } + override fun observeProfileChanges(confederationId: HexKey): Flow> = + combine( + database.confederationDao().observeEventsForConfederation(confederationId), + database.groupSignedEventDao().observeCountByChatRoomIdAndKind(confederationId, MetadataEvent.KIND), + ) { rows, _ -> rows }.map { rows -> + ConfederationProfileManager.statusesFrom(rows, ConfederationProfileManager.profiles(database, confederationId), Clock.System.now().epochSeconds) + } + + override fun observeKnownConfederations(): Flow> = + combine( + database.confederationCeremonyDao().observeConfederations(), + database.confederationDao().observeCharterAuthors(), + ) { recorded, chartered -> (recorded.map { it.id } + chartered).distinct().sorted() }.distinctUntilChanged() + + override suspend fun extraRelaysFor(event: ConfederationEvent): List = + if (event.kind == MetadataEvent.KIND) ConfederationProfileManager.publishRelaysFor(database, event.pubKey) else emptyList() + + override suspend fun membership(confederationId: HexKey): ConfederationProfileManager.Membership? = + ConfederationProfileManager.membership(database, confederationId) + + override fun observeProfile(confederationId: HexKey): Flow = + combine( + database.confederationDao().observeEventsForConfederation(confederationId), + database.groupSignedEventDao().observeCountByChatRoomIdAndKind(confederationId, MetadataEvent.KIND), + ) { _, _ -> Unit }.map { ConfederationProfileManager.profiles(database, confederationId).newestProfile } + + override suspend fun roleHolders(confederationId: HexKey): Map> = + ConfederationSigningManager.held(database, confederationId)?.plan?.let { plan -> + plan.groups.associateWith { group -> plan.seats.filter { it.group == group }.map { it.admin } } + } ?: emptyMap() + + override suspend fun formingProposalOf(confederationId: HexKey): HexKey? = + database.confederationCeremonyDao().getConfederation(confederationId)?.proposalId + + override suspend fun holdsRoomOf(confederationId: HexKey): Boolean = + database.chatRoomDao().findChatRoomById(confederationId) != null + + override suspend fun profileChangeProblem(chatRoomId: String, userPublicKey: HexKey, confederationId: HexKey): ProfileChangeProblem? { + val membership = ConfederationProfileManager.membership(database, confederationId) ?: return ProfileChangeProblem.NoRecord + if (!membership.includes(chatRoomId)) return ProfileChangeProblem.NotMember + val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return ProfileChangeProblem.NotMember + if (room.chatRoom.mlsGroupState == null || room.chatRoom.leftGroupAt != null) return ProfileChangeProblem.CannotSign + if (!FrostSigningManager.canSign(database, chatRoomId)) return ProfileChangeProblem.CannotSign + if (RoomAdmins.of(database, chatRoomId)?.admins?.contains(userPublicKey) != true) return ProfileChangeProblem.NotAdmin + if (ConfederationManager.announcedInboxKey(database, chatRoomId, userPublicKey) == null) return ProfileChangeProblem.NoInbox + membership.othersThan(chatRoomId).firstOrNull { !InboxReplies.hasAnnouncedKey(database, it) }?.let { + return ProfileChangeProblem.GroupWithoutInbox(ConfederationManager.nameOf(database, it)) + } + return null + } + + override suspend fun proposingGroupsFor(userPublicKey: HexKey, confederationId: HexKey): List { + val membership = ConfederationProfileManager.membership(database, confederationId) ?: return emptyList() + return membership.groups.filter { profileChangeProblem(it, userPublicKey, confederationId) == null } + } + + override suspend fun profileBaseOf(changeId: HexKey): UserMetadata? { + val change = ConfederationProfileManager.change(database, changeId) ?: return null + val profiles = ConfederationProfileManager.profiles(database, change.confederation) + val base = change.base?.let { id -> + database.confederationDao().getEvent(id)?.toEvent() + ?: database.groupSignedEventDao().getById(id)?.toEvent() + } + return base?.let(ConfederationProfileRefusal::metadataOf) ?: profiles.newestProfile?.metadata?.takeIf { change.base != null } + } + + override suspend fun proposeProfileChange( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + confederationId: HexKey, + tags: Array>, + content: String, + ): FrostSigningSession = ConfederationProfileManager.proposeChange(database, localChatRoom, userPublicKey, confederationId, tags, content) + + override suspend fun proposeProfileEndorsement(localChatRoom: LocalChatRoom, userPublicKey: HexKey, changeId: HexKey): FrostSigningSession = + ConfederationProfileManager.proposeEndorsement(database, localChatRoom, userPublicKey, changeId) + + override suspend fun proposeProfileObjection(localChatRoom: LocalChatRoom, userPublicKey: HexKey, changeId: HexKey, reason: String): FrostSigningSession = + ConfederationProfileManager.proposeObjection(database, localChatRoom, userPublicKey, changeId, reason) + + override fun observePendingProfileAnswer(chatRoomId: String, changeId: HexKey): Flow = + pendingProfileSession(chatRoomId) { rumor -> rumor.kind != ConfederationKinds.PROFILE_CHANGE && ConfederationProfileStatements.changeIdOf(rumor) == changeId } + + override fun observePendingProfileChange(chatRoomId: String, confederationId: HexKey): Flow = + pendingProfileSession(chatRoomId) { rumor -> rumor.kind == ConfederationKinds.PROFILE_CHANGE && ConfederationProfileStatements.confederationOf(rumor) == confederationId } + + private fun pendingProfileSession(chatRoomId: String, matches: (Event) -> Boolean): Flow = + database.frostSigningSessionDao().observeSessionsForChatRoom(chatRoomId).map { sessions -> + sessions.firstOrNull { local -> + local.session.stage != FrostSigningStage.COMPLETE && + local.session.stage != FrostSigningStage.FAILED && + ConfederationRefusal.Carried.from(database.confederationDao().getSigning(local.session.id)).rumor + ?.takeIf { it.kind in ConfederationKinds.PROFILE_CHANGE_KINDS }?.let(matches) == true + }?.session + } + + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + override fun observeProfileChange(changeId: HexKey): Flow = + database.confederationDao().observeEventsForProposal(changeId).map { rows -> + val change = rows.firstOrNull { it.id == changeId && it.kind == ConfederationKinds.PROFILE_CHANGE } ?: return@map null + change.confederationId + }.distinctUntilChanged().flatMapLatest { confederationId -> + if (confederationId == null) flowOf(null) else observeProfileChanges(confederationId).map { list -> list.firstOrNull { it.change.id == changeId } } + } + override suspend fun isAdmin(chatRoomId: String, userPublicKey: HexKey): Boolean = RoomAdmins.of(database, chatRoomId)?.admins?.contains(userPublicKey) == true diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt index 659f5d0c..357bd78c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt @@ -6,6 +6,7 @@ import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import com.vitorpamplona.quartz.nip01Core.crypto.verify +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate import kotlin.time.Clock import kotlin.time.Instant import mobi.giza.compose.database.GizaDatabase @@ -47,6 +48,8 @@ object ConfederationManager { * filed this way: it arrives through an inbox, as [recordStatement]. */ suspend fun record(database: GizaDatabase, event: Event): Boolean { + // A formed confederation's profile, heard on a relay (docs/confederation-profile.md, D7). + if (event.kind == com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent.KIND) return ConfederationProfileManager.hearProfile(database, event) if (event.kind != ConfederationKinds.CHARTER) return false if (!GroupKeyStateEvent.isSignedByRoom(event, event.pubKey)) { logger.w("Charter ${event.id.take(8)} does not verify as its author's; dropping") @@ -208,6 +211,10 @@ object ConfederationManager { suspend fun onSigned(database: GizaDatabase, session: FrostSigningSession, signedEvents: List) { val rumor = ConfederationRefusal.Carried.from(database.confederationDao().getSigning(session.id)).rumor ?: return if (signedEvents.none { it.kind == InboxSeal.KIND && it.pubKey.equals(session.chatRoomId, ignoreCase = true) }) return + if (rumor.kind in ConfederationKinds.PROFILE_CHANGE_KINDS) { + ConfederationProfileManager.onSigned(database, session, rumor, signedEvents) + return + } recordStatement(database, rumor, seal = null, inboxRoomId = session.chatRoomId) } @@ -384,13 +391,20 @@ object ConfederationManager { * and once to itself (D1, D6). Throws, with a reason a person can read, when the group has no * announced inbox here, a recipient has announced none, or the statement would not fit. */ - private suspend fun proposeStatement( + internal suspend fun proposeStatement( database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, rumor: Event, recipients: List, invitation: String?, + /** + * What the group signs beside the seals in the same session: a profile change's voucher + * (docs/confederation-profile.md, D5). Last in the batch, after every seal. + */ + extra: List> = emptyList(), + /** What to say instead when the statement would not fit, in the caller's terms. */ + tooLarge: ((bytes: Int) -> String)? = null, ): FrostSigningSession { val group = localChatRoom.chatRoom.id val key = announcedInboxKey(database, group, userPublicKey) @@ -401,7 +415,7 @@ object ConfederationManager { } val secret = key.secretKey!!.hexToByteArray() val built = InboxReplies.sealRumor(group, rumor, resolved, secret, key.generation) - return proposeSealed(database, localChatRoom, userPublicKey, rumor, built, secret, invitation) + return proposeSealed(database, localChatRoom, userPublicKey, rumor, built, secret, invitation, extra, tooLarge) } /** @@ -417,22 +431,25 @@ object ConfederationManager { built: InboxReplies.Built, inboxSecret: ByteArray, invitation: String?, + extra: List> = emptyList(), + tooLarge: ((bytes: Int) -> String)? = null, ): FrostSigningSession { val group = localChatRoom.chatRoom.id val sealed = built.manifest.seal(inboxSecret) val carried = ConfederationRefusal.Carried(rumorJson = InboxSeal.rumorJson(rumor), invitationJson = invitation) - val bytes = FrostSigningEvents.encodeProposal(built.seals.map { Event(it.createdAt.toString(), group, it.createdAt, it.kind, it.tags, it.content, "") }).length + + val batch: List> = built.seals + extra + val bytes = FrostSigningEvents.encodeProposal(batch.map { Event(it.createdAt.toString(), group, it.createdAt, it.kind, it.tags, it.content, "") }).length + sealed.length + carried.toTags().sumOf { it.sumOf { value -> value.length } } check(bytes <= ConfederationKinds.MAX_STATEMENT_BYTES) { - "This statement would be ${bytes / 1000} KB, more than one message can carry: name fewer groups" + tooLarge?.invoke(bytes) ?: "This statement would be ${bytes / 1000} KB, more than one message can carry: name fewer groups" } val session = FrostSigningManager.proposeSigningBatch( database = database, localChatRoom = localChatRoom, userPublicKey = userPublicKey, - events = built.seals, + events = batch, proposalTags = arrayOf(InboxReplyManifest.tag(sealed)) + carried.toTags(), ) ConfederationRefusal.remember(database, session.id, carried, null) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileFollowThrough.kt new file mode 100644 index 00000000..6791665a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileFollowThrough.kt @@ -0,0 +1,117 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import kotlin.coroutines.cancellation.CancellationException +import kotlin.time.Clock +import kotlin.time.Duration +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Instant +import kotlinx.coroutines.delay +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.ConfederationSigningAttempt +import mobi.giza.compose.database.model.ConfederationSigningStage +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState + +/** + * From a change its groups endorsed to the confederation's signature on it, with nobody asked + * (docs/confederation-profile.md, D6). + * + * Once a role holder's device holds vouchers from `T` groups for a change, somebody has to start the + * signing. Nobody is in charge, so an order says who: the roster's people sorted bytewise, the first + * at once, the `k`-th once `k` [WAIT_PER_PLACE]s have passed since the `T`-th voucher reached their + * device with no attempt for it heard. A failed attempt -- a nonce lost to a restart, a selected + * device gone quiet -- is started again by the same rule, after a delay that doubles from + * [WAIT_PER_PLACE] up to [MAX_BACKOFF], until the change expires. + */ +object ConfederationProfileFollowThrough { + private val logger = Logger.withTag("ConfederationProfileFollowThrough") + private val mutex = Mutex() + + val WAIT_PER_PLACE: Duration = 10.minutes + val MAX_BACKOFF: Duration = 2.hours + private val LOOK_AGAIN: Duration = 1.minutes + + /** Looks at every change this device holds, every [LOOK_AGAIN], for as long as it runs. */ + suspend fun observe(database: GizaDatabase, keyPair: KeyPair) { + val secret = keyPair.privKey ?: return + val me = keyPair.pubKey.toHexKey() + while (true) { + runCatching { sweep(database, me, secret) }.onFailure { + if (it is CancellationException) throw it + logger.e("Could not follow profile changes through", it) + } + delay(LOOK_AGAIN) + } + } + + /** One look at every change this device holds. Returns the attempts it started. */ + suspend fun sweep(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray, now: Instant = Clock.System.now()): List = + database.confederationDao().getProfileChanges().mapNotNull { row -> + runCatching { takeNextStep(database, row.id, userPublicKey, nostrPrivateKey, now) } + .onFailure { if (it is CancellationException) throw it; logger.e("Could not follow ${row.id.take(8)} through", it) } + .getOrNull() + } + + /** + * Starts the confederation's signing of [changeId]'s kind:0 if it is [userPublicKey]'s turn, and + * returns the attempt it started; null when there is nothing to do here yet. + */ + suspend fun takeNextStep( + database: GizaDatabase, + changeId: HexKey, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + now: Instant = Clock.System.now(), + ): ConfederationSigningAttempt? = mutex.withLock { + val change = ConfederationProfileManager.change(database, changeId) ?: return@withLock null + val held = ConfederationSigningManager.held(database, change.confederation) ?: return@withLock null + val place = held.plan.people.sorted().indexOf(userPublicKey).takeIf { it >= 0 } ?: return@withLock null + val room = database.chatRoomDao().findChatRoomById(held.confederation.id) ?: return@withLock null + val status = ConfederationProfileManager.status(database, changeId, now.epochSeconds) ?: return@withLock null + if (status.state != ConfederationProfileChangeState.ENDORSED) return@withLock null + + val vouchers = ConfederationSigningManager.vouchersFor(database, held, change.profileId, now.epochSeconds) + if (vouchers.size < held.plan.proposal.threshold) return@withLock null + + val attempts = database.confederationCeremonyDao().getAttempts(held.confederation.id, userPublicKey) + .filter { runCatching { Event.fromJson(it.eventJson).id }.getOrNull() == change.profileId } + if (attempts.any { it.isRunning || it.stage == ConfederationSigningStage.COMPLETE }) return@withLock null + + val failures = attempts.filter { it.stage == ConfederationSigningStage.FAILED } + val since = if (failures.isEmpty()) { + arrivalOfThreshold(database, change.confederation, vouchers.map { it.id }.toSet(), held.plan.proposal.threshold) ?: return@withLock null + } else { + failures.maxOf { it.updatedAt } + backoff(failures.size) + } + if (now < since + WAIT_PER_PLACE * place) return@withLock null + + logger.i("Starting the confederation's signing of change ${changeId.take(8)}, place $place, after ${failures.size} failed attempt(s)") + ConfederationSigningManager.propose( + database, room, userPublicKey, change.profile.kind, change.profile.tags, change.profile.content, nostrPrivateKey, + createdAt = change.profile.createdAt, vouchers = vouchers, + ) + } + + /** How long after the [failures]-th failure the next attempt waits, before each place's own wait. */ + fun backoff(failures: Int): Duration { + var wait = WAIT_PER_PLACE + repeat((failures - 1).coerceAtLeast(0)) { wait = (wait * 2).coerceAtMost(MAX_BACKOFF) } + return wait + } + + /** When the [threshold]-th of [voucherIds] reached this device: the moment the change could be signed. */ + private suspend fun arrivalOfThreshold(database: GizaDatabase, confederationId: HexKey, voucherIds: Set, threshold: Int): Instant? = + database.confederationDao().getEventsForConfederation(confederationId) + .filter { it.kind == ConfederationKinds.VOUCHER && it.id in voucherIds } + .map { it.receivedAt } + .sorted() + .getOrNull(threshold - 1) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileManager.kt new file mode 100644 index 00000000..d88ea343 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileManager.kt @@ -0,0 +1,440 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.crypto.verify +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import kotlin.time.Clock +import kotlin.time.Instant +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ConfederationEvent +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.GroupSignedEvent +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent +import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus +import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements +import mobi.giza.compose.nostr.frost.GroupKeyStateEvent +import mobi.giza.compose.nostr.inbox.InboxSeal + +/** + * A formed confederation's profile, decided by its groups (docs/confederation-profile.md): filing + * what the groups say about a change, and reading back where each change stands. + * + * A change, an endorsement and an objection are rumors one group seals to every other through their + * inboxes, as the formation's statements are; a voucher is the one thing a group signs that can be + * shown to anyone, and it is what the confederation's role holders act on (D5). All of them are + * filed in `ConfederationEvent` under the confederation they are about, the change's id standing as + * their `proposalId`. + */ +object ConfederationProfileManager { + private val logger = Logger.withTag("ConfederationProfileManager") + + // ---- filing ---------------------------------------------------------------------------------- + + /** + * Files [rumor], a change or an answer one of this device's groups' inboxes ([inboxRoomId]) + * opened from [seal], or its own group signed (no seal). Returns whether it was new. + * + * A seal, when there is one, must verify and be its rumor's author's: that is what makes a rumor + * the group's word. Callers have opened it already; this checks again. + */ + suspend fun recordStatement(database: GizaDatabase, rumor: Event, seal: Event?, inboxRoomId: String?): Boolean { + if (rumor.kind !in ConfederationKinds.PROFILE_CHANGE_KINDS) return false + if (seal != null && (!seal.verify() || !seal.pubKey.equals(rumor.pubKey, ignoreCase = true))) { + logger.w("Profile statement ${rumor.id.take(8)} came in a seal that is not its author's; dropping") + return false + } + val (changeId, confederation) = when (rumor.kind) { + ConfederationKinds.PROFILE_CHANGE -> ConfederationProfileStatements.parseChange(rumor)?.let { it.id to it.confederation } + else -> ConfederationProfileStatements.parseAnswer(rumor)?.let { it.changeId to it.confederation } + } ?: run { + logger.w("Profile statement ${rumor.id.take(8)} of kind ${rumor.kind} is not well formed; dropping") + return false + } + val filed = database.confederationDao().record( + ConfederationEvent( + id = rumor.id, + kind = rumor.kind, + pubKey = rumor.pubKey, + proposalId = changeId, + eventCreatedAt = rumor.createdAt, + eventJson = InboxSeal.rumorJson(rumor), + sealJson = seal?.toJson(), + inboxRoomId = inboxRoomId, + confederationId = confederation, + ) + ) + // Once per statement, by construction: the row above is written once. An answer filed before + // its change had nothing to name, so the change writes their lines now: wraps arrive in any order. + if (filed) runCatching { + announce(database, rumor, changeId) + if (rumor.kind == ConfederationKinds.PROFILE_CHANGE) { + database.confederationDao().getEventsForProposal(changeId) + .filter { it.kind == ConfederationKinds.ENDORSEMENT || it.kind == ConfederationKinds.OBJECTION } + .forEach { announce(database, it.toEvent(), changeId) } + } + }.onFailure { logger.w(throwable = it) { "Filed ${rumor.id.take(8)} but could not write its line" } } + return filed + } + + /** + * A system line in each member group's room this device holds, for [statement] about [changeId] + * (D8). Written by each device for itself, sending nothing; the line carries the change's id so + * it opens the change. + */ + private suspend fun announce(database: GizaDatabase, statement: Event, changeId: HexKey) { + val change = change(database, changeId) ?: return + val name = membership(database, change.confederation)?.name ?: "the confederation" + change.groups.mapNotNull { database.chatRoomDao().findChatRoomById(it) }.forEach { room -> + val roomId = room.chatRoom.id + val who = ConfederationManager.nameOf(database, statement.pubKey, roomId) + val proposer = ConfederationManager.nameOf(database, change.proposingGroup, roomId).let { if (it == "This group") "this group" else it } + val (type, content) = when (statement.kind) { + ConfederationKinds.PROFILE_CHANGE -> ChatMessage.TYPE_CONFEDERATION_PROFILE_PROPOSED to + if (statement.pubKey == roomId) "This group proposed a new profile for $name" else "$who proposes a new profile for $name" + ConfederationKinds.ENDORSEMENT -> ChatMessage.TYPE_CONFEDERATION_PROFILE_ENDORSED to + "$who endorsed $proposer's change to $name's profile" + ConfederationKinds.OBJECTION -> { + val reason = ConfederationProfileStatements.parseAnswer(statement)?.reason?.takeIf { it.isNotBlank() }?.let { ": $it" } ?: "" + ChatMessage.TYPE_CONFEDERATION_PROFILE_OBJECTED to if (statement.pubKey == change.proposingGroup) { + "$who withdrew its change to $name's profile$reason" + } else { + "$who objected to $proposer's change to $name's profile$reason" + } + } + else -> return@forEach + } + database.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = statement.pubKey, + isUserMessage = false, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = roomId, + content = content, + messageType = type, + createdAt = Instant.fromEpochSeconds(statement.createdAt), + frostSigningSessionId = changeId, + ) + ) + } + } + + /** + * Files [voucher] if it is well formed and its group's key signed it. Returns whether it was new. + * Anyone can check one: it needs nothing but the group's npub (Phase 0, check 5). + */ + suspend fun recordVoucher(database: GizaDatabase, voucher: Event): Boolean { + val parsed = ConfederationProfileStatements.parseVoucher(voucher) ?: run { + logger.w("Voucher ${voucher.id.take(8)} is not well formed; dropping") + return false + } + if (!GroupKeyStateEvent.isSignedByRoom(voucher, voucher.pubKey)) { + logger.w("Voucher ${voucher.id.take(8)} does not verify as ${voucher.pubKey.take(8)}'s; dropping") + return false + } + return database.confederationDao().record( + ConfederationEvent( + id = voucher.id, + kind = voucher.kind, + pubKey = voucher.pubKey, + proposalId = parsed.changeId, + eventCreatedAt = voucher.createdAt, + eventJson = voucher.toJson(), + confederationId = parsed.confederation, + ) + ) + } + + /** + * Files [signed], a kind:0 its confederation's key signed, under that confederation: from its own + * signing, or off a relay. [changeId] is the change it came from, where this device knows it. + * Returns whether it was new. + * + * Not a `GroupSignedEvent`: that table hangs off a room, and a member of a member group who is + * no admin holds no room for the confederation, only its charter and this. + */ + suspend fun recordProfile(database: GizaDatabase, signed: Event, changeId: HexKey? = null): Boolean { + if (signed.kind != MetadataEvent.KIND || !GroupKeyStateEvent.isSignedByRoom(signed, signed.pubKey)) { + logger.w("Profile ${signed.id.take(8)} is not a kind:0 its author signed; dropping") + return false + } + val change = changeId ?: database.confederationDao().getEventsForConfederation(signed.pubKey) + .firstOrNull { it.kind == ConfederationKinds.PROFILE_CHANGE && ConfederationProfileStatements.parseChange(it.toEvent())?.profileId == signed.id }?.id + val filed = database.confederationDao().record( + ConfederationEvent( + id = signed.id, + kind = signed.kind, + pubKey = signed.pubKey, + proposalId = change ?: signed.id, + eventCreatedAt = signed.createdAt, + eventJson = signed.toJson(), + confederationId = signed.pubKey, + ) + ) + if (filed) runCatching { announcePublished(database, signed) } + .onFailure { logger.w(throwable = it) { "Filed profile ${signed.id.take(8)} but could not write its line" } } + return filed + } + + /** + * A kind:0 heard on a relay: filed if its author is a confederation this device knows, by record + * or charter, and its key signed it (D7). How a member who is not an admin learns of a new profile. + */ + suspend fun hearProfile(database: GizaDatabase, event: Event): Boolean { + if (event.kind != MetadataEvent.KIND) return false + if (membership(database, event.pubKey) == null) return false + return recordProfile(database, event) + } + + /** + * "Atlas has a new profile", in each member group's room this device holds, once per profile and + * only for the newest: an older one arriving late changes nothing a reader sees. The line carries + * the confederation's id, so it opens the confederation. + */ + private suspend fun announcePublished(database: GizaDatabase, signed: Event) { + val profiles = profiles(database, signed.pubKey) + if (profiles.newest?.second != signed.id) return + val membership = membership(database, signed.pubKey) ?: return + val newName = ConfederationProfileRefusal.metadataOf(signed)?.anyName()?.takeIf { it.isNotBlank() } + membership.groups.mapNotNull { database.chatRoomDao().findChatRoomById(it) }.forEach { room -> + database.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = signed.pubKey, + isUserMessage = false, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = room.chatRoom.id, + content = if (newName != null && newName != membership.name) "${membership.name} has a new profile, as $newName" else "${membership.name} has a new profile", + messageType = ChatMessage.TYPE_CONFEDERATION_PROFILE_PUBLISHED, + createdAt = Instant.fromEpochSeconds(signed.createdAt), + frostSigningSessionId = signed.pubKey, + ) + ) + } + } + + /** + * Where a confederation's signed profile is sent besides the public relays: each member group's + * inbox relays, which its members' devices already read (D7). + */ + suspend fun publishRelaysFor(database: GizaDatabase, confederationId: HexKey): List { + val membership = membership(database, confederationId) ?: return emptyList() + return membership.groups.flatMap { group -> + InboxAnnouncements.relaysOf(database, group).ifEmpty { InboxReplies.announcedRelaysOf(database, group) } + }.map { it.url }.distinct() + } + + // ---- reading --------------------------------------------------------------------------------- + + /** The change [changeId], if this device holds it. */ + suspend fun change(database: GizaDatabase, changeId: HexKey): ConfederationProfileStatements.Change? = + database.confederationDao().getEvent(changeId) + ?.takeIf { it.kind == ConfederationKinds.PROFILE_CHANGE } + ?.let { ConfederationProfileStatements.parseChange(it.toEvent()) } + + /** Where [changeId] stands on this device, or null if it does not hold the change. */ + suspend fun status(database: GizaDatabase, changeId: HexKey, now: Long = Clock.System.now().epochSeconds): ConfederationProfileChangeStatus? { + val change = change(database, changeId) ?: return null + val rows = database.confederationDao().getEventsForProposal(changeId) + return statusOf(change, rows, profiles(database, change.confederation), now) + } + + /** Every change to [confederationId]'s profile this device holds, newest first, with where each stands. */ + suspend fun statusesOf(database: GizaDatabase, confederationId: HexKey, now: Long = Clock.System.now().epochSeconds): List = + statusesFrom(database.confederationDao().getEventsForConfederation(confederationId), profiles(database, confederationId), now) + + /** [statusesOf], from rows and signed kind:0s already read: what a flow's emission is handed. */ + fun statusesFrom(rows: List, profiles: Profiles, now: Long): List { + val byChange = rows.groupBy { it.proposalId } + return rows.filter { it.kind == ConfederationKinds.PROFILE_CHANGE } + .mapNotNull { row -> + val change = ConfederationProfileStatements.parseChange(row.toEvent()) ?: return@mapNotNull null + statusOf(change, byChange[change.id].orEmpty(), profiles, now) + } + .sortedWith(compareByDescending { it.change.createdAt }.thenByDescending { it.change.id }) + } + + private fun statusOf( + change: ConfederationProfileStatements.Change, + rows: List, + profiles: Profiles, + now: Long, + ): ConfederationProfileChangeStatus { + val events = rows.map { it.toEvent() } + return ConfederationProfileChangeStatus.of( + change = change, + answers = events.mapNotNull { if (it.kind == ConfederationKinds.PROFILE_CHANGE) null else ConfederationProfileStatements.parseAnswer(it) }, + vouchers = events.filter { it.kind == ConfederationKinds.VOUCHER }.mapNotNull(ConfederationProfileStatements::parseVoucher), + newestProfile = profiles.newest, + published = change.profileId in profiles.signedIds, + now = now, + ) + } + + /** The kind:0s a confederation has signed that this device holds: their ids, and the newest. */ + class Profiles(val signedIds: Set, val newest: Pair?, val newestProfile: GroupNostrProfile?) { + companion object { + val NONE = Profiles(emptySet(), null, null) + } + } + + /** + * The kind:0s [confederationId] has signed that this device holds: those filed under it by + * [recordProfile], and those its room holds where this device is in it. + */ + suspend fun profiles(database: GizaDatabase, confederationId: HexKey): Profiles { + val filed = database.confederationDao().getEventsForConfederation(confederationId) + .filter { it.kind == MetadataEvent.KIND } + .map { GroupSignedEvent.fromEvent(it.toEvent(), chatRoomId = confederationId) } + val rows = (filed + database.groupSignedEventDao().getByChatRoomIdAndKind(confederationId, MetadataEvent.KIND)) + .distinctBy { it.id } + .filter { it.publicKey == confederationId && it.verifies() } + val newest = GroupNostrProfile.newestAmong(rows, confederationId) + return Profiles( + signedIds = rows.map { it.id }.toSet(), + newest = newest?.let { it.signedAt.epochSeconds to it.signedEvent.id }, + newestProfile = newest, + ) + } + // ---- who the confederation is ---------------------------------------------------------------- + + /** + * A formed confederation as this device knows it: its groups and how many of them must act, from + * its record where this device holds a role in it, else from its charter. [fromRecord] says which, + * since only the record is checked against what the groups agreed to (D1). + */ + data class Membership( + val confederation: HexKey, + val name: String, + val groups: List, + val threshold: Int, + val fromRecord: Boolean, + ) { + fun includes(group: HexKey): Boolean = group in groups + + fun othersThan(group: HexKey): List = groups.filter { it != group } + } + + suspend fun membership(database: GizaDatabase, confederationId: HexKey): Membership? { + ConfederationSigningManager.held(database, confederationId)?.let { held -> + return Membership(confederationId, held.confederation.name, held.plan.groups, held.plan.proposal.threshold, fromRecord = true) + } + val charter = database.confederationDao().getCharters(confederationId) + .firstNotNullOfOrNull { ConfederationCharterEvent.parse(it.toEvent()) } ?: return null + val threshold = charter.threshold + ?: statusesOf(database, confederationId).firstOrNull()?.change?.threshold + ?: return null + return Membership(confederationId, charter.name, charter.groups.sorted(), threshold, fromRecord = false) + } + + /** Every formed confederation [group] is a member of, as far as this device knows: by record or charter. */ + suspend fun confederationsOf(database: GizaDatabase, group: HexKey): List { + val recorded = database.confederationCeremonyDao().getConfederationIdsOfGroup(group) + val chartered = database.confederationDao().getChartersNaming(group).mapNotNull { row -> + ConfederationCharterEvent.parse(row.toEvent())?.takeIf { group in it.groups }?.confederation + } + return (recorded + chartered).distinct() + } + + // ---- proposing ------------------------------------------------------------------------------- + + /** What the form says when a profile will not fit one statement to every group (Phase 0, check 3). */ + fun tooLongFor(groups: Int): String = "This profile is too long to send to $groups groups. Shorten its about." + + /** + * Proposes, in [localChatRoom], that its group propose a new profile for [confederationId]: a kind:0 + * with [tags] and [content], editing the newest one this device holds (D2). The group's quorum signs + * one seal per member group and the voucher that makes it the group's endorsement (D5). + */ + suspend fun proposeChange( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + confederationId: HexKey, + tags: Array>, + content: String, + createdAt: Long = Clock.System.now().epochSeconds, + expiresAt: Long = createdAt + ConfederationKinds.DEFAULT_CHANGE_EXPIRY_SECONDS, + ): FrostSigningSession { + val group = localChatRoom.chatRoom.id + val membership = membership(database, confederationId) + ?: throw IllegalStateException("This device holds no record of that confederation") + check(membership.includes(group)) { "This group is not one of ${membership.name}'s" } + val base = profiles(database, confederationId).newest?.second + val rumor = ConfederationProfileStatements.change( + group, membership.othersThan(group), confederationId, membership.threshold, base, tags, content, createdAt, expiresAt, + ) + val change = ConfederationProfileStatements.parseChange(rumor) ?: throw IllegalStateException("That profile cannot be proposed") + return ConfederationManager.proposeStatement( + database, localChatRoom, userPublicKey, rumor, change.addressees, invitation = null, + extra = listOf(ConfederationProfileStatements.voucherTemplate(change, createdAt)), + tooLarge = { tooLongFor(change.groups.size) }, + ) + } + + /** Proposes that this group endorse [changeId], vouching for its kind:0 (D3, D5). */ + suspend fun proposeEndorsement( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + changeId: HexKey, + createdAt: Long = Clock.System.now().epochSeconds, + ): FrostSigningSession { + val group = localChatRoom.chatRoom.id + val (change, invitation) = heldChange(database, changeId, group) + val rumor = ConfederationProfileStatements.endorsement(group, change, createdAt) + return ConfederationManager.proposeStatement( + database, localChatRoom, userPublicKey, rumor, change.othersThan(group), invitation, + extra = listOf(ConfederationProfileStatements.voucherTemplate(change, createdAt)), + tooLarge = { tooLongFor(change.groups.size) }, + ) + } + + /** Proposes that this group object to [changeId], saying [reason]; from the group that proposed it, a withdrawal. */ + suspend fun proposeObjection( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + changeId: HexKey, + reason: String = "", + createdAt: Long = Clock.System.now().epochSeconds, + ): FrostSigningSession { + val group = localChatRoom.chatRoom.id + val (change, invitation) = heldChange(database, changeId, group) + val rumor = ConfederationProfileStatements.objection(group, change, reason, createdAt) + return ConfederationManager.proposeStatement(database, localChatRoom, userPublicKey, rumor, change.othersThan(group), invitation) + } + + /** The change [changeId] and the seal that carried it to [group]: null for a change this group made. */ + private suspend fun heldChange(database: GizaDatabase, changeId: HexKey, group: HexKey): Pair { + val row = database.confederationDao().getEvent(changeId)?.takeIf { it.kind == ConfederationKinds.PROFILE_CHANGE } + ?: throw IllegalStateException("This device does not hold that change") + val change = ConfederationProfileStatements.parseChange(row.toEvent()) ?: throw IllegalStateException("That change is not well formed") + check(change.names(group)) { "That change is not addressed to this group" } + return change to row.sealJson + } + + /** + * The group signed a session over a profile statement: file the statement, and the voucher it + * signed beside the seals, on every device that completes the session. The device that proposed it + * wraps and sends the seals (`InboxReplies.onSigned`). + */ + suspend fun onSigned(database: GizaDatabase, session: FrostSigningSession, rumor: Event, signedEvents: List) { + recordStatement(database, rumor, seal = null, inboxRoomId = session.chatRoomId) + signedEvents.filter { it.kind == ConfederationKinds.VOUCHER && it.pubKey.equals(session.chatRoomId, ignoreCase = true) } + .forEach { voucher -> + recordVoucher(database, voucher) + // Into the confederation's room, where its role holders act on it (D5): from this + // device, if its owner holds one of the group's seats. + ConfederationSigningManager.postVoucher(database, session.userPublicKey, voucher) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileRefusal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileRefusal.kt new file mode 100644 index 00000000..53c79650 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationProfileRefusal.kt @@ -0,0 +1,174 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.verify +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata +import kotlin.time.Clock +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState +import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements +import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements.Change +import mobi.giza.compose.nostr.inbox.InboxSeal + +/** + * What a member's device refuses to sign for its group about a confederation's profile, out loud + * (docs/confederation-profile.md, Phase 2). `ConfederationRefusal` routes a session here when the + * statement it carries is a change, an endorsement or an objection. + * + * A signer reads what it signs, as for the formation's statements: it holds the group's inbox key, + * every seal holds the carried statement, to exactly the confederation's other groups. Then the + * statement itself: a change is this group's, to a profile that can be read, editing the newest + * profile this device holds; an answer answers a change this device can read and that is still + * open; and a change or an endorsement comes with one voucher for exactly its kind:0, which is what + * the confederation's role holders will act on (D5). An objection carries none. + */ +object ConfederationProfileRefusal { + const val UNKNOWN_CONFEDERATION = "Declined: this device holds no record of that confederation" + const val NOT_MEMBER = "Declined: the statement is not addressed to exactly the confederation's groups" + const val THRESHOLD = "Declined: the change states a threshold the confederation was not formed with" + const val UNREADABLE = "Declined: the proposed profile is one nothing could show" + const val STALE = "Declined: the confederation's profile has changed since this was written" + const val EXPIRY = "Declined: the change has expired, or stays open longer than seven days" + const val UNKNOWN_CHANGE = "Declined: this device has not seen the change being answered" + const val CLOSED = "Declined: the change is no longer open" + const val ANSWERED = "Declined: this group has already answered the change" + const val NOT_PROPOSER = "Declined: only the group that proposed a change can withdraw it" + const val VOUCHER = "Declined: the endorsement it signs beside the seals is not for exactly this change" + + /** Leeway on the seven-day ceiling, for a proposer whose clock runs ahead of this one's. */ + private const val CLOCK_SLACK_SECONDS = 60L * 60 + + /** + * Why this device declines to sign [seals] and [extras] for [chatRoomId], given the statement + * [rumor] they carry and the session's [carried] invitation; null if it may be put to its member. + * [read] is the seals already opened and checked by `ConfederationRefusal`. + */ + suspend fun of( + database: GizaDatabase, + chatRoomId: String, + userPublicKey: HexKey, + rumor: Event, + extras: List, + carried: ConfederationRefusal.Carried, + now: Long = Clock.System.now().epochSeconds, + ): String? { + val confederation = ConfederationProfileStatements.confederationOf(rumor) ?: return ConfederationRefusal.SHAPE + val membership = ConfederationProfileManager.membership(database, confederation) ?: return UNKNOWN_CONFEDERATION + if (!membership.includes(chatRoomId)) return NOT_MEMBER + val addressees = rumor.tags.filter { it.size >= 2 && it[0] == "p" }.map { it[1] }.toSet() + if (addressees != membership.othersThan(chatRoomId).toSet()) return NOT_MEMBER + + return when (rumor.kind) { + ConfederationKinds.PROFILE_CHANGE -> { + val change = ConfederationProfileStatements.parseChange(rumor) ?: return ConfederationRefusal.SHAPE + changeRefusal(database, chatRoomId, membership, change, now) ?: voucherRefusal(chatRoomId, change, extras) + } + else -> { + val answer = ConfederationProfileStatements.parseAnswer(rumor) ?: return ConfederationRefusal.SHAPE + val change = changeFor(database, chatRoomId, userPublicKey, answer.changeId, carried) ?: return UNKNOWN_CHANGE + if (!answer.answers(change)) return ConfederationRefusal.SHAPE + val status = ConfederationProfileManager.status(database, change.id, now) ?: return UNKNOWN_CHANGE + when { + answer.isEndorsement -> when { + change.proposingGroup == chatRoomId || status.hasAnswered(chatRoomId) -> ANSWERED + status.state != ConfederationProfileChangeState.OPEN && status.state != ConfederationProfileChangeState.ENDORSED -> CLOSED + else -> voucherRefusal(chatRoomId, change, extras) + } + change.proposingGroup == chatRoomId -> when { + extras.isNotEmpty() -> ConfederationRefusal.SHAPE + status.state != ConfederationProfileChangeState.OPEN && status.state != ConfederationProfileChangeState.ENDORSED -> CLOSED + else -> null + } + else -> when { + extras.isNotEmpty() -> ConfederationRefusal.SHAPE + status.hasAnswered(chatRoomId) -> ANSWERED + status.state != ConfederationProfileChangeState.OPEN && status.state != ConfederationProfileChangeState.ENDORSED -> CLOSED + else -> null + } + } + } + } + } + + /** D2's rules for a change this group proposes. */ + private suspend fun changeRefusal( + database: GizaDatabase, + chatRoomId: String, + membership: ConfederationProfileManager.Membership, + change: Change, + now: Long, + ): String? { + if (change.proposingGroup != chatRoomId) return NOT_MEMBER + if (membership.fromRecord && change.threshold != membership.threshold) return THRESHOLD + if (change.expiresAt <= now) return EXPIRY + if (change.expiresAt > now + ConfederationKinds.MAX_CHANGE_EXPIRY_SECONDS + CLOCK_SLACK_SECONDS) return EXPIRY + if (GroupStatementRefusal.isUnreadableProfile(change.profile.tags, change.profile.content)) return UNREADABLE + // An edit of anything but the newest profile this device holds would undo it. An unknown base + // is only a warning: this device may not have heard the newest profile yet. + val newest = ConfederationProfileManager.profiles(database, change.confederation).newest?.second + if (newest != null && newest != change.base) return STALE + return null + } + + /** Exactly one voucher, last, from this group, for exactly [change]'s kind:0 and expiry. */ + private fun voucherRefusal(chatRoomId: String, change: Change, extras: List): String? { + val voucher = extras.singleOrNull() ?: return VOUCHER + if (!voucher.pubKey.equals(chatRoomId, ignoreCase = true)) return VOUCHER + val parsed = ConfederationProfileStatements.parseVoucher(voucher) ?: return VOUCHER + return if (parsed.vouchesFor(change)) null else VOUCHER + } + + /** + * The change an answer answers: held already, or opened from the invitation the signing proposal + * carried with this device's own inbox key and verified as its author's -- then filed, as the + * inbox would have filed it. + */ + private suspend fun changeFor(database: GizaDatabase, roomId: HexKey, userPublicKey: HexKey, changeId: HexKey, carried: ConfederationRefusal.Carried): Change? { + ConfederationProfileManager.change(database, changeId)?.let { return it } + val seal = carried.invitationJson?.let { Event.fromJsonOrNull(it) }?.takeIf { it.kind == InboxSeal.KIND && it.verify() } ?: return null + val keys = database.inboxKeyDao().getKeys(roomId, userPublicKey).mapNotNull { it.secretKey } + val opened = keys.firstNotNullOfOrNull { InboxSeal.open(seal, it.hexToByteArray()) } ?: return null + val change = ConfederationProfileStatements.parseChange(opened.rumor)?.takeIf { it.id == changeId && it.names(roomId) } ?: return null + ConfederationProfileManager.recordStatement(database, opened.rumor, seal, roomId) + return change + } + + /** + * What a member should read before approving a session over a profile statement: what would + * change, field by field, and who has endorsed it so far. + */ + suspend fun notes(database: GizaDatabase, chatRoomId: String, rumor: Event): List { + val change = ConfederationProfileStatements.parseChange(rumor) + ?: ConfederationProfileStatements.parseAnswer(rumor)?.let { ConfederationProfileManager.change(database, it.changeId) } + ?: return emptyList() + val name = ConfederationProfileManager.membership(database, change.confederation)?.name ?: "the confederation" + val base = ConfederationProfileManager.profiles(database, change.confederation).newestProfile?.metadata + val notes = mutableListOf("A new profile for $name") + notes += differences(base, metadataOf(change.profile)).map { (field, before, after) -> "$field: ${before ?: "(none)"} → ${after ?: "(cleared)"}" } + .ifEmpty { listOf("No field changes") } + notes += "${change.threshold} of ${change.groups.size} groups must endorse it" + ConfederationProfileManager.status(database, change.id)?.let { status -> + notes += "Endorsed so far by " + status.endorsers.map { ConfederationManager.nameOf(database, it, chatRoomId) }.joinToString() + } + return notes + } + + fun metadataOf(profile: Event): UserMetadata? = + MetadataEvent(profile.id, profile.pubKey, profile.createdAt, profile.tags, profile.content, profile.sig).contactMetaData() + + /** The fields a person edits, as (label, before, after), for those that differ. */ + fun differences(before: UserMetadata?, after: UserMetadata?): List> { + fun String?.clean() = this?.takeIf { it.isNotBlank() } + return listOf( + Triple("Name", before?.anyName().clean(), after?.anyName().clean()), + Triple("About", before?.about.clean(), after?.about.clean()), + Triple("Picture", before?.picture.clean(), after?.picture.clean()), + Triple("Website", before?.website.clean(), after?.website.clean()), + Triple("Nip05", before?.nip05.clean(), after?.nip05.clean()), + ).filter { it.second != it.third } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationPublisher.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationPublisher.kt index 9878b90a..f481f9c6 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationPublisher.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationPublisher.kt @@ -56,7 +56,7 @@ class ConfederationPublisher( /** Sends [event] to every relay it should reach. Whether any accepted it. */ suspend fun publish(event: ConfederationEvent): Boolean { - val targets = Relays.eventPublishRelaySet.map { it.url } + val targets = (Relays.eventPublishRelaySet.map { it.url } + repository.extraRelaysFor(event)) .map { it.trim() } .filter { it.startsWith("wss://") || it.startsWith("ws://") } .distinct() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRefusal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRefusal.kt index 177a5ed5..ec8fb0e0 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRefusal.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRefusal.kt @@ -84,7 +84,18 @@ object ConfederationRefusal { /** Whether a session over [events], carrying [carried], is this refusal's to judge. */ fun involves(events: List, carried: Carried?): Boolean = - carried?.rumorJson != null || events.any { ConfederationKinds.isConfederationKind(it.kind) } + carried?.rumorJson != null || events.any { isOwnKind(it.kind) } + + /** + * A kind only a confederation statement's session signs: the public ones a peer might still ask + * for, a profile change's statements asked for bare, and a voucher, which Giza signs only beside + * the seals of the change or endorsement it vouches for (docs/confederation-profile.md, D11). + */ + private fun isOwnKind(kind: Int): Boolean = + ConfederationKinds.isConfederationKind(kind) || kind in ConfederationKinds.PROFILE_CHANGE_KINDS || kind == ConfederationKinds.VOUCHER + + private fun isSealedKind(kind: Int): Boolean = + ConfederationStatements.isStatementKind(kind) || kind in ConfederationKinds.PROFILE_CHANGE_KINDS /** * Why this device, as [userPublicKey], declines to sign [events] for the room [chatRoomId], or @@ -100,12 +111,16 @@ object ConfederationRefusal { now: Long = Clock.System.now().epochSeconds, ): String? { if (!involves(events, carried)) return null - if (events.any { ConfederationKinds.isConfederationKind(it.kind) }) return PUBLIC - if (events.isEmpty() || events.any { it.kind != InboxSeal.KIND }) return SHAPE - val rumor = carried.rumor?.takeIf { ConfederationStatements.isStatementKind(it.kind) } ?: return SHAPE + if (events.any { ConfederationKinds.isConfederationKind(it.kind) || it.kind in ConfederationKinds.PROFILE_CHANGE_KINDS }) return PUBLIC + // The seals, then at most what is signed beside them: a profile change's voucher. + val seals = events.takeWhile { it.kind == InboxSeal.KIND } + val extras = events.drop(seals.size) + if (seals.isEmpty() || extras.any { it.kind != ConfederationKinds.VOUCHER }) return SHAPE + val rumor = carried.rumor?.takeIf { isSealedKind(it.kind) } ?: return SHAPE + if (extras.isNotEmpty() && rumor.kind !in ConfederationKinds.PROFILE_CHANGE_KINDS) return SHAPE if (!rumor.pubKey.equals(chatRoomId, ignoreCase = true)) return NOT_LISTED - val read = when (val result = InboxRefusal.readSealed(database, chatRoomId, userPublicKey, events, manifest, ConfederationStatements::isStatementKind)) { + val read = when (val result = InboxRefusal.readSealed(database, chatRoomId, userPublicKey, seals, manifest, ::isSealedKind)) { is InboxRefusal.Read.Refused -> return if (result.reason == InboxRefusal.REPLY_NO_KEY) CANNOT_READ else SEALS is InboxRefusal.Read.Ok -> result.reply } @@ -113,6 +128,9 @@ object ConfederationRefusal { // Every recipient is a group, reached at the key its own 10044 announced. if (read.manifest.seals.filterIndexed { index, _ -> index != read.manifest.groupCopy }.any { it.announcement == null }) return NO_INBOX if (rumor.createdAt !in (now - STATEMENT_SLACK_SECONDS)..(now + STATEMENT_SLACK_SECONDS)) return TIME + if (rumor.kind in ConfederationKinds.PROFILE_CHANGE_KINDS) { + return ConfederationProfileRefusal.of(database, chatRoomId, userPublicKey, rumor, extras, carried, now) + } return when (rumor.kind) { ConfederationKinds.PROPOSAL -> { @@ -190,6 +208,7 @@ object ConfederationRefusal { val carried = Carried.from(database.confederationDao().getSigning(sessionId)) if (!involves(events, carried)) return emptyList() val rumor = carried.rumor ?: return emptyList() + if (rumor.kind in ConfederationKinds.PROFILE_CHANGE_KINDS) return ConfederationProfileRefusal.notes(database, chatRoomId, rumor) val proposal = ConfederationStatements.parseProposal(rumor) ?: ConfederationStatements.parseAnswer(rumor)?.let { ConfederationManager.proposal(database, it.proposalId) } ?: return emptyList() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt index 6c8f592f..368d95e1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt @@ -40,6 +40,8 @@ import mobi.giza.compose.database.model.MarmotInnerEvent import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder.Plan @@ -82,6 +84,15 @@ object ConfederationSigningManager { const val RESTARTED = "A device restarted while signing, so this attempt cannot finish. Propose it again" + /** A kind:0 asked for without enough of its groups' vouchers (docs/confederation-profile.md, D5). */ + const val THROUGH_GROUPS = "A confederation's profile changes through its groups, and not enough of them have endorsed this one" + + /** A kind:0 older than one the confederation has already signed: relays would keep the newer. */ + const val SUPERSEDED = "The confederation has signed a newer profile since" + + /** Two attempts over the same kind:0: the one whose id sorts first goes on (D6). */ + const val CROSSED = "Another attempt is signing this change" + // ---- what a confederation is on this device ------------------------------------------------ /** Everything this device holds about one confederation, read back from storage. */ @@ -111,7 +122,36 @@ object ConfederationSigningManager { held(database, confederationId)?.plan?.seatsOf(userPublicKey)?.isNotEmpty() == true /** Why this device would not sign [event] for [held]'s confederation, or null. */ - private fun refusalOf(held: Held, event: Event): String? = when { + private suspend fun refusalOf(database: GizaDatabase, held: Held, event: Event): String? = + basicRefusalOf(held, event) ?: if (event.kind == MetadataEvent.KIND) profileRefusalOf(database, held, event) else null + + /** + * A kind:0 is signed only on its groups' word: vouchers from at least `T` member groups, each for + * exactly this kind:0 and not expired, and no newer profile signed since (docs/confederation-profile.md, D5). + */ + private suspend fun profileRefusalOf(database: GizaDatabase, held: Held, event: Event): String? { + if (vouchedGroups(database, held, event.id).size < held.plan.proposal.threshold) return THROUGH_GROUPS + val newest = ConfederationProfileManager.profiles(database, held.confederation.id).newest + if (newest != null && newest.second != event.id && (newest.first > event.createdAt || (newest.first == event.createdAt && newest.second < event.id))) return SUPERSEDED + return null + } + + /** The member groups whose unexpired voucher for [profileId] this device holds. */ + internal suspend fun vouchedGroups(database: GizaDatabase, held: Held, profileId: HexKey, now: Long = Clock.System.now().epochSeconds): Set = + vouchersFor(database, held, profileId, now).map { it.pubKey }.toSet() + + /** The vouchers for [profileId] this device holds, one per member group, unexpired. */ + internal suspend fun vouchersFor(database: GizaDatabase, held: Held, profileId: HexKey, now: Long = Clock.System.now().epochSeconds): List = + database.confederationDao().getEventsForConfederation(held.confederation.id) + .filter { it.kind == ConfederationKinds.VOUCHER } + .map { it.toEvent() } + .filter { voucher -> + val parsed = ConfederationProfileStatements.parseVoucher(voucher) + parsed != null && parsed.profileId == profileId && parsed.expiresAt >= now && voucher.pubKey in held.plan.groups + } + .distinctBy { it.pubKey } + + private fun basicRefusalOf(held: Held, event: Event): String? = when { event.pubKey != held.confederation.id -> "The event is not authored by the confederation" event.kind !in SIGNABLE_KINDS -> "A confederation signs only its profile, its posts and its charter here" event.kind == ConfederationCharterEvent.KIND && !isTrueCharter(held, event) -> @@ -122,10 +162,11 @@ object ConfederationSigningManager { else -> null } - /** A charter names exactly the groups the confederation was formed from, under its name. */ + /** A charter names exactly the groups the confederation was formed from, under its name, and its threshold if it says one. */ private fun isTrueCharter(held: Held, event: Event): Boolean { val charter = ConfederationCharterEvent.parse(event) ?: return false - return charter.groups.toSet() == held.plan.groups.toSet() && charter.name == held.confederation.name + return charter.groups.toSet() == held.plan.groups.toSet() && charter.name == held.confederation.name && + (charter.threshold == null || charter.threshold == held.plan.proposal.threshold) } /** The charter [held]'s confederation would sign: its groups, under its name. */ @@ -133,7 +174,7 @@ object ConfederationSigningManager { val held = held(database, confederationId) ?: return null return Triple( ConfederationCharterEvent.KIND, - ConfederationCharterEvent.assembleTags(held.confederation.name, held.plan.groups), + ConfederationCharterEvent.assembleTags(held.confederation.name, held.plan.groups, held.plan.proposal.threshold), ConfederationCharterEvent.content(held.confederation.name, held.plan.groups.size), ) } @@ -150,13 +191,16 @@ object ConfederationSigningManager { content: String, nostrPrivateKey: ByteArray, createdAt: Long = Clock.System.now().epochSeconds, + /** For a kind:0: the groups' vouchers it is signed on, carried on the proposal (D5). */ + vouchers: List = emptyList(), ): ConfederationSigningAttempt = mutex.withLock { val roomId = localChatRoom.chatRoom.id val held = held(database, roomId) ?: throw IllegalStateException("This device holds no confederation for this room") check(held.plan.seatsOf(userPublicKey).isNotEmpty()) { "Only someone who holds a role in the confederation can propose for it" } val id = EventHasher.hashId(roomId, createdAt, kind, tags, content) val event = Event(id, roomId, createdAt, kind, tags, content, "") - refusalOf(held, event)?.let { throw IllegalArgumentException(it) } + vouchers.forEach { ConfederationProfileManager.recordVoucher(database, it) } + refusalOf(database, held, event)?.let { throw IllegalArgumentException(it) } val attempt = ConfederationSigningAttempt( id = RandomInstance.bytes(32).toHex(), @@ -168,13 +212,66 @@ object ConfederationSigningManager { stage = ConfederationSigningStage.SELECTING, ) database.confederationCeremonyDao().upsertAttempt(attempt) - announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED, "A proposal for the confederation to sign: ${describe(event)}") - broadcast(database, localChatRoom, attempt, ConfederationSigningEvents.PROPOSAL, event.toJson()) - publishAvailability(database, localChatRoom, attempt, held, available = true) + if (event.kind == MetadataEvent.KIND) { + val carried = vouchersFor(database, held, event.id) + announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED, profileLine(database, carried)) + broadcast(database, localChatRoom, attempt, ConfederationSigningEvents.PROPOSAL, event.toJson(), carried.map { arrayOf(ConfederationSigningEvents.VOUCHER_TAG, it.toJson()) }) + publishAvailabilityByGroup(database, localChatRoom, attempt, held, carried.map { it.pubKey }.toSet()) + settleCrossing(database, localChatRoom, held, attempt, event.id) + } else { + announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED, "A proposal for the confederation to sign: ${describe(event)}") + broadcast(database, localChatRoom, attempt, ConfederationSigningEvents.PROPOSAL, event.toJson()) + publishAvailability(database, localChatRoom, attempt, held, available = true) + } advance(database, localChatRoom, attempt.id, nostrPrivateKey) database.confederationCeremonyDao().getAttempt(attempt.id)!! } + /** The line a profile's signing writes in the confederation's room: whose word it is signed on. */ + private suspend fun profileLine(database: GizaDatabase, vouchers: List): String = + "Signing the profile endorsed by " + vouchers.map { ConfederationManager.nameOf(database, it.pubKey) }.joinToString() + + /** + * Two attempts over one kind:0 -- two people in the order who both thought it their turn -- end in + * the one whose id sorts first, on every device; the others are ended out loud (D6). + */ + private suspend fun settleCrossing(database: GizaDatabase, room: LocalChatRoom, held: Held, attempt: ConfederationSigningAttempt, eventId: HexKey) { + val running = database.confederationCeremonyDao().getAttempts(held.confederation.id, attempt.userPublicKey) + .filter { it.isRunning && runCatching { Event.fromJson(it.eventJson).id }.getOrNull() == eventId } + if (running.size < 2) return + val keep = running.minBy { it.id } + running.filter { it.id != keep.id }.forEach { failOut(database, room, it, CROSSED) } + } + + // ---- vouchers -------------------------------------------------------------------------------- + + /** + * Carries [voucher], which this device's group just signed, into the confederation's room for + * [userPublicKey], who holds a seat in that group: what the other role holders act on (D5). + * Several of the group's role holders send the same one; receivers keep one. + */ + suspend fun postVoucher(database: GizaDatabase, userPublicKey: HexKey, voucher: Event) { + val parsed = ConfederationProfileStatements.parseVoucher(voucher) ?: return + val held = held(database, parsed.confederation) ?: return + if (held.plan.seatsOf(userPublicKey).none { it.group == voucher.pubKey }) return + val room = database.chatRoomDao().findChatRoomById(held.confederation.id) ?: return + val createdAt = Clock.System.now().epochSeconds + val content = voucher.toJson() + val tags = emptyArray>() + val id = EventHasher.hashId(userPublicKey, createdAt, ConfederationSigningEvents.VOUCHER, tags, content) + database.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = id, + publicKey = userPublicKey, + kind = ConfederationSigningEvents.VOUCHER, + createdAt = Instant.fromEpochSeconds(createdAt), + tags = tags, + content = content, + chatRoomId = room.chatRoom.id, + ) + ) + } + // ---- inbound --------------------------------------------------------------------------- suspend fun process( @@ -184,6 +281,15 @@ object ConfederationSigningManager { userPublicKey: HexKey, nostrPrivateKey: ByteArray, ) = mutex.withLock { + if (innerEvent.kind == ConfederationSigningEvents.VOUCHER) { + // From a role holder of the group that signed it; kept if it is that group's own. + val held = held(database, localChatRoom.chatRoom.id) ?: return@withLock + val voucher = Event.fromJsonOrNull(innerEvent.content) ?: return@withLock + if (held.plan.seatsOf(innerEvent.pubKey).none { it.group == voucher.pubKey }) return@withLock + if (ConfederationProfileStatements.parseVoucher(voucher)?.confederation != held.confederation.id) return@withLock + ConfederationProfileManager.recordVoucher(database, voucher) + return@withLock + } val attemptId = ConfederationSigningEvents.parseSessionId(innerEvent.tags) ?: return@withLock val held = held(database, localChatRoom.chatRoom.id) ?: run { logger.i("Signing message for ${localChatRoom.chatRoom.id.take(12)}, which is no confederation here; leaving it stored") @@ -221,7 +327,8 @@ object ConfederationSigningManager { userPublicKey = userPublicKey, eventJson = event.toJson(), ) - val refusal = refusalOf(held, event) + ConfederationSigningEvents.parseVouchers(innerEvent.tags).forEach { ConfederationProfileManager.recordVoucher(database, it) } + val refusal = refusalOf(database, held, event) if (refusal != null) { // Declined out loud, as a FROST member declines what it cannot check: this person's // roles will not sign, and the group can tell that from a phone in a pocket. @@ -231,11 +338,35 @@ object ConfederationSigningManager { return database.confederationCeremonyDao().getAttempt(attemptId) } database.confederationCeremonyDao().upsertAttempt(attempt) + if (event.kind == MetadataEvent.KIND) { + // Nobody is asked: each seat's group has already said, by its voucher or by not giving + // one (docs/confederation-profile.md, D5). + val vouchers = vouchersFor(database, held, event.id) + announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED, profileLine(database, vouchers)) + publishAvailabilityByGroup(database, localChatRoom, attempt, held, vouchers.map { it.pubKey }.toSet()) + replayStoredMessages(database, held, attempt) + settleCrossing(database, localChatRoom, held, attempt, event.id) + return database.confederationCeremonyDao().getAttempt(attemptId) + } announce(database, attempt, ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED, "A proposal for the confederation to sign: ${describe(event)}") replayStoredMessages(database, held, attempt) return database.confederationCeremonyDao().getAttempt(attemptId) } + /** + * This person's answer for each of their seats, from what their groups said: yes where the seat's + * group vouched for the event, no where it did not. Says it as approved or declined, so nobody + * is asked. + */ + private suspend fun publishAvailabilityByGroup(database: GizaDatabase, room: LocalChatRoom, attempt: ConfederationSigningAttempt, held: Held, vouched: Set) { + if (own(database, attempt, ConfederationSigningEvents.AVAILABILITY) != null) return + val seats = held.plan.seatsOf(attempt.userPublicKey) + val answers = seats.associate { it.group to if (it.group in vouched) ConfederationSigningEvents.YES else ConfederationSigningEvents.NO } + val now = Clock.System.now() + update(database, attempt) { if (answers.values.any { it == ConfederationSigningEvents.YES }) it.copy(approvedAt = now) else it.copy(declinedAt = now) } + publishOwn(database, room, attempt, ConfederationSigningEvents.AVAILABILITY, ConfederationRitualEvents.encodeByGroup(answers)) + } + /** * Files one message. Per-person messages only from a person holding a role, with a value for * exactly their roles; the session only from the proposer; a failure from anyone with a role. @@ -273,7 +404,7 @@ object ConfederationSigningManager { val room = database.chatRoomDao().findChatRoomById(attempt.confederationId) ?: return@withLock val held = held(database, attempt.confederationId) ?: return@withLock // Checked again: what is signed has to be what this device would sign now. - refusalOf(held, Event.fromJson(attempt.eventJson))?.let { why -> + refusalOf(database, held, Event.fromJson(attempt.eventJson))?.let { why -> update(database, attempt) { it.copy(declinedAt = Clock.System.now(), failureReason = why) } publishAvailability(database, room, attempt, held, available = false) return@withLock @@ -434,6 +565,15 @@ object ConfederationSigningManager { ConfederationManager.record(database, signed) if (attempt.proposerPublicKey == attempt.userPublicKey) database.confederationDao().markOwn(signed.id, attempt.id) } + // A profile its groups decided: filed under the confederation beside the change it came from, + // and owed to relays by the device that started the signing (docs/confederation-profile.md, D7). + if (signed.kind == MetadataEvent.KIND) { + val changeId = vouchersFor(database, held, signed.id, now = 0).firstNotNullOfOrNull { ConfederationProfileStatements.parseVoucher(it)?.changeId } + ConfederationProfileManager.recordProfile(database, signed, changeId) + // Owed by every device that signed it, not only the one that started it: the same event + // from several devices is one event to a relay, and nobody waits on one phone (D7, as built). + database.confederationDao().markOwn(signed.id, attempt.id) + } logger.i("Confederation ${held.confederation.id.take(12)} signed ${signed.id.take(8)}") } @@ -504,8 +644,15 @@ object ConfederationSigningManager { } /** Queues a rumor for the confederation's Marmot room, encrypted to the room as a group event. */ - private suspend fun broadcast(database: GizaDatabase, room: LocalChatRoom, attempt: ConfederationSigningAttempt, kind: Kind, content: String) { - val tags = arrayOf(ConfederationSigningEvents.sessionTag(attempt.id)) + private suspend fun broadcast( + database: GizaDatabase, + room: LocalChatRoom, + attempt: ConfederationSigningAttempt, + kind: Kind, + content: String, + extraTags: List> = emptyList(), + ) { + val tags = (listOf(ConfederationSigningEvents.sessionTag(attempt.id)) + extraTags).toTypedArray() val createdAt = Clock.System.now().epochSeconds val id = EventHasher.hashId(attempt.userPublicKey, createdAt, kind, tags, content) database.marmotInnerEventDao().upsert( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt index 24dffd7c..6ff91b1b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt @@ -98,6 +98,13 @@ object GroupInboxManager { database.groupInboxDao().markOpened(wrap.id, key.generation) return null } + // A formed confederation's groups deciding its profile: the confederation's to file, as + // the formation's statements are (docs/confederation-profile.md, D2 and D3). + if (rumor.kind in ConfederationKinds.PROFILE_CHANGE_KINDS) { + ConfederationProfileManager.recordStatement(database, rumor, opened.seal, roomId) + database.groupInboxDao().markOpened(wrap.id, key.generation) + return null + } // NIP-40: a message already past its expiry is not filed; the ledger keeps the wrap's id // but not its words (docs/disappearing-messages.md, D6). if (DisappearingMessages.expirationOf(rumor.tags, rumor.createdAt)?.let { DisappearingMessages.isExpired(it, Clock.System.now().epochSeconds) } == true) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt index d596aa7b..a35a345b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt @@ -19,6 +19,7 @@ import mobi.giza.compose.database.model.GroupInboxPublication import mobi.giza.compose.database.model.InboxKeyState import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.nostr.Relays +import mobi.giza.compose.nostr.confederation.ConfederationKinds import mobi.giza.compose.nostr.confederation.ConfederationStatements import mobi.giza.compose.nostr.inbox.InboxAnnouncement import mobi.giza.compose.nostr.inbox.InboxConversation @@ -190,9 +191,13 @@ object InboxReplies { return } val (key, manifest) = opened - // In the order the proposal fixed, which is the manifest's. + // In the order the proposal fixed, which is the manifest's. Only the seals: a confederation's + // profile change signs a voucher in the same batch, after them, which goes nowhere from here + // (docs/confederation-profile.md, D5). val signedById = seals.associateBy { it.id } - val ordered = database.frostSigningSessionDao().getItems(session.id).sortedBy { it.itemIndex }.map { signedById[it.eventId] } + val ordered = database.frostSigningSessionDao().getItems(session.id).sortedBy { it.itemIndex } + .filter { Event.fromJsonOrNull(it.unsignedEventJson)?.kind == InboxSeal.KIND } + .map { signedById[it.eventId] } if (ordered.size != manifest.seals.size) return // The rumor's lifetime, read from the group's own copy: each wrap asks relays to drop it a @@ -228,7 +233,7 @@ object InboxReplies { val rumor = InboxSeal.rumorInside(copy.content, InboxReplyManifest.selfConversationKey(key.secretKey!!.hexToByteArray()), roomId) ?: return // A confederation's statement is the confederation's to file, not a conversation in the // inbox (docs/confederation-without-coordinator.md, D7). - if (ConfederationStatements.isStatementKind(rumor.kind)) return + if (ConfederationStatements.isStatementKind(rumor.kind) || rumor.kind in ConfederationKinds.PROFILE_CHANGE_KINDS) return val participants = InboxConversation.participantsOf(rumor, roomId) database.groupInboxDao().insertMessage( GroupInboxMessage( @@ -250,6 +255,11 @@ object InboxReplies { } /** Where [publicKey] reads private mail: their 10050, as this device last heard it. */ + /** The inbox relays [publicKey] has announced, as this device has heard them; nothing if none. */ + internal suspend fun announcedRelaysOf(database: GizaDatabase, publicKey: HexKey): List = + database.nostrEventDao().getNostrEventByPublicKeyAndKind(publicKey, InboxAnnouncement.RELAYS_KIND) + ?.toEvent()?.let { InboxAnnouncement.announcedRelaysOf(it) }.orEmpty() + private suspend fun relaysOf(database: GizaDatabase, publicKey: HexKey): List = database.nostrEventDao().getNostrEventByPublicKeyAndKind(publicKey, InboxAnnouncement.RELAYS_KIND) ?.toEvent()?.let { InboxAnnouncement.announcedRelaysOf(it) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt index f2ab0043..6aafb590 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt @@ -3,6 +3,7 @@ package mobi.giza.compose.managers import co.touchlab.kermit.Logger import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import com.vitorpamplona.quartz.nip01Core.core.toHexKey import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair import com.vitorpamplona.quartz.nip01Core.relay.commands.toRelay.ReqCmd @@ -234,9 +235,13 @@ class LiveSubscriptionManager( * public; what groups say to each other about forming one goes between their inboxes * (docs/confederation-without-coordinator.md, D12). */ - internal fun confederationFilters(roomIds: List): List = + internal fun confederationFilters(roomIds: List, confederationIds: List = emptyList()): List = roomIds.chunked(MAX_CONFEDERATION_IDS).map { chunk -> Filter(kinds = listOf(ConfederationKinds.CHARTER), tags = mapOf("p" to chunk), limit = INITIAL_GROUP_HISTORY_LIMIT) + } + confederationIds.distinct().sorted().chunked(MAX_CONFEDERATION_IDS).map { chunk -> + // Each known confederation's own profile: how every member of every member group + // hears it changed (docs/confederation-profile.md, D7). Replaceable, so one each. + Filter(kinds = listOf(MetadataEvent.KIND), authors = chunk, limit = chunk.size) } /** @@ -423,8 +428,10 @@ class LiveSubscriptionManager( */ @OptIn(FlowPreview::class) private suspend fun followConfederations(publicKey: HexKey, keyPair: KeyPair, repository: ConfederationRepository) { - chatRepository.observeChatRoomListByPublicKey(publicKey).map(::confederationRoomIdsFrom).distinctUntilChanged() - .map(::confederationFilters) + combine( + chatRepository.observeChatRoomListByPublicKey(publicKey).map(::confederationRoomIdsFrom).distinctUntilChanged(), + repository.observeKnownConfederations(), + ) { roomIds, confederationIds -> confederationFilters(roomIds, confederationIds) } .distinctUntilChanged() .debounce(GROUP_CHANGE_DEBOUNCE) .collectLatest { filters -> diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationCharterEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationCharterEvent.kt index c8f6ac95..b9804dc1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationCharterEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationCharterEvent.kt @@ -4,6 +4,7 @@ import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.Kind import mobi.giza.compose.nostr.confederation.tags.ConfederationGroupTag +import mobi.giza.compose.nostr.confederation.tags.ConfederationThresholdTag /** * A confederation saying, with its own key, which groups it is made of (docs/confederation.md, @@ -16,6 +17,7 @@ import mobi.giza.compose.nostr.confederation.tags.ConfederationGroupTag * tags: * ["p", , "", "group"] one per member group * ["name", ] + * ["threshold", ""] how many groups must act; absent on early charters * ["alt", ...] * ``` * @@ -31,11 +33,17 @@ object ConfederationCharterEvent { const val NAME_TAG = "name" const val ALT_TAG = "alt" - data class Charter(val id: HexKey, val confederation: HexKey, val name: String, val groups: List) + /** + * [threshold] is how many of the groups must act for the confederation to sign: what a device + * that holds no record of the confederation needs to tell whether a change to its profile has + * been endorsed (docs/confederation-profile.md, D1). Null on a charter signed before it was said. + */ + data class Charter(val id: HexKey, val confederation: HexKey, val name: String, val groups: List, val threshold: Int? = null) - fun assembleTags(name: String, groups: List): Array> = ( - groups.sorted().map { ConfederationGroupTag.assemble(it, null) } + listOf( + fun assembleTags(name: String, groups: List, threshold: Int? = null): Array> = ( + groups.sorted().map { ConfederationGroupTag.assemble(it, null) } + listOfNotNull( arrayOf(NAME_TAG, name), + threshold?.let { ConfederationThresholdTag.assemble(it.toString()) }, arrayOf(ALT_TAG, ALT), ) ).toTypedArray() @@ -48,6 +56,11 @@ object ConfederationCharterEvent { if (groups.size !in ConfederationKinds.MIN_GROUPS..ConfederationKinds.MAX_GROUPS) return null if (groups.any { !ConfederationKinds.isPublicKey(it) } || groups.toSet().size != groups.size) return null val name = event.tags.filter { it.size >= 2 && it[0] == NAME_TAG }.singleOrNull()?.get(1)?.takeIf { it.isNotBlank() } ?: return null - Charter(event.id, event.pubKey, name, groups) + val thresholds = event.tags.filter { it.size >= 2 && it[0] == ConfederationThresholdTag.TAG_NAME } + if (thresholds.size > 1) return null + val threshold = thresholds.singleOrNull()?.let { tag -> + tag[1].toIntOrNull()?.takeIf { it.toString() == tag[1] && it in ConfederationKinds.MIN_GROUPS..groups.size } ?: return null + } + Charter(event.id, event.pubKey, name, groups, threshold) }.getOrNull() } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationKinds.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationKinds.kt index 854735d5..fd9b788f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationKinds.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationKinds.kt @@ -25,6 +25,29 @@ object ConfederationKinds { val ALL: Set = setOf(PROPOSAL, ACCEPTANCE, REJECTION, WITHDRAWAL, CHARTER) + /** + * A formed confederation's groups deciding its profile (docs/confederation-profile.md): a group + * proposing a change, and every other group endorsing or objecting to it. Rumors only, sealed + * group to group like the proposal's statements; never on a relay, so never in [ALL]. + */ + const val PROFILE_CHANGE: Kind = 9435 + const val ENDORSEMENT: Kind = 9436 + const val OBJECTION: Kind = 9437 + + /** + * A group vouching, with its own signature, for one event its confederation is to sign: signed in + * the same session as the group's 9435 or 9436, and carried only into the confederation's room, + * where it is a role holder's consent (D5). Never published, so never in [ALL]. + */ + const val VOUCHER: Kind = 9438 + + /** The statements of a profile change. The voucher is not one: it is signed, not sealed. */ + val PROFILE_CHANGE_KINDS: Set = setOf(PROFILE_CHANGE, ENDORSEMENT, OBJECTION) + + /** How long a profile change stays open by default, and at most (D2). */ + const val DEFAULT_CHANGE_EXPIRY_SECONDS: Long = 3L * 24 * 60 * 60 + const val MAX_CHANGE_EXPIRY_SECONDS: Long = 7L * 24 * 60 * 60 + /** The answers a group can give, and the one a proposing group can take back. */ val ANSWERS: Set = setOf(ACCEPTANCE, REJECTION, WITHDRAWAL) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileChangeStatus.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileChangeStatus.kt new file mode 100644 index 00000000..067a392d --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileChangeStatus.kt @@ -0,0 +1,115 @@ +package mobi.giza.compose.nostr.confederation + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements.Answer +import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements.Change +import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements.Voucher + +/** Where a proposed change to a confederation's profile stands (docs/confederation-profile.md, D4). */ +enum class ConfederationProfileChangeState { + /** Waiting on groups to answer. */ + OPEN, + + /** Enough groups endorsed it: the confederation's signing is under way. */ + ENDORSED, + + /** The confederation signed it, and this device holds it signed. */ + PUBLISHED, + + /** A newer profile is held: relays keep only the newest, so this one would change nothing. */ + SUPERSEDED, + + /** So many groups objected that it can no longer reach the threshold. */ + DECLINED, + + /** Its proposing group took it back. */ + WITHDRAWN, + + /** Its expiry passed before it was signed. */ + EXPIRED, +} + +/** What each group has said about a change. */ +enum class ConfederationProfileAnswer { PROPOSED, ENDORSED, OBJECTED, WAITING } + +/** + * A change and everything said about it, and the state that follows, computed whenever it is read: + * every device that holds the same statements computes the same thing. + * + * One answer counts per group: its first, by `created_at` and then id, and only if dated by the + * change's expiry, so whether a change was endorsed in time does not depend on when a device heard + * of it (docs/confederation.md, D8). The proposing group's own 9435 is its endorsement, and its 9437 + * a withdrawal. + */ +data class ConfederationProfileChangeStatus( + val change: Change, + /** Each answering group's counted answer. */ + val answers: Map, + /** Each group's voucher for this kind:0, where this device holds one. */ + val vouchers: Map, + val state: ConfederationProfileChangeState, +) { + /** The groups that endorsed it, the proposer first. */ + val endorsers: List + get() = change.groups.filter { answerOf(it) == ConfederationProfileAnswer.PROPOSED || answerOf(it) == ConfederationProfileAnswer.ENDORSED } + + val objectors: List get() = change.groups.filter { answerOf(it) == ConfederationProfileAnswer.OBJECTED } + + fun answerOf(group: HexKey): ConfederationProfileAnswer = when { + group == change.proposingGroup -> ConfederationProfileAnswer.PROPOSED + else -> when (answers[group]?.isEndorsement) { + true -> ConfederationProfileAnswer.ENDORSED + false -> ConfederationProfileAnswer.OBJECTED + null -> ConfederationProfileAnswer.WAITING + } + } + + fun hasAnswered(group: HexKey): Boolean = group == change.proposingGroup || group in answers + + /** The proposer's withdrawal, if it made one. */ + val withdrawal: Answer? get() = answers[change.proposingGroup] + + val isOpen: Boolean get() = state == ConfederationProfileChangeState.OPEN + + companion object { + /** + * The status of [change] given what this device holds: [answers] and [vouchers] about it, the + * newest signed kind:0 of the confederation it holds ([newestProfile], by `created_at` and id), + * and whether it holds [change]'s own kind:0 signed ([published]). + */ + fun of( + change: Change, + answers: List, + vouchers: List, + newestProfile: Pair?, + published: Boolean, + now: Long, + ): ConfederationProfileChangeStatus { + val counted = answers + .filter { it.answers(change) && it.createdAt <= change.expiresAt } + .filter { it.group != change.proposingGroup || !it.isEndorsement } + .sortedWith(compareBy({ it.createdAt }, { it.id })) + .distinctBy { it.group } + .associateBy { it.group } + val vouched = vouchers.filter { it.vouchesFor(change) }.distinctBy { it.group }.associateBy { it.group } + + val endorsing = 1 + counted.values.count { it.isEndorsement && it.group != change.proposingGroup } + val objecting = counted.values.count { !it.isEndorsement && it.group != change.proposingGroup } + val groups = change.groups.size + val newer = newestProfile?.let { (createdAt, id) -> + id != change.profileId && (createdAt > change.createdAt || (createdAt == change.createdAt && id < change.profileId)) + } == true + + val state = when { + published -> ConfederationProfileChangeState.PUBLISHED + counted.containsKey(change.proposingGroup) -> ConfederationProfileChangeState.WITHDRAWN + newer -> ConfederationProfileChangeState.SUPERSEDED + change.isExpiredAt(now) -> ConfederationProfileChangeState.EXPIRED + endorsing >= change.threshold -> ConfederationProfileChangeState.ENDORSED + groups - objecting < change.threshold -> ConfederationProfileChangeState.DECLINED + else -> ConfederationProfileChangeState.OPEN + } + return ConfederationProfileChangeStatus(change, counted, vouched, state) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileStatements.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileStatements.kt new file mode 100644 index 00000000..2907f955 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileStatements.kt @@ -0,0 +1,272 @@ +package mobi.giza.compose.nostr.confederation + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler +import mobi.giza.compose.nostr.confederation.tags.ConfederationThresholdTag + +/** + * What a formed confederation's groups say to each other about its profile + * (docs/confederation-profile.md, D2, D3 and D5). + * + * ``` + * 9435 rumor a group proposing a new profile + * content: the unsigned kind:0, as JSON, its id included and its signature empty + * tags: ["p", ] …, ["confederation", ], + * ["threshold", ""], ["base", ] (absent when none), + * ["expiration", ""] + * 9436 rumor a group endorsing it content: empty + * 9437 rumor a group objecting to it, or content: a reason, or nothing + * the proposing group withdrawing it + * tags (both): ["p", ] …, ["confederation", ], + * ["e", ], ["profile", ] + * 9438 signed a group vouching for the kind:0, signed by its quorum in the same session as its + * 9435 or 9436 and never published + * tags: ["confederation", ], ["profile", ], ["e", ], + * ["expiration", ""] + * ``` + * + * The kind:0 is dated when it is proposed and its `created_at` is the 9435's own, so its id is + * fixed before anyone answers, and every answer, voucher and signing attempt names that id. + * + * Parsing is all or nothing, as for the formation's statements: whether the groups agree is + * [ConfederationProfileChangeStatus]'s to compute and whether a device signs is the refusal's. + */ +object ConfederationProfileStatements { + const val CONFEDERATION_TAG = "confederation" + const val BASE_TAG = "base" + const val PROFILE_TAG = "profile" + const val EXPIRATION_TAG = "expiration" + + /** A proposed change, as [parseChange] reads it from its rumor. */ + data class Change( + /** The rumor's id: what every answer and voucher names. */ + val id: HexKey, + val proposingGroup: HexKey, + val createdAt: Long, + val confederation: HexKey, + /** Every other member group, in the order the tags give them. */ + val addressees: List, + /** How many groups must endorse it: the confederation's outer threshold, as the proposer states it. */ + val threshold: Int, + /** The kind:0 this edits, or null for the confederation's first. */ + val base: HexKey?, + val expiresAt: Long, + /** The kind:0 the confederation would sign: unsigned, its id computed. */ + val profile: Event, + ) { + /** Every member group, the proposer first. */ + val groups: List get() = listOf(proposingGroup) + addressees + + val profileId: HexKey get() = profile.id + + fun names(group: HexKey): Boolean = group in groups + + fun othersThan(group: HexKey): List = groups.filter { it != group } + + fun isExpiredAt(epochSeconds: Long): Boolean = epochSeconds > expiresAt + } + + /** An endorsement, an objection, or the proposer's withdrawal. */ + data class Answer( + val id: HexKey, + val kind: Kind, + val group: HexKey, + val createdAt: Long, + val changeId: HexKey, + val confederation: HexKey, + val profileId: HexKey, + val addressees: List, + /** An objection's or a withdrawal's reason; empty for an endorsement. */ + val reason: String, + ) { + val isEndorsement: Boolean get() = kind == ConfederationKinds.ENDORSEMENT + + /** Whether this answers [change], addressed to every other group it names. */ + fun answers(change: Change): Boolean = + changeId == change.id && profileId == change.profileId && confederation == change.confederation && + change.names(group) && addressees.toSet() == change.othersThan(group).toSet() + } + + /** A group's voucher, as [parseVoucher] reads it from the signed event. */ + data class Voucher( + val id: HexKey, + val group: HexKey, + val createdAt: Long, + val confederation: HexKey, + val profileId: HexKey, + val changeId: HexKey, + val expiresAt: Long, + ) { + /** Whether this vouches for exactly [change]'s kind:0. */ + fun vouchesFor(change: Change): Boolean = + changeId == change.id && profileId == change.profileId && confederation == change.confederation && + expiresAt == change.expiresAt && change.names(group) + } + + // ---- building -------------------------------------------------------------------------------- + + /** The unsigned kind:0 [confederation] would sign, with its id. */ + fun unsignedProfile(confederation: HexKey, createdAt: Long, tags: Array>, content: String): Event = + Event(EventHasher.hashId(confederation, createdAt, MetadataEvent.KIND, tags, content), confederation, createdAt, MetadataEvent.KIND, tags, content, "") + + /** + * The 9435 [group] would send to [others], proposing that [confederation] sign a kind:0 with + * [profileTags] and [profileContent], dated [createdAt] like the rumor itself. + */ + fun change( + group: HexKey, + others: List, + confederation: HexKey, + threshold: Int, + base: HexKey?, + profileTags: Array>, + profileContent: String, + createdAt: Long, + expiresAt: Long, + ): Event { + val profile = unsignedProfile(confederation, createdAt, profileTags, profileContent) + val tags = others.filter { it != group }.distinct().map { arrayOf("p", it) } + listOfNotNull( + arrayOf(CONFEDERATION_TAG, confederation), + ConfederationThresholdTag.assemble(threshold.toString()), + base?.let { arrayOf(BASE_TAG, it) }, + arrayOf(EXPIRATION_TAG, expiresAt.toString()), + ) + return rumor(group, ConfederationKinds.PROFILE_CHANGE, tags.toTypedArray(), profile.toJson(), createdAt) + } + + fun endorsement(group: HexKey, change: Change, createdAt: Long): Event = + answer(group, ConfederationKinds.ENDORSEMENT, change, "", createdAt) + + /** [group] objecting to [change]; from its proposing group, a withdrawal. */ + fun objection(group: HexKey, change: Change, reason: String, createdAt: Long): Event = + answer(group, ConfederationKinds.OBJECTION, change, reason, createdAt) + + private fun answer(group: HexKey, kind: Kind, change: Change, content: String, createdAt: Long): Event { + val tags = change.othersThan(group).map { arrayOf("p", it) } + listOf( + arrayOf(CONFEDERATION_TAG, change.confederation), + arrayOf("e", change.id), + arrayOf(PROFILE_TAG, change.profileId), + ) + return rumor(group, kind, tags.toTypedArray(), content, createdAt) + } + + /** What a group signs beside its seals to vouch for [change]'s kind:0. The signer sets the author. */ + fun voucherTemplate(change: Change, createdAt: Long): EventTemplate = EventTemplate( + createdAt, + ConfederationKinds.VOUCHER, + arrayOf( + arrayOf(CONFEDERATION_TAG, change.confederation), + arrayOf(PROFILE_TAG, change.profileId), + arrayOf("e", change.id), + arrayOf(EXPIRATION_TAG, change.expiresAt.toString()), + ), + "", + ) + + private fun rumor(author: HexKey, kind: Kind, tags: Array>, content: String, createdAt: Long): Event = + RumorAssembler.assembleRumor(pubKey = author, ev = EventTemplate(createdAt, kind, tags, content)) + + // ---- reading --------------------------------------------------------------------------------- + + /** The change in [rumor], or null if it is not a well-formed one. */ + fun parseChange(rumor: Event): Change? = runCatching { + if (rumor.kind != ConfederationKinds.PROFILE_CHANGE) return null + if (!ConfederationKinds.isPublicKey(rumor.pubKey)) return null + val addressees = addresseesOf(rumor.tags) ?: return null + if (rumor.pubKey in addressees) return null + val groups = addressees.size + 1 + if (groups !in ConfederationKinds.MIN_GROUPS..ConfederationKinds.MAX_SUPERGROUP_GROUPS) return null + + val confederation = single(rumor.tags, CONFEDERATION_TAG)?.takeIf(ConfederationKinds::isPublicKey) ?: return null + if (confederation == rumor.pubKey || confederation in addressees) return null + val thresholdText = single(rumor.tags, ConfederationThresholdTag.TAG_NAME) ?: return null + val threshold = thresholdText.toIntOrNull()?.takeIf { it.toString() == thresholdText } ?: return null + if (threshold !in ConfederationKinds.MIN_GROUPS..groups) return null + val bases = rumor.tags.filter { it.isNotEmpty() && it[0] == BASE_TAG } + if (bases.size > 1) return null + val base = bases.singleOrNull()?.let { it.getOrNull(1)?.takeIf(ConfederationKinds::isHex32) ?: return null } + val expiresAt = single(rumor.tags, EXPIRATION_TAG)?.toLongOrNull() ?: return null + if (expiresAt <= rumor.createdAt) return null + if (rumor.tags.any { it.isNotEmpty() && it[0] == "e" }) return null + + val profile = Event.fromJsonOrNull(rumor.content) ?: return null + if (profile.kind != MetadataEvent.KIND || profile.pubKey != confederation) return null + if (profile.createdAt != rumor.createdAt || profile.sig.isNotEmpty()) return null + if (profile.id != EventHasher.hashId(profile.pubKey, profile.createdAt, profile.kind, profile.tags, profile.content)) return null + + Change( + id = rumor.id, + proposingGroup = rumor.pubKey, + createdAt = rumor.createdAt, + confederation = confederation, + addressees = addressees, + threshold = threshold, + base = base, + expiresAt = expiresAt, + profile = profile, + ) + }.getOrNull() + + /** The endorsement or objection in [rumor], or null if it is not a well-formed one. */ + fun parseAnswer(rumor: Event): Answer? = runCatching { + if (rumor.kind != ConfederationKinds.ENDORSEMENT && rumor.kind != ConfederationKinds.OBJECTION) return null + if (!ConfederationKinds.isPublicKey(rumor.pubKey)) return null + val addressees = addresseesOf(rumor.tags) ?: return null + if (rumor.pubKey in addressees) return null + val confederation = single(rumor.tags, CONFEDERATION_TAG)?.takeIf(ConfederationKinds::isPublicKey) ?: return null + val changeId = single(rumor.tags, "e")?.takeIf(ConfederationKinds::isHex32) ?: return null + val profileId = single(rumor.tags, PROFILE_TAG)?.takeIf(ConfederationKinds::isHex32) ?: return null + if (rumor.kind == ConfederationKinds.ENDORSEMENT && rumor.content.isNotEmpty()) return null + Answer( + id = rumor.id, + kind = rumor.kind, + group = rumor.pubKey, + createdAt = rumor.createdAt, + changeId = changeId, + confederation = confederation, + profileId = profileId, + addressees = addressees, + reason = rumor.content, + ) + }.getOrNull() + + /** + * The voucher [event] is, or null if it is not a well-formed one. Reads its shape only: whether + * its group's key signed it is for the caller to check against the group it names. + */ + fun parseVoucher(event: Event): Voucher? = runCatching { + if (event.kind != ConfederationKinds.VOUCHER || event.content.isNotEmpty()) return null + if (!ConfederationKinds.isPublicKey(event.pubKey)) return null + if (event.tags.size != 4) return null + val confederation = single(event.tags, CONFEDERATION_TAG)?.takeIf(ConfederationKinds::isPublicKey) ?: return null + val profileId = single(event.tags, PROFILE_TAG)?.takeIf(ConfederationKinds::isHex32) ?: return null + val changeId = single(event.tags, "e")?.takeIf(ConfederationKinds::isHex32) ?: return null + val expiresAt = single(event.tags, EXPIRATION_TAG)?.toLongOrNull() ?: return null + Voucher(event.id, event.pubKey, event.createdAt, confederation, profileId, changeId, expiresAt) + }.getOrNull() + + /** The change a statement is about: its own id for a change, its `e` for an answer. */ + fun changeIdOf(rumor: Event): HexKey? = when (rumor.kind) { + ConfederationKinds.PROFILE_CHANGE -> parseChange(rumor)?.id + else -> parseAnswer(rumor)?.changeId + } + + /** The confederation a statement or voucher names, read without parsing the rest. */ + fun confederationOf(event: Event): HexKey? = single(event.tags, CONFEDERATION_TAG) + + private fun addresseesOf(tags: Array>): List? { + val named = tags.filter { it.isNotEmpty() && it[0] == "p" }.map { it.getOrNull(1) ?: return null } + if (named.isEmpty()) return null + if (named.any { !ConfederationKinds.isPublicKey(it) }) return null + if (named.toSet().size != named.size) return null + return named + } + + private fun single(tags: Array>, name: String): String? = + tags.filter { it.size >= 2 && it[0] == name }.singleOrNull()?.get(1) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationSigningEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationSigningEvents.kt index e1ef3989..09c1c467 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationSigningEvents.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationSigningEvents.kt @@ -21,6 +21,7 @@ import kotlinx.serialization.json.put * | 30393 | each selected | per role: its public nonce | * | 30394 | each selected | per role: its confirmation of the transcript and the event | * | 30395 | each selected | per role: its member partial | + * | 30396 | a role holder | a group's signed voucher for a kind:0 (docs/confederation-profile.md) | * | 30399 | anyone | failure, with a reason | * * Only the selection needs a coordinator: approvals arrive in a different order on every device, @@ -38,7 +39,21 @@ object ConfederationSigningEvents { const val PARTIALS: Kind = 30395 const val FAILURE: Kind = 30399 - val ALL: Set = setOf(PROPOSAL, AVAILABILITY, SESSION, NONCES, CONFIRMATIONS, PARTIALS, FAILURE) + /** + * A group's voucher for a kind:0 its confederation is to sign, carried into the confederation's + * room by the group's role holders once the group has signed it (docs/confederation-profile.md, + * D5). No attempt yet, so no session tag: it is what an attempt is started from. + */ + const val VOUCHER: Kind = 30396 + + /** On a 30390 over a kind:0: one signed 9438 per group that vouched for it. */ + const val VOUCHER_TAG = "voucher" + + val ALL: Set = setOf(PROPOSAL, AVAILABILITY, SESSION, NONCES, CONFIRMATIONS, PARTIALS, VOUCHER, FAILURE) + + /** The vouchers a 30390 carries, as the events they are. */ + fun parseVouchers(tags: Array>): List = + tags.filter { it.size >= 2 && it[0] == VOUCHER_TAG }.mapNotNull { com.vitorpamplona.quartz.nip01Core.core.Event.fromJsonOrNull(it[1]) } /** Sent once per person, a value per role. */ val PER_PERSON: Set = setOf(AVAILABILITY, NONCES, CONFIRMATIONS, PARTIALS) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationClassifier.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationClassifier.kt index c13494b2..2b9bc0d6 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationClassifier.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationClassifier.kt @@ -57,6 +57,9 @@ object NotificationClassifier { Line.TYPE_CONFEDERATION_ACCEPTED, Line.TYPE_CONFEDERATION_REJECTED, Line.TYPE_CONFEDERATION_FORMED, + // Another group asking this one about the confederation's profile, and the profile it ends in. + Line.TYPE_CONFEDERATION_PROFILE_PROPOSED, + Line.TYPE_CONFEDERATION_PROFILE_PUBLISHED, Line.TYPE_INBOX_KEY_COMPLETE, Line.TYPE_MEMBER_ADDED, Line.TYPE_MEMBER_LEFT, @@ -102,6 +105,8 @@ object NotificationClassifier { Line.TYPE_CONFEDERATION_CEREMONY_FAILED, Line.TYPE_CONFEDERATION_SIGNING_PROPOSED, Line.TYPE_CONFEDERATION_SIGNING_FAILED, + Line.TYPE_CONFEDERATION_PROFILE_ENDORSED, + Line.TYPE_CONFEDERATION_PROFILE_OBJECTED, Line.TYPE_INBOX_KEY_STARTED, Line.TYPE_INBOX_KEY_FAILED, Line.TYPE_INBOX_ANNOUNCED, 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 181c54e3..99c3ce9f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -161,6 +161,16 @@ interface ChatRepository { */ suspend fun keyCeremonyOfRoom(chatRoomId: String): mobi.giza.compose.ui.view.state.KeyCeremonyLink? = null + /** This room's confederation, said in its groups, if it is one's room. docs/confederation-profile.md, D9. */ + suspend fun confederationRoomInfo(chatRoomId: String): mobi.giza.compose.ui.view.state.ConfederationRoomInfo? = null + + /** + * The formed confederations the group of [chatRoomId] is a member of, as (id, name), by record or + * charter: what the group's screen lists, each opening the confederation's own screen. + * docs/confederation-profile.md, D1. + */ + suspend fun memberConfederations(chatRoomId: String): List> = emptyList() + /** The confederation whose room [chatRoomId] is, by name, if its record verifies here. docs/confederation.md, Phase 13. */ suspend fun confederationOfRoom(chatRoomId: String): String? = null diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt index 95bcc68c..2563a088 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt @@ -16,6 +16,10 @@ import mobi.giza.compose.database.model.FrostSigningSession import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.managers.ConfederationManager import mobi.giza.compose.nostr.confederation.ConfederationStatus +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus +import mobi.giza.compose.managers.ConfederationProfileManager +import mobi.giza.compose.nostr.GroupNostrProfile +import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata /** * The confederation's events on this device, for the relay layer and the screens @@ -110,6 +114,70 @@ interface ConfederationRepository { /** The confederations [groupPublicKey] is part of, on this device. docs/confederation.md, Phase 12. */ fun observeConfederationsOf(groupPublicKey: HexKey): Flow> + /** + * Every change to [confederationId]'s profile this device holds, newest first, with where each + * stands, as it changes. docs/confederation-profile.md, D4. + */ + fun observeProfileChanges(confederationId: HexKey): Flow> = flowOf(emptyList()) + + /** One change to a confederation's profile, as it changes; null while this device does not hold it. */ + fun observeProfileChange(changeId: HexKey): Flow = flowOf(null) + + /** Every formed confederation this device knows of, by record or charter: whose kind:0 the relays are asked for (D7). */ + fun observeKnownConfederations(): Flow> = flowOf(emptyList()) + + /** Relays an owed event goes to besides the public ones: a confederation's profile, to each member group's inbox relays. */ + suspend fun extraRelaysFor(event: ConfederationEvent): List = emptyList() + + /** A formed confederation as this device knows it: by its record, or by its charter. docs/confederation-profile.md, D1. */ + suspend fun membership(confederationId: HexKey): ConfederationProfileManager.Membership? = null + + /** The newest profile the confederation has signed that this device holds, as it changes. */ + fun observeProfile(confederationId: HexKey): Flow = flowOf(null) + + /** Who holds the confederation's roles, by group: empty on a device that holds no record of it. */ + suspend fun roleHolders(confederationId: HexKey): Map> = emptyMap() + + /** The proposal the confederation was formed from, where this device holds it. */ + suspend fun formingProposalOf(confederationId: HexKey): HexKey? = null + + /** Whether this device holds the confederation's own room. */ + suspend fun holdsRoomOf(confederationId: HexKey): Boolean = false + + /** + * Why [userPublicKey] cannot put a change to [confederationId]'s profile to the group of + * [chatRoomId], or null when they can (D2). + */ + suspend fun profileChangeProblem(chatRoomId: String, userPublicKey: HexKey, confederationId: HexKey): ProfileChangeProblem? = + ProfileChangeProblem.NoRecord + + /** The member groups of [confederationId] this device is in whose statements [userPublicKey] can put to them. */ + suspend fun proposingGroupsFor(userPublicKey: HexKey, confederationId: HexKey): List = emptyList() + + /** What the change edits, read where this device holds it: the base, else the newest profile held. */ + suspend fun profileBaseOf(changeId: HexKey): UserMetadata? = null + + suspend fun proposeProfileChange( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + confederationId: HexKey, + tags: Array>, + content: String, + ): FrostSigningSession = throw UnsupportedOperationException("No confederation here") + + suspend fun proposeProfileEndorsement(localChatRoom: LocalChatRoom, userPublicKey: HexKey, changeId: HexKey): FrostSigningSession = + throw UnsupportedOperationException("No confederation here") + + /** An objection; from the group that proposed the change, its withdrawal. */ + suspend fun proposeProfileObjection(localChatRoom: LocalChatRoom, userPublicKey: HexKey, changeId: HexKey, reason: String): FrostSigningSession = + throw UnsupportedOperationException("No confederation here") + + /** A session in [chatRoomId]'s group over an answer to [changeId] that has not finished, if any: one at a time. */ + fun observePendingProfileAnswer(chatRoomId: String, changeId: HexKey): Flow = flowOf(null) + + /** A session in [chatRoomId]'s group proposing a change to [confederationId]'s profile that has not finished, if any. */ + fun observePendingProfileChange(chatRoomId: String, confederationId: HexKey): Flow = flowOf(null) + companion object { /** Holds nothing and proposes nothing: for screens and tests with no confederation behind them. */ val NO_OP_CONFEDERATION_REPOSITORY: ConfederationRepository = object : ConfederationRepository { @@ -155,3 +223,24 @@ interface ConfederationRepository { } } } + +/** Why a member cannot put a change to a confederation's profile to their group (docs/confederation-profile.md, D2). */ +sealed interface ProfileChangeProblem { + /** This device knows neither the confederation's record nor its charter. */ + data object NoRecord : ProfileChangeProblem + + /** This group is not one of the confederation's. */ + data object NotMember : ProfileChangeProblem + + /** The room is closed, or this device holds no share of the group's key. */ + data object CannotSign : ProfileChangeProblem + + /** The member is not one of the group's admins. */ + data object NotAdmin : ProfileChangeProblem + + /** This device does not hold the inbox key the group has announced. */ + data object NoInbox : ProfileChangeProblem + + /** Another member group has announced no inbox, so it cannot be asked. */ + data class GroupWithoutInbox(val name: String) : ProfileChangeProblem +} 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 10f1a59c..f69b23aa 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt @@ -168,6 +168,13 @@ object ProposedEvent { ConfederationKinds.WITHDRAWAL -> Summary(label = "Withdrawing a confederation proposal", detail = event.content) + // What makes a group's change to its confederation's profile, or its endorsement of + // one, something the confederation can act on (docs/confederation-profile.md, D5). + ConfederationKinds.VOUCHER -> Summary( + label = "Endorsing a new profile for a confederation", + detail = "Lets the confederation's admins sign it once enough groups endorse it", + ) + // 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 16b0f121..1000a949 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 @@ -36,6 +36,7 @@ import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxSettingsRoute import mobi.giza.compose.ui.view.state.InboxRowSummary import androidx.compose.material.icons.filled.Mail import mobi.giza.compose.ui.composable.navigation.routes.ConfederationsRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRoute import mobi.giza.compose.ui.composable.navigation.routes.GroupDmSetupRoute import mobi.giza.compose.ui.view.state.GroupDmRow import mobi.giza.compose.resources.open_the_groups_messages @@ -48,6 +49,10 @@ import mobi.giza.compose.resources.only_its_admins_read_them import mobi.giza.compose.ExperimentalFeatures import androidx.compose.material.icons.filled.Hub import mobi.giza.compose.resources.confederations +import mobi.giza.compose.resources.member_of_confederation +import mobi.giza.compose.resources.group_and_its_role_holders +import mobi.giza.compose.resources.admins_who_joined_later_are_not_here +import mobi.giza.compose.resources.open_the_confederation import mobi.giza.compose.resources.no_confederations_yet import mobi.giza.compose.resources.one_confederation_proposal import mobi.giza.compose.resources.n_confederation_proposals @@ -832,6 +837,30 @@ fun ChatRoomDetailScreen( text = stringResource(Res.string.this_is_the_confederations_room, name), style = MaterialTheme.typography.bodyMedium, ) + // Its groups, and who holds each one's roles: the room's + // members are people, and this says whose. docs/confederation-profile.md, D9. + chatRoomDetailUIState.confederationRoom?.let { room -> + room.groups.forEach { (group, holders) -> + Text( + text = stringResource(Res.string.group_and_its_role_holders, group, holders.joinToString(", ")), + style = MaterialTheme.typography.bodySmall, + ) + } + Text( + text = stringResource(Res.string.admins_who_joined_later_are_not_here, room.name), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + room.homeGroupId?.let { home -> + TextButton(onClick = { + onNavigateToRoute.invoke( + ConfederationRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = home, confederationId = room.confederationId) + ) + }) { + Text(stringResource(Res.string.open_the_confederation)) + } + } + } // Its charter, which it signs itself (Phase 15). if (chatRoomDetailUIState.canSignAsConfederation && identityCanSign) { Text( @@ -857,6 +886,26 @@ fun ChatRoomDetailScreen( } } + // Each formed confederation this group is in, which opens it: its + // profile, its groups, and the changes to its profile. + // docs/confederation-profile.md, D1. + chatRoomDetailUIState.memberConfederations.forEach { (confederationId, name) -> + item { + MemberConfederationRow( + name = name, + onClick = { + onNavigateToRoute.invoke( + ConfederationRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + confederationId = confederationId, + ) + ) + }, + ) + } + } + if (ExperimentalFeatures.confederation) { item { ConfederationsRow( @@ -1450,6 +1499,9 @@ fun ChatRoomDetailScreen( adminLabel.takeIf { localParticipant.participant.adminAt != null }, (if (beingRotatedAway) shareBeingRotatedAwayLabel else shareLabel) .takeIf { memberPublicKey in chatRoomDetailUIState.shareHolders }, + // In a confederation's room: the groups this person holds roles for. + chatRoomDetailUIState.confederationRoom?.groupsOfMember?.get(memberPublicKey) + ?.takeIf { it.isNotEmpty() }?.joinToString(", "), ) Column { if (roles.isNotEmpty()) { @@ -2349,6 +2401,24 @@ private fun GroupInboxRow( } /** The row that opens a group's confederations: how many proposals name it. docs/confederation.md. */ +/** A formed confederation this group is a member of. docs/confederation-profile.md, D1. */ +@Composable +private fun MemberConfederationRow( + name: String, + onClick: () -> Unit, +) { + Card( + modifier = Modifier.fillMaxWidth(), + onClick = onClick + ) { + ListItem( + leadingContent = { Icon(Icons.Default.Hub, contentDescription = Decorative) }, + trailingContent = { Icon(Icons.Default.ChevronRight, contentDescription = Decorative) }, + headlineContent = { Text(text = stringResource(Res.string.member_of_confederation, name), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + ) + } +} + @Composable private fun ConfederationsRow( proposalCount: Int, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt index 9d1ab5bb..ce1816ab 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt @@ -54,11 +54,15 @@ import mobi.giza.compose.repository.DkgRepository import mobi.giza.compose.repository.FrostSigningRepository import mobi.giza.compose.repository.NostrRepository import mobi.giza.compose.ui.composable.navigation.routes.ConfederationSigningRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProfileChangeRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRoute import mobi.giza.compose.ui.composable.navigation.routes.ChatRoomDetailRoute import mobi.giza.compose.ui.composable.navigation.routes.DkgRitualRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRitualRoute import mobi.giza.compose.ui.view.state.KeyCeremonyLink import mobi.giza.compose.resources.open_the_key_ceremony +import mobi.giza.compose.resources.open_the_confederation +import mobi.giza.compose.resources.the_key_ceremony_for_is_complete import mobi.giza.compose.resources.this_room_runs_a_key_ceremony import mobi.giza.compose.resources.this_room_waits_for_you_to_join import mobi.giza.compose.ui.composable.navigation.routes.ProposalListRoute @@ -208,8 +212,16 @@ fun ChatRoomMessagingScreen( KeyCeremonyBanner( link = link, onOpen = { + // Once the ceremony has made the confederation, the way from here + // is to it (docs/confederation-profile.md, D10). + val formed = link.formed + val home = formed?.homeGroupId onNavigateToRoute.invoke( - ConfederationRitualRoute(activeUserPublicKey = activeUserPublicKey, proposalId = link.proposalId) + if (formed != null && home != null) { + ConfederationRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = home, confederationId = formed.confederationId) + } else { + ConfederationRitualRoute(activeUserPublicKey = activeUserPublicKey, proposalId = link.proposalId) + } ) }, ) @@ -240,6 +252,16 @@ fun ChatRoomMessagingScreen( ConfederationSigningRoute(activeUserPublicKey = activeUserPublicKey, attemptId = attemptId) ) }, + onOpenConfederationProfileChange = { changeId -> + onNavigateToRoute.invoke( + ConfederationProfileChangeRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, changeId = changeId) + ) + }, + onOpenConfederation = { confederationId -> + onNavigateToRoute.invoke( + ConfederationRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, confederationId = confederationId) + ) + }, onOpenSigning = { sessionId -> onNavigateToRoute.invoke( proposalDestination( @@ -281,163 +303,168 @@ fun ChatRoomMessagingScreen( // the ime inset already covers the navigation bar area this row is // separately reserving. Getting the combination right wants a device // with a keyboard open, not a compiler. - Column( - modifier = Modifier.fillMaxWidth() - .background(BottomAppBarDefaults.containerColor) - .navigationBarsPadding() - ) { - // An armed composer has to be impossible to miss. The whole risk - // of this feature is somebody sending to the room what they meant - // for one person, or the reverse, and by the time either is on the - // wire it cannot be taken back. Hence three signals at once: the - // chip, the placeholder, and the tinted field. - val directMessageRecipient = chatMessageListViewModel.directMessageRecipient + // A key ceremony's room once the ceremony has made its confederation: + // anything typed here would reach the founding people as people, which + // is what the confederation's groups are for (docs/confederation-profile.md, D10). + if (chatRoomDetailUIState.keyCeremony?.formed == null) { + Column( + modifier = Modifier.fillMaxWidth() + .background(BottomAppBarDefaults.containerColor) + .navigationBarsPadding() + ) { + // An armed composer has to be impossible to miss. The whole risk + // of this feature is somebody sending to the room what they meant + // for one person, or the reverse, and by the time either is on the + // wire it cannot be taken back. Hence three signals at once: the + // chip, the placeholder, and the tinted field. + val directMessageRecipient = chatMessageListViewModel.directMessageRecipient - if (directMessageRecipient != null) { - Row( - modifier = Modifier - .fillMaxWidth() - .background(MaterialTheme.colorScheme.primaryContainer) - .padding(horizontal = MaterialTheme.spacing.containerPadding, vertical = MaterialTheme.spacing.space75), - horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - verticalAlignment = Alignment.CenterVertically - ) { - Icon( - Icons.Default.Lock, - contentDescription = Decorative, - modifier = Modifier.size(16.dp), - tint = MaterialTheme.colorScheme.onPrimaryContainer - ) - - Text( - modifier = Modifier.weight(1f), - text = stringResource(Res.string.private_to, chatMessageListViewModel.nameFor(directMessageRecipient.participantPublicKey)), - color = MaterialTheme.colorScheme.onPrimaryContainer, - style = MaterialTheme.typography.labelMedium - ) - - // The one way back to the room, and it has to be one tap. - IconButton( - onClick = { chatMessageListViewModel.cancelDirectMessage() } + if (directMessageRecipient != null) { + Row( + modifier = Modifier + .fillMaxWidth() + .background(MaterialTheme.colorScheme.primaryContainer) + .padding(horizontal = MaterialTheme.spacing.containerPadding, vertical = MaterialTheme.spacing.space75), + horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + verticalAlignment = Alignment.CenterVertically ) { Icon( - Icons.Default.Close, - contentDescription = "Send to the whole group instead", + Icons.Default.Lock, + contentDescription = Decorative, + modifier = Modifier.size(16.dp), tint = MaterialTheme.colorScheme.onPrimaryContainer ) + + Text( + modifier = Modifier.weight(1f), + text = stringResource(Res.string.private_to, chatMessageListViewModel.nameFor(directMessageRecipient.participantPublicKey)), + color = MaterialTheme.colorScheme.onPrimaryContainer, + style = MaterialTheme.typography.labelMedium + ) + + // The one way back to the room, and it has to be one tap. + IconButton( + onClick = { chatMessageListViewModel.cancelDirectMessage() } + ) { + Icon( + Icons.Default.Close, + contentDescription = "Send to the whole group instead", + tint = MaterialTheme.colorScheme.onPrimaryContainer + ) + } } } - } - Box( - modifier = Modifier.fillMaxWidth() - ) { - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = textFieldState, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent, - focusedContainerColor = if (directMessageRecipient != null) { - MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.3f) - } else { - Color.Transparent - }, - unfocusedContainerColor = if (directMessageRecipient != null) { - MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.3f) - } else { - Color.Transparent - } - ), - placeholder = { - Text( - text = if (directMessageRecipient != null) { - stringResource(Res.string.private_message_to, chatMessageListViewModel.nameFor(directMessageRecipient.participantPublicKey)) + Box( + modifier = Modifier.fillMaxWidth() + ) { + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + state = textFieldState, + colors = OutlinedTextFieldDefaults.colors( + focusedBorderColor = Color.Transparent, + unfocusedBorderColor = Color.Transparent, + disabledBorderColor = Color.Transparent, + focusedContainerColor = if (directMessageRecipient != null) { + MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.3f) } else { - stringResource(Res.string.say_what_now) + Color.Transparent + }, + unfocusedContainerColor = if (directMessageRecipient != null) { + MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.3f) + } else { + Color.Transparent } - ) - }, - trailingIcon = { - if (textFieldState.text.isEmpty()) { - IconButton( - onClick = { - + ), + placeholder = { + Text( + text = if (directMessageRecipient != null) { + stringResource(Res.string.private_message_to, chatMessageListViewModel.nameFor(directMessageRecipient.participantPublicKey)) + } else { + stringResource(Res.string.say_what_now) } - ) { - Icon( - Icons.Default.Mic, - contentDescription = "Voice" - ) - } + ) + }, + trailingIcon = { + if (textFieldState.text.isEmpty()) { + IconButton( + onClick = { - } else { - IconButton( - onClick = { - chatMessageListViewModel.sendMessage( - textFieldState = textFieldState + } + ) { + Icon( + Icons.Default.Mic, + contentDescription = "Voice" + ) + } + + } else { + IconButton( + onClick = { + chatMessageListViewModel.sendMessage( + textFieldState = textFieldState + ) + } + ) { + Icon( + Icons.AutoMirrored.Filled.Send, + contentDescription = "Send" ) } - ) { - Icon( - Icons.AutoMirrored.Filled.Send, - contentDescription = "Send" - ) } } - } - ) - } + ) + } - // Row( - // modifier = Modifier.padding(4.dp), - // horizontalArrangement = Arrangement.spacedBy(4.dp) - // ) { - // IconButton( - // onClick = { - // - // } - // ) { - // Icon( - // Icons.Default.InsertEmoticon, - // contentDescription = "Add emoji" - // ) - // } - // - // IconButton( - // onClick = { - // - // } - // ) { - // Icon( - // Icons.Default.AlternateEmail, - // contentDescription = "Mention profile" - // ) - // } - // - // IconButton( - // onClick = { - // - // } - // ) { - // Icon( - // Icons.Default.Collections, - // contentDescription = "Attach media" - // ) - // } - // - // IconButton( - // onClick = { - // - // } - // ) { - // Icon( - // Icons.Default.LocationOn, - // contentDescription = "Send location" - // ) - // } - // } + // Row( + // modifier = Modifier.padding(4.dp), + // horizontalArrangement = Arrangement.spacedBy(4.dp) + // ) { + // IconButton( + // onClick = { + // + // } + // ) { + // Icon( + // Icons.Default.InsertEmoticon, + // contentDescription = "Add emoji" + // ) + // } + // + // IconButton( + // onClick = { + // + // } + // ) { + // Icon( + // Icons.Default.AlternateEmail, + // contentDescription = "Mention profile" + // ) + // } + // + // IconButton( + // onClick = { + // + // } + // ) { + // Icon( + // Icons.Default.Collections, + // contentDescription = "Attach media" + // ) + // } + // + // IconButton( + // onClick = { + // + // } + // ) { + // Icon( + // Icons.Default.LocationOn, + // contentDescription = "Send location" + // ) + // } + // } + } } } } @@ -567,11 +594,12 @@ private fun KeyCeremonyBanner(link: KeyCeremonyLink, onOpen: () -> Unit) { Icon(Icons.Default.Key, contentDescription = Decorative) Text( modifier = Modifier.weight(1f).padding(vertical = MaterialTheme.spacing.compactPadding), - text = stringResource(if (link.joined) Res.string.this_room_runs_a_key_ceremony else Res.string.this_room_waits_for_you_to_join), + text = link.formed?.let { stringResource(Res.string.the_key_ceremony_for_is_complete, it.name) } + ?: stringResource(if (link.joined) Res.string.this_room_runs_a_key_ceremony else Res.string.this_room_waits_for_you_to_join), style = MaterialTheme.typography.bodyMedium, ) TextButton(onClick = onOpen) { - Text(stringResource(Res.string.open_the_key_ceremony)) + Text(stringResource(if (link.formed?.homeGroupId != null) Res.string.open_the_confederation else Res.string.open_the_key_ceremony)) } } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileChangeScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileChangeScreen.kt new file mode 100644 index 00000000..491ce713 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileChangeScreen.kt @@ -0,0 +1,295 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.input.TextFieldLineLimits +import androidx.compose.foundation.text.input.rememberTextFieldState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Block +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.HourglassEmpty +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Instant +import mobi.giza.compose.extensions.toFormattedTimeAndDateString +import mobi.giza.compose.nostr.confederation.ConfederationProfileAnswer +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.about +import mobi.giza.compose.resources.answer_endorsed +import mobi.giza.compose.resources.answer_objected +import mobi.giza.compose.resources.answer_proposed +import mobi.giza.compose.resources.answer_waiting +import mobi.giza.compose.resources.being_signed_waiting_on +import mobi.giza.compose.resources.confederation_groups +import mobi.giza.compose.resources.confederation_proposed_by +import mobi.giza.compose.resources.could_not_ask_the_group_to_answer +import mobi.giza.compose.resources.endorse +import mobi.giza.compose.resources.endorsing_lets_the_confederation_sign +import mobi.giza.compose.resources.n_of_m_endorsements +import mobi.giza.compose.resources.name +import mobi.giza.compose.resources.no_field_changes +import mobi.giza.compose.resources.nostr_address +import mobi.giza.compose.resources.object_to_the_change +import mobi.giza.compose.resources.open_the_signing_session +import mobi.giza.compose.resources.open_until +import mobi.giza.compose.resources.picture_url +import mobi.giza.compose.resources.profile_change +import mobi.giza.compose.resources.profile_field_becomes +import mobi.giza.compose.resources.profile_field_empty +import mobi.giza.compose.resources.profile_field_was +import mobi.giza.compose.resources.reason_optional +import mobi.giza.compose.resources.this_device_does_not_hold_that_change +import mobi.giza.compose.resources.waiting_for_the_group_to_sign_its_answer +import mobi.giza.compose.resources.website +import mobi.giza.compose.resources.withdraw_the_change +import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.Decorative +import mobi.giza.compose.ui.composable.widgets.EmptyState +import mobi.giza.compose.ui.composable.widgets.ErrorState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.composable.widgets.rememberNotifier +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.ConfederationProfileChangeViewModel +import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState +import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState.FieldName +import org.jetbrains.compose.resources.stringResource + +/** + * One proposed change to a confederation's profile, seen from one of its groups + * (docs/confederation-profile.md, D3): what it would change, field by field, how every group has + * answered, and this group's answer. Answering is a group signature, so each button opens a signing + * session and the screen goes to it. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ConfederationProfileChangeScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + changeId: HexKey, + initialUIState: ConfederationProfileChangeUIState = ConfederationProfileChangeUIState.Loading, + chatRepository: ChatRepository, + confederationRepository: ConfederationRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val viewModel: ConfederationProfileChangeViewModel = viewModel( + factory = ConfederationProfileChangeViewModel.factory( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + changeId = changeId, + initialUIState = initialUIState, + chatRepository = chatRepository, + confederationRepository = confederationRepository, + ) + ) + LaunchedEffect(true) { + if (initialUIState == ConfederationProfileChangeUIState.Loading) viewModel.initiate() + } + + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotAnswer = stringResource(Res.string.could_not_ask_the_group_to_answer) + val identityCanSign = LocalCanSign.current + val reasonField = rememberTextFieldState() + val state by viewModel.uiState.collectAsState() + val toSession: (String) -> Unit = { sessionId -> + onNavigateToRoute(FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId)) + } + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + modifier = Modifier.imePadding(), + topBar = { + TopAppBar( + title = { Text(text = stringResource(Res.string.profile_change), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + ) { padding -> + ScreenStateTransition(state) { uiState -> + when (val current = uiState) { + is ConfederationProfileChangeUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = current.message, onRetry = null) + + ConfederationProfileChangeUIState.Loading -> LoadingDataIndicator(modifier = Modifier.padding(padding)) + + ConfederationProfileChangeUIState.NotHeld -> EmptyState( + modifier = Modifier.padding(padding), + message = stringResource(Res.string.this_device_does_not_hold_that_change), + ) + + is ConfederationProfileChangeUIState.Loaded -> Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + val change = current.status.change + val nameOf = { key: HexKey -> current.names[key] ?: key.take(12) } + + Text(text = current.confederationName, style = MaterialTheme.typography.headlineSmall) + Text(text = changeStateLabel(current.status.state), style = MaterialTheme.typography.labelLarge) + Text(text = stringResource(Res.string.confederation_proposed_by, nameOf(change.proposingGroup))) + Text(text = stringResource(Res.string.n_of_m_endorsements, current.status.endorsers.size, change.threshold)) + Text( + text = stringResource(Res.string.open_until, Instant.fromEpochSeconds(change.expiresAt).toFormattedTimeAndDateString()), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + // What it would change. + HorizontalDivider() + if (current.differences.isEmpty()) { + Text(stringResource(Res.string.no_field_changes)) + } + current.differences.forEach { field -> + val empty = stringResource(Res.string.profile_field_empty) + ListItem( + leadingContent = { Icon(Icons.Default.Edit, contentDescription = Decorative) }, + headlineContent = { Text(fieldLabel(field.name)) }, + supportingContent = { + Column { + Text( + text = stringResource(Res.string.profile_field_was, field.before ?: empty), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text(text = stringResource(Res.string.profile_field_becomes, field.after ?: empty)) + } + }, + ) + } + + // How every group has answered. + HorizontalDivider() + Text(text = stringResource(Res.string.confederation_groups), style = MaterialTheme.typography.titleSmall) + change.groups.forEach { group -> + val answer = current.status.answerOf(group) + ListItem( + leadingContent = { + Icon( + imageVector = when (answer) { + ConfederationProfileAnswer.PROPOSED, ConfederationProfileAnswer.ENDORSED -> Icons.Default.CheckCircle + ConfederationProfileAnswer.OBJECTED -> Icons.Default.Block + ConfederationProfileAnswer.WAITING -> Icons.Default.HourglassEmpty + }, + contentDescription = Decorative, + ) + }, + headlineContent = { Text(text = nameOf(group), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + supportingContent = { + Text( + stringResource( + when (answer) { + ConfederationProfileAnswer.PROPOSED -> Res.string.answer_proposed + ConfederationProfileAnswer.ENDORSED -> Res.string.answer_endorsed + ConfederationProfileAnswer.OBJECTED -> Res.string.answer_objected + ConfederationProfileAnswer.WAITING -> Res.string.answer_waiting + } + ) + (current.status.answers[group]?.reason?.takeIf { it.isNotBlank() }?.let { ": $it" } ?: "") + ) + }, + ) + } + + // Once enough groups have endorsed it: who the signing is still waiting on. + if (current.status.state == ConfederationProfileChangeState.ENDORSED) { + val unvouched = current.status.endorsers.filter { it !in current.status.vouchers.keys } + if (unvouched.isNotEmpty()) { + Text( + text = stringResource(Res.string.being_signed_waiting_on, unvouched.joinToString { nameOf(it) }), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + current.pendingSessionId?.let { sessionId -> + HorizontalDivider() + Text(text = stringResource(Res.string.waiting_for_the_group_to_sign_its_answer)) + TextButton(onClick = { toSession(sessionId) }) { Text(stringResource(Res.string.open_the_signing_session)) } + } + + if (current.canEndorseOrObject && identityCanSign) { + HorizontalDivider() + Text( + text = stringResource(Res.string.endorsing_lets_the_confederation_sign), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Button( + modifier = Modifier.fillMaxWidth(), + enabled = !current.isActing, + onClick = { viewModel.endorse(onSuccess = toSession, onFailure = { notify(couldNotAnswer) }) }, + ) { Text(stringResource(Res.string.endorse)) } + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + state = reasonField, + label = { Text(stringResource(Res.string.reason_optional)) }, + lineLimits = TextFieldLineLimits.SingleLine, + ) + OutlinedButton( + modifier = Modifier.fillMaxWidth(), + enabled = !current.isActing, + onClick = { viewModel.objectTo(reasonField.text.toString(), onSuccess = toSession, onFailure = { notify(couldNotAnswer) }) }, + ) { Text(stringResource(Res.string.object_to_the_change)) } + } + + if (current.canWithdraw && identityCanSign) { + HorizontalDivider() + OutlinedButton( + modifier = Modifier.fillMaxWidth(), + enabled = !current.isActing, + onClick = { viewModel.objectTo("", onSuccess = toSession, onFailure = { notify(couldNotAnswer) }) }, + ) { Text(stringResource(Res.string.withdraw_the_change)) } + } + } + } + } + } +} + +@Composable +private fun fieldLabel(field: FieldName): String = stringResource( + when (field) { + FieldName.NAME -> Res.string.name + FieldName.ABOUT -> Res.string.about + FieldName.PICTURE -> Res.string.picture_url + FieldName.WEBSITE -> Res.string.website + FieldName.NIP05 -> Res.string.nostr_address + } +) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationScreen.kt new file mode 100644 index 00000000..3ba909ac --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationScreen.kt @@ -0,0 +1,328 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ChevronRight +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.Groups +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import mobi.giza.compose.extensions.toFormattedTimeAndDateString +import mobi.giza.compose.extensions.toNpub +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.repository.ProfileChangeProblem +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.change_declined +import mobi.giza.compose.resources.change_endorsed +import mobi.giza.compose.resources.change_expired +import mobi.giza.compose.resources.change_open +import mobi.giza.compose.resources.change_published +import mobi.giza.compose.resources.change_superseded +import mobi.giza.compose.resources.change_withdrawn +import mobi.giza.compose.resources.confederation_groups +import mobi.giza.compose.resources.confederation_groups_to_act +import mobi.giza.compose.resources.confederation_has_no_profile_yet +import mobi.giza.compose.resources.confederation_profile +import mobi.giza.compose.resources.confederation_proposed_by +import mobi.giza.compose.resources.edit_the_confederations_profile +import mobi.giza.compose.resources.how_it_was_formed +import mobi.giza.compose.resources.n_admins_hold_its_key +import mobi.giza.compose.resources.n_of_m_endorsements +import mobi.giza.compose.resources.no_name_on_this_profile +import mobi.giza.compose.resources.no_profile_changes_yet +import mobi.giza.compose.resources.only_admins_see_profile_changes +import mobi.giza.compose.resources.open_the_confederations_room +import mobi.giza.compose.resources.open_the_signing_session +import mobi.giza.compose.resources.profile_changes +import mobi.giza.compose.resources.profile_problem_cannot_sign +import mobi.giza.compose.resources.profile_problem_group_without_inbox +import mobi.giza.compose.resources.profile_problem_no_inbox +import mobi.giza.compose.resources.profile_problem_no_record +import mobi.giza.compose.resources.profile_problem_not_admin +import mobi.giza.compose.resources.profile_problem_not_member +import mobi.giza.compose.resources.this_device_knows_nothing_of_that_confederation +import mobi.giza.compose.resources.waiting_for_the_group_to_sign_its_answer +import mobi.giza.compose.ui.composable.navigation.routes.ChatRoomMessagingRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProfileChangeRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProposalRoute +import mobi.giza.compose.ui.composable.navigation.routes.EditConfederationProfileRoute +import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.Decorative +import mobi.giza.compose.ui.composable.widgets.EmptyState +import mobi.giza.compose.ui.composable.widgets.ErrorState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.composable.widgets.profile.ProfileAvatar +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.ConfederationViewModel +import mobi.giza.compose.ui.view.state.ConfederationUIState +import org.jetbrains.compose.resources.stringResource + +/** + * A formed confederation, seen from one of its member groups (docs/confederation-profile.md, D1): + * its profile, the groups it is made of, and the changes to its profile, with the way to propose one. + * + * Every member of a member group can open it. Members who are not admins hold none of the groups' + * statements, so for them it shows what is public -- the charter's groups and the signed profile -- + * and says why the changes are missing rather than showing none. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ConfederationScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + confederationId: HexKey, + initialConfederationUIState: ConfederationUIState = ConfederationUIState.Loading, + chatRepository: ChatRepository, + confederationRepository: ConfederationRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val viewModel: ConfederationViewModel = viewModel( + factory = ConfederationViewModel.factory( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + confederationId = confederationId, + initialConfederationUIState = initialConfederationUIState, + chatRepository = chatRepository, + confederationRepository = confederationRepository, + ) + ) + LaunchedEffect(true) { + if (initialConfederationUIState == ConfederationUIState.Loading) viewModel.initiate() + } + val state by viewModel.uiState.collectAsState() + val identityCanSign = LocalCanSign.current + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(text = (state as? ConfederationUIState.Loaded)?.name ?: "", maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + ) { padding -> + ScreenStateTransition(state) { uiState -> + when (val current = uiState) { + is ConfederationUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = current.message, onRetry = null) + + ConfederationUIState.Loading -> LoadingDataIndicator(modifier = Modifier.padding(padding)) + + ConfederationUIState.NotHeld -> EmptyState( + modifier = Modifier.padding(padding), + message = stringResource(Res.string.this_device_knows_nothing_of_that_confederation), + ) + + is ConfederationUIState.Loaded -> Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + // The profile, as the confederation signed it. + Text(text = stringResource(Res.string.confederation_profile), style = MaterialTheme.typography.titleSmall) + ConfederationProfileCard(current) + + current.pendingSessionId?.let { sessionId -> + Text(text = stringResource(Res.string.waiting_for_the_group_to_sign_its_answer)) + TextButton(onClick = { onNavigateToRoute(FrostSigningRoute(activeUserPublicKey, chatRoomId, sessionId)) }) { + Text(stringResource(Res.string.open_the_signing_session)) + } + } + if (current.readsChanges) { + Button( + modifier = Modifier.fillMaxWidth(), + enabled = current.canEdit && identityCanSign, + onClick = { onNavigateToRoute(EditConfederationProfileRoute(activeUserPublicKey, chatRoomId, confederationId)) }, + ) { + Icon(Icons.Default.Edit, contentDescription = Decorative) + Text(text = stringResource(Res.string.edit_the_confederations_profile), modifier = Modifier.padding(start = MaterialTheme.spacing.relatedGap)) + } + current.problem?.let { problem -> + Text( + text = problemText(problem), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + // The groups it is made of. + HorizontalDivider() + Text(text = stringResource(Res.string.confederation_groups), style = MaterialTheme.typography.titleSmall) + Text( + text = stringResource(Res.string.confederation_groups_to_act, current.threshold, current.groups.size), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + current.groups.forEach { group -> + ListItem( + leadingContent = { Icon(Icons.Default.Groups, contentDescription = Decorative) }, + headlineContent = { Text(text = group.name, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + supportingContent = if (group.roleHolders.isEmpty()) null else { + { + Column { + Text(stringResource(Res.string.n_admins_hold_its_key, group.roleHolders.size)) + Text( + text = group.roleHolders.joinToString(", "), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + } + }, + ) + } + + // The changes to its profile: only the groups' admins hold them. + HorizontalDivider() + Text(text = stringResource(Res.string.profile_changes), style = MaterialTheme.typography.titleSmall) + when { + !current.readsChanges -> EmptyState(message = stringResource(Res.string.only_admins_see_profile_changes)) + current.changes.isEmpty() -> EmptyState(message = stringResource(Res.string.no_profile_changes_yet)) + else -> current.changes.forEach { change -> + ProfileChangeCard( + status = change, + proposer = current.names[change.change.proposingGroup] ?: change.change.proposingGroup.take(12), + onClick = { onNavigateToRoute(ConfederationProfileChangeRoute(activeUserPublicKey, chatRoomId, change.change.id)) }, + ) + } + } + + HorizontalDivider() + if (current.holdsRoom) { + TextButton(onClick = { onNavigateToRoute(ChatRoomMessagingRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = confederationId, relayHint = null)) }) { + Text(stringResource(Res.string.open_the_confederations_room)) + } + } + current.formingProposalId?.let { proposalId -> + TextButton(onClick = { onNavigateToRoute(ConfederationProposalRoute(activeUserPublicKey, chatRoomId, proposalId)) }) { + Text(stringResource(Res.string.how_it_was_formed)) + } + } + } + } + } + } +} + +@Composable +private fun ConfederationProfileCard(state: ConfederationUIState.Loaded) { + val profile = state.profile + Card(modifier = Modifier.fillMaxWidth()) { + ListItem( + leadingContent = { ProfileAvatar(publicKey = state.confederationId, picture = profile?.picture(), name = profile?.name() ?: state.name) }, + headlineContent = { + Text( + text = profile?.let { it.name() ?: stringResource(Res.string.no_name_on_this_profile) } ?: state.name, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + }, + supportingContent = { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + if (profile == null) { + Text(stringResource(Res.string.confederation_has_no_profile_yet)) + } else { + profile.nip05()?.let { Text(text = it, style = MaterialTheme.typography.labelMedium, maxLines = 1, overflow = TextOverflow.Ellipsis) } + profile.about()?.let { Text(text = it, maxLines = 3, overflow = TextOverflow.Ellipsis) } + profile.website()?.let { Text(text = it, style = MaterialTheme.typography.labelMedium, maxLines = 1, overflow = TextOverflow.Ellipsis) } + } + Text( + text = state.confederationId.hexToByteArray().toNpub(), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + }, + ) + } +} + +@Composable +private fun ProfileChangeCard(status: ConfederationProfileChangeStatus, proposer: String, onClick: () -> Unit) { + val name = mobi.giza.compose.managers.ConfederationProfileRefusal.metadataOf(status.change.profile)?.anyName()?.takeIf { it.isNotBlank() } + Card(modifier = Modifier.fillMaxWidth(), onClick = onClick) { + ListItem( + headlineContent = { Text(text = name ?: stringResource(Res.string.no_name_on_this_profile), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + overlineContent = { Text(changeStateLabel(status.state)) }, + supportingContent = { + Column { + Text(stringResource(Res.string.confederation_proposed_by, proposer)) + Text( + text = stringResource(Res.string.n_of_m_endorsements, status.endorsers.size, status.change.threshold), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + text = kotlin.time.Instant.fromEpochSeconds(status.change.createdAt).toFormattedTimeAndDateString(), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + }, + trailingContent = { Icon(Icons.Default.ChevronRight, contentDescription = Decorative) }, + ) + } +} + +@Composable +internal fun changeStateLabel(state: ConfederationProfileChangeState): String = stringResource( + when (state) { + ConfederationProfileChangeState.OPEN -> Res.string.change_open + ConfederationProfileChangeState.ENDORSED -> Res.string.change_endorsed + ConfederationProfileChangeState.PUBLISHED -> Res.string.change_published + ConfederationProfileChangeState.SUPERSEDED -> Res.string.change_superseded + ConfederationProfileChangeState.DECLINED -> Res.string.change_declined + ConfederationProfileChangeState.WITHDRAWN -> Res.string.change_withdrawn + ConfederationProfileChangeState.EXPIRED -> Res.string.change_expired + } +) + +@Composable +internal fun problemText(problem: ProfileChangeProblem): String = when (problem) { + ProfileChangeProblem.NoRecord -> stringResource(Res.string.profile_problem_no_record) + ProfileChangeProblem.NotMember -> stringResource(Res.string.profile_problem_not_member) + ProfileChangeProblem.CannotSign -> stringResource(Res.string.profile_problem_cannot_sign) + ProfileChangeProblem.NotAdmin -> stringResource(Res.string.profile_problem_not_admin) + ProfileChangeProblem.NoInbox -> stringResource(Res.string.profile_problem_no_inbox) + is ProfileChangeProblem.GroupWithoutInbox -> stringResource(Res.string.profile_problem_group_without_inbox, problem.name) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt index 29b663cb..0849d14d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt @@ -45,6 +45,7 @@ import mobi.giza.compose.resources.confederations import mobi.giza.compose.resources.propose_a_confederation import mobi.giza.compose.resources.this_device_holds_no_confederation_proposals_for_this_group import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProposalRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRoute import mobi.giza.compose.ui.composable.navigation.routes.ProposeConfederationRoute import mobi.giza.compose.ui.composable.navigation.routes.Route import mobi.giza.compose.ui.composable.widgets.Decorative @@ -147,8 +148,16 @@ fun ConfederationsScreen( ConfederationProposalCard( item = item, onClick = { + // A formed confederation opens itself rather than the vote that + // made it: docs/confederation-profile.md, D1. onNavigateToRoute( - ConfederationProposalRoute( + item.confederationId?.let { confederationId -> + ConfederationRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + confederationId = confederationId, + ) + } ?: ConfederationProposalRoute( activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, proposalId = item.status.proposal.id, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditConfederationProfileScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditConfederationProfileScreen.kt new file mode 100644 index 00000000..ea93f1ac --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditConfederationProfileScreen.kt @@ -0,0 +1,183 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Draw +import androidx.compose.material3.BottomAppBar +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.a_change_goes_to_every_group +import mobi.giza.compose.resources.could_not_propose_the_change +import mobi.giza.compose.resources.edit_confederation_profile +import mobi.giza.compose.resources.propose_from +import mobi.giza.compose.resources.propose_to_the_groups +import mobi.giza.compose.resources.this_device_knows_nothing_of_that_confederation +import mobi.giza.compose.resources.what_the_confederation_says_about_itself +import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.Decorative +import mobi.giza.compose.ui.composable.widgets.EmptyState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.NostrProfileFields +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.composable.widgets.buttons.ExtendedFab +import mobi.giza.compose.ui.composable.widgets.rememberNostrProfileFieldStates +import mobi.giza.compose.ui.composable.widgets.rememberNotifier +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.EditConfederationProfileViewModel +import mobi.giza.compose.ui.view.state.EditConfederationProfileUIState +import org.jetbrains.compose.resources.stringResource + +/** + * The form for a change to a confederation's profile (docs/confederation-profile.md, D2): the same + * fields as a group's, seeded from the confederation's newest profile. Pressing the button asks a + * group -- the member's own, or one they pick when they are an admin of more than one -- to propose + * it, sealed to every other group's inbox. Nothing about the profile has changed when this closes: + * it changes once enough groups have endorsed it and the confederation has signed it. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun EditConfederationProfileScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + confederationId: HexKey, + initialUIState: EditConfederationProfileUIState = EditConfederationProfileUIState.Loading, + chatRepository: ChatRepository, + confederationRepository: ConfederationRepository, + onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val viewModel: EditConfederationProfileViewModel = viewModel( + factory = EditConfederationProfileViewModel.factory( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + confederationId = confederationId, + initialUIState = initialUIState, + chatRepository = chatRepository, + confederationRepository = confederationRepository, + ) + ) + LaunchedEffect(true) { + if (initialUIState == EditConfederationProfileUIState.Loading) viewModel.initiate() + } + + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotPropose = stringResource(Res.string.could_not_propose_the_change) + val identityCanSign = LocalCanSign.current + val state by viewModel.uiState.collectAsState() + + ScreenStateTransition(state) { uiState -> + when (val current = uiState) { + EditConfederationProfileUIState.Loading -> LoadingDataIndicator() + + EditConfederationProfileUIState.NotHeld -> EmptyState(message = stringResource(Res.string.this_device_knows_nothing_of_that_confederation)) + + is EditConfederationProfileUIState.Loaded -> { + val fields = rememberNostrProfileFieldStates(current.profile) + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + modifier = Modifier.imePadding(), + topBar = { + TopAppBar( + title = { Text(text = stringResource(Res.string.edit_confederation_profile), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + bottomBar = { + BottomAppBar( + actions = {}, + floatingActionButton = { + ExtendedFab( + label = stringResource(Res.string.propose_to_the_groups), + icon = { Icon(Icons.Default.Draw, contentDescription = Decorative) }, + enabled = current.selectedGroup != null && !current.isActing && identityCanSign, + onClick = { + viewModel.propose( + fields = fields, + // Onto the group's signing session: the profile changes only + // once enough groups endorse it, so going back to the + // confederation would read as a failure. + onSuccess = { groupId, sessionId -> + onNavigateToRouteAndPopUpInclusive( + FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = groupId, sessionId = sessionId) + ) + }, + onFailure = { reason -> notify(reason ?: couldNotPropose) }, + ) + }, + ) + }, + ) + }, + ) { innerPadding -> + Column( + modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + Text(text = current.name, style = MaterialTheme.typography.headlineSmall) + Text(stringResource(Res.string.what_the_confederation_says_about_itself)) + Text( + text = stringResource(Res.string.a_change_goes_to_every_group, current.threshold, current.groupCount), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + current.problem?.let { problem -> + Text(text = problemText(problem), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) + } + + // Only an admin of more than one member group has a choice to make. + if (current.proposingGroups.size > 1) { + Text(text = stringResource(Res.string.propose_from), style = MaterialTheme.typography.titleSmall) + current.proposingGroups.forEach { group -> + ListItem( + modifier = Modifier.selectable( + selected = group == current.selectedGroup, + role = Role.RadioButton, + onClick = { viewModel.select(group) }, + ), + leadingContent = { RadioButton(selected = group == current.selectedGroup, onClick = null) }, + headlineContent = { Text(text = current.names[group] ?: group.take(12), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + ) + } + } + + NostrProfileFields(fields) + } + } + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditGroupNostrProfileScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditGroupNostrProfileScreen.kt index d59a79c1..182ccf28 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditGroupNostrProfileScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/EditGroupNostrProfileScreen.kt @@ -1,6 +1,5 @@ package mobi.giza.compose.ui.composable -import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer @@ -10,25 +9,14 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.text.input.TextFieldLineLimits -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.foundation.text.input.rememberTextFieldState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.Notes -import androidx.compose.material.icons.filled.AlternateEmail import androidx.compose.material.icons.filled.Draw -import androidx.compose.material.icons.filled.Image -import androidx.compose.material.icons.filled.Link -import androidx.compose.material.icons.filled.Title import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.BottomAppBarDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.Surface @@ -39,8 +27,6 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.text.style.TextAlign import androidx.lifecycle.viewmodel.compose.viewModel import mobi.giza.compose.database.model.ChatRoom @@ -55,6 +41,8 @@ import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator import mobi.giza.compose.ui.composable.widgets.LocalCanSign import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.NostrProfileFields +import mobi.giza.compose.ui.composable.widgets.rememberNostrProfileFieldStates import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition import mobi.giza.compose.ui.composable.widgets.buttons.ExtendedFab import mobi.giza.compose.ui.composable.widgets.rememberNotifier @@ -66,21 +54,11 @@ import mobi.giza.compose.ui.view.model.EditGroupNostrProfileViewModel import mobi.giza.compose.ui.view.state.EditGroupNostrProfileUIState import com.vitorpamplona.quartz.nip01Core.core.HexKey import mobi.giza.compose.resources.Res -import mobi.giza.compose.resources.about import mobi.giza.compose.resources.could_not_ask_the_group_to_sign_this_profile import mobi.giza.compose.resources.edit_nostr_profile -import mobi.giza.compose.resources.eg_a_group_translating_hard_books -import mobi.giza.compose.resources.eg_group_example_com -import mobi.giza.compose.resources.eg_https_example_com -import mobi.giza.compose.resources.eg_https_example_com_group_png -import mobi.giza.compose.resources.eg_translation_collective -import mobi.giza.compose.resources.name -import mobi.giza.compose.resources.nostr_address -import mobi.giza.compose.resources.picture_url import mobi.giza.compose.resources.propose_nostr_profile import mobi.giza.compose.resources.the_group_signs_its_profile_so_it_takes_a_quorum import mobi.giza.compose.resources.this_group_has_no_shared_key_to_sign_a_profile -import mobi.giza.compose.resources.website import mobi.giza.compose.resources.what_the_group_says_about_itself_on_nostr import org.jetbrains.compose.resources.stringResource @@ -147,13 +125,8 @@ fun EditGroupNostrProfileScreen( val profile = editGroupNostrProfileUIState.groupNostrProfile // Seeded from the profile the group already signed, so the form is - // an edit of it. `rememberTextFieldState` saves what is typed, which - // is what survives a rotation with the edits intact. - val nameFieldState = rememberTextFieldState(profile?.name() ?: "") - val aboutFieldState = rememberTextFieldState(profile?.about() ?: "") - val pictureFieldState = rememberTextFieldState(profile?.picture() ?: "") - val websiteFieldState = rememberTextFieldState(profile?.website() ?: "") - val nip05FieldState = rememberTextFieldState(profile?.nip05() ?: "") + // an edit of it, and saved as typed, so a rotation keeps the edits. + val fields = rememberNostrProfileFieldStates(profile) // The room and this device's share, and the identity: an npub-only // profile cannot send the proposal at all. docs/npub-sign-in.md. @@ -186,11 +159,11 @@ fun EditGroupNostrProfileScreen( localChatRoom = editGroupNostrProfileUIState.localChatRoom, groupNostrProfile = profile, - nameField = nameFieldState, - aboutField = aboutFieldState, - pictureField = pictureFieldState, - websiteField = websiteFieldState, - nip05Field = nip05FieldState, + nameField = fields.name, + aboutField = fields.about, + pictureField = fields.picture, + websiteField = fields.website, + nip05Field = fields.nip05, onSuccess = { sessionId -> // Onto the session rather than back // to the group. The profile has not @@ -253,50 +226,7 @@ fun EditGroupNostrProfileScreen( ) } - NostrProfileField( - state = nameFieldState, - icon = Icons.Default.Title, - iconDescription = "Name of the group", - label = stringResource(Res.string.name), - placeholder = stringResource(Res.string.eg_translation_collective) - ) - - NostrProfileField( - state = aboutFieldState, - icon = Icons.AutoMirrored.Filled.Notes, - iconDescription = "What the group is for", - label = stringResource(Res.string.about), - placeholder = stringResource( - Res.string.eg_a_group_translating_hard_books - ), - // The one field with prose in it, and the only one a - // single line would truncate while it was being typed. - lineLimits = TextFieldLineLimits.MultiLine(maxHeightInLines = 3) - ) - - NostrProfileField( - state = pictureFieldState, - icon = Icons.Default.Image, - iconDescription = "Picture of the group", - label = stringResource(Res.string.picture_url), - placeholder = stringResource(Res.string.eg_https_example_com_group_png) - ) - - NostrProfileField( - state = websiteFieldState, - icon = Icons.Default.Link, - iconDescription = "Website of the group", - label = stringResource(Res.string.website), - placeholder = stringResource(Res.string.eg_https_example_com) - ) - - NostrProfileField( - state = nip05FieldState, - icon = Icons.Default.AlternateEmail, - iconDescription = "Nostr address of the group", - label = stringResource(Res.string.nostr_address), - placeholder = stringResource(Res.string.eg_group_example_com) - ) + NostrProfileFields(fields) } } } @@ -328,43 +258,6 @@ fun EditGroupNostrProfileScreen( } } -/** - * One field of the profile, in the shape the app's other forms use. - * - * Five of these on one screen is what makes it worth a function: the borderless - * outlined field over the bottom bar's tint is four lines of colours apiece, and - * five copies of that is where a divergence hides. - */ -@Composable -private fun NostrProfileField( - state: TextFieldState, - icon: ImageVector, - iconDescription: String, - label: String, - placeholder: String, - lineLimits: TextFieldLineLimits = TextFieldLineLimits.SingleLine -) { - OutlinedTextField( - modifier = Modifier.fillMaxWidth().background(BottomAppBarDefaults.containerColor), - state = state, - lineLimits = lineLimits, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon(icon, contentDescription = iconDescription) - }, - label = { - Text(text = label) - }, - placeholder = { - Text(text = placeholder) - } - ) -} - @ConformancePreviews @Composable private fun EditGroupNostrProfileScreenPreview() { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index c616211e..92450844 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -10,6 +10,12 @@ import mobi.giza.compose.ui.composable.BroadcastGroupSignedEventScreen import mobi.giza.compose.ui.composable.navigation.routes.AddGroupPostRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationsRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProposalRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRoute +import mobi.giza.compose.ui.composable.navigation.routes.EditConfederationProfileRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProfileChangeRoute +import mobi.giza.compose.ui.composable.ConfederationScreen +import mobi.giza.compose.ui.composable.EditConfederationProfileScreen +import mobi.giza.compose.ui.composable.ConfederationProfileChangeScreen import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRitualRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationSigningRoute import mobi.giza.compose.ui.composable.ConfederationSigningScreen @@ -1363,6 +1369,51 @@ fun GizaNavHost( onNavigateBack = { navController.popBackStack() } ) } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + ConfederationScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + confederationId = route.confederationId, + chatRepository = databaseChatRepository, + confederationRepository = databaseConfederationRepository, + onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) }, + onNavigateBack = { navController.popBackStack() } + ) + } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + EditConfederationProfileScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + confederationId = route.confederationId, + chatRepository = databaseChatRepository, + confederationRepository = databaseConfederationRepository, + onNavigateToRouteAndPopUpInclusive = { signingRoute -> + // Replace the form so back returns to the confederation rather than to + // an edit whose proposal has already gone to the group. + navController.navigate(route = signingRoute) { + popUpTo { inclusive = true } + } + }, + onNavigateBack = { navController.popBackStack() } + ) + } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + ConfederationProfileChangeScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + changeId = route.changeId, + chatRepository = databaseChatRepository, + confederationRepository = databaseConfederationRepository, + onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) }, + onNavigateBack = { navController.popBackStack() } + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationRoute.kt new file mode 100644 index 00000000..38e6766e --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationRoute.kt @@ -0,0 +1,31 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** + * A formed confederation, seen from one of its member groups: its profile, its groups and the + * changes to its profile (docs/confederation-profile.md, D1). [chatRoomId] is the group's room it + * was opened from, which is the group a change made here is proposed from. + */ +@Serializable +data class ConfederationRoute( + val activeUserPublicKey: String, + val chatRoomId: String, + val confederationId: String, +): Route() + +/** The form for a change to a confederation's profile, proposed by one of its groups (D2). */ +@Serializable +data class EditConfederationProfileRoute( + val activeUserPublicKey: String, + val chatRoomId: String, + val confederationId: String, +): Route() + +/** One proposed change to a confederation's profile, and this group's answer to it (D3). */ +@Serializable +data class ConfederationProfileChangeRoute( + val activeUserPublicKey: String, + val chatRoomId: String, + val changeId: String, +): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/NostrProfileFields.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/NostrProfileFields.kt new file mode 100644 index 00000000..7366fa33 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/NostrProfileFields.kt @@ -0,0 +1,137 @@ +package mobi.giza.compose.ui.composable.widgets + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.text.input.TextFieldLineLimits +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.foundation.text.input.rememberTextFieldState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.Notes +import androidx.compose.material.icons.filled.AlternateEmail +import androidx.compose.material.icons.filled.Image +import androidx.compose.material.icons.filled.Link +import androidx.compose.material.icons.filled.Title +import androidx.compose.material3.BottomAppBarDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedTextFieldDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.about +import mobi.giza.compose.resources.eg_a_group_translating_hard_books +import mobi.giza.compose.resources.eg_group_example_com +import mobi.giza.compose.resources.eg_https_example_com +import mobi.giza.compose.resources.eg_https_example_com_group_png +import mobi.giza.compose.resources.eg_translation_collective +import mobi.giza.compose.resources.name +import mobi.giza.compose.resources.nostr_address +import mobi.giza.compose.resources.picture_url +import mobi.giza.compose.resources.website +import org.jetbrains.compose.resources.stringResource + +/** + * The five fields of a nostr profile a group or a confederation edits here: what the group's form + * and the confederation's share (docs/confederation-profile.md, D2), so they cannot drift apart. + * + * Seeded from the profile already signed, so the form is an edit of it, and saved as typed, so a + * rotation keeps the edits. [template] turns them into the kind:0 to sign, built on the newest + * profile so a field this form does not offer is carried across (`GroupNostrProfile.template`). + */ +class NostrProfileFieldStates( + val name: TextFieldState, + val about: TextFieldState, + val picture: TextFieldState, + val website: TextFieldState, + val nip05: TextFieldState, +) { + fun template(latest: GroupNostrProfile?): EventTemplate = GroupNostrProfile.template( + latest = latest, + name = name.text.toString().trim(), + about = about.text.toString().trim(), + picture = picture.text.toString().trim(), + website = website.text.toString().trim(), + nip05 = nip05.text.toString().trim(), + ) +} + +@Composable +fun rememberNostrProfileFieldStates(profile: GroupNostrProfile?): NostrProfileFieldStates = NostrProfileFieldStates( + name = rememberTextFieldState(profile?.name() ?: ""), + about = rememberTextFieldState(profile?.about() ?: ""), + picture = rememberTextFieldState(profile?.picture() ?: ""), + website = rememberTextFieldState(profile?.website() ?: ""), + nip05 = rememberTextFieldState(profile?.nip05() ?: ""), +) + +/** The five fields, in the order a profile reads. Each icon sits beside its label, so it is decorative. */ +@Composable +fun NostrProfileFields(states: NostrProfileFieldStates) { + NostrProfileField( + state = states.name, + icon = Icons.Default.Title, + label = stringResource(Res.string.name), + placeholder = stringResource(Res.string.eg_translation_collective), + ) + NostrProfileField( + state = states.about, + icon = Icons.AutoMirrored.Filled.Notes, + label = stringResource(Res.string.about), + placeholder = stringResource(Res.string.eg_a_group_translating_hard_books), + // The one field with prose in it, and the only one a single line would truncate while it + // was being typed. + lineLimits = TextFieldLineLimits.MultiLine(maxHeightInLines = 3), + ) + NostrProfileField( + state = states.picture, + icon = Icons.Default.Image, + label = stringResource(Res.string.picture_url), + placeholder = stringResource(Res.string.eg_https_example_com_group_png), + ) + NostrProfileField( + state = states.website, + icon = Icons.Default.Link, + label = stringResource(Res.string.website), + placeholder = stringResource(Res.string.eg_https_example_com), + ) + NostrProfileField( + state = states.nip05, + icon = Icons.Default.AlternateEmail, + label = stringResource(Res.string.nostr_address), + placeholder = stringResource(Res.string.eg_group_example_com), + ) +} + +/** + * One field of the profile, in the shape the app's other forms use: the borderless outlined field + * over the bottom bar's tint is four lines of colours apiece, and five copies of that is where a + * divergence hides. + */ +@Composable +private fun NostrProfileField( + state: TextFieldState, + icon: ImageVector, + label: String, + placeholder: String, + lineLimits: TextFieldLineLimits = TextFieldLineLimits.SingleLine, +) { + OutlinedTextField( + modifier = Modifier.fillMaxWidth().background(BottomAppBarDefaults.containerColor), + state = state, + lineLimits = lineLimits, + colors = OutlinedTextFieldDefaults.colors( + focusedBorderColor = Color.Transparent, + unfocusedBorderColor = Color.Transparent, + disabledBorderColor = Color.Transparent, + ), + leadingIcon = { Icon(icon, contentDescription = Decorative) }, + label = { Text(text = label) }, + placeholder = { Text(text = placeholder) }, + ) +} 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 8e56dfa9..ff3528d9 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 @@ -41,6 +41,7 @@ import androidx.compose.material.icons.filled.CallMerge import androidx.compose.material.icons.filled.Campaign import androidx.compose.material.icons.filled.FactCheck import androidx.compose.material.icons.filled.Draw +import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.Download import androidx.compose.material.icons.filled.History import androidx.compose.material.icons.filled.Hub @@ -127,6 +128,10 @@ fun ChatTranscript( onOpenSigning: (sessionId: String?) -> Unit, /** Opens a confederation's request to sign: docs/confederation.md, Phase 15. */ onOpenConfederationSigning: (attemptId: String) -> Unit = {}, + /** Opens a change to a confederation's profile: docs/confederation-profile.md, D8. */ + onOpenConfederationProfileChange: (changeId: String) -> Unit = {}, + /** Opens a confederation, from the line saying it has a new profile. */ + onOpenConfederation: (confederationId: String) -> Unit = {}, /** Opens the room's proposals, all of them, whatever their state. */ onOpenProposals: () -> Unit, ) { @@ -394,6 +399,28 @@ fun ChatTranscript( return@items } + // A change to a confederation's profile, or the profile it ended in: + // each opens what it is about. docs/confederation-profile.md, D8. + if (localChatMessage.chatMessage.messageType in ChatMessage.CONFEDERATION_PROFILE_TYPES) { + val target = localChatMessage.chatMessage.frostSigningSessionId + RitualNotice( + localChatMessage = localChatMessage, + isAnswered = true, + isSettled = true, + onClick = target?.let { + { + if (localChatMessage.chatMessage.messageType == ChatMessage.TYPE_CONFEDERATION_PROFILE_PUBLISHED) { + onOpenConfederation(it) + } else { + onOpenConfederationProfileChange(it) + } + } + }, + opens = null, + ) + return@items + } + if (localChatMessage.chatMessage.messageType in ChatMessage.GROUP_IDENTITY_TYPES) { RitualNotice( localChatMessage = localChatMessage, @@ -925,6 +952,10 @@ private fun RitualNotice( ChatMessage.TYPE_CONFEDERATION_FORMED -> Icons.Default.Hub ChatMessage.TYPE_CONFEDERATION_SIGNING_PROPOSED -> Icons.Default.Draw ChatMessage.TYPE_CONFEDERATION_SIGNING_FAILED -> Icons.Default.ErrorOutline + ChatMessage.TYPE_CONFEDERATION_PROFILE_PROPOSED -> Icons.Default.Edit + ChatMessage.TYPE_CONFEDERATION_PROFILE_ENDORSED -> Icons.Default.CheckCircle + ChatMessage.TYPE_CONFEDERATION_PROFILE_OBJECTED -> Icons.Default.Block + ChatMessage.TYPE_CONFEDERATION_PROFILE_PUBLISHED -> Icons.Default.Hub else -> Icons.Default.PanTool 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 a40d9237..7044af76 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 @@ -135,6 +135,8 @@ class ChatRoomDetailViewModel( confederationProposalCount = chatRepository.confederationProposalCount(chatRoomId), inbox = chatRepository.inboxSummary(localChatRoom), confederationName = chatRepository.confederationOfRoom(chatRoomId), + confederationRoom = if (ExperimentalFeatures.confederation) chatRepository.confederationRoomInfo(chatRoomId) else null, + memberConfederations = if (ExperimentalFeatures.confederation) chatRepository.memberConfederations(chatRoomId) else emptyList(), groupDmRow = runCatching { chatRepository.groupDmRow(chatRoomId, localChatRoom.chatRoom.userPublicKey) } .onFailure { if (it is CancellationException) throw it else logger.w(throwable = it) { "Couldn't read $chatRoomId's messages row" } } .getOrNull(), diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationProfileChangeViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationProfileChangeViewModel.kt new file mode 100644 index 00000000..41693e6a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationProfileChangeViewModel.kt @@ -0,0 +1,132 @@ +package mobi.giza.compose.ui.view.model + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.managers.ConfederationProfileRefusal +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState +import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState.Field +import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState.FieldName + +/** + * One change to a confederation's profile from one of its groups, and the group's answer to it + * (docs/confederation-profile.md, D3). Answering is a group signature, so each button opens a + * signing session and the screen goes to it; one answer at a time. + */ +class ConfederationProfileChangeViewModel( + val activeUserPublicKey: HexKey, + val chatRoomId: String, + val changeId: HexKey, + initialUIState: ConfederationProfileChangeUIState, + val chatRepository: ChatRepository, + val confederationRepository: ConfederationRepository, +) : ViewModel() { + private val logger = Logger.withTag(TAG) + private val state = MutableStateFlow(initialUIState) + val uiState: StateFlow = state.asStateFlow() + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) ?: run { + state.value = ConfederationProfileChangeUIState.Error("Couldn't find the group") + return@launch + } + val canAnswer = GroupStatementCapability.roomIsOpen(localChatRoom) && chatRepository.canSign(chatRoomId) && + confederationRepository.isAdmin(chatRoomId, activeUserPublicKey) && + confederationRepository.holdsAnnouncedInbox(chatRoomId, activeUserPublicKey) + val base = confederationRepository.profileBaseOf(changeId) + + combine( + confederationRepository.observeProfileChange(changeId), + confederationRepository.observePendingProfileAnswer(chatRoomId, changeId), + ) { status, pending -> status to pending }.collect { (status, pending) -> + if (status == null) { + state.value = ConfederationProfileChangeUIState.NotHeld + return@collect + } + val acting = (state.value as? ConfederationProfileChangeUIState.Loaded)?.isActing == true + state.value = ConfederationProfileChangeUIState.Loaded( + localChatRoom = localChatRoom, + status = status, + confederationName = confederationRepository.membership(status.change.confederation)?.name ?: "", + differences = differences(base, ConfederationProfileRefusal.metadataOf(status.change.profile)), + names = status.change.groups.associateWith { confederationRepository.nameOf(it, chatRoomId) }, + canAnswer = canAnswer, + pendingSessionId = pending?.id, + isActing = acting, + ) + } + } + } + + fun endorse(onSuccess: (String) -> Unit, onFailure: () -> Unit) = act(onSuccess, onFailure) { loaded -> + confederationRepository.proposeProfileEndorsement(loaded.localChatRoom, activeUserPublicKey, changeId) + } + + /** An objection, with [reason]; from the group that proposed the change, its withdrawal. */ + fun objectTo(reason: String, onSuccess: (String) -> Unit, onFailure: () -> Unit) = act(onSuccess, onFailure) { loaded -> + confederationRepository.proposeProfileObjection(loaded.localChatRoom, activeUserPublicKey, changeId, reason.trim()) + } + + private fun act( + onSuccess: (String) -> Unit, + onFailure: () -> Unit, + propose: suspend (ConfederationProfileChangeUIState.Loaded) -> FrostSigningSession, + ) { + val loaded = state.value as? ConfederationProfileChangeUIState.Loaded ?: return + if (loaded.isActing) return + state.update { (it as? ConfederationProfileChangeUIState.Loaded)?.copy(isActing = true) ?: it } + viewModelScope.launch(Dispatchers.IO) { + val session = runCatching { propose(loaded) } + .onFailure { logger.e("Could not ask $chatRoomId to answer $changeId", it) } + .getOrNull() + state.update { (it as? ConfederationProfileChangeUIState.Loaded)?.copy(isActing = false) ?: it } + viewModelScope.launch(Dispatchers.Main) { if (session != null) onSuccess(session.id) else onFailure() } + } + } + + companion object { + private const val TAG = "ConfederationProfileChangeViewModel" + + /** The fields a person edits that differ between [before] and [after]. */ + fun differences(before: UserMetadata?, after: UserMetadata?): List { + fun String?.clean() = this?.takeIf { it.isNotBlank() } + return listOf( + Field(FieldName.NAME, before?.anyName().clean(), after?.anyName().clean()), + Field(FieldName.ABOUT, before?.about.clean(), after?.about.clean()), + Field(FieldName.PICTURE, before?.picture.clean(), after?.picture.clean()), + Field(FieldName.WEBSITE, before?.website.clean(), after?.website.clean()), + Field(FieldName.NIP05, before?.nip05.clean(), after?.nip05.clean()), + ).filter { it.before != it.after } + } + + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + changeId: HexKey, + initialUIState: ConfederationProfileChangeUIState = ConfederationProfileChangeUIState.Loading, + chatRepository: ChatRepository, + confederationRepository: ConfederationRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + ConfederationProfileChangeViewModel(activeUserPublicKey, chatRoomId, changeId, initialUIState, chatRepository, confederationRepository) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationViewModel.kt new file mode 100644 index 00000000..96ff91c4 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationViewModel.kt @@ -0,0 +1,96 @@ +package mobi.giza.compose.ui.view.model + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.launch +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.ui.view.state.ConfederationUIState + +/** + * A formed confederation from one of its member groups (docs/confederation-profile.md, D1): its + * profile, its groups, and the changes to its profile. Watched, since a change, an answer and a newly + * signed profile all arrive while the screen is open. + */ +class ConfederationViewModel( + val activeUserPublicKey: HexKey, + val chatRoomId: String, + val confederationId: HexKey, + initialConfederationUIState: ConfederationUIState, + val chatRepository: ChatRepository, + val confederationRepository: ConfederationRepository, +) : ViewModel() { + private val state = MutableStateFlow(initialConfederationUIState) + val uiState: StateFlow = state.asStateFlow() + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) ?: run { + state.value = ConfederationUIState.Error("Couldn't find the group") + return@launch + } + val membership = confederationRepository.membership(confederationId) ?: run { + state.value = ConfederationUIState.NotHeld + return@launch + } + val holders = confederationRepository.roleHolders(confederationId) + val names = membership.groups.associateWith { confederationRepository.nameOf(it, chatRoomId) } + val groups = membership.groups.map { group -> + ConfederationUIState.Group(group, names.getValue(group), holders[group].orEmpty().map { confederationRepository.nameOf(it) }) + } + val readsChanges = confederationRepository.isAdmin(chatRoomId, activeUserPublicKey) + val problem = confederationRepository.profileChangeProblem(chatRoomId, activeUserPublicKey, confederationId) + val formingProposalId = confederationRepository.formingProposalOf(confederationId) + val holdsRoom = confederationRepository.holdsRoomOf(confederationId) + + combine( + confederationRepository.observeProfile(confederationId), + confederationRepository.observeProfileChanges(confederationId), + confederationRepository.observePendingProfileChange(chatRoomId, confederationId), + ) { profile, changes, pending -> Triple(profile, changes, pending) }.collect { (profile, changes, pending) -> + state.value = ConfederationUIState.Loaded( + localChatRoom = localChatRoom, + confederationId = confederationId, + name = membership.name, + threshold = membership.threshold, + groups = groups, + profile = profile, + changes = changes, + readsChanges = readsChanges, + problem = problem, + pendingSessionId = pending?.id, + formingProposalId = formingProposalId, + holdsRoom = holdsRoom, + names = names, + ) + } + } + } + + companion object { + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + confederationId: HexKey, + initialConfederationUIState: ConfederationUIState = ConfederationUIState.Loading, + chatRepository: ChatRepository, + confederationRepository: ConfederationRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + ConfederationViewModel( + activeUserPublicKey, chatRoomId, confederationId, initialConfederationUIState, chatRepository, confederationRepository, + ) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationsViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationsViewModel.kt index 14c00b2b..a1971c14 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationsViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationsViewModel.kt @@ -48,7 +48,7 @@ class ConfederationsViewModel( combine( confederationRepository.observeStatusesNaming(chatRoomId), confederationRepository.observeConfederationsOf(chatRoomId), - ) { statuses, formed -> statuses to formed.map { it.proposalId }.toSet() }.collect { (statuses, formed) -> + ) { statuses, formed -> statuses to formed.associate { it.proposalId to it.id } }.collect { (statuses, formed) -> confederationsUIState = ConfederationsUIState.Loaded( localChatRoom = localChatRoom, proposals = statuses.map { status -> @@ -56,6 +56,7 @@ class ConfederationsViewModel( status = status, proposerName = confederationRepository.nameOf(status.proposal.proposingGroup, chatRoomId), formed = status.proposal.id in formed, + confederationId = formed[status.proposal.id], ) }, canPropose = canPropose, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditConfederationProfileViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditConfederationProfileViewModel.kt new file mode 100644 index 00000000..c22f972a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditConfederationProfileViewModel.kt @@ -0,0 +1,105 @@ +package mobi.giza.compose.ui.view.model + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.ui.composable.widgets.NostrProfileFieldStates +import mobi.giza.compose.ui.view.state.EditConfederationProfileUIState + +/** + * The form for a change to a confederation's profile (docs/confederation-profile.md, D2). Pressing + * the button proposes rather than saves: the group chosen signs a statement proposing the change, + * sealed to every other member group's inbox, and the screen hands over to that signing session. + */ +class EditConfederationProfileViewModel( + val activeUserPublicKey: HexKey, + val chatRoomId: String, + val confederationId: HexKey, + initialUIState: EditConfederationProfileUIState, + val chatRepository: ChatRepository, + val confederationRepository: ConfederationRepository, +) : ViewModel() { + private val logger = Logger.withTag(TAG) + private val state = MutableStateFlow(initialUIState) + val uiState: StateFlow = state.asStateFlow() + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val membership = confederationRepository.membership(confederationId) ?: run { + state.value = EditConfederationProfileUIState.NotHeld + return@launch + } + val groups = confederationRepository.proposingGroupsFor(activeUserPublicKey, confederationId) + .sortedBy { if (it == chatRoomId) 0 else 1 } + state.value = EditConfederationProfileUIState.Loaded( + confederationId = confederationId, + name = membership.name, + threshold = membership.threshold, + groupCount = membership.groups.size, + profile = confederationRepository.observeProfile(confederationId).first(), + proposingGroups = groups, + names = membership.groups.associateWith { confederationRepository.nameOf(it) }, + problem = if (groups.isEmpty()) confederationRepository.profileChangeProblem(chatRoomId, activeUserPublicKey, confederationId) else null, + selectedGroup = groups.firstOrNull(), + ) + } + } + + fun select(group: HexKey) = state.update { (it as? EditConfederationProfileUIState.Loaded)?.copy(selectedGroup = group) ?: it } + + /** + * Asks the selected group to propose [fields] as the confederation's profile. [onFailure] gets a + * reason a person can read when there is one: a profile too long for every group's seal. + */ + fun propose(fields: NostrProfileFieldStates, onSuccess: (groupId: String, sessionId: String) -> Unit, onFailure: (String?) -> Unit) { + val loaded = state.value as? EditConfederationProfileUIState.Loaded ?: return + val group = loaded.selectedGroup ?: return + if (loaded.isActing) return + state.update { (it as? EditConfederationProfileUIState.Loaded)?.copy(isActing = true) ?: it } + val template = fields.template(loaded.profile) + viewModelScope.launch(Dispatchers.IO) { + val result = runCatching { + val room = chatRepository.getChatRoomByIdentifier(group) ?: throw IllegalStateException("Couldn't find the group") + confederationRepository.proposeProfileChange(room, activeUserPublicKey, confederationId, template.tags, template.content) + }.onFailure { logger.e("Could not propose a profile for $confederationId", it) } + state.update { (it as? EditConfederationProfileUIState.Loaded)?.copy(isActing = false) ?: it } + viewModelScope.launch(Dispatchers.Main) { + result.fold( + onSuccess = { onSuccess(group, it.id) }, + onFailure = { onFailure((it as? IllegalStateException)?.message?.takeIf { message -> message.startsWith("This profile is too long") }) }, + ) + } + } + } + + companion object { + private const val TAG = "EditConfederationProfileViewModel" + + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + confederationId: HexKey, + initialUIState: EditConfederationProfileUIState = EditConfederationProfileUIState.Loading, + chatRepository: ChatRepository, + confederationRepository: ConfederationRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + EditConfederationProfileViewModel(activeUserPublicKey, chatRoomId, confederationId, initialUIState, chatRepository, confederationRepository) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModel.kt index 15395d18..a6ebda91 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/EditGroupNostrProfileViewModel.kt @@ -48,9 +48,11 @@ class EditGroupNostrProfileViewModel( val isActionPending: MutableState = mutableStateOf(false) - /** Whether this room is a confederation's, whose statements the confederation signs. Read at load. */ - var isConfederation: Boolean = false - private set + /** + * Never, now: a confederation's profile is not edited from its room but proposed by one of its + * groups (docs/confederation-profile.md, D5). Kept so the screen's routing reads the same. + */ + val isConfederation: Boolean = false fun initiateEditGroupNostrProfile() { viewModelScope.launch(Dispatchers.IO) { @@ -64,9 +66,11 @@ class EditGroupNostrProfileViewModel( groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), // The same condition the group detail screen gates the entry // point on. + // Not a confederation's room: its profile changes through its groups, from + // its own screen (docs/confederation-profile.md, D5). canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && - (frostSigningRepository.canSign(chatRoomId) || - chatRepository.canSignAsConfederation(chatRoomId).also { isConfederation = it }), + frostSigningRepository.canSign(chatRoomId) && + !chatRepository.canSignAsConfederation(chatRoomId), ) } } @@ -113,19 +117,13 @@ class EditGroupNostrProfileViewModel( viewModelScope.launch(Dispatchers.IO) { val session = runCatching { - // A confederation's room signs through the confederation, not a FROST - // key: docs/confederation.md, Phase 15. - if (isConfederation) { - chatRepository.proposeAsConfederation(localChatRoom, template.kind, template.tags, template.content) - } else { - frostSigningRepository.proposeSigning( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - kind = template.kind, - tags = template.tags, - content = template.content, - )?.id - } + frostSigningRepository.proposeSigning( + localChatRoom = localChatRoom, + userPublicKey = activeUserPublicKey, + kind = template.kind, + tags = template.tags, + content = template.content, + )?.id }.onFailure { error -> logger.e("Failed to propose a nostr profile for $chatRoomId", error) }.getOrNull() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupNostrProfileViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupNostrProfileViewModel.kt index f23b1e7e..01d16f85 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupNostrProfileViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupNostrProfileViewModel.kt @@ -44,7 +44,7 @@ class GroupNostrProfileViewModel( localChatRoom = localChatRoom, groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && - (chatRepository.canSign(chatRoomId) || chatRepository.canSignAsConfederation(chatRoomId)), + chatRepository.canSign(chatRoomId) && !chatRepository.canSignAsConfederation(chatRoomId), ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt index 4f858ce0..73908a7a 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 @@ -77,6 +77,12 @@ sealed interface ChatRoomDetailUIState { val confederationProposalCount: Int = 0, /** The group's inbox, for its row; null where this device has nothing of it to show. */ val inbox: InboxRowSummary? = null, + /** This room's confederation, by its groups and who holds their roles. docs/confederation-profile.md, D9. */ + val confederationRoom: ConfederationRoomInfo? = null, + + /** The formed confederations this group is a member of, as (id, name): each opens its own screen. */ + val memberConfederations: List> = emptyList(), + /** The confederation whose room this is, by name: its membership is fixed until it can sign. */ val confederationName: String? = null, /** What the group's direct messages show here, or nothing. docs/group-threshold-ecdh.md. */ @@ -189,3 +195,15 @@ sealed interface ChatRoomDetailUIState { data object Loading: ChatRoomDetailUIState } +/** + * A confederation's own room, said in its groups (docs/confederation-profile.md, D9): each group with + * the people who hold its roles, each person's groups, and the member group this device opens the + * confederation's screen from. + */ +data class ConfederationRoomInfo( + val confederationId: String, + val name: String, + val groups: List>>, + val groupsOfMember: Map>, + val homeGroupId: String?, +) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomMessagingUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomMessagingUIState.kt index 3caf0000..b4866e0c 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomMessagingUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomMessagingUIState.kt @@ -26,4 +26,12 @@ data class KeyCeremonyLink( val proposalId: HexKey, /** Whether this device's owner has joined the latest attempt. */ val joined: Boolean, + /** + * The confederation the ceremony made, once it has: the room has nothing more to do, and the way + * from it is to the confederation (docs/confederation-profile.md, D10). + */ + val formed: FormedConfederation? = null, ) + +/** A formed confederation, and the member group this device opens it from. */ +data class FormedConfederation(val confederationId: HexKey, val name: String, val homeGroupId: String?) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationProfileChangeUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationProfileChangeUIState.kt new file mode 100644 index 00000000..fd3dfad9 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationProfileChangeUIState.kt @@ -0,0 +1,45 @@ +package mobi.giza.compose.ui.view.state + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus + +/** One change to a confederation's profile, seen from one of its groups (docs/confederation-profile.md, D3). */ +sealed interface ConfederationProfileChangeUIState { + data class Loaded( + val localChatRoom: LocalChatRoom, + val status: ConfederationProfileChangeStatus, + val confederationName: String, + /** Each field that would change, as (field, before, after). */ + val differences: List, + val names: Map = emptyMap(), + /** Whether this member can put an answer to the group: an admin with a share and the group's inbox key. */ + val canAnswer: Boolean = false, + /** An answer this group is being asked to sign, not yet signed: one at a time. */ + val pendingSessionId: String? = null, + val isActing: Boolean = false, + ) : ConfederationProfileChangeUIState { + private val roomId get() = localChatRoom.chatRoom.id + private val live get() = status.state == ConfederationProfileChangeState.OPEN || status.state == ConfederationProfileChangeState.ENDORSED + + /** Another group's change this group has not answered, still open. */ + val canEndorseOrObject: Boolean + get() = canAnswer && pendingSessionId == null && live && + status.change.proposingGroup != roomId && !status.hasAnswered(roomId) + + /** This group's own change, not yet published or closed. */ + val canWithdraw: Boolean + get() = canAnswer && pendingSessionId == null && live && status.change.proposingGroup == roomId + } + + enum class FieldName { NAME, ABOUT, PICTURE, WEBSITE, NIP05 } + + data class Field(val name: FieldName, val before: String?, val after: String?) + + data object NotHeld : ConfederationProfileChangeUIState + + data class Error(val message: String) : ConfederationProfileChangeUIState + + data object Loading : ConfederationProfileChangeUIState +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationUIState.kt new file mode 100644 index 00000000..98977442 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationUIState.kt @@ -0,0 +1,46 @@ +package mobi.giza.compose.ui.view.state + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus +import mobi.giza.compose.repository.ProfileChangeProblem + +/** A formed confederation, seen from one of its member groups (docs/confederation-profile.md, D1). */ +sealed interface ConfederationUIState { + data class Loaded( + val localChatRoom: LocalChatRoom, + val confederationId: HexKey, + val name: String, + /** How many of [groups] must act for it to sign. */ + val threshold: Int, + val groups: List, + /** The newest profile the confederation has signed that this device holds. */ + val profile: GroupNostrProfile? = null, + /** The changes to its profile this device holds, newest first: an admin's device holds them, nobody else's. */ + val changes: List = emptyList(), + /** Whether this member reads the groups' statements: one of the group's admins. */ + val readsChanges: Boolean = false, + /** Why this member cannot propose a change from this group, or null when they can. */ + val problem: ProfileChangeProblem? = null, + /** A change this group is being asked to propose, not yet signed. */ + val pendingSessionId: String? = null, + /** The proposal the confederation was formed from, where this device holds it. */ + val formingProposalId: HexKey? = null, + /** Whether this device holds the confederation's own room. */ + val holdsRoom: Boolean = false, + /** How to name each group. */ + val names: Map = emptyMap(), + ) : ConfederationUIState { + val canEdit: Boolean get() = problem == null && pendingSessionId == null + } + + /** A member group, with the admins who hold its roles where this device knows them. */ + data class Group(val publicKey: HexKey, val name: String, val roleHolders: List) + + data object NotHeld : ConfederationUIState + + data class Error(val message: String) : ConfederationUIState + + data object Loading : ConfederationUIState +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationsUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationsUIState.kt index c311a154..7c544cef 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationsUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationsUIState.kt @@ -14,7 +14,13 @@ sealed interface ConfederationsUIState { ) : ConfederationsUIState /** One proposal, and how to name the group that made it. */ - data class Item(val status: ConfederationStatus, val proposerName: String, val formed: Boolean = false) + data class Item( + val status: ConfederationStatus, + val proposerName: String, + val formed: Boolean = false, + /** The formed confederation's id, which its card opens. docs/confederation-profile.md, D1. */ + val confederationId: String? = null, + ) data class Error(val message: String) : ConfederationsUIState diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/EditConfederationProfileUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/EditConfederationProfileUIState.kt new file mode 100644 index 00000000..1be68c43 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/EditConfederationProfileUIState.kt @@ -0,0 +1,28 @@ +package mobi.giza.compose.ui.view.state + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.repository.ProfileChangeProblem + +/** The form for a change to a confederation's profile (docs/confederation-profile.md, D2). */ +sealed interface EditConfederationProfileUIState { + data class Loaded( + val confederationId: HexKey, + val name: String, + val threshold: Int, + val groupCount: Int, + /** The profile the change edits: the newest this device holds. */ + val profile: GroupNostrProfile?, + /** The member groups this member can propose from, the one it was opened from first. */ + val proposingGroups: List, + val names: Map, + /** Why the group it was opened from cannot propose, when no group can. */ + val problem: ProfileChangeProblem?, + val selectedGroup: HexKey?, + val isActing: Boolean = false, + ) : EditConfederationProfileUIState + + data object NotHeld : EditConfederationProfileUIState + + data object Loading : EditConfederationProfileUIState +} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt index 859739c9..7ff46821 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt @@ -58,6 +58,15 @@ class ConfederationRelayTest { ExperimentalFeatures.confederationOverride = null } + @Test + fun `a known confederation adds one filter for its own profile, by its key`() { + val atlas = "ab".repeat(32) + val filters = LiveSubscriptionManager.confederationFilters(listOf("room-a"), listOf(atlas)) + assertEquals(2, filters.size) + assertEquals(listOf(0), filters[1].kinds, "docs/confederation-profile.md, D7") + assertEquals(listOf(atlas), filters[1].authors) + } + // --- the subscription @Test diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileStatementsTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileStatementsTest.kt new file mode 100644 index 00000000..21026ca3 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProfileStatementsTest.kt @@ -0,0 +1,175 @@ +package mobi.giza.compose.nostr.confederation + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.PrivateKey +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 mobi.giza.compose.extensions.toHex + +/** What a formed confederation's groups say about its profile, and where a change stands (docs/confederation-profile.md, Phase 1). */ +class ConfederationProfileStatementsTest { + private fun npub(n: Int): HexKey = PrivateKey(ByteArray(32).also { it[0] = 0x17; it[31] = n.toByte() }).publicKey().xOnly().value.toHex() + + private val agora = npub(1) + private val polis = npub(2) + private val ekklesia = npub(3) + private val atlas = npub(9) + private val now = 1_790_000_000L + private val expiry = now + ConfederationKinds.DEFAULT_CHANGE_EXPIRY_SECONDS + + private fun changeRumor( + by: HexKey = agora, + others: List = listOf(polis, ekklesia), + threshold: Int = 2, + base: HexKey? = "ba".repeat(32), + content: String = """{"name":"Atlas"}""", + createdAt: Long = now, + ): Event = ConfederationProfileStatements.change(by, others, atlas, threshold, base, emptyArray(), content, createdAt, expiry) + + private val change get() = ConfederationProfileStatements.parseChange(changeRumor())!! + + private fun rebuilt(rumor: Event, tags: Array> = rumor.tags, content: String = rumor.content): Event = + Event(EventHasher.hashId(rumor.pubKey, rumor.createdAt, rumor.kind, tags, content), rumor.pubKey, rumor.createdAt, rumor.kind, tags, content, "") + + // ---- the wire ------------------------------------------------------------------------------- + + @Test + fun `a change carries the kind 0 the confederation would sign, dated and named before anyone answers`() { + val rumor = changeRumor() + val parsed = assertNotNull(ConfederationProfileStatements.parseChange(rumor)) + assertEquals(listOf(agora, polis, ekklesia), parsed.groups) + assertEquals(atlas, parsed.confederation) + assertEquals(2, parsed.threshold) + assertEquals("ba".repeat(32), parsed.base) + assertEquals(atlas, parsed.profile.pubKey) + assertEquals(0, parsed.profile.kind) + assertEquals(rumor.createdAt, parsed.profile.createdAt) + assertEquals("", rumor.sig, "a rumor") + assertEquals("", parsed.profile.sig, "and its kind:0 unsigned") + assertEquals(EventHasher.hashId(atlas, now, 0, emptyArray(), """{"name":"Atlas"}"""), parsed.profileId) + } + + @Test + fun `a first profile has no base`() { + assertNull(ConfederationProfileStatements.parseChange(changeRumor(base = null))!!.base) + } + + @Test + fun `a change is refused whole when any part of it is wrong`() { + val rumor = changeRumor() + fun without(name: String) = rebuilt(rumor, rumor.tags.filter { it[0] != name }.toTypedArray()) + assertNull(ConfederationProfileStatements.parseChange(without("confederation"))) + assertNull(ConfederationProfileStatements.parseChange(without("threshold"))) + assertNull(ConfederationProfileStatements.parseChange(without("expiration"))) + assertNull(ConfederationProfileStatements.parseChange(without("p")), "a change to nobody") + + // The kind:0 is the confederation's, dated as the rumor, unsigned, with its own id. + val profile = ConfederationProfileStatements.parseChange(rumor)!!.profile + fun withProfile(p: Event) = rebuilt(rumor, content = p.toJson()) + assertNull(ConfederationProfileStatements.parseChange(withProfile(ConfederationProfileStatements.unsignedProfile(polis, now, emptyArray(), "{}"))), "someone else's profile") + assertNull(ConfederationProfileStatements.parseChange(withProfile(ConfederationProfileStatements.unsignedProfile(atlas, now + 1, emptyArray(), "{}"))), "dated otherwise") + assertNull(ConfederationProfileStatements.parseChange(withProfile(Event("00".repeat(32), atlas, now, 0, emptyArray(), "{}", ""))), "an id that is not its hash") + assertNull(ConfederationProfileStatements.parseChange(withProfile(Event(profile.id, atlas, now, 0, profile.tags, profile.content, "ab".repeat(64)))), "already signed") + assertNull(ConfederationProfileStatements.parseChange(withProfile(ConfederationProfileStatements.unsignedProfile(atlas, now, emptyArray(), "{}").let { Event(EventHasher.hashId(atlas, now, 1, emptyArray(), "{}"), atlas, now, 1, emptyArray(), "{}", "") })), "a post, not a profile") + + assertNull(ConfederationProfileStatements.parseChange(changeRumor(threshold = 4)), "more groups than it names") + assertNull(ConfederationProfileStatements.parseChange(changeRumor(threshold = 1)), "a threshold of one") + assertEquals(listOf(polis), ConfederationProfileStatements.parseChange(changeRumor(others = listOf(polis, agora)))!!.addressees, "naming itself is tidied away") + val selfNamed = rebuilt(rumor, rumor.tags + arrayOf(arrayOf("p", agora))) + assertNull(ConfederationProfileStatements.parseChange(selfNamed), "and refused when it arrives that way") + } + + @Test + fun `answers name the change and its kind 0, and go to every other group`() { + val endorsement = ConfederationProfileStatements.endorsement(polis, change, now + 5) + val parsed = assertNotNull(ConfederationProfileStatements.parseAnswer(endorsement)) + assertTrue(parsed.isEndorsement) + assertEquals(change.id, parsed.changeId) + assertEquals(change.profileId, parsed.profileId) + assertEquals(setOf(agora, ekklesia), parsed.addressees.toSet()) + assertTrue(parsed.answers(change)) + + val objection = assertNotNull(ConfederationProfileStatements.parseAnswer(ConfederationProfileStatements.objection(ekklesia, change, "Too long", now + 5))) + assertFalse(objection.isEndorsement) + assertEquals("Too long", objection.reason) + + // An endorsement says nothing but that it endorses. + assertNull(ConfederationProfileStatements.parseAnswer(rebuilt(endorsement, content = "and also"))) + // To fewer groups than the change names, it does not answer it. + val partial = rebuilt(endorsement, endorsement.tags.filter { !(it[0] == "p" && it[1] == ekklesia) }.toTypedArray()) + assertFalse(ConfederationProfileStatements.parseAnswer(partial)!!.answers(change)) + } + + @Test + fun `a voucher names the change, its kind 0 and its expiry, and nothing else`() { + val template = ConfederationProfileStatements.voucherTemplate(change, now + 5) + val voucher = Event(EventHasher.hashId(polis, template.createdAt, template.kind, template.tags, template.content), polis, template.createdAt, template.kind, template.tags, template.content, "") + val parsed = assertNotNull(ConfederationProfileStatements.parseVoucher(voucher)) + assertTrue(parsed.vouchesFor(change)) + assertEquals(ConfederationKinds.VOUCHER, voucher.kind) + + val other = ConfederationProfileStatements.parseChange(changeRumor(content = """{"name":"Other"}"""))!! + assertFalse(parsed.vouchesFor(other), "a voucher is for one kind:0") + assertNull(ConfederationProfileStatements.parseVoucher(Event(voucher.id, polis, voucher.createdAt, voucher.kind, voucher.tags + arrayOf(arrayOf("x", "y")), "", ""))) + } + + @Test + fun `none of the new kinds is public`() { + (ConfederationKinds.PROFILE_CHANGE_KINDS + ConfederationKinds.VOUCHER).forEach { + assertFalse(it in ConfederationKinds.ALL, "$it would be subscribed to and broadcast") + assertTrue(it in 1000..9999) + } + } + + // ---- the state ------------------------------------------------------------------------------ + + private fun statusOf( + vararg answers: Event, + newest: Pair? = null, + published: Boolean = false, + at: Long = now + 60, + change: ConfederationProfileStatements.Change = this.change, + ) = ConfederationProfileChangeStatus.of(change, answers.mapNotNull(ConfederationProfileStatements::parseAnswer), emptyList(), newest, published, at) + + private fun endorse(by: HexKey, at: Long = now + 5) = ConfederationProfileStatements.endorsement(by, change, at) + private fun objectTo(by: HexKey, at: Long = now + 5) = ConfederationProfileStatements.objection(by, change, "", at) + + @Test + fun `the proposer is the first endorsement, and the threshold's worth of groups endorses it`() { + assertEquals(ConfederationProfileChangeState.OPEN, statusOf().state) + val endorsed = statusOf(endorse(polis)) + assertEquals(ConfederationProfileChangeState.ENDORSED, endorsed.state) + assertEquals(listOf(agora, polis), endorsed.endorsers) + assertEquals(ConfederationProfileAnswer.WAITING, endorsed.answerOf(ekklesia)) + } + + @Test + fun `an objection is counted, but blocks only when the threshold is out of reach`() { + assertEquals(ConfederationProfileChangeState.OPEN, statusOf(objectTo(polis)).state, "Ekklesia can still make it two") + assertEquals(ConfederationProfileChangeState.ENDORSED, statusOf(objectTo(polis), endorse(ekklesia)).state, "two of three is the rule") + assertEquals(ConfederationProfileChangeState.DECLINED, statusOf(objectTo(polis), objectTo(ekklesia)).state) + } + + @Test + fun `a group's first answer is its answer, and only one dated by the expiry counts`() { + val status = statusOf(objectTo(polis, now + 5), endorse(polis, now + 9)) + assertEquals(ConfederationProfileAnswer.OBJECTED, status.answerOf(polis)) + assertEquals(ConfederationProfileChangeState.OPEN, statusOf(endorse(polis, expiry + 1), at = now + 60).state, "too late to count") + } + + @Test + fun `withdrawn, published, superseded and expired`() { + assertEquals(ConfederationProfileChangeState.WITHDRAWN, statusOf(objectTo(agora)).state) + assertEquals(ConfederationProfileChangeState.PUBLISHED, statusOf(endorse(polis), published = true).state) + assertEquals(ConfederationProfileChangeState.SUPERSEDED, statusOf(endorse(polis), newest = (now + 1) to "ff".repeat(32)).state) + assertEquals(ConfederationProfileChangeState.ENDORSED, statusOf(endorse(polis), newest = (now - 1) to "ff".repeat(32)).state, "an older profile is what it replaces") + assertEquals(ConfederationProfileChangeState.EXPIRED, statusOf(at = expiry + 1).state) + assertEquals(ConfederationProfileChangeState.EXPIRED, statusOf(endorse(polis), at = expiry + 1).state, "nothing signs past the expiry") + } +} 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 7033e8c7..e1c8bcbb 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 @@ -71,10 +71,11 @@ class ShippedProfileUpgradeJvmTest { * direct messages by threshold ECDH (docs/group-threshold-ecdh.md, Phase 4), 48 for * notifications' read marks and ledger (docs/notifications-and-background-sync.md, Phase 3) and * 49 for the confederation's statements between inboxes (docs/confederation-without-coordinator.md) and - * 50 for disappearing messages (docs/disappearing-messages.md, Phase 2), so the upgrade crosses - * fourteen generated migrations and the file has to come out at the last. + * 50 for disappearing messages (docs/disappearing-messages.md, Phase 2) and 51 for a formed + * confederation's profile changes (docs/confederation-profile.md), so the upgrade crosses fifteen + * generated migrations and the file has to come out at the last. */ - private val current = 50 + private val current = 51 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/ConfederationProfileNetworkJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileNetworkJvmTest.kt new file mode 100644 index 00000000..17593085 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileNetworkJvmTest.kt @@ -0,0 +1,229 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import fr.acinq.bitcoin.Crypto +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Instant +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.Confederation +import mobi.giza.compose.database.model.ConfederationSigningStage +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState +import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents +import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents + +/** + * docs/confederation-profile.md, Phase 8: the plan end to end. Three groups of three admins, each + * signing by FROST and holding an inbox, form a confederation through the real statements and the + * real key ceremony on nine devices. Then Agora's admin changes its name from the confederation's + * screen's calls: Agora's quorum signs the change to every group's inbox, Polis's quorum endorses it, + * and the confederation signs it with nobody asked again. Every admin of every group reads it, every + * group's room says so, and a member of Polis who is no admin hears it from a relay. + */ +class ConfederationProfileNetworkJvmTest { + private val network = ConfederationTestGroups(keySeries = 4) + private val agora = network.groups[0] + private val polis = network.groups[1] + private val ekklesia = network.groups[2] + private val databases = mutableListOf() + + private lateinit var confederation: Confederation + private val ceremonyRooms = mutableMapOf() + private val confederationRooms = mutableMapOf() + private val received = mutableMapOf>() + + @BeforeTest + fun formed() = runBlocking { + network.setUp() + val people = network.everyDevice.map { it.publicKey } + network.everyDevice.forEach { device -> people.forEach { profile(device.db, it) } } + + // The statements, group to group: Agora proposes, Polis and Ekklesia accept. + network.signed(agora) { device -> + ConfederationManager.proposeConfederation( + device.db, device.room(), device.publicKey, listOf(polis.roomId, ekklesia.roomId), threshold = 2, name = "Atlas", + expiresAt = Clock.System.now().epochSeconds + ConfederationKinds.DEFAULT_EXPIRY_SECONDS, + ).id + } + val proposalId = agora.devices[0].db.confederationDao().getProposals().single().id + network.signed(polis) { ConfederationManager.proposeAcceptance(it.db, it.room(), it.publicKey, proposalId).id } + network.signed(ekklesia) { ConfederationManager.proposeAcceptance(it.db, it.room(), it.publicKey, proposalId).id } + + // The key ceremony, every admin joining, in the NIP-17 room every device derives. + network.everyDevice.forEach { device -> + ceremonyRooms[device.publicKey] = device.db.nostrNip17Dao().createNip17ChatRoom(device.publicKey, people - device.publicKey, "Atlas")!! + received[device.publicKey] = mutableSetOf() + } + network.everyDevice.forEach { ConfederationRitualManager.join(it.db, proposalId, it.publicKey, it.secret) } + pumpCeremony() + confederation = assertNotNull(agora.devices[0].db.confederationCeremonyDao().getConfederationForProposal(proposalId), "formed") + + // The confederation's room on every device: its MLS state is not this test's business. + network.everyDevice.forEach { device -> + device.db.chatRoomDao().upsert(ChatRoom(id = confederation.id, userPublicKey = device.publicKey, subject = "#Atlas", description = null, mlsGroupState = "00")) + confederationRooms[device.publicKey] = device.db.chatRoomDao().findChatRoomById(confederation.id)!! + received[device.publicKey] = mutableSetOf() + } + } + + @AfterTest + fun close() { + ConfederationSigningManager.forgetSignersForTest() + databases.forEach { it.close() } + network.close() + } + + private suspend fun profile(db: GizaDatabase, key: HexKey) { + if (db.profileDao().getProfileByPublicKey(key) != null) return + val eventId = Crypto.sha256(("p" + key).encodeToByteArray()).toHex() + db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = key, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = key, nostrEventId = eventId, displayName = key.take(6), createdAt = Instant.fromEpochSeconds(1_790_000_000))) + } + + /** The ceremony's gift wraps, from every device to every other, until nothing moves. */ + private suspend fun pumpCeremony() { + var moved = true + while (moved) { + moved = false + for (from in network.everyDevice) for (to in network.everyDevice) { + if (from === to) continue + val fromRoom = ceremonyRooms.getValue(from.publicKey) + val toRoom = ceremonyRooms.getValue(to.publicKey) + from.db.giftWrapPayloadDao().getByChatRoomAndKinds(fromRoom.chatRoom.id, ConfederationRitualEvents.ALL.toList()) + .filter { it.publicKey == from.publicKey }.sortedBy { it.createdAt } + .forEach { original -> + if (!received.getValue(to.publicKey).add(original.id)) return@forEach + moved = true + to.db.giftWrapPayloadDao().upsert(original.copy(chatRoomId = toRoom.chatRoom.id)) + ConfederationRitualManager.process( + to.db, toRoom, + Event(original.id, original.publicKey, original.createdAt.epochSeconds, original.kind, original.tags, original.content, ""), + to.publicKey, to.secret, + ) + } + } + } + } + + /** The confederation's room: vouchers and the signing, from every device to every other. */ + private suspend fun pumpConfederationRoom() { + var moved = true + while (moved) { + moved = false + for (from in network.everyDevice) for (to in network.everyDevice) { + if (from === to) continue + from.db.marmotInnerEventDao().getByChatRoomAndKinds(confederation.id, ConfederationSigningEvents.ALL.toList()) + .filter { it.publicKey == from.publicKey }.sortedWith(compareBy({ it.createdAt }, { it.kind })) + .forEach { q -> + if (!received.getValue(to.publicKey).add(q.id)) return@forEach + moved = true + to.db.marmotInnerEventDao().upsert(q) + ConfederationSigningManager.process( + to.db, confederationRooms.getValue(to.publicKey), + Event(q.id, q.publicKey, q.createdAt.epochSeconds, q.kind, q.tags, q.content, ""), to.publicKey, to.secret, + ) + } + } + } + } + + private suspend fun sweepEverywhere() = + network.everyDevice.flatMap { ConfederationProfileFollowThrough.sweep(it.db, it.publicKey, it.secret) } + + private suspend fun proposeName(name: String): HexKey { + network.signed(agora) { device -> + ConfederationProfileManager.proposeChange(device.db, device.room(), device.publicKey, confederation.id, emptyArray(), """{"name":"$name","display_name":"$name"}""").id + } + return agora.devices[0].db.confederationDao().getEventsForConfederation(confederation.id) + .filter { it.kind == ConfederationKinds.PROFILE_CHANGE }.maxBy { it.eventCreatedAt }.id + } + + private suspend fun states(changeId: HexKey) = network.everyDevice.map { ConfederationProfileManager.status(it.db, changeId)?.state }.toSet() + + @Test + fun `a change proposed by one group, endorsed by another, is signed and read everywhere`() = runBlocking { + val changeId = proposeName("Atlas of the Coast") + assertEquals(setOf(ConfederationProfileChangeState.OPEN), states(changeId), "every admin of every group holds it") + pumpConfederationRoom() + assertEquals(emptyList(), sweepEverywhere(), "one group's voucher is not enough to start anything") + + network.signed(polis) { ConfederationProfileManager.proposeEndorsement(it.db, it.room(), it.publicKey, changeId).id } + assertEquals(setOf(ConfederationProfileChangeState.ENDORSED), states(changeId)) + pumpConfederationRoom() + + val started = sweepEverywhere() + assertEquals(1, started.size, "the first in the order starts the signing, and only they do") + pumpConfederationRoom() + + network.everyDevice.forEach { device -> + val attempt = device.db.confederationCeremonyDao().getAttempts(confederation.id, device.publicKey).single() + assertEquals(ConfederationSigningStage.COMPLETE, attempt.stage, "${device.name}: ${attempt.failureReason}") + assertTrue(!ConfederationSigningManager.isAwaitingApproval(attempt), "${device.name} was not asked") + assertEquals(ConfederationProfileChangeState.PUBLISHED, ConfederationProfileManager.status(device.db, changeId)?.state, device.name) + assertEquals("Atlas of the Coast", ConfederationProfileManager.profiles(device.db, confederation.id).newestProfile?.name(), device.name) + } + + // Each group's room said what happened, on every one of its admins' devices. + ekklesia.devices.forEach { device -> + val lines = device.db.chatMessageDao().getChatMessagesByChatRoomId(ekklesia.roomId).map { it.chatMessage.messageType } + assertTrue(ChatMessage.TYPE_CONFEDERATION_PROFILE_PROPOSED in lines, "${device.name}: $lines") + assertTrue(ChatMessage.TYPE_CONFEDERATION_PROFILE_ENDORSED in lines, "${device.name}: $lines") + assertTrue(ChatMessage.TYPE_CONFEDERATION_PROFILE_PUBLISHED in lines, "${device.name}: $lines") + } + + // A member of Polis who is no admin: no inbox key, no role, only Polis's room. The charter and + // the profile reach them from a relay. + val signed = Event.fromJson(started.single().let { attempt -> + network.everyDevice.first { it.publicKey == attempt.userPublicKey }.db.confederationCeremonyDao().getAttempt(attempt.id)!!.signedEventJson!! + }) + val charter = signCharter() + val watcher = getRoomDatabase(Room.inMemoryDatabaseBuilder()).also { databases += it } + val watcherKey = "f".repeat(63) + "1" + profile(watcher, watcherKey) + watcher.chatRoomDao().upsert(ChatRoom(id = polis.roomId, userPublicKey = watcherKey, subject = "#Polis", description = null, mlsGroupState = "00")) + assertTrue(ConfederationManager.record(watcher, charter)) + assertTrue(ConfederationManager.record(watcher, signed)) + assertEquals("Atlas of the Coast", ConfederationProfileManager.profiles(watcher, confederation.id).newestProfile?.name()) + assertEquals(1, watcher.chatMessageDao().getChatMessagesByChatRoomId(polis.roomId).count { it.chatMessage.messageType == ChatMessage.TYPE_CONFEDERATION_PROFILE_PUBLISHED }) + assertEquals(MetadataEvent.KIND, signed.kind) + } + + @Test + fun `a change another group objects to and its proposer withdraws is never signed`() = runBlocking { + val changeId = proposeName("Not Atlas") + network.signed(ekklesia) { ConfederationProfileManager.proposeObjection(it.db, it.room(), it.publicKey, changeId, "Keep the name").id } + network.signed(agora) { ConfederationProfileManager.proposeObjection(it.db, it.room(), it.publicKey, changeId).id } + assertEquals(setOf(ConfederationProfileChangeState.WITHDRAWN), states(changeId)) + pumpConfederationRoom() + assertEquals(emptyList(), sweepEverywhere()) + network.everyDevice.forEach { assertEquals(null, ConfederationProfileManager.profiles(it.db, confederation.id).newestProfile) } + } + + /** The confederation's charter, signed the direct way its charter still is: proposed and approved in its room. */ + private suspend fun signCharter(): Event { + val proposer = agora.devices[0] + val (kind, tags, content) = assertNotNull(ConfederationSigningManager.charterTemplate(proposer.db, confederation.id)) + val attempt = ConfederationSigningManager.propose(proposer.db, confederationRooms.getValue(proposer.publicKey), proposer.publicKey, kind, tags, content, proposer.secret) + pumpConfederationRoom() + network.everyDevice.filter { it !== proposer }.forEach { ConfederationSigningManager.approve(it.db, attempt.id, it.secret) } + pumpConfederationRoom() + return Event.fromJson(assertNotNull(proposer.db.confederationCeremonyDao().getAttempt(attempt.id)?.signedEventJson, "the charter is signed")) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfilePremiseJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfilePremiseJvmTest.kt new file mode 100644 index 00000000..8f3e3e04 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfilePremiseJvmTest.kt @@ -0,0 +1,136 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.frost.FrostSigningEvents +import mobi.giza.compose.nostr.frost.GroupKeyStateEvent +import mobi.giza.compose.nostr.inbox.InboxAnnouncement +import mobi.giza.compose.nostr.inbox.InboxReplyManifest +import mobi.giza.compose.nostr.inbox.InboxSeal +import mobi.giza.compose.nostr.inbox.InboxWire + +/** + * What docs/confederation-profile.md rests on, checked before anything is built on it (Phase 0, + * checks 2, 3 and 5). Check 1 is a reading of quartz and the app's kinds, and check 4 is + * `ConfederationSigningJvmTest`'s first case, which Phase 5 flips; both are recorded in the plan. + */ +class ConfederationProfilePremiseJvmTest { + private val databases = mutableListOf() + private var network: ConfederationTestGroups? = null + + @AfterTest + fun close() { + databases.forEach { it.close() } + network?.close() + } + + private fun key(n: Int, tag: Int) = ByteArray(32).also { it[0] = tag.toByte(); it[30] = (n shr 8).toByte(); it[31] = n.toByte() } + + private fun signed(secret: ByteArray, template: EventTemplate): Event { + val pubKey = InboxWire.publicKeyOf(secret) + val id = EventHasher.hashId(pubKey, template.createdAt, template.kind, template.tags, template.content) + return Event(id, pubKey, template.createdAt, template.kind, template.tags, template.content, Nip01Crypto.sign(id.hexToByteArray(), secret).toHex()) + } + + // ---- check 2: a batch of seals and one voucher, as the code stands --------------------- + + @Test + fun `today a statement's batch holding anything but seals is declined as a shape this device does not sign`() = runBlocking { + val db = getRoomDatabase(Room.inMemoryDatabaseBuilder()).also { databases += it } + val group = InboxWire.publicKeyOf(key(1, 0x41)) + val seal = Event("aa".repeat(32), group, 1_790_000_000, InboxSeal.KIND, arrayOf(arrayOf("n", "ab".repeat(32))), "sealed", "") + val voucher = Event("bb".repeat(32), group, 1_790_000_000, 9438, arrayOf(arrayOf("profile", "cc".repeat(32))), "", "") + val carried = ConfederationRefusal.Carried(rumorJson = """{"kind":9435}""", invitationJson = null) + assertEquals( + ConfederationRefusal.SHAPE, + ConfederationRefusal.of(db, group, "dd".repeat(32), listOf(seal, voucher), carried, manifest = null), + "Phase 2 teaches the refusal a voucher beside the seals", + ) + } + + // ---- check 3: how big a profile change to N groups is ----------------------------------- + + /** The bytes a FROST proposal for one 9435 to [groups] groups carries, with a kind:0 of [profileBytes]. */ + private fun changeBytes(groups: Int, profileBytes: Int): Int { + val npubs = (0 until groups).map { InboxWire.publicKeyOf(key(it, 0x51)) } + val confederation = InboxWire.publicKeyOf(key(0, 0x55)) + val inboxSecret = key(0, 0x52) + val about = "a".repeat(profileBytes) + val profile = """{"pubkey":"$confederation","created_at":1790000000,"kind":0,"tags":[],"content":"{\"name\":\"Atlas\",\"about\":\"$about\"}"}""" + val tags = npubs.drop(1).map { arrayOf("p", it) } + listOf( + arrayOf("confederation", confederation), arrayOf("base", "ee".repeat(32)), arrayOf("expiration", "1790259200"), + ) + val rumor = RumorAssembler.assembleRumor(npubs[0], EventTemplate(1_790_000_000, 9435, tags.toTypedArray(), profile)) + val recipients = npubs.mapIndexed { i, npub -> + val announced = if (i == 0) InboxWire.publicKeyOf(inboxSecret) else InboxWire.publicKeyOf(key(i, 0x54)) + val announcement = if (i == 0) null else signed(key(i, 0x51), InboxAnnouncement.keyTemplate(announced, 1_789_000_000)) + Triple(npub, announced, announcement) + } + val seals = recipients.map { (_, announced, _) -> + val t = InboxSeal.template(rumor, inboxSecret, announced, 1_789_900_000) + val id = EventHasher.hashId(npubs[0], t.createdAt, t.kind, t.tags, t.content) + Event(id, npubs[0], t.createdAt, t.kind, t.tags, t.content, "") + } + val voucherTags = arrayOf( + arrayOf("confederation", confederation), arrayOf("profile", "ff".repeat(32)), arrayOf("e", rumor.id), arrayOf("expiration", "1790259200"), + ) + val voucher = Event(EventHasher.hashId(npubs[0], 1_790_000_000, 9438, voucherTags, ""), npubs[0], 1_790_000_000, 9438, voucherTags, "", "") + val manifest = InboxReplyManifest(0, recipients.map { (npub, k, announcement) -> InboxReplyManifest.Entry(npub, k, announcement?.toJson()) }, 0) + return FrostSigningEvents.encodeProposal(seals + voucher).length + manifest.seal(inboxSecret).length + InboxSeal.rumorJson(rumor).length + } + + /** The longest profile text, in steps of 50 bytes, a change to [groups] groups can carry. */ + private fun largestProfile(groups: Int): Int = + (0..400).map { it * 50 }.lastOrNull { changeBytes(groups, it) <= ConfederationKinds.MAX_STATEMENT_BYTES } ?: -1 + + @Test + fun `a profile change carries the profile once per group, so the profile it can carry shrinks as the groups grow`() { + val at4k = (2..ConfederationKinds.MAX_SUPERGROUP_GROUPS).associateWith { changeBytes(it, 4_000) } + println("Profile change proposal bytes by groups, a 4 KB profile: $at4k") + val largest = (2..ConfederationKinds.MAX_SUPERGROUP_GROUPS).associateWith(::largestProfile) + println("Largest profile text that fits, by groups: $largest") + assertTrue(at4k.getValue(ConfederationKinds.MAX_SUPERGROUP_GROUPS) > ConfederationKinds.MAX_STATEMENT_BYTES, "a 4 KB profile does not fit twelve groups") + assertTrue(largest.getValue(ConfederationKinds.MAX_SUPERGROUP_GROUPS) >= 1_000, "a profile of a kilobyte fits twelve groups: $largest") + } + + // ---- check 5: a voucher verifies on a device in neither the group's room nor its inbox ---- + + @Test + fun `a voucher the group's quorum signed verifies under its npub anywhere`() = runBlocking { + val groups = ConfederationTestGroups(names = listOf("Agora", "Polis"), keySeries = 2).also { network = it } + groups.setUp() + val agora = groups.groups[0] + val now = kotlin.time.Clock.System.now().epochSeconds + // Signed the way Giza signs one: beside the seals of a change, in the same session + // (Phase 2 declines a voucher asked for on its own). The charter names the two groups. + val atlasKey = ByteArray(32).also { it[0] = 0x4b; it[31] = 1 } + val atlas = InboxWire.publicKeyOf(atlasKey) + val charter = signed(atlasKey, EventTemplate(now - 60, ConfederationKinds.CHARTER, + mobi.giza.compose.nostr.confederation.ConfederationCharterEvent.assembleTags("Atlas", groups.groups.map { it.roomId }, threshold = 2), "")) + groups.everyDevice.forEach { ConfederationManager.record(it.db, charter) } + val sessionId = groups.signed(agora) { device -> + ConfederationProfileManager.proposeChange(device.db, device.room(), device.publicKey, atlas, emptyArray(), """{"name":"Atlas"}""").id + } + val voucher = agora.devices[2].db.groupSignedEventDao().getByChatRoomIdAndKind(agora.roomId, 9438) + .single { it.frostSigningSessionId == sessionId }.toEvent() + + // A device that knows only Agora's npub: no room, no inbox key, no share. + assertTrue(GroupKeyStateEvent.isSignedByRoom(voucher, agora.roomId), "Agora's quorum signed it as Agora") + val forged = Event(voucher.id, groups.groups[1].roomId, voucher.createdAt, voucher.kind, voucher.tags, voucher.content, voucher.sig) + assertTrue(!GroupKeyStateEvent.isSignedByRoom(forged, groups.groups[1].roomId), "and not as anyone else") + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileReceiveJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileReceiveJvmTest.kt new file mode 100644 index 00000000..fe6e834d --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileReceiveJvmTest.kt @@ -0,0 +1,113 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import fr.acinq.bitcoin.PrivateKey +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.time.Clock +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.managers.ConfederationStatementFixture.key +import mobi.giza.compose.managers.ConfederationStatementFixture.npub +import mobi.giza.compose.managers.ConfederationStatementFixture.seal +import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements +import mobi.giza.compose.notifications.NotificationClassifier + +/** + * What a member group's device writes when it hears about a change to its confederation's profile + * (docs/confederation-profile.md, Phase 3): a line in each of its member groups' rooms, once per + * statement, whatever order the wraps arrive in. + */ +class ConfederationProfileReceiveJvmTest { + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + private val agora = key(1) + private val polis = key(2) + private val ekklesia = key(3) + private val atlasKey = key(9) + private val atlas = npub(atlasKey) + private val me = npub(key(20)) + private val now = Clock.System.now().epochSeconds + + @BeforeTest + fun setUp() = runBlocking { + // This device is in Polis and Ekklesia. + db.nostrEventDao().upsert(NostrEvent(id = "e$me".take(64), pubKey = me, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = me, nostrEventId = "e$me".take(64))) + listOf(polis to "#Polis", ekklesia to "#Ekklesia").forEach { (k, subject) -> + db.chatRoomDao().upsert(ChatRoom(id = npub(k), userPublicKey = me, subject = subject, description = null, mlsGroupState = "00")) + } + val tags = ConfederationCharterEvent.assembleTags("Atlas", listOf(npub(agora), npub(polis), npub(ekklesia)), threshold = 2) + ConfederationManager.record(db, signed(atlasKey, EventTemplate(now - 60, ConfederationKinds.CHARTER, tags, ""))) + } + + @AfterTest + fun close() = db.close() + + private fun signed(by: PrivateKey, template: EventTemplate): Event { + val pubKey = npub(by) + val id = EventHasher.hashId(pubKey, template.createdAt, template.kind, template.tags, template.content) + return Event(id, pubKey, template.createdAt, template.kind, template.tags, template.content, Nip01Crypto.sign(id.hexToByteArray(), by.value.toByteArray()).toHex()) + } + + private val changeRumor: Event = ConfederationProfileStatements.change( + npub(agora), listOf(npub(polis), npub(ekklesia)), atlas, 2, null, emptyArray(), """{"name":"Atlas"}""", now, now + 1000, + ) + private val change: ConfederationProfileStatements.Change = ConfederationProfileStatements.parseChange(changeRumor)!! + + private suspend fun lines(room: PrivateKey) = db.chatMessageDao().getChatMessagesByChatRoomId(npub(room)) + .map { it.chatMessage }.filter { it.messageType in ChatMessage.CONFEDERATION_PROFILE_TYPES } + + @Test + fun `a change from another group is a line in each of this device's member groups' rooms, that opens it`() = runBlocking { + ConfederationProfileManager.recordStatement(db, changeRumor, seal(agora, changeRumor), npub(polis)) + listOf(polis, ekklesia).forEach { room -> + val line = lines(room).single() + assertEquals(ChatMessage.TYPE_CONFEDERATION_PROFILE_PROPOSED, line.messageType) + assertEquals("${ConfederationManager.nameOf(db, npub(agora))} proposes a new profile for Atlas", line.content) + assertEquals(change.id, line.frostSigningSessionId, "the line opens the change") + } + // Heard again, nothing new. + ConfederationProfileManager.recordStatement(db, changeRumor, seal(agora, changeRumor), npub(polis)) + assertEquals(1, lines(polis).size) + } + + @Test + fun `an answer that arrives before its change gets its line when the change does`() = runBlocking { + val objection = ConfederationProfileStatements.objection(npub(ekklesia), change, "Not that name", now + 5) + ConfederationProfileManager.recordStatement(db, objection, seal(ekklesia, objection), npub(polis)) + assertEquals(emptyList(), lines(polis)) + + ConfederationProfileManager.recordStatement(db, changeRumor, seal(agora, changeRumor), npub(polis)) + val polisLines = lines(polis).sortedBy { it.createdAt } + assertEquals( + listOf(ChatMessage.TYPE_CONFEDERATION_PROFILE_PROPOSED, ChatMessage.TYPE_CONFEDERATION_PROFILE_OBJECTED), + polisLines.map { it.messageType }, + ) + assertEquals("${ConfederationManager.nameOf(db, npub(ekklesia))} objected to ${ConfederationManager.nameOf(db, npub(agora))}'s change to Atlas's profile: Not that name", polisLines[1].content) + assertEquals("This group objected to ${ConfederationManager.nameOf(db, npub(agora))}'s change to Atlas's profile: Not that name", lines(ekklesia).single { it.messageType == ChatMessage.TYPE_CONFEDERATION_PROFILE_OBJECTED }.content) + } + + @Test + fun `another group proposing notifies, and the answers are quiet`() { + assertEquals(true, ChatMessage.TYPE_CONFEDERATION_PROFILE_PROPOSED in NotificationClassifier.GROUP_ACTIVITY) + assertEquals(true, ChatMessage.TYPE_CONFEDERATION_PROFILE_PUBLISHED in NotificationClassifier.GROUP_ACTIVITY) + assertEquals(true, ChatMessage.TYPE_CONFEDERATION_PROFILE_ENDORSED in NotificationClassifier.SILENT) + assertEquals(true, ChatMessage.TYPE_CONFEDERATION_PROFILE_OBJECTED in NotificationClassifier.SILENT) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileRelayJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileRelayJvmTest.kt new file mode 100644 index 00000000..92a2e76f --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileRelayJvmTest.kt @@ -0,0 +1,118 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import fr.acinq.bitcoin.PrivateKey +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Instant +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.repository.DatabaseConfederationRepository +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.managers.ConfederationStatementFixture.key +import mobi.giza.compose.managers.ConfederationStatementFixture.npub +import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.inbox.InboxAnnouncement + +/** + * The confederation's profile on the public wire (docs/confederation-profile.md, Phase 6): a device + * that holds only the charter -- a member of a member group who is not an admin -- hears the signed + * profile off a relay, files it, and says so in its group's room; and an owed profile goes to every + * member group's inbox relays as well as the public ones. + */ +class ConfederationProfileRelayJvmTest { + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + private val repository = DatabaseConfederationRepository(db, kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined)) + + private val agora = key(1) + private val polis = key(2) + private val atlasKey = key(9) + private val atlas = npub(atlasKey) + private val me = npub(key(20)) + private val now = Clock.System.now().epochSeconds + + @BeforeTest + fun setUp() = runBlocking { + db.nostrEventDao().upsert(NostrEvent(id = "e$me".take(64), pubKey = me, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = me, nostrEventId = "e$me".take(64))) + // A member of Polis, and nothing more: no record of the confederation, no inbox key. + db.chatRoomDao().upsert(ChatRoom(id = npub(polis), userPublicKey = me, subject = "#Polis", description = null, mlsGroupState = "00")) + val tags = ConfederationCharterEvent.assembleTags("Atlas", listOf(npub(agora), npub(polis)), threshold = 2) + assertTrue(ConfederationManager.record(db, signed(atlasKey, EventTemplate(now - 60, ConfederationKinds.CHARTER, tags, "")))) + } + + @AfterTest + fun close() = db.close() + + private fun signed(by: PrivateKey, template: EventTemplate): Event { + val pubKey = npub(by) + val id = EventHasher.hashId(pubKey, template.createdAt, template.kind, template.tags, template.content) + return Event(id, pubKey, template.createdAt, template.kind, template.tags, template.content, Nip01Crypto.sign(id.hexToByteArray(), by.value.toByteArray()).toHex()) + } + + private fun profile(content: String, at: Long = now, by: PrivateKey = atlasKey) = signed(by, EventTemplate(at, MetadataEvent.KIND, emptyArray(), content)) + + private suspend fun publishedLines() = db.chatMessageDao().getChatMessagesByChatRoomId(npub(polis)) + .map { it.chatMessage }.filter { it.messageType == ChatMessage.TYPE_CONFEDERATION_PROFILE_PUBLISHED } + + @Test + fun `a member with only the charter hears the profile, and its group's room says so`() = runBlocking { + assertTrue(repository.record(profile("""{"name":"Atlas of the Coast"}""")), "filed from the relay") + assertEquals("Atlas of the Coast", repository.observeProfile(atlas).first()?.name()) + val line = publishedLines().single() + assertEquals("Atlas has a new profile, as Atlas of the Coast", line.content) + assertEquals(atlas, line.frostSigningSessionId, "the line opens the confederation") + assertEquals(listOf(atlas), repository.observeKnownConfederations().first(), "and the relays are asked for it by its key") + } + + @Test + fun `an older profile heard late changes nothing a reader sees`() = runBlocking { + repository.record(profile("""{"name":"Atlas of the Coast"}""", at = now)) + repository.record(profile("""{"name":"Atlas"}""", at = now - 100)) + assertEquals("Atlas of the Coast", repository.observeProfile(atlas).first()?.name()) + assertEquals(1, publishedLines().size) + } + + @Test + fun `a kind 0 from anyone but a known confederation is not the confederation's`() = runBlocking { + assertFalse(repository.record(profile("""{"name":"Someone"}""", by = key(30)))) + assertFalse(repository.record(Event(profile("{}").id, atlas, now, 0, emptyArray(), "{}", "00".repeat(64))), "nor one its key did not sign") + assertEquals(emptyList(), publishedLines()) + } + + @Test + fun `an owed profile goes to every member group's inbox relays as well`() = runBlocking { + val relays = listOf("wss://agora.example.com", "wss://polis.example.com") + listOf(agora, polis).zip(relays).forEach { (group, url) -> + val announcement = signed(group, InboxAnnouncement.relaysTemplate(listOf(RelayUrlNormalizer.normalizeOrNull(url)!!), now - 30)) + db.nostrEventDao().upsert( + NostrEvent( + id = announcement.id, pubKey = announcement.pubKey, kind = announcement.kind, tags = announcement.tags, + content = announcement.content, sig = announcement.sig, createdAt = Instant.fromEpochSeconds(announcement.createdAt), + ) + ) + } + repository.record(profile("""{"name":"Atlas"}""")) + val row = db.confederationDao().getEventsForConfederation(atlas).single { it.kind == MetadataEvent.KIND } + assertEquals(relays.map { "$it/" }.toSet(), repository.extraRelaysFor(row).toSet()) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileStatementJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileStatementJvmTest.kt new file mode 100644 index 00000000..ded3e132 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileStatementJvmTest.kt @@ -0,0 +1,235 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import fr.acinq.bitcoin.PrivateKey +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState +import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements +import mobi.giza.compose.nostr.frost.FrostSigningEvents + +/** + * A formed confederation's groups deciding its profile, group to group (docs/confederation-profile.md, + * Phase 2): three real groups, each signing by FROST and holding an inbox, a charter naming them, and + * every statement sealed by one group's quorum to every other group's inbox. Then what a member's + * device refuses to sign. + */ +class ConfederationProfileStatementJvmTest { + private val network = ConfederationTestGroups(keySeries = 3) + private val agora = network.groups[0] + private val polis = network.groups[1] + private val ekklesia = network.groups[2] + private val atlasKey = PrivateKey(ByteArray(32).also { it[0] = 0x4a; it[31] = 1 }) + private val atlas: HexKey = atlasKey.publicKey().xOnly().value.toHex() + private val now get() = Clock.System.now().epochSeconds + + @BeforeTest + fun setUp() = runBlocking { + network.setUp() + val charter = signed( + atlasKey, + EventTemplate( + now - 60, ConfederationKinds.CHARTER, + ConfederationCharterEvent.assembleTags("Atlas", network.groups.map { it.roomId }, threshold = 2), + ConfederationCharterEvent.content("Atlas", 3), + ), + ) + network.everyDevice.forEach { assertTrue(ConfederationManager.record(it.db, charter)) } + } + + @AfterTest + fun close() = network.close() + + private fun signed(by: PrivateKey, template: EventTemplate): Event { + val pubKey = by.publicKey().xOnly().value.toHex() + val id = EventHasher.hashId(pubKey, template.createdAt, template.kind, template.tags, template.content) + return Event(id, pubKey, template.createdAt, template.kind, template.tags, template.content, Nip01Crypto.sign(id.hexToByteArray(), by.value.toByteArray()).toHex()) + } + + private val profile = """{"name":"Atlas of the Coast","about":"Three groups"}""" + + private suspend fun proposeChange(content: String = profile, except: Set = emptySet()): HexKey { + network.signed(agora, except) { device -> + ConfederationProfileManager.proposeChange(device.db, device.room(), device.publicKey, atlas, emptyArray(), content).id + } + return agora.devices[0].db.confederationDao().getEventsForConfederation(atlas).single { it.kind == ConfederationKinds.PROFILE_CHANGE }.id + } + + private suspend fun states(changeId: HexKey) = network.everyDevice.map { ConfederationProfileManager.status(it.db, changeId)?.state }.toSet() + + // ---- group to group ---------------------------------------------------------------------------- + + @Test + fun `a change reaches every admin of every group, and the proposer's quorum vouches for it`() = runBlocking { + val changeId = proposeChange() + assertEquals(setOf(ConfederationProfileChangeState.OPEN), states(changeId)) + network.everyDevice.forEach { device -> + val status = assertNotNull(ConfederationProfileManager.status(device.db, changeId), "on ${device.name}") + assertEquals(listOf(agora.roomId), status.endorsers) + assertEquals("Atlas of the Coast", ConfederationProfileRefusal.metadataOf(status.change.profile)?.anyName()) + } + // Agora's voucher, signed in the same session, is on Agora's devices and nobody else's. + agora.devices.forEach { assertEquals(setOf(agora.roomId), ConfederationProfileManager.status(it.db, changeId)!!.vouchers.keys) } + polis.devices.forEach { assertEquals(emptySet(), ConfederationProfileManager.status(it.db, changeId)!!.vouchers.keys) } + // Nobody's inbox shows it as a conversation. + network.everyDevice.forEach { assertEquals(emptyList(), it.db.groupInboxDao().getMessages(network.groups.first { g -> it in g.devices }.roomId)) } + } + + @Test + fun `a second group's endorsement makes it endorsed everywhere`() = runBlocking { + val changeId = proposeChange() + network.signed(polis) { ConfederationProfileManager.proposeEndorsement(it.db, it.room(), it.publicKey, changeId).id } + assertEquals(setOf(ConfederationProfileChangeState.ENDORSED), states(changeId)) + polis.devices.forEach { assertEquals(setOf(polis.roomId), ConfederationProfileManager.status(it.db, changeId)!!.vouchers.keys) } + } + + @Test + fun `two objections out of three decline it, and the proposer can withdraw one still open`() = runBlocking { + val changeId = proposeChange() + network.signed(polis) { ConfederationProfileManager.proposeObjection(it.db, it.room(), it.publicKey, changeId, "Too long").id } + assertEquals(setOf(ConfederationProfileChangeState.OPEN), states(changeId)) + network.signed(agora) { ConfederationProfileManager.proposeObjection(it.db, it.room(), it.publicKey, changeId).id } + assertEquals(setOf(ConfederationProfileChangeState.WITHDRAWN), states(changeId)) + } + + @Test + fun `a device that missed the change answers from the invitation its signing proposal carries`() = runBlocking { + val forgetful = polis.devices[1] + val changeId = proposeChange(except = setOf(forgetful)) + assertNull(ConfederationProfileManager.change(forgetful.db, changeId)) + network.signed(polis) { ConfederationProfileManager.proposeEndorsement(it.db, it.room(), it.publicKey, changeId).id } + assertNotNull(ConfederationProfileManager.change(forgetful.db, changeId), "filed from the carried invitation") + } + + @Test + fun `a profile too long for every group's seal is refused before anything is asked`() = runBlocking { + val device = agora.devices[0] + val failure = assertFailsWith { + ConfederationProfileManager.proposeChange(device.db, device.room(), device.publicKey, atlas, emptyArray(), """{"about":"${"a".repeat(20_000)}"}""") + } + assertEquals(ConfederationProfileManager.tooLongFor(3), failure.message) + } + + // ---- refusals ---------------------------------------------------------------------------------- + + private val proposer get() = agora.devices[0] + private val signer get() = agora.devices[1] + + private suspend fun declines(device: GroupInboxHarness.Device, roomId: HexKey) = + device.db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(FrostSigningEvents.DECLINE)) + .filter { it.publicKey == device.publicKey }.map { it.content } + + private suspend fun assertAsked(device: GroupInboxHarness.Device, sessionId: String) { + val session = assertNotNull(device.db.frostSigningSessionDao().getSessionById(sessionId)) + assertNull(session.signDeclinedAt, "not declined: ${ConfederationRefusal.reasonFor(device.db, sessionId)}") + } + + private suspend fun assertDeclined(device: GroupInboxHarness.Device, roomId: HexKey, sessionId: String, reason: String) { + val session = assertNotNull(device.db.frostSigningSessionDao().getSessionById(sessionId)) + assertNotNull(session.signDeclinedAt, "declined: ${ConfederationRefusal.reasonFor(device.db, sessionId)}") + assertEquals(listOf(reason), declines(device, roomId)) + } + + private suspend fun propose(build: suspend (GroupInboxHarness.Device) -> FrostSigningSession): FrostSigningSession = + build(proposer).also { agora.harness.pump() } + + @Test + fun `a change is put to the member with what it would change`() = runBlocking { + val session = propose { ConfederationProfileManager.proposeChange(it.db, it.room(), it.publicKey, atlas, emptyArray(), profile) } + assertAsked(signer, session.id) + val notes = ConfederationRefusal.notes(signer.db, agora.roomId, session.id, signer.db.frostSigningSessionDao().getItems(session.id).map { Event.fromJson(it.unsignedEventJson) }) + assertTrue(notes.contains("A new profile for Atlas"), "$notes") + assertTrue(notes.contains("Name: (none) → Atlas of the Coast"), "$notes") + assertTrue(notes.contains("2 of 3 groups must endorse it"), "$notes") + } + + @Test + fun `a device that holds a newer profile than the change edits declines it`() = runBlocking { + val newer = signed(atlasKey, EventTemplate(now - 30, 0, emptyArray(), """{"name":"Atlas"}""")) + ConfederationProfileManager.recordProfile(signer.db, newer) + val session = propose { ConfederationProfileManager.proposeChange(it.db, it.room(), it.publicKey, atlas, emptyArray(), profile) } + assertDeclined(signer, agora.roomId, session.id, ConfederationProfileRefusal.STALE) + } + + @Test + fun `a device that has never heard of the confederation declines`() = runBlocking { + signer.db.confederationDao().getCharters(atlas).forEach { signer.db.confederationDao().deleteEvent(it.id) } + val session = propose { ConfederationProfileManager.proposeChange(it.db, it.room(), it.publicKey, atlas, emptyArray(), profile) } + assertDeclined(signer, agora.roomId, session.id, ConfederationProfileRefusal.UNKNOWN_CONFEDERATION) + } + + @Test + fun `a profile nothing could show is declined`() = runBlocking { + val session = propose { ConfederationProfileManager.proposeChange(it.db, it.room(), it.publicKey, atlas, emptyArray(), "not a profile") } + assertDeclined(signer, agora.roomId, session.id, ConfederationProfileRefusal.UNREADABLE) + } + + @Test + fun `a voucher for anything but exactly the change is declined`() = runBlocking { + val session = propose { device -> + val rumor = ConfederationProfileStatements.change( + agora.roomId, listOf(polis.roomId, ekklesia.roomId), atlas, 2, null, emptyArray(), profile, now, now + 1000, + ) + val other = ConfederationProfileStatements.parseChange( + ConfederationProfileStatements.change(agora.roomId, listOf(polis.roomId, ekklesia.roomId), atlas, 2, null, emptyArray(), "{}", now, now + 1000), + )!! + ConfederationManager.proposeStatement( + device.db, device.room(), device.publicKey, rumor, listOf(polis.roomId, ekklesia.roomId), invitation = null, + extra = listOf(ConfederationProfileStatements.voucherTemplate(other, now)), + ) + } + assertDeclined(signer, agora.roomId, session.id, ConfederationProfileRefusal.VOUCHER) + } + + @Test + fun `a change with no voucher is declined`() = runBlocking { + val session = propose { device -> + val rumor = ConfederationProfileStatements.change( + agora.roomId, listOf(polis.roomId, ekklesia.roomId), atlas, 2, null, emptyArray(), profile, now, now + 1000, + ) + ConfederationManager.proposeStatement(device.db, device.room(), device.publicKey, rumor, listOf(polis.roomId, ekklesia.roomId), invitation = null) + } + assertDeclined(signer, agora.roomId, session.id, ConfederationProfileRefusal.VOUCHER) + } + + @Test + fun `a voucher asked for on its own is declined`() = runBlocking { + val change = ConfederationProfileStatements.parseChange( + ConfederationProfileStatements.change(agora.roomId, listOf(polis.roomId, ekklesia.roomId), atlas, 2, null, emptyArray(), profile, now, now + 1000), + )!! + val session = propose { FrostSigningManager.proposeSigningBatch(it.db, it.room(), it.publicKey, listOf(ConfederationProfileStatements.voucherTemplate(change, now))) } + assertDeclined(signer, agora.roomId, session.id, ConfederationRefusal.SHAPE) + } + + @Test + fun `answering a change that is closed, or twice, is declined`() = runBlocking { + val changeId = proposeChange() + network.signed(polis) { ConfederationProfileManager.proposeObjection(it.db, it.room(), it.publicKey, changeId).id } + val again = ConfederationProfileManager.proposeEndorsement(polis.devices[0].db, polis.devices[0].room(), polis.devices[0].publicKey, changeId) + polis.harness.pump() + assertDeclined(polis.devices[1], polis.roomId, again.id, ConfederationProfileRefusal.ANSWERED) + + network.signed(ekklesia) { ConfederationProfileManager.proposeObjection(it.db, it.room(), it.publicKey, changeId).id } + assertEquals(setOf(ConfederationProfileChangeState.DECLINED), states(changeId)) + val late = ConfederationProfileManager.proposeObjection(agora.devices[0].db, agora.devices[0].room(), agora.devices[0].publicKey, changeId) + agora.harness.pump() + assertDeclined(agora.devices[1], agora.roomId, late.id, ConfederationProfileRefusal.CLOSED) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileStorageJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileStorageJvmTest.kt new file mode 100644 index 00000000..d4db316c --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationProfileStorageJvmTest.kt @@ -0,0 +1,116 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import fr.acinq.bitcoin.PrivateKey +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.repository.DatabaseConfederationRepository +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.managers.ConfederationStatementFixture.key +import mobi.giza.compose.managers.ConfederationStatementFixture.npub +import mobi.giza.compose.managers.ConfederationStatementFixture.seal +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState +import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements + +/** A confederation's profile changes, filed and read back (docs/confederation-profile.md, Phase 1). */ +class ConfederationProfileStorageJvmTest { + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun close() = db.close() + + private val agora = key(1) + private val polis = key(2) + private val ekklesia = key(3) + private val atlasKey = key(9) + private val atlas = npub(atlasKey) + private val now = Clock.System.now().epochSeconds + + private fun changeRumor(content: String = """{"name":"Atlas"}""", createdAt: Long = now) = ConfederationProfileStatements.change( + npub(agora), listOf(npub(polis), npub(ekklesia)), atlas, 2, null, emptyArray(), content, createdAt, + createdAt + ConfederationKinds.DEFAULT_CHANGE_EXPIRY_SECONDS, + ) + + private fun signed(by: PrivateKey, template: EventTemplate): Event { + val pubKey = npub(by) + val id = EventHasher.hashId(pubKey, template.createdAt, template.kind, template.tags, template.content) + return Event(id, pubKey, template.createdAt, template.kind, template.tags, template.content, Nip01Crypto.sign(id.hexToByteArray(), by.value.toByteArray()).toHex()) + } + + private suspend fun file(by: PrivateKey, rumor: Event) = ConfederationProfileManager.recordStatement(db, rumor, seal(by, rumor), inboxRoomId = null) + + @Test + fun `a change and its answers are filed under the confederation, once each`() = runBlocking { + val rumor = changeRumor() + assertTrue(file(agora, rumor)) + assertFalse(file(agora, rumor), "a second copy is the same one") + val change = ConfederationProfileStatements.parseChange(rumor)!! + assertTrue(file(polis, ConfederationProfileStatements.endorsement(npub(polis), change, now + 1))) + + val row = assertNotNull(db.confederationDao().getEvent(rumor.id)) + assertEquals(atlas, row.confederationId) + assertEquals(rumor.id, row.proposalId, "a change stands as its own proposal") + assertEquals(2, db.confederationDao().getEventsForConfederation(atlas).size) + assertEquals(emptyList(), db.confederationDao().getProposals(), "not a formation proposal") + + assertEquals(ConfederationProfileChangeState.ENDORSED, ConfederationProfileManager.status(db, rumor.id)?.state) + } + + @Test + fun `a statement in a seal that is not its author's is dropped`() = runBlocking { + val rumor = changeRumor() + assertFalse(ConfederationProfileManager.recordStatement(db, rumor, seal(polis, rumor), null)) + assertEquals(null, db.confederationDao().getEvent(rumor.id)) + } + + @Test + fun `a voucher is filed only if its group's key signed it`() = runBlocking { + val change = ConfederationProfileStatements.parseChange(changeRumor())!! + val voucher = signed(polis, ConfederationProfileStatements.voucherTemplate(change, now + 1)) + assertTrue(ConfederationProfileManager.recordVoucher(db, voucher)) + + val forged = Event(voucher.id, npub(ekklesia), voucher.createdAt, voucher.kind, voucher.tags, voucher.content, voucher.sig) + assertFalse(ConfederationProfileManager.recordVoucher(db, forged)) + + file(agora, changeRumor()) + val status = assertNotNull(ConfederationProfileManager.status(db, change.id)) + assertEquals(setOf(npub(polis)), status.vouchers.keys) + } + + @Test + fun `the confederation's signed profile publishes one change and supersedes the older`() = runBlocking { + val older = changeRumor("""{"name":"Atlas"}""", createdAt = now - 10) + val newer = changeRumor("""{"name":"Atlas of the Coast"}""", createdAt = now) + file(agora, older) + file(agora, newer) + val profile = ConfederationProfileStatements.parseChange(newer)!!.profile + val signedProfile = signed(atlasKey, EventTemplate(profile.createdAt, profile.kind, profile.tags, profile.content)) + assertEquals(profile.id, signedProfile.id) + assertTrue(ConfederationProfileManager.recordProfile(db, signedProfile, newer.id), "filed with no room for the confederation") + assertFalse(ConfederationProfileManager.recordProfile(db, Event(signedProfile.id, atlas, signedProfile.createdAt, 0, signedProfile.tags, signedProfile.content, "00".repeat(64)))) + + val states = ConfederationProfileManager.statusesOf(db, atlas).associate { it.change.id to it.state } + assertEquals(ConfederationProfileChangeState.PUBLISHED, states[newer.id]) + assertEquals(ConfederationProfileChangeState.SUPERSEDED, states[older.id]) + assertEquals(listOf(newer.id, older.id), ConfederationProfileManager.statusesOf(db, atlas).map { it.change.id }, "newest first") + + val repository = DatabaseConfederationRepository(db, this) + assertEquals(listOf(newer.id, older.id), repository.observeProfileChanges(atlas).first().map { it.change.id }) + assertEquals(ConfederationProfileChangeState.SUPERSEDED, repository.observeProfileChange(older.id).first()?.state) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt index 4a1acab3..c5df5012 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt @@ -33,6 +33,11 @@ import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents import mobi.giza.compose.nostr.frost.GroupKeyStateEvent +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeState +import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.minutes /** * A confederation signing as itself, one person per device (docs/confederation.md, Phase 14): a @@ -105,7 +110,7 @@ class ConfederationSigningJvmTest { } } - private fun propose(kind: Int = MetadataEvent.KIND, content: String = """{"name":"Atlas","about":"A group of groups"}""") = runBlocking { + private fun propose(kind: Int = TextNoteEvent.KIND, content: String = "The first words of a group of groups") = runBlocking { ConfederationSigningManager.propose(proposer.db, proposer.room, proposer.person, kind, emptyArray(), content, proposer.nsec) } @@ -116,7 +121,7 @@ class ConfederationSigningJvmTest { private fun attempts(attemptId: String) = runBlocking { devices.values.associate { it.person to it.db.confederationCeremonyDao().getAttempt(attemptId) } } @Test - fun `the confederation signs its profile, and every device holds it signed as the room`() { + fun `the confederation signs a post, and every device holds it signed as the room`() { val attempt = propose() pump() approve(attempt.id, people - 11) @@ -129,8 +134,156 @@ class ConfederationSigningJvmTest { runBlocking { devices.values.forEach { d -> - val rows = d.db.groupSignedEventDao().getByChatRoomIdAndKind(confederation.id, MetadataEvent.KIND) - assertEquals("Atlas", assertNotNull(GroupNostrProfile.newestAmong(rows, confederation.id)).name()) + assertEquals(listOf(signed.first().id), d.db.groupSignedEventDao().getByChatRoomIdAndKind(confederation.id, TextNoteEvent.KIND).map { it.id }) + } + } + } + + // ---- docs/confederation-profile.md, Phase 5: a profile on its groups' word ------------------ + + @Test + fun `a profile proposed in the room directly is refused, since it changes through its groups`() { + val failure = assertFailsWith { propose(kind = MetadataEvent.KIND, content = """{"name":"Atlas"}""") } + assertEquals(ConfederationSigningManager.THROUGH_GROUPS, failure.message) + } + + private val now get() = Clock.System.now().epochSeconds + + /** Agora proposes a profile and Polis endorses it, every device holding both, as their inboxes would. */ + private fun endorsedChange(content: String = """{"name":"Atlas","about":"A group of groups"}""", endorsers: List = listOf(1)): ConfederationProfileStatements.Change = runBlocking { + val rumor = ConfederationProfileStatements.change( + groups[0], groups.drop(1), confederation.id, 2, null, emptyArray(), content, now - 5, now + 1000, + ) + val change = ConfederationProfileStatements.parseChange(rumor)!! + val answers = endorsers.map { i -> network.groupKeys[i] to ConfederationProfileStatements.endorsement(groups[i], change, now - 4) } + devices.values.forEach { d -> + ConfederationProfileManager.recordStatement(d.db, rumor, ConfederationStatementFixture.seal(network.groupKeys[0], rumor), null) + answers.forEach { (key, answer) -> ConfederationProfileManager.recordStatement(d.db, answer, ConfederationStatementFixture.seal(key, answer), null) } + } + change + } + + /** [group]'s voucher for [change], as its quorum signs it, posted into the room by its role holder [poster]. */ + private fun vouch(change: ConfederationProfileStatements.Change, group: Int, poster: Int) = runBlocking { + val template = ConfederationProfileStatements.voucherTemplate(change, now - 3) + val key = network.groupKeys[group] + val id = com.vitorpamplona.quartz.nip01Core.crypto.EventHasher.hashId(groups[group], template.createdAt, template.kind, template.tags, template.content) + val voucher = Event(id, groups[group], template.createdAt, template.kind, template.tags, template.content, + com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto.sign(id.hexToByteArray(), key.value.toByteArray()).toHex()) + val device = devices.getValue(npub(secret(poster))) + ConfederationProfileManager.recordVoucher(device.db, voucher) + ConfederationSigningManager.postVoucher(device.db, device.person, voucher) + } + + /** The role holders in the follow-through's order: the roster's people, sorted. */ + private val order get() = devices.values.sortedBy { it.person } + + private fun sweep(at: Instant = Clock.System.now(), who: List = order) = runBlocking { + who.flatMap { ConfederationProfileFollowThrough.sweep(it.db, it.person, it.nsec, at) } + } + + private fun profileAttempts(change: ConfederationProfileStatements.Change) = runBlocking { + devices.values.associate { d -> + d.person to d.db.confederationCeremonyDao().getAttempts(confederation.id, d.person) + .filter { Event.fromJson(it.eventJson).id == change.profileId } + } + } + + @Test + fun `two groups' vouchers, and the profile is signed with nobody asked`() { + val change = endorsedChange() + vouch(change, group = 0, poster = 11) + vouch(change, group = 1, poster = 21) + pump() + + val started = sweep() + assertEquals(1, started.size, "the first in the order starts it, and only they do") + pump() + + profileAttempts(change).forEach { (person, list) -> + val attempt = list.single() + assertEquals(ConfederationSigningStage.COMPLETE, attempt.stage, "${person.take(6)}: ${attempt.failureReason}") + assertTrue(!ConfederationSigningManager.isAwaitingApproval(attempt), "nobody is asked") + } + runBlocking { + // Ekklesia did not vouch, so its admins' seats said no. + listOf(31, 32, 33).forEach { n -> + val said = devices.getValue(npub(secret(n))).db.confederationCeremonyDao() + .getSigningMessage(profileAttempts(change).values.first().single().id, npub(secret(n)), ConfederationSigningEvents.AVAILABILITY) + assertEquals(mapOf(groups[2] to ConfederationSigningEvents.NO), ConfederationRitualEvents.decodeByGroup(said!!.payload)) + } + devices.values.forEach { d -> + assertEquals(ConfederationProfileChangeState.PUBLISHED, ConfederationProfileManager.status(d.db, change.id)?.state, "on ${d.person.take(6)}") + assertEquals("Atlas", ConfederationProfileManager.profiles(d.db, confederation.id).newestProfile?.name()) + } + assertEquals(1, started.single().let { a -> devices.values.first { it.person == a.userPublicKey } }.db.confederationDao().observeUnpublished().first() + .count { it.kind == MetadataEvent.KIND }, "the device that started it owes it to relays") + } + } + + @Test + fun `with only one group's voucher there is nothing to start`() { + val change = endorsedChange(endorsers = emptyList()) + vouch(change, group = 0, poster = 11) + pump() + assertEquals(emptyList(), sweep(Clock.System.now() + 1.hours)) + } + + @Test + fun `with the first in the order away, the second starts it ten minutes later`() { + val change = endorsedChange() + vouch(change, group = 0, poster = 11) + vouch(change, group = 1, poster = 21) + pump() + val rest = order.drop(1) + assertEquals(emptyList(), sweep(Clock.System.now() + 5.minutes, rest), "not yet") + val started = sweep(Clock.System.now() + 11.minutes, rest) + assertEquals(listOf(order[1].person), started.map { it.userPublicKey }) + } + + @Test + fun `an attempt lost to a restart is started again after the backoff, and signs`() { + val change = endorsedChange() + vouch(change, group = 0, poster = 11) + vouch(change, group = 1, poster = 21) + pump() + sweep() + pump(hold = { it.kind == ConfederationSigningEvents.NONCES }) + ConfederationSigningManager.forgetSignersForTest() + pump() + profileAttempts(change).values.forEach { assertEquals(ConfederationSigningStage.FAILED, it.single().stage) } + + assertEquals(emptyList(), sweep(Clock.System.now() + 5.minutes), "the backoff first") + assertEquals(1, sweep(Clock.System.now() + 11.minutes).size) + pump() + profileAttempts(change).forEach { (person, list) -> + assertEquals(ConfederationSigningStage.COMPLETE, list.last().stage, "${person.take(6)}: ${list.last().failureReason}") + } + } + + @Test + fun `two attempts over one change end in the one whose id sorts first`() { + val change = endorsedChange() + vouch(change, group = 0, poster = 11) + vouch(change, group = 1, poster = 21) + pump() + val vouchers = runBlocking { ConfederationSigningManager.vouchersFor(proposer.db, ConfederationSigningManager.held(proposer.db, confederation.id)!!, change.profileId) } + val a = order[0] + val b = order[1] + val attempts = listOf(a, b).map { d -> + runBlocking { + ConfederationSigningManager.propose(d.db, d.room, d.person, 0, change.profile.tags, change.profile.content, d.nsec, change.profile.createdAt, vouchers) + } + } + pump() + val keep = attempts.minBy { it.id }.id + profileAttempts(change).forEach { (person, list) -> + list.forEach { attempt -> + if (attempt.id == keep) { + assertEquals(ConfederationSigningStage.COMPLETE, attempt.stage, "${person.take(6)}: ${attempt.failureReason}") + } else { + assertEquals(ConfederationSigningStage.FAILED, attempt.stage) + } } } } @@ -180,6 +333,33 @@ class ConfederationSigningJvmTest { assertFailsWith { propose(kind = TextNoteEvent.KIND, content = " ") } } + // ---- docs/confederation-profile.md, Phase 7: rooms that say what they are ------------------ + + @Test + fun `the confederation's room says which group each of its people holds roles for`() = runBlocking { + val polisMember = devices.getValue(npub(secret(22))) + polisMember.db.chatRoomDao().upsert(ChatRoom(id = groups[1], userPublicKey = polisMember.person, subject = "#Polis", description = null, mlsGroupState = "00")) + val repository = mobi.giza.compose.database.repository.DatabaseChatRepository(polisMember.db, kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined)) + + val info = assertNotNull(repository.confederationRoomInfo(confederation.id)) + assertEquals("Atlas", info.name) + assertEquals(listOf("Agora", "Polis", "Ekklesia").sorted(), info.groups.map { it.first }.sorted()) + info.groups.forEach { (_, holders) -> assertEquals(3, holders.size) } + assertEquals(listOf("Polis"), info.groupsOfMember[npub(secret(22))]) + assertEquals(groups[1], info.homeGroupId, "the confederation's screen opens from the member group this device is in") + assertEquals(null, repository.confederationRoomInfo(groups[1]), "a member group's own room is not the confederation's") + } + + @Test + fun `once formed, the key ceremony's room leads to the confederation`() = runBlocking { + val device = devices.getValue(npub(secret(11))) + val repository = mobi.giza.compose.database.repository.DatabaseChatRepository(device.db, kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined)) + val link = assertNotNull(repository.keyCeremonyOfRoom(device.ceremonyDevice.room.chatRoom.id)) + val formed = assertNotNull(link.formed, "the ceremony made the confederation") + assertEquals(confederation.id, formed.confederationId) + assertEquals("Atlas", formed.name) + } + // ---- Phase 15: the charter ------------------------------------------------------------ @Test diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileScreensJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileScreensJvmTest.kt new file mode 100644 index 00000000..e21d5d90 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationProfileScreensJvmTest.kt @@ -0,0 +1,213 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Box +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.assertIsDisplayed +import androidx.compose.ui.test.assertIsEnabled +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.runDesktopComposeUiTest +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto +import kotlin.test.Test +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.GroupSignedEvent +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.managers.ConfederationStatementFixture +import mobi.giza.compose.nostr.GroupNostrProfile +import mobi.giza.compose.nostr.confederation.ConfederationProfileChangeStatus +import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.repository.ProfileChangeProblem +import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.view.model.ConfederationProfileChangeViewModel +import mobi.giza.compose.ui.view.state.ConfederationProfileChangeUIState +import mobi.giza.compose.ui.view.state.ConfederationUIState +import mobi.giza.compose.ui.view.state.EditConfederationProfileUIState + +/** A confederation's screen, its profile form and a change to its profile, as a member meets them (docs/confederation-profile.md, Phase 4). */ +@OptIn(ExperimentalTestApi::class) +class ConfederationProfileScreensJvmTest { + private val agora = ConfederationStatementFixture.npub(1) + private val polis = ConfederationStatementFixture.npub(2) + private val atlasKey = ConfederationStatementFixture.key(9) + private val atlas = ConfederationStatementFixture.npub(atlasKey) + private val now = 1_790_000_000L + + private val localChatRoom = LocalChatRoom( + chatRoom = ChatRoom(id = agora, userPublicKey = "a".repeat(64), subject = "#Agora", description = null, mlsGroupState = "state") + ) + + private val signedProfile: GroupNostrProfile = run { + val content = """{"name":"Atlas","about":"Two groups"}""" + val id = EventHasher.hashId(atlas, now - 100, 0, emptyArray(), content) + val event = Event(id, atlas, now - 100, 0, emptyArray(), content, Nip01Crypto.sign(id.hexToByteArray(), atlasKey.value.toByteArray()).toHex()) + GroupNostrProfile.of(GroupSignedEvent.fromEvent(event, chatRoomId = atlas), atlas)!! + } + + private fun change(by: String, content: String = """{"name":"Atlas of the Coast","about":"Two groups"}""") = + ConfederationProfileStatements.parseChange( + ConfederationProfileStatements.change(by, listOf(if (by == agora) polis else agora), atlas, 2, signedProfile.signedEvent.id, emptyArray(), content, now, now + 1000) + )!! + + private fun status(change: ConfederationProfileStatements.Change) = + ConfederationProfileChangeStatus.of(change, emptyList(), emptyList(), null, published = false, now = now + 1) + + private fun loaded( + readsChanges: Boolean = true, + problem: ProfileChangeProblem? = null, + changes: List = emptyList(), + ) = ConfederationUIState.Loaded( + localChatRoom = localChatRoom, + confederationId = atlas, + name = "Atlas", + threshold = 2, + groups = listOf( + ConfederationUIState.Group(agora, "Agora", listOf("alice", "bob")), + ConfederationUIState.Group(polis, "Polis", emptyList()), + ), + profile = signedProfile, + changes = changes, + readsChanges = readsChanges, + problem = problem, + names = mapOf(agora to "This group", polis to "Polis"), + ) + + // ---- the confederation's screen ---------------------------------------------------------------- + + @Test + fun `an admin sees the profile, the groups with who holds their roles, the changes and the way to edit`() = renderConfederation( + loaded(changes = listOf(status(change(by = polis)))) + ) { + onNodeWithText("Two groups").assertIsDisplayed() + onNodeWithText("Polis").assertIsDisplayed() + onNodeWithText("2 admins hold its key").assertIsDisplayed() + onNodeWithText("alice, bob").assertIsDisplayed() + onNodeWithText("2 of 2 groups to act").assertIsDisplayed() + onNodeWithText("Atlas of the Coast").assertIsDisplayed() + onNodeWithText("Proposed by Polis").assertIsDisplayed() + onNodeWithText("Endorsed by 1 of the 2 groups it needs").assertIsDisplayed() + onNodeWithText("Edit profile").assertIsEnabled() + } + + @Test + fun `a member who is not an admin sees what is public, and why the changes are missing`() = renderConfederation(loaded(readsChanges = false)) { + onNodeWithText("Two groups").assertIsDisplayed() + onNodeWithText("Only the group's admins see proposed changes.").assertIsDisplayed() + onAllNodesWithText("Edit profile").assertCountEquals(0) + } + + @Test + fun `an admin who cannot propose is told why`() = renderConfederation(loaded(problem = ProfileChangeProblem.GroupWithoutInbox("Polis"))) { + onNodeWithText("Polis has no inbox, so it cannot be asked").assertIsDisplayed() + onNodeWithText("Edit profile").assertIsNotEnabled() + } + + // ---- a change ---------------------------------------------------------------------------------- + + private fun changeState(change: ConfederationProfileStatements.Change, pending: String? = null) = ConfederationProfileChangeUIState.Loaded( + localChatRoom = localChatRoom, + status = status(change), + confederationName = "Atlas", + differences = ConfederationProfileChangeViewModel.differences( + signedProfile.metadata, + mobi.giza.compose.managers.ConfederationProfileRefusal.metadataOf(change.profile), + ), + names = mapOf(agora to "This group", polis to "Polis"), + canAnswer = true, + pendingSessionId = pending, + ) + + @Test + fun `another group's change says what it would change, and offers both answers`() = renderChange(changeState(change(by = polis))) { + onNodeWithText("Was: Atlas").assertIsDisplayed() + onNodeWithText("Becomes: Atlas of the Coast").assertIsDisplayed() + onAllNodesWithText("Two groups", substring = true).assertCountEquals(0) + onNodeWithText("Proposed it").assertIsDisplayed() + onNodeWithText("Endorse").assertIsDisplayed() + onNodeWithText("Object").assertIsDisplayed() + onAllNodesWithText("Withdraw the change").assertCountEquals(0) + } + + @Test + fun `this group's own change can be withdrawn, not endorsed`() = renderChange(changeState(change(by = agora))) { + onNodeWithText("Withdraw the change").assertIsDisplayed() + onAllNodesWithText("Endorse").assertCountEquals(0) + } + + @Test + fun `while an answer is being signed, the buttons give way to it`() = renderChange(changeState(change(by = polis), pending = "s".repeat(64))) { + onNodeWithText("Waiting for the group to sign its answer").assertIsDisplayed() + onAllNodesWithText("Endorse").assertCountEquals(0) + } + + // ---- the form ---------------------------------------------------------------------------------- + + private fun form(groups: List) = EditConfederationProfileUIState.Loaded( + confederationId = atlas, name = "Atlas", threshold = 2, groupCount = 2, profile = signedProfile, + proposingGroups = groups, names = mapOf(agora to "Agora", polis to "Polis"), problem = null, selectedGroup = groups.firstOrNull(), + ) + + @Test + fun `the form starts from the signed profile and says who it goes to`() = renderForm(form(listOf(agora))) { + // The heading, and the name field seeded from the profile the confederation signed. + onAllNodesWithText("Atlas").assertCountEquals(2) + onNodeWithText("Two groups").assertIsDisplayed() + onNodeWithText("The confederation signs it once 2 of its 2 groups have endorsed it", substring = true).assertIsDisplayed() + onAllNodesWithText("Propose from").assertCountEquals(0) + onNodeWithText("Propose to the groups").assertIsEnabled() + } + + @Test + fun `an admin of two member groups picks which proposes`() = renderForm(form(listOf(agora, polis))) { + onNodeWithText("Propose from").assertIsDisplayed() + onNodeWithText("Agora").assertIsDisplayed() + onNodeWithText("Polis").assertIsDisplayed() + } + + private fun renderConfederation(state: ConfederationUIState, assertions: ComposeUiTest.() -> Unit) = render(assertions) { + ConfederationScreen( + activeUserPublicKey = "a".repeat(64), chatRoomId = agora, confederationId = atlas, initialConfederationUIState = state, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, confederationRepository = ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY, + onNavigateToRoute = {}, onNavigateBack = {}, + ) + } + + private fun renderChange(state: ConfederationProfileChangeUIState, assertions: ComposeUiTest.() -> Unit) = render(assertions) { + ConfederationProfileChangeScreen( + activeUserPublicKey = "a".repeat(64), chatRoomId = agora, changeId = "c".repeat(64), initialUIState = state, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, confederationRepository = ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY, + onNavigateToRoute = {}, onNavigateBack = {}, + ) + } + + private fun renderForm(state: EditConfederationProfileUIState, assertions: ComposeUiTest.() -> Unit) = render(assertions) { + EditConfederationProfileScreen( + activeUserPublicKey = "a".repeat(64), chatRoomId = agora, confederationId = atlas, initialUIState = state, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, confederationRepository = ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY, + onNavigateToRouteAndPopUpInclusive = {}, onNavigateBack = {}, + ) + } + + private fun render(assertions: ComposeUiTest.() -> Unit, content: @androidx.compose.runtime.Composable () -> Unit) = + runDesktopComposeUiTest(width = 400, height = 3000) { + setContent { + GizaTheme { + ProvideSnackbarHost { + Box(modifier = Modifier.fillMaxSize()) { content() } + } + } + } + assertions() + } +} diff --git a/docs/README.md b/docs/README.md index 219d04a8..dce5ded4 100644 --- a/docs/README.md +++ b/docs/README.md @@ -17,6 +17,7 @@ the [retired](./retired/) notes now. | [subgroups.md](./subgroups.md) | a group making another group — the four ceremonies, what the parent's signature actually covers, and why the child's key is fresh rather than derived | | [confederation.md](./confederation.md) | a group made of groups: a phased plan, built behind a flag that is off in release but for its device run and the room's governance. Agreeing to form (Part A), the key ceremony and room (Part B), and the confederation signing its profile, posts and charter (Part C). Groups with a public nostr profile propose, accept or reject a confederation in public, an acceptance carries the group's admins sealed to the coordinator in a way every signer recomputes, and the confederation's DKG and Marmot room follow. Covers why the public events are regular kinds, why nothing can be encrypted from or to a group's npub, how the coordinator is kept from substituting a roster, and why everything after the agreement waits on upstream publishing the distributed rounds. Its coordinator and its public statements have since been replaced (confederation-without-coordinator.md) | | [confederation-without-coordinator.md](./confederation-without-coordinator.md) | a confederation nobody coordinates: a phased plan, built but for its device run and behind flags that are off in release. The proposal and every answer travel as NIP-17 messages between the groups' NIP-4E inboxes, each sealed by its group's quorum, so every admin of every group reads every admin list and computes the outcome, and the key ceremony derives its room and session seed and computes the coordinator's broadcast on every device. Covers why a group could be the DKG's coordinator and does not need to be, why the admin lists stop being a payload encrypted to one person, why a confederation names at most twelve groups, how a group that says different things to different groups is caught, and who makes the confederation's room when nobody is in charge | +| [confederation-profile.md](./confederation-profile.md) | a formed confederation's nostr profile, decided by its groups: a phased plan, built but for its device run and behind flags that are off in release. The confederation gets its own screen, reached from each member group's screen, and an edit there is a statement by the editing group, sealed by its quorum and sent to every member group's inbox, which the others endorse or object to by their own quorums. Once `T` groups have endorsed, each group's signed voucher is a role holder's consent, so the confederation signs and publishes the profile with nobody asked again. Covers why the rule is `T` of `N`, why a transferable voucher is needed beside the non-transferable seals, who starts the signing, and how the confederation's room and the key ceremony's room come to say what they are | | [confederation-upstream.md](./confederation-upstream.md) | the work below Giza that unblocks the confederation's Parts B and C: a phased plan, not built, across secp256k1-zkp, secp256k1-kmp and bitcoin-kmp. Covers why the one-process DKG and signing cannot simply be exposed step by step (the coordinator derives everyone's key state, acknowledgment is signed before the share is stored, nonce randomness is derived from the session id), why every DKG step can stay stateless, the storage contract a device follows, and Prefractal as an all-groups-must-sign path that needs no upstream work | | [automatic-key-ceremony.md](./automatic-key-ceremony.md) | joining is the only approval: a phased plan, built but for its device session, that makes a key ceremony run by itself after a member joins. Covers why contributing and confirming were never decisions a person could add to, the resume sweep that replaces the tap, the coordinator's follow-up steps and the one key state a device can sign without asking, and why abandon stays | | [ceremony-creation.md](./ceremony-creation.md) | one place to start a key ceremony — how joining a subgroup's ceremony opened a second one for the parent room, the screen that showed a ceremony and offered to start one in the same button, and the removal of the nip30303 documents, whose kinds collided with the ceremony's, leaving the member chronicle with nothing to carry and nothing to say | diff --git a/docs/confederation-profile.md b/docs/confederation-profile.md new file mode 100644 index 00000000..40604e05 --- /dev/null +++ b/docs/confederation-profile.md @@ -0,0 +1,794 @@ +# A confederation's profile, decided by its groups + +A plan to run a formed confederation's nostr profile (its kind:0) from the place where people +already understand a confederation: the group's own screen. From there, an admin opens +the confederation's screen, edits its profile, and the edit goes out as a **proposal from their group +to every other group's inbox**. The other groups endorse it or object, each by its own quorum. +Once enough groups have endorsed, the confederation signs the new profile and it is published. +Nobody is asked a second time. + +Read [confederation.md](./confederation.md) (Parts B and C: the key, the room, the nested +signing), then [confederation-without-coordinator.md](./confederation-without-coordinator.md), +whose statements, seals and refusals this plan reuses for a new kind of statement, and +[group-inbox.md](./group-inbox.md), which carries them. +[group-nostr-profile-and-posts.md](./group-nostr-profile-and-posts.md) defines what a group's +profile is and how its form works. This plan reuses that form. + +Written against `3b0b3c9a`, on 2026-11-22. **Built, Phases 0 to 8**, on `claude/confederation-profile`, +behind `ExperimentalFeatures.confederation` and `ExperimentalFeatures.groupInbox`, both off in release. +The device run (Phase 9) has not been done. Each phase says under it what was built and where it +differs from what it planned. Paths starting `K/` are under `composeApp/src/commonMain/kotlin/mobi/giza/compose/`. + +| phase | commit | result | +|---|---|---| +| 0 | `3e05a28b` | the plan, and three premises as tests. **A profile change carries the whole kind:0 in every group's seal: 1.1 KB of profile fits twelve groups, 13 KB fits two** | +| 1 | `4994248d` | kinds 9435–9438, the state of a change, and one nullable column (schema 51, built as 50) rather than three tables | +| 2 | `c293514d` | a group proposes, endorses or objects, sealed to every member group's inbox, its voucher signed in the same session; seven refusals. The charter gains its threshold | +| 3 | `44cbe596` | a line in every member group's room for every statement, in any order | +| 4 | `5d6bbcd5` | the confederation's screen, its profile form and a change's screen, reached from the group's screen | +| 5 | `8d494ddb` | vouchers into the confederation's room; the first in the order starts the signing; nobody asked; crossing attempts and retries; the direct kind:0 path closed | +| 6 | `19cd1aae` | the signed profile owed by every signer, to the public and every group's inbox relays; heard by every member by the confederation's key | +| 7 | `6285033c` | the confederation's room names its groups; the ceremony's room, once formed, leads to the confederation and takes no messages | +| 8 | `33e88f62` | the plan end to end on nine devices, formed the real way, and the record. **No device run** | + +Full `jvmTest` 1,903, all passing (from 1,864 before Phase 1); `m3Audit`, `brandAudit` and +`walletAudit` at their budgets; `compileDebugKotlinAndroid` builds. + +**Merged into `giza`** after disappearing messages (docs/disappearing-messages.md), which had taken +schema 50 for its storage first. This plan's column is therefore **v51**, `AutoMigration(50, 51)`; +every "schema 50" below is that one, as it was numbered while it was built. One conflict besides: in +`GroupInboxManager`, a profile statement is handed to the confederation before the inbox's NIP-40 +expiry check, as the formation's statements already were. After the merge, full `jvmTest` 1,978, all +passing, with the audits at budget and `compileDebugKotlinAndroid` building. + +--- + +## What is wrong today + +Traced through the code at `3b0b3c9a`, with the working tree's ceremony-room changes applied. + +**The confederation's room does not show which groups are in it.** `ConfederationFollowThrough` +makes a Marmot room whose members are the people who hold roles: every admin of every group, +at the time it formed. The room's detail screen lists them as people. The confederation is made +of groups, and the room does not say which group each person belongs to. The device already +knows: `ConfederationRosterBuilder.Plan.seatsOf(person)` gives each person's seats, and each +seat names its group. Nothing reads it for display. + +**The proposal screen is the only place that shows the confederation as groups.** +`ConfederationProposalScreen` lists every group, by name, with its answer. That is the right +view of a confederation, but it is framed as a proposal. Once the confederation has formed, +the card on `ConfederationsScreen` says "Formed" (`ConfederationsUIState.Item.formed`) and +still opens the proposal. That screen has nothing to say about a confederation after it +exists. + +**The key ceremony's NIP-17 room has nothing to do once the ceremony ends.** The room is made +over the roster's people (`deriveChatRoomId(people)`, D8 of the coordinator-free plan), so it +appears in everyone's chat list. It carries 30381–30385 while the ceremony runs. After that it +receives nothing. The working tree adds a banner that links the room to its ceremony +(`ChatRoomMessagingUIState.keyCeremony`, `ConfederationRitualManager.proposalOfRoom`). After +formation, the banner has nothing to point to. + +**The confederation's profile is edited by people, not groups.** Phase 15 of +[confederation.md](./confederation.md) opened the existing editors in the confederation's room. +`EditGroupNostrProfileViewModel` sees `canSignAsConfederation` and sends the kind:0 to +`ChatRepository.proposeAsConfederation`, which calls `ConfederationSigningManager.propose`. Every +role holder is then asked in that room (30391), as a person. The groups never decide anything as +groups, and their inboxes never hear of it. A group's members who are not admins never hear of +it either. Two admins from the same group can sign the confederation's profile with no one else +in their group knowing. + +--- + +## What changes, in one table + +| | today | this plan | +|---|---|---| +| where a profile is edited | the confederation's Marmot room, by a role holder | the **confederation's screen**, reached from any member group's screen, by an admin of that group | +| what an edit is | a signing attempt (30390) in the confederation's room | a **statement by a group** (9435), sealed by its quorum, sent to **every member group's inbox** | +| who decides | each role holder, as a person, in 30391 | each **group**, by its quorum: endorse (9436) or object (9437) | +| how many must agree | `T` groups' worth of role holders saying yes, one by one | `T` groups endorsing. The proposing group's statement counts as its endorsement | +| what a role holder is asked | to approve the attempt | **nothing.** Their device says yes for each seat whose group vouched (D5) | +| who starts the signing | the person who proposed | the first role holder in a fixed order who holds `T` vouchers, with a fallback (D6) | +| who publishes the kind:0 | nobody automatically (the broadcast screen) | the device that started the signing, owed until a relay takes it (D7) | +| what each group's room says | nothing, unless a member holds a role | a line when a change is proposed, endorsed, objected to, published (D8) | +| the confederation's room | members as people | members labelled by group, with a groups card (D9) | +| the ceremony's NIP-17 room after formation | an open chat with nothing in it | read-only, with a banner linking to the confederation's screen (D10) | + +--- + +## Decisions + +### D1. A formed confederation gets its own screen, reached from the group's + +`ConfederationScreen` (route `ConfederationRoute(activeUserPublicKey, chatRoomId, confederationId)`, +where `chatRoomId` is the member group's room it was opened from) is the **confederation's detail +screen**. It is reached in two ways: + +- from `ChatRoomDetailScreen`: one row per formed confederation the group is in ("Member of + Polis League"), placed above the existing Confederations row; +- from `ConfederationsScreen`: a card whose proposal has formed opens this screen instead of + the proposal. The proposal screen stays reachable from here, under "How it was formed". + +It shows, top to bottom: + +1. **The profile**: picture, name, about, website, nip05, npub. This is the newest valid kind:0 + authored by the confederation's id (D7). +2. **The groups**: each member group by name, with the number of roles it holds. For a device + that holds the record, it also lists who holds those roles. This is the view the proposal + screen gives, but describing the confederation rather than the vote that made it. +3. **Profile changes**: each open change, and the most recent closed ones, with their state and + each group's answer (D4). +4. **Edit profile**, for a member who can put a statement to their group (D2). +5. Links to the confederation's room, when this device holds it, and to the proposal. + +**Who sees what.** Every member of a member group's room can open the screen. Members who are +not admins hold no record and none of the statements between the groups, so for them it is +built from public data: the charter (9434) for the groups and the kind:0 for the profile. +Admins also see the changes, because those come through the group inbox, which only admins +read. The screen does not guess. A part it cannot fill shows an `EmptyState` that says why: +"Only the group's admins see proposed changes." + +The confederation's groups come from the `Confederation` record when the device holds one, and +from a verified charter otherwise. The charter is the confederation's own signed list of its +groups. That is enough for a device that never took part to know whom a change must go to. + +### D2. An edit is a statement by a group: kind 9435, to every member group's inbox + +An admin edits the profile on `EditConfederationProfileScreen`. It is the existing profile form, +moved out of `EditGroupNostrProfileScreen` into a shared `NostrProfileForm` composable, with +its own view model. **Propose** does not ask the confederation to sign. It asks *the admin's +group* to sign a statement proposing the change. That statement goes through +`ConfederationManager.proposeStatement`, as the confederation's proposals and answers do now: +one seal per member group (this group's own copy included), sealed with the group's inbox key, +signed by the group's quorum through FROST, and wrapped to each group's 10050 relays. + +``` +9435 rumor, pubkey = the proposing group's npub +tags: + ["p", ] … + ["confederation", ] + ["base", ] absent when the confederation has none + ["expiration", ""] default 3 days, at most 7 +content: the unsigned kind:0, as JSON: + {"pubkey":"","created_at":,"kind":0,"tags":[…],"content":"…"} +``` + +The kind:0's `created_at` is fixed when it is proposed, so its **id is fixed before anyone +answers**. Every endorsement, voucher and signing attempt names that id. Nothing that is signed +later can differ from what was endorsed. + +**Who can propose:** a member of the group's room with a share in its active generation, who +holds the group's announced inbox key (an admin, as D5 of the coordinator-free plan requires). +Every member group must have announced an inbox. The form checks the same things +`ProposeConfederationScreen` checks before it allows **Propose**, and gives the same reasons: +"Set up the group's inbox first", or "Agora has no inbox, so it cannot be asked". + +**An admin of two member groups** picks which group proposes, from a choice on the form that +appears only when there is more than one group to pick from. The group is the author. The person is not. + +**Size.** One seal per group, each holding the whole kind:0, so the profile a change can carry +shrinks as the groups grow: about 13 KB of text to two groups, 4 KB to six, **1.1 KB to twelve** +(Phase 0, check 3). A name, an about of a paragraph, a picture URL, a website and a nip05 fit any +confederation. The check against `MAX_STATEMENT_BYTES` that `proposeSealed` already makes refuses a +larger one, and the form says why in a profile's terms: "This profile is too long to send to 12 +groups. Shorten its about." + +### D3. Answers: endorse (9436) or object (9437), each by the group's quorum + +``` +9436 rumor endorsement +tags: ["p", ] …, ["confederation", ], ["e", <9435 rumor id>], + ["profile", ] +content: empty + +9437 rumor objection; from the proposing group, a withdrawal +tags: as 9436 +content: an optional reason, plain text +``` + +An answer goes to **every** member group, not only the proposer. Every admin of every group sees +how every group answered, as with the formation statements. Each answer's signing session carries +the 9435's seal in `confederation_invitation`, as answers to a proposal already do. A signer +therefore does not depend on its own inbox having received the change. + +`ConfederationProposalScreen`'s Accept/Decline pair becomes **Endorse** / **Object** on the change's +own screen (`ConfederationProfileChangeScreen`, opened from the confederation's screen and from the +line in the group's room). Under them is the change as a field-by-field difference from the +profile it edits: + +``` +Name Polis League → Polis League of the Coast +Picture (unchanged) +About (cleared) +``` + +The same difference appears in `ProposedEvent`'s summary on the FROST approval screen. A member +who opens the signing session from the room's transcript sees what their group is being asked to +say, not "Event of kind 13". + +### D4. A change's state is computed from the statements held, on every device + +`ConfederationProfileChange.State`, computed whenever it is read, as `ConfederationStatus` is for +proposals. `E` is the number of groups that endorsed (the proposer included), `O` the number that +objected, and `N` and `T` are the confederation's. + +| state | when | +|---|---| +| `WITHDRAWN` | the proposing group's 9437 is held | +| `PUBLISHED` | a signed kind:0 with the change's id is held | +| `SUPERSEDED` | a signed kind:0 for the confederation with a later `created_at` is held | +| `ENDORSED` | `E ≥ T`: the signing is under way (D6) | +| `DECLINED` | `N − O < T`: it can no longer reach `T` | +| `EXPIRED` | past its expiry and not `ENDORSED` | +| `OPEN` | otherwise | + +An answer counts only if its own `created_at` is at or before the expiry. This is the +existing rule ([confederation.md](./confederation.md) D8), so whether a change was endorsed in +time does not depend on when a device heard of it. + +**The rule is `T` of `N`, not all of `N`.** `T` is what the groups agreed to when they formed +it ("2 of 3 groups to act"), and it is also what the signature needs. If an objecting group +could block a change that `T` groups endorsed, the confederation would be governed by unanimity +while its key works by threshold. An objection is still recorded and shown to every group. + +**Changes may overlap.** Two open changes may exist at once. Whichever is published first wins, +and any change with an earlier `created_at` becomes `SUPERSEDED`, because relays keep only the +newest kind:0. A later change published first makes an earlier one pointless, and its signing +is refused (D6). + +### D5. A group's endorsement makes a voucher, and a voucher is a role holder's consent + +The sealed 9435 and 9436 are good evidence for the groups' admins, but they are not +**transferable**. A seal opens only with the inbox key it was sealed to (D3 of the +coordinator-free plan). The people who must act on an endorsement are the confederation's role +holders, in the confederation's room. Some of them are no longer admins of their group and +hold no inbox key, and none of them can show another group's seal to anyone. So the group's +signing session signs one more event in the same batch: + +``` +9438 voucher, signed by the group's npub (FROST, same session), never published +tags: ["confederation", ], ["profile", ], ["e", <9435 rumor id>], + ["expiration", ] +content: empty +``` + +A 9435 or 9436 batch is `N` seals plus one voucher. It is signed in the one FROST session the +group is already asked for, so this costs no extra question. When it completes, every device in +the group's room holds the signed voucher (`FrostSigningManager.complete` → `applySignedEvent`). + +**Carried into the confederation's room.** Each role holder of the group whose device holds the +signed voucher posts it into the confederation's Marmot room as a new message, **30396** +(`ConfederationSigningEvents.VOUCHER`). Copies from several devices are deduplicated by the +voucher's id. A role holder's device that receives one verifies the group's signature against +the roster's group key, then files it. + +**A voucher is consent.** `ConfederationSigningManager.acceptProposal` gains a path for an attempt +over a kind:0. The 30390 must carry vouchers (`["voucher", ]`) from at least `T` +distinct member groups. Each must verify under its group's npub, name exactly this event's id, and +not be expired. A device then sends its 30391 **without asking anyone**: yes for each of its seats +whose group vouched, no for each that did not. A seat in a group that objected never signs. + +That moves the decision from each person to each group. A role holder who would have said no as +a person signs anyway if their group's quorum said yes. This is deliberate: the confederation +was formed with `t_g` set to each group's own threshold, and a role holder holds their share as +an admin of their group. The appendix covers asking each role holder as well. + +**The direct path closes for kind:0.** `ConfederationSigningManager.refusalOf` refuses a kind:0 +that carries fewer than `T` valid vouchers: "A confederation's profile changes through its groups." +`EditGroupNostrProfileViewModel` stops treating a confederation's room as a signer for kind:0. +The profile row on that room's detail screen opens the confederation's screen. Posts (kind:1) and +the charter keep the direct path for now (*Out of scope*). + +### D6. Who starts the signing, and what happens when it fails + +Once a role holder's device holds vouchers from `T` groups for one change, and no attempt for +that kind:0 is running: + +- **The order** is the roster's people sorted bytewise, the same order D11 of the + coordinator-free plan uses for making the room. +- **Person `k`** starts an attempt if none for this kind:0 has arrived **`k × 10` minutes** after + the `T`-th voucher reached their device. One person away adds ten minutes of delay, not an + indefinite wait. Ten minutes rather than D11's hour, because signing needs devices online at + the same time and should run while the endorsing people still have their phones in hand. +- **Crossing attempts** over the same kind:0 both run until one finishes. The attempt whose id + sorts first continues everywhere. The other is ended out loud with "Another attempt is signing + this change", as crossing inbox ceremonies are. +- **A failed attempt is retried by the same rule**, from its failure: `RESTARTED` (a nonce lost + to a restart), or a selected device that stopped answering. The delay doubles each time, from + ten minutes up to two hours, until the change expires. The change's screen says "Signing: + waiting for Agora's admins", naming the groups whose roles have not yet said yes. +- **Refusals before starting:** the change is not `PUBLISHED`, `SUPERSEDED` or expired, and no + signed kind:0 for the confederation with a later `created_at` is held. + +An attempt started this way does not announce "A proposal for the confederation to sign" in the +room as a question. It writes one line that names the change and the groups that vouched. + +### D7. The signed profile is published, and every member group hears it + +`ConfederationSigningManager.complete` already files the signed event as a `GroupSignedEvent` under +the confederation's id on every role holder's device. Added: + +- **Owed to relays.** On the device that started the attempt, the signed kind:0 is marked owed, + and `ConfederationPublisher` sends it, as it sends the charter. It goes to the publish set and + to each member group's 10050 relays, and backs off from a minute up to half an hour until a relay + takes it. Any other role holder's device may publish the same event too. It is the same + event, so duplicates are harmless. It sends only if the event is still unpublished an hour + later, the same fallback idea as D6. +- **Heard by every member group.** `live-confederation` gains a filter + `{"kinds":[0], "authors":[every confederation id this device knows]}`. Known ids come from the + `Confederation` rows and from charters filed for this device's groups. A kind:0 that arrives + is verified and filed as a `GroupSignedEvent` under the confederation's id. That is how a member + who is not an admin learns of the new profile, and how the confederation's screen reads it. +- **Read** by a new `ConfederationProfile.newestOf(confederationId)`, which is + `GroupNostrProfile.newestAmong` over those rows. + +### D8. Lines in each group's room, written by each device for itself + +New `ChatMessage` types, written by each device into its own member groups' rooms, and sending +nothing. This is the pattern `ConfederationFormation` already follows. + +| type | text | who writes it | +|---|---|---| +| `TYPE_CONFEDERATION_PROFILE_PROPOSED` | "Agora proposes a new profile for Polis League" | admins' devices, from the 9435 | +| `TYPE_CONFEDERATION_PROFILE_ENDORSED` | "Ekklesia endorsed Agora's change to Polis League's profile" | admins' devices, from each 9436 | +| `TYPE_CONFEDERATION_PROFILE_OBJECTED` | "Ekklesia objected to …: " | admins' devices, from each 9437 | +| `TYPE_CONFEDERATION_PROFILE_PUBLISHED` | "Polis League has a new profile" | **every** member's device, from the kind:0 off relays | + +Each line carries the change id and opens `ConfederationProfileChangeScreen`. The published line +carries the confederation id and opens `ConfederationScreen`. Members who are not admins see +their own group's signing session through its existing line, and then the published line. That +is the same visibility they have for formation statements. + +`NotificationClassifier` treats a 9435 from another group, received by an admin of a group that +has not answered, as needing attention, the way a signing session waiting for you does. The +other lines are quiet. + +### D9. The confederation's room shows its groups + +On a confederation's room, `ChatRoomDetailScreen`: + +- labels each member with their groups, from `Plan.seatsOf(member)` named by + `ConfederationManager.nameOf`: "Thandi · Ekklesia, Agora". Someone who holds roles in two groups + is shown once with both names; +- gains a **Groups** card above the members, listing each group with its role holders. The card + links to the confederation's screen; +- states that the room is fixed at the people who held roles at formation, and what that means: + "Admins who joined a group after Polis League formed are not here." + +### D10. The ceremony's room is closed once the ceremony ends + +The NIP-17 room the ceremony ran in stays on the device. Its messages are the evidence the +genesis was built from, and a later attempt over the same roster meets there. After +`ConfederationFormation.onComplete`: + +- the banner the working tree adds (`keyCeremony`) says "The key ceremony for Polis League is + complete" and links to `ConfederationScreen`; +- the composer is hidden, the same way it is for a room nobody can write to. + Anything typed there would reach only the founding people as people, which is what this plan + is trying to stop; +- the room moves below the active conversations in the chat list, ordered by its last message + like any other room. It is not hidden. A person who goes looking for it should find it. + +If a ceremony is retried (D10 of the coordinator-free plan), the room opens again, because the +retry runs there. + +### D11. Behind both flags; the kinds are rumors and a voucher, never public + +Everything here needs `ExperimentalFeatures.confederation` and `ExperimentalFeatures.groupInbox`. +Kinds 9435–9437 are rumor kinds and 9438 is a voucher. **None joins `ConfederationKinds.ALL`**, +which drives the public subscription and `BROADCASTABLE_KINDS`. They go in a new +`ConfederationKinds.PROFILE_CHANGE_KINDS`. A FROST batch that tries to sign any of them as a +bare event, rather than as a voucher beside its seals, is declined by `ConfederationRefusal`. That +check runs even with the flags off, as every refusal does. A device that receives a 9438 on its +own, outside a 30390, files nothing. + +--- + +## Who is asked what + +| step | who is asked | what they decide | automatic after that | +|---|---|---|---| +| propose | one admin of group A, on the confederation's screen | the new profile | building the 9435, the seals, the voucher | +| A signs | A's quorum | that A proposes this profile | wrapping to every member group's inbox; A's role holders posting A's voucher | +| a change arrives | nobody | — | every admin's device in every group files it and writes a line | +| B answers | one admin of B, then B's quorum | endorse or object | wrapping to every group; B's voucher into the confederation's room | +| `T` groups have vouched | nobody | — | the first role holder in order starts the signing; every role holder's device says yes for its vouched seats | +| signed | nobody | — | published; every member's device files it and writes "has a new profile" | + +People are asked twice in total, once per group, and both questions are group signing +sessions they already know how to answer. + +--- + +## Phases + +One commit per phase, in the repository's style (`feat: … (confederation-profile, Phase n)`). +Every phase leaves `./gradlew :composeApp:jvmTest` and `:composeApp:m3Audit` green, and `check`'s +brand and wallet audits at budget. + +### Phase 0: land what is in flight, this document, five checks + +The working tree's ceremony-room changes (`keyCeremonyOfRoom`, `joinablePlan`, +`ConfederationRitualUIState.Joinable`, the messaging screen's banner) are committed first, as +their own commit. D10 builds on that banner. + +Then this document and its row in [README.md](./README.md), and before code: + +1. **The kinds.** 9435–9438 appear in no NIP, nor in quartz, Curare or Bennu, and 30396 is unused + (30390–30395 and 30399 are signing's, 30410–30416 the inbox's). +2. **A mixed batch.** On the inbox's harness, a FROST batch of `N` kind-13 seals plus one kind 9438 + proposes, passes `ConfederationRefusal`'s routing (by the `confederation_rumor` tag) and + `InboxRefusal`'s manifest check, signs, and leaves the signed 9438 on every member's device. + If the manifest check refuses a batch that is not all seals, the voucher is signed in a second + session started automatically on completion, and D5 says so. +3. **Size.** A 9435 for twelve groups with a 4 KB kind:0, against `MAX_STATEMENT_BYTES`. Record + the largest profile that fits. +4. **Pin today.** `ConfederationProfileTodayJvmTest`: a role holder's kind:0 through + `proposeAsConfederation` signs with no group asked; the confederation's room lists members + without groups. Both are flipped on purpose in Phases 5 and 7. +5. **A voucher verifies anywhere.** A 9438 signed by group B's FROST session verifies under B's + npub on a device that is in neither B's room nor B's inbox, given only the roster. + +**Done when** all five are recorded here and checks 2, 4 and 5 are tests. + +**Done**, on 2026-11-22. The in-flight work had already landed as `50f73e17`. +`ConfederationProfilePremiseJvmTest` keeps checks 2, 3 and 5: + +| check | result | +|---|---| +| 1. the kinds | **free.** Neither 9435–9438 nor 30396 appears in quartz 2.20.1's sources or anywhere in the app; [confederation.md](./confederation.md)'s Phase 0 found nothing in the NIP table between 9321 and 9734 | +| 2. a mixed batch | **does not pass today, and both obstacles are ours.** `ConfederationRefusal.of` declines any batch with a non-seal in it as `SHAPE`, and `InboxReplies.wrapAndOwe` sends nothing when a session has more items than its manifest has seals. Phase 2 teaches both about the one voucher, rather than signing it in a second session: a second session is a second question to the quorum | +| 3. size | **a 4 KB profile does not fit twelve groups** (118 KB against 60 KB): every seal carries the whole kind:0. The largest profile text that fits, by groups: 13.6 KB for 2, 7.3 KB for 4, 4.1 KB for 6, 2.9 KB for 8, 1.8 KB for 10, **1.1 KB for 12**. D2 now says so, and the form gives the reason in a profile's terms | +| 4. pin today | `ConfederationSigningJvmTest`'s first case already pins it: a role holder's kind:0 through `ConfederationSigningManager.propose` signs with no group asked. Phase 5 flips it. The room's member list is pinned by Phase 7's own test | +| 5. a voucher anywhere | **holds.** A 9438 signed by a group's FROST session verifies under its npub through `GroupKeyStateEvent.isSignedByRoom`, given nothing but the npub, and not under another group's | + +### Phase 1: the wire, and the storage + +- `K/nostr/confederation/ConfederationProfileStatements.kt`: build and strictly parse 9435–9437 + rumors and the 9438 voucher. The parser refuses an embedded event that is not kind 0, does not + have the confederation as its author, or is not a readable profile + (`GroupStatementRefusal.isUnreadableProfile`). `ConfederationKinds.PROFILE_CHANGE_KINDS`, + `ConfederationSigningEvents.VOUCHER = 30396` and the `voucher` tag. +- `ConfederationProfileChange.State` and the computation of D4, as a pure function over the held + statements, the vouchers and the newest kind:0. Tested exhaustively, since every screen and the + starter rule read it. +- Schema **50**, `AutoMigration(49, 50)`, new tables only: + - `ConfederationProfileChange`: rumor id, confederation id, proposing group, the unsigned + kind:0's JSON and id, base, expiry, `created_at`, and the seal that delivered it; + - `ConfederationProfileAnswer`: change id, group, kind, rumor id, reason, `created_at`, seal; + - `ConfederationVoucher`: voucher id, change id, group, signed JSON. +- `ConfederationRepository` gains `observeProfileChanges(confederationId)`, + `observeProfileChange(changeId)` and `observeProfile(confederationId)`, with `NO_OP` overrides. + +Tests: `ConfederationProfileStatementsTest` (bytes pinned, every refusal), +`ConfederationProfileChangeStateTest`, `ConfederationProfileStorageJvmTest`. + +**Built.** Where it differs from the above: + +| what the phase said | what it turned out to be | +|---|---| +| three new tables | **one nullable column.** `ConfederationEvent` gains `confederationId` (schema 50, `AutoMigration(49, 50)`), and changes, answers, vouchers and the signed kind:0 are filed there, the change's rumor id standing as their `proposalId`. It is already the table "for every kind" the formation uses, its `ownSessionId`/`publishedAt` already carry what is owed to relays, and the `ConfederationSigning` rows that carry a statement past its proposal fit a change unchanged | +| the signed kind:0 in `GroupSignedEvent` under the confederation's id (D7) | **in `ConfederationEvent` too**, through `ConfederationProfileManager.recordProfile`. `GroupSignedEvent` has a foreign key to `ChatRoom`, and a member of a member group who is not an admin holds no room for the confederation. `profiles` reads both | +| the 9435's tags | **plus `["threshold", ""]`.** A device without the confederation's record (an admin promoted since it formed) has no other way to know `T`; a device with the record checks it (Phase 2) | +| D4's `ENDORSED` past the expiry | **`EXPIRED`.** The voucher carries the change's expiry and nothing signs past it, so an endorsed change not signed by then is over | +| `ConfederationProfileChangeStateTest` | folded into `ConfederationProfileStatementsTest`, 11 cases with the wire's; `ConfederationProfileStorageJvmTest` 4 | + +### Phase 2: proposing and answering through the inboxes (D2, D3, D5's batch) + +- `ConfederationProfileManager.proposeChange`, `endorse`, `object` and `withdraw`. Each builds its + rumor, resolves recipients from the confederation's groups (record, else charter), and goes + through `ConfederationManager.proposeStatement`, which gains an optional extra signed event + for the voucher. +- `ConfederationRefusal` gains arms for 9435–9437 in the four places it sits (arrival, approval, + decline reason, resend). A signer declines unless: + 1. this device holds the group's announced inbox key (as today); + 2. every seal holds `confederation_rumor` byte for byte, one per member group (as today); + 3. the `p` tags are exactly the confederation's other groups, from the record or a verified + charter. Otherwise: "This device holds no record of that confederation"; + 4. for a 9435: the kind:0 is the confederation's, readable, its `created_at` within ten minutes + of now, the expiry at most seven days away, and **this device holds no kind:0 newer than its + base**. Otherwise: "Polis League's profile has changed since this was written". An unknown + base is a warning, not a refusal; + 5. for a 9436 or 9437: the carried 9435 opens with this group's inbox key and verifies as its + author's, is `OPEN` here, and this group has not answered; + 6. the voucher in the batch names exactly the kind:0 and change in the rumor, with the same + expiry. For a 9437 there is no voucher, and a batch that has one is declined. +- `ProposedEvent` summarises each kind with the field difference of D3. + +Tests: `ConfederationProfileDeclineJvmTest`, one case per refusal, on `SigningProposalHarness`. +`ConfederationProfileProposeJvmTest`: a three-group fixture where A's admin proposes, A's quorum +signs, and every group's admins' devices hold the 9435. + +**Built.** `ConfederationProfileStatementJvmTest` 13/13, on `ConfederationTestGroups`' three real +groups (FROST and inboxes) with a charter naming them: a change reaches every admin of every group +with the proposer's voucher on the proposer's devices only; a second group's endorsement makes it +`ENDORSED` everywhere; objections and a withdrawal; a device that missed the change answers from the +carried invitation; a profile too long refused before anything is asked; and seven refusals (stale, +unknown confederation, unreadable, a wrong voucher, no voucher, a voucher on its own, answering twice +or after it closed). Where it differs from the above: + +| what the phase said | what it turned out to be | +|---|---| +| two test files | one, since both need the same three groups and charter | +| the confederation's groups "from the record, else a verified charter" | as said, and the **charter gains `["threshold", ""]`** (`ConfederationCharterEvent.assembleTags`, optional on parse so earlier charters still read). Without it a device holding only the charter cannot know `T`; such a device falls back to the newest change's stated threshold, and proposes nothing if it has neither. A role holder still refuses a charter whose threshold is not the confederation's | +| `proposeStatement` "gains an optional extra signed event" | `extra` (the voucher, last in the batch) and `tooLarge`, so a profile that will not fit is refused in a profile's words before anything is asked | +| routing received rumors, in Phase 3 | **here**: the one branch in `GroupInboxManager` that hands 9435–9437 to `ConfederationProfileManager.recordStatement`, which the tests above need. And `InboxReplies` files no outgoing inbox copy of a profile statement, as it files none of the formation's | +| `ConfederationRefusal`'s routing | the batch is read as the seals and then at most one voucher. Any other non-seal, a voucher with a formation statement, or a profile statement or voucher asked for bare is declined as before (`SHAPE` or `PUBLIC`) | +| the threshold check (D2, step 3) | only where the device holds the record: against a charter there is nothing to check it with | + +### Phase 3: receiving (D4, D8) + +- `GroupInboxManager` routes rumors of `PROFILE_CHANGE_KINDS` to `ConfederationProfileManager.record` + beside the existing `ConfederationManager.recordStatement` call, storing them with their seal. + A 9436 or 9437 that arrives before its 9435 is stored and gets its line once the 9435 arrives. + This is the same fix Phase 7 of [confederation.md](./confederation.md) needed. +- The lines of D8, and `NotificationClassifier`'s one new case. + +Tests: `ConfederationProfileReceiveJvmTest`, covering out-of-order arrival, a seal from a group +that is not a member (dropped and logged), and a duplicate. + +**Built.** `ConfederationProfileReceiveJvmTest` 3/3: a change from another group is one line in each +of this device's member groups' rooms, carrying the change's id; heard twice, still one; an objection +that arrives before its change gets its line when the change does; the classifier's two sets. The +routing itself landed in Phase 2. A seal that is not its rumor's author's is dropped by +`recordStatement`, tested in Phase 1's storage test. The lines carry the change's id in +`frostSigningSessionId`, the column the confederation's signing lines already use for an attempt's +id, so no schema change: Phase 4 makes them open the change. `TYPE_CONFEDERATION_PROFILE_PROPOSED` +and `…_PUBLISHED` are group activity; `…_ENDORSED` and `…_OBJECTED` are silent. + +### Phase 4: the screens (D1, D2, D3) + +- `ConfederationScreen` + `ConfederationViewModel` + `ConfederationUIState` (loading, error, + not held, loaded), with the parts and visibility rules of D1. The **Edit profile** button is + gated on D2's conditions, as `ConfederationsScreen` gates **Propose a confederation**. +- `EditConfederationProfileScreen`: `NostrProfileForm` extracted from + `EditGroupNostrProfileScreen` (both screens then use it), the group picker for an admin of + several groups, and **Propose to the groups**. On success it goes to the FROST signing session, + as answering a proposal does. +- `ConfederationProfileChangeScreen`: the difference from the base, every group's answer, + **Endorse** / **Object** (with an optional reason) / **Withdraw**, the open signing session if + there is one, and the signing state of D6 once endorsed. +- `ChatRoomDetailScreen`: one row per formed confederation. `ConfederationsScreen`: a formed card + opens `ConfederationScreen`. +- Routes in `GizaNavHost`, each with `NavigateBackButton`. Strings in the catalogue, sentence + case, with no "supergroup", "voucher", "rumor" or "NIP-4E" shown to a person. A voucher appears + in the interface only as "endorsed". + +Tests: `ConfederationProfileScreensJvmTest`, covering each state, the gating of each button, and +the non-admin view built from the charter and kind:0 alone. `m3Audit` at budget, with no new +`.dp` spacing, colour literal or title-case string. + +**Built.** `ConfederationProfileScreensJvmTest` 8/8; `m3Audit` at budget; `compileDebugKotlinAndroid` +builds. Where it differs from the above: + +| what the phase said | what it turned out to be | +|---|---| +| `NostrProfileForm` | `widgets/NostrProfileFields.kt`: the five fields and a `NostrProfileFieldStates` holder whose `template` builds the kind:0. Its icons are now `Decorative`, since each sits beside its label; they carried hard-coded English descriptions before | +| the edit screen's own view model | as said; its failure carries the profile-sized reason when there is one, so "too long for 12 groups" reaches the snackbar instead of a generic failure | +| "Signing: waiting for Agora's admins" (D6) | the change's screen names the endorsing groups whose voucher this device has not yet seen. Phase 5 is what makes those vouchers arrive | +| repository methods | on `ConfederationRepository` as interface defaults, so `NO_OP_CONFEDERATION_REPOSITORY` and every fake needed no change; `ProfileChangeProblem` says why a member cannot propose, which the screen and the form turn into words | +| the group detail screen's row | `ChatRepository.memberConfederations`, by record or charter; each row reads "Member of Atlas" and opens the confederation | +| the lines (Phase 3) open the change | `ChatTranscript` gains `onOpenConfederationProfileChange` and `onOpenConfederation`; the published line opens the confederation | + +### Phase 5: from endorsement to signature (D5, D6) + +- The 30396 voucher message: posted by each role holder's device when its group's 9435 or 9436 + session completes, verified and filed on arrival, and deduplicated. +- `ConfederationSigningManager`: a 30390 over a kind:0 carries its vouchers. `acceptProposal` checks + them and answers 30391 per seat with no person asked. `refusalOf` refuses a kind:0 without `T` + vouchers. `SIGNABLE_KINDS` is unchanged. +- `ConfederationProfileFollowThrough`, run from the sweep `SynchronizationViewModel` already runs + and when a voucher arrives. It applies D6's order and delay, the crossing rule, and retry with + backoff, and it stops at expiry, `SUPERSEDED` or `PUBLISHED`. +- `EditGroupNostrProfileViewModel` stops routing kind:0 to `proposeAsConfederation`. The + confederation's room opens `ConfederationScreen` for its profile. Phase 0 check 4's first pin + is flipped. + +Tests: extend `ConfederationSigningJvmTest`, three groups of three on nine devices with `T = 2`: + +- A proposes and B endorses, so the signature is made with no role holder asked, and C's seats + say no; +- A proposes and B and C object, so the change is `DECLINED` and no attempt starts; +- the first person in the order is offline, so the second starts after ten minutes (on a test + clock); +- a restart between nonces and confirmations, followed by a retry that succeeds; +- crossing attempts, where the one whose id sorts first survives everywhere; +- a kind:0 proposed directly in the room, which is refused; +- a role holder who is no longer an admin of B still signs for B's seat on B's voucher. + +**Built.** `ConfederationSigningJvmTest` 13/13 (from 7): two groups' vouchers and the profile is signed +on all nine devices with nobody asked, Ekklesia's seats saying no and every device reading the change +as `PUBLISHED`; one group's voucher and nothing starts; the first in the order away and the second +starting ten minutes later; a restart between nonces and confirmations, then the backoff, then a +second attempt that signs; two attempts at once ending in the one whose id sorts first; and Phase 0's +pin flipped (a kind:0 proposed in the room is refused with `THROUGH_GROUPS`). The direct-path cases +now sign a post. Where it differs from the above: + +| what the phase said | what it turned out to be | +|---|---| +| the vouchers a 30390 carries, checked on arrival | checked, and **filed** (`recordVoucher`), so `refusalOf` reads them back from the table on approval and at the end: an attempt needs no new column | +| `acceptProposal` sends 30391 "without asking anyone" | and marks the attempt approved, or declined where none of the person's seats vouched, so `isAwaitingApproval` is false and the signing screen asks nothing | +| crossing attempts | settled the moment a device holds two running attempts over one kind:0, on proposing and on arrival: every device fails the same one out loud with `CROSSED` | +| a role holder who is no longer an admin of B | holds by construction: the automatic answer reads only the seat's group's voucher and never the group's admins, so no case was added | +| `ConfederationSigningManager.refusalOf` | also refuses a kind:0 older than one the confederation has already signed (`SUPERSEDED`), which the follow-through would otherwise sign for nothing | +| 30396 | in `ConfederationSigningEvents.ALL`, so it travels as the signing's other messages do; `process` takes it before looking for a session tag, and keeps it only from a role holder of the group that signed it | +| the confederation's room opens `ConfederationScreen` for its profile | its profile screen no longer offers an edit (`GroupNostrProfileViewModel`, `EditGroupNostrProfileViewModel`); the way from that room to the confederation's screen is Phase 7's | +| the voucher premise (Phase 0, check 5) | now signs its voucher beside a real change's seals, since a voucher asked for on its own is declined | + +### Phase 6: publishing and hearing (D7) + +- The kind:0 owed on the starter's device, sent by `ConfederationPublisher` to the publish set + and every member group's 10050 relays. The other role holders' devices send it as a fallback + after an hour. +- `live-confederation`'s kind:0 filter by author. A kind:0 that arrives is verified and filed under + the confederation's id. `ConfederationProfile.newestOf`. +- `TYPE_CONFEDERATION_PROFILE_PUBLISHED` on every member's device, and the change moves to + `PUBLISHED`. Other changes with an earlier `created_at` move to `SUPERSEDED`. + +Tests: `ConfederationProfileRelayTest`, with the relay as a copy, covering that a member of A who +is not an admin and holds no role sees the new profile on the confederation's screen, and that a +later change published before an earlier one supersedes it. + +**Built.** `ConfederationProfileRelayJvmTest` 4/4: a device holding only the charter hears the profile +off a relay, reads it as the confederation's newest, and writes "Atlas has a new profile, as …" in its +group's room, opening the confederation; an older profile heard late changes nothing a reader sees; +a kind:0 from anyone but a known confederation, or one its key did not sign, is not filed; an owed +profile goes to every member group's announced inbox relays too. `ConfederationRelayTest` gains the +filter by author. Supersession was already Phase 1's and is tested there. Where it differs from the +above: + +| what the phase said | what it turned out to be | +|---|---| +| owed on the starter's device, the others as a fallback after an hour | **owed by every device that signed it.** The same event from several devices is one event to a relay, and a fallback would have needed a way to tell that nobody else's copy got out, which nothing here can see | +| "the published line on every member's device, from the kind:0 off relays" | from wherever the kind:0 is first filed -- the signing's end on a role holder's device, a relay everywhere else -- and only for the newest profile held | +| the subscription's confederation ids | `ConfederationRepository.observeKnownConfederations`: every `Confederation` row and every charter's author, so the filter follows a charter as it arrives | +| a kind:0 off a relay | `ConfederationManager.record` hands it to `ConfederationProfileManager.hearProfile`, which files it only for a confederation this device knows by record or charter | + +### Phase 7: rooms that say what they are (D9, D10) + +- The confederation's room: members labelled by group, the **Groups** card, and the sentence about + admins who joined later. Phase 0 check 4's second pin is flipped. +- The ceremony's room after formation: the banner links to the confederation, the composer is + hidden, and the room moves below active conversations. It opens again for a retry. + +Tests: `ConfederationScreensJvmTest` gains the labelled members and a person in two groups shown +once. The messaging screen's test covers a formed ceremony room with no composer. + +**Built.** `ConfederationSigningJvmTest` gains two cases (15): on a Polis admin's device the +confederation's room names its three groups, each with its three role holders, names the person's own +group beside them, and opens the confederation's screen from Polis's room; and once formed, the key +ceremony's room leads to the confederation it made. Audits at budget. Where it differs from the above: + +| what the phase said | what it turned out to be | +|---|---| +| a **Groups** card above the members | the groups go into the confederation's card the room already had ("This is the room of the confederation Atlas…"), one line a group with its role holders, then the sentence about later admins and **Open the confederation**. One card about whose room it is, rather than two | +| each member labelled with their groups | beside "Admin" and "Share" on the member's row, as one more label | +| the ceremony's room moves below active conversations | **not done.** The chat list sorts every room by its last message, and an ended ceremony's room stops getting messages, so it sinks on its own; a special order for one kind of room was more than this needed. The banner and the hidden composer are built | +| tested through the screens | through `DatabaseChatRepository.confederationRoomInfo` and `keyCeremonyOfRoom` on the nine-device harness, which is where the facts come from; the screens only lay them out | + +### Phase 8: the network run + +`ConfederationProfileNetworkJvmTest`, the plan end to end on `ConfederationNetworkJvmTest`'s +harness: three groups of three, real FROST and confederation signatures, and relays as copies. +A's admin edits the name from the confederation's screen. Every admin of B and C gets a line and +a notification. B endorses. The profile is signed with no further question, published, and read +back on all nine devices and on a non-admin member's device in each group. Then a second change +that C objects to and A withdraws. + +**Built.** `ConfederationProfileNetworkJvmTest` 2/2, on `ConfederationTestGroups` rather than +`ConfederationNetworkJvmTest`'s fixture: three groups of three admins, each signing by real FROST and +holding a real inbox, **form the confederation the real way** -- Agora's proposal and the two +acceptances sealed group to group, then the key ceremony on all nine devices in the NIP-17 room each +derives -- and then decide its profile. Agora's change reaches every admin of every group; Agora's +voucher alone starts nothing; Polis's endorsement makes it `ENDORSED` everywhere; one device, the first +in the order, starts the signing, and all nine finish it without being asked; every device reads the +new name and the change as `PUBLISHED`; Ekklesia's room has the proposed, endorsed and published lines +on each of its admins' devices; and a member of Polis who is no admin, holding only Polis's room, +hears the charter and the profile from a relay and gets the published line. The second case: Ekklesia +objects, Agora withdraws, and nothing is signed. Notifications are the classifier's, tested in Phase 3, +not again here. + +### Phase 9: the record, and devices + +This document's header and progress table, as the other confederation plans keep theirs, and a +row-by-row "where the build chose differently". Then a device run: two phones and the desktop +build, two real groups with inboxes, one change proposed, endorsed, signed and seen on a third +client by npub. Record what did not happen. + +**The record done; the device run not.** Nothing here has run on a device or a desktop client: no +change has crossed real inboxes between real groups, no confederation has signed a profile across real +phones whose nonces live only in memory, and the timing D6 rests on -- ten minutes a place, role +holders online together -- has only been exercised on a test clock. The ten minutes, the two-hour cap +and the one-minute sweep are guesses until a device run says otherwise. + +--- + +## What this does not do + +- **Posts and the charter** still go through the direct path, with each role holder asked as a + person. The wire of D2 is general (the 9435 carries one unsigned event), so moving kind:1 and + 9434 over is a refusal and a form each. That is the obvious next plan. +- **Admins who joined after formation** cannot sign for the confederation. They hold no role, + because the room and the roster are fixed at the founders until governance is built + ([confederation.md](./confederation.md), Phase 15). They *can* propose and endorse, because + those are their group's statements, and a voucher is their group's. +- **A newly promoted admin cannot read changes proposed before their promotion** + ([group-inbox.md](./group-inbox.md) D15). Their group's later answers still work, because each + carries the 9435 it answers. +- **Signing needs devices online together.** A voucher makes a role holder's consent automatic, + but their nonce still has to be made while the attempt runs. D6's retries carry the change + across gaps; nothing carries it past its expiry. +- **Not for value.** Upstream's warning on its confederation module stands. + +## Risks + +| risk | what to do | +|---|---| +| `InboxRefusal`'s manifest check refuses a batch that is not all seals | sign the voucher in a second session, started automatically on completion (Phase 0, check 2) | +| a profile too large for twelve seals | the existing size refusal, with the largest that fits recorded (check 3) | +| two groups each propose a change at once | both run; the newer `created_at` wins on relays, and an older one published second is refused (D4, D6) | +| no `T` groups' role holders are online together | retries with backoff until expiry, and the change's screen names the groups still being waited on | +| a group's quorum equivocates, sealing different 9435s to different groups | the change's id is the kind:0's id, which every voucher names. Groups endorsing different kind:0s produce vouchers for different ids, and neither reaches `T` | +| a role holder disagrees with their group's endorsement | by design their seat signs (D5); the appendix covers asking them as well | +| a stale voucher signed long after it was given | vouchers expire with their change, and nothing signs past expiry | + +## Out of scope + +- Moving posts (kind:1) and the charter (9434) onto group statements. +- Governance of the confederation's room and roster: admins added later, admins removed. +- A role holder's per-confederation setting to be asked each time (appendix). +- Threshold-ECDH member groups, as in the coordinator-free plan. + +--- + +## Appendix: considered and not chosen + +| idea | why not | +|---|---| +| keep the edit in the confederation's room, and only *notify* the groups' inboxes | the groups would hear about it without deciding it, and two role holders of one group could still speak for the confederation with their group unaware | +| every group must endorse (unanimity) | the confederation was formed as `T` of `N`, and its key signs that way. Unanimity would let one group stop everything forever | +| ask each role holder as well as each group | two questions per change per person. The group's quorum already is the role holders of that group, at its own threshold. Worth an opt-in per role holder if it is missed in practice | +| send the sealed 9436 into the confederation's room instead of a voucher | a seal is not transferable: only the group it was sealed to can open it | +| make the 9435/9436 rumors themselves signed | rumors are unsigned on purpose, and the seal already makes them binding between groups. The voucher is the one transferable statement, kept separate and never published | +| run the confederation's nested signing through the groups' inboxes | nonces, confirmations and partials are high-volume, person-to-person, and must stay in memory. The Marmot room already carries them | +| delete the ceremony's NIP-17 room after formation | its messages are the genesis evidence, and a retry needs the room | + +--- + +## Order and size + +| phase | rough size | depends on | +|---|---|---| +| 0 | the in-flight commit, scratch tests, this document | — | +| 1 | ~450 main, ~400 test, an auto-migration | 0 | +| 2 | ~450 main, ~450 test | 1 | +| 3 | ~200 main, ~250 test | 2 | +| 4 | ~900 main, ~400 test | 3 | +| 5 | ~500 main, ~600 test | 2 | +| 6 | ~250 main, ~250 test | 5 | +| 7 | ~250 main, ~150 test | 0 | +| 8 | ~400 test | 4, 6 | +| 9 | docs and a device session | all | + +Phases 3 and 5 can be built side by side once 2 is in, and Phase 4 can follow 3 while 5 and 6 go on. +Phase 7 touches neither the statements nor the signing, so it can be built at any point after 0. +That makes it a good first piece to ship, since it fixes the "which groups are these people" +problem without waiting on the rest. + +## Checking the work + +```bash +./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest +``` + +```bash +./gradlew :composeApp:m3Audit +``` + +```bash +./gradlew check +``` + +The new tags (`confederation`, `profile`, `base`, `voucher`) are wire tags, not hash inputs, so +no `mantra/…` tag is added. Bennu is named nowhere but in comments, and no kind in `RetiredKinds` +is touched.