diff --git a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/48.json b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/48.json new file mode 100644 index 00000000..bccd89f4 --- /dev/null +++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/48.json @@ -0,0 +1,7238 @@ +{ + "formatVersion": 1, + "database": { + "version": 48, + "identityHash": "446fdb6f17eaa57c1f2b06b4af19aa7d", + "entities": [ + { + "tableName": "BroadcastNostrEventReceipt", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `nostrEventId` TEXT NOT NULL, `unsignedNostrEventId` INTEGER, `isAccepted` INTEGER NOT NULL, `isSync` INTEGER NOT NULL, `relayURL` TEXT NOT NULL, `messages` TEXT, FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "isAccepted", + "columnName": "isAccepted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isSync", + "columnName": "isSync", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messages", + "columnName": "messages", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_BroadcastNostrEventReceipt_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventReceipt_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_BroadcastNostrEventReceipt_isAccepted", + "unique": false, + "columnNames": [ + "isAccepted" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventReceipt_isAccepted` ON `${TABLE_NAME}` (`isAccepted`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "BroadcastNostrEventRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `nostrEventId` TEXT NOT NULL, `unsignedNostrEventId` INTEGER, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_BroadcastNostrEventRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_BroadcastNostrEventRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Connection", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sourcePublicKey` TEXT NOT NULL, `destinationPublicKey` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`sourcePublicKey`, `destinationPublicKey`), FOREIGN KEY(`sourcePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`destinationPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sourcePublicKey", + "columnName": "sourcePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "destinationPublicKey", + "columnName": "destinationPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sourcePublicKey", + "destinationPublicKey" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sourcePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "destinationPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + } + ] + }, + { + "tableName": "ChatMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `senderPublicKey` TEXT NOT NULL, `isUserMessage` INTEGER NOT NULL, `giftWrapPayloadId` TEXT, `marmotGroupEventId` TEXT, `marmotInnerEventId` TEXT, `chatRoomId` TEXT NOT NULL, `replyToMessageId` INTEGER, `quotedMessageId` INTEGER, `content` TEXT NOT NULL, `messageType` TEXT NOT NULL, `directMessageRecipientPublicKey` TEXT, `frostSigningSessionId` TEXT, `dkgSessionId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`giftWrapPayloadId`) REFERENCES `GiftWrapPayload`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`marmotGroupEventId`) REFERENCES `MarmotGroupEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`marmotInnerEventId`) REFERENCES `MarmotInnerEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isUserMessage", + "columnName": "isUserMessage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "giftWrapPayloadId", + "columnName": "giftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotInnerEventId", + "columnName": "marmotInnerEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToMessageId", + "columnName": "replyToMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "quotedMessageId", + "columnName": "quotedMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messageType", + "columnName": "messageType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "directMessageRecipientPublicKey", + "columnName": "directMessageRecipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ChatMessage_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ChatMessage_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "GiftWrapPayload", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapPayloadId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MarmotGroupEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotGroupEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MarmotInnerEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotInnerEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageBroadcastNostrEventRequestRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `broadcastNostrEventRequestId` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`broadcastNostrEventRequestId`) REFERENCES `BroadcastNostrEventRequest`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "broadcastNostrEventRequestId", + "columnName": "broadcastNostrEventRequestId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "BroadcastNostrEventRequest", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "broadcastNostrEventRequestId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageBroadcastNostrEventReceiptRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `broadcastNostrEventReceiptId` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`broadcastNostrEventReceiptId`) REFERENCES `BroadcastNostrEventReceipt`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "broadcastNostrEventReceiptId", + "columnName": "broadcastNostrEventReceiptId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "BroadcastNostrEventReceipt", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "broadcastNostrEventReceiptId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageNostrEventRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatRoom", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `subject` TEXT, `description` TEXT, `mlsGroupState` TEXT, `initialGiftWrapPayloadId` TEXT, `leftGroupAt` INTEGER, `joinedGroupAt` INTEGER, `chronicleRequestedAt` INTEGER, `parentChatRoomId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`userPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`initialGiftWrapPayloadId`) REFERENCES `GiftWrapPayload`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT" + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT" + }, + { + "fieldPath": "mlsGroupState", + "columnName": "mlsGroupState", + "affinity": "TEXT" + }, + { + "fieldPath": "initialGiftWrapPayloadId", + "columnName": "initialGiftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "leftGroupAt", + "columnName": "leftGroupAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "joinedGroupAt", + "columnName": "joinedGroupAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "chronicleRequestedAt", + "columnName": "chronicleRequestedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "userPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "GiftWrapPayload", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "initialGiftWrapPayloadId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Confederation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `ceremonyId` TEXT NOT NULL, `name` TEXT NOT NULL, `roster` TEXT NOT NULL, `keyState` TEXT NOT NULL, `genesis` TEXT NOT NULL, `configSeq` INTEGER NOT NULL, `rosterHash` TEXT NOT NULL, `keyStateHash` TEXT NOT NULL, `recoveryPackages` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ceremonyId", + "columnName": "ceremonyId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roster", + "columnName": "roster", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyState", + "columnName": "keyState", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "genesis", + "columnName": "genesis", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "configSeq", + "columnName": "configSeq", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rosterHash", + "columnName": "rosterHash", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyStateHash", + "columnName": "keyStateHash", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "recoveryPackages", + "columnName": "recoveryPackages", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Confederation_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Confederation_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + } + ] + }, + { + "tableName": "ConfederationCeremony", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `proposalId` TEXT NOT NULL, `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, 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" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ConfederationEvent_proposalId", + "unique": false, + "columnNames": [ + "proposalId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_proposalId` ON `${TABLE_NAME}` (`proposalId`)" + }, + { + "name": "index_ConfederationEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_ConfederationEvent_publishedAt", + "unique": false, + "columnNames": [ + "publishedAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationEvent_publishedAt` ON `${TABLE_NAME}` (`publishedAt`)" + } + ] + }, + { + "tableName": "ConfederationInvitee", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`proposalId` TEXT NOT NULL, `groupPublicKey` TEXT NOT NULL, PRIMARY KEY(`proposalId`, `groupPublicKey`))", + "fields": [ + { + "fieldPath": "proposalId", + "columnName": "proposalId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "groupPublicKey", + "columnName": "groupPublicKey", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "proposalId", + "groupPublicKey" + ] + }, + "indices": [ + { + "name": "index_ConfederationInvitee_groupPublicKey", + "unique": false, + "columnNames": [ + "groupPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ConfederationInvitee_groupPublicKey` ON `${TABLE_NAME}` (`groupPublicKey`)" + } + ] + }, + { + "tableName": "ConfederationSigning", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `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, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "receiverPublicKey", + "columnName": "receiverPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receiverRelayHit", + "columnName": "receiverRelayHit", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapSeal", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `giftWrapMessageId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapMessageId`) REFERENCES `GiftWrapMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "giftWrapMessageId", + "columnName": "giftWrapMessageId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "GiftWrapMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapMessageId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapPayload", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `quotedEventId` TEXT, `giftWrapSealId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapSealId`) REFERENCES `GiftWrapSeal`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedEventId", + "columnName": "quotedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "giftWrapSealId", + "columnName": "giftWrapSealId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "GiftWrapSeal", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapSealId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "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, 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 + } + ], + "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`)" + } + ], + "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, PRIMARY KEY(`chatRoomId`, `rumorId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "rumorId", + "columnName": "rumorId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapId", + "columnName": "wrapId", + "affinity": "TEXT" + }, + { + "fieldPath": "conversationId", + "columnName": "conversationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participants", + "columnName": "participants", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rumorJson", + "columnName": "rumorJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "outgoing", + "columnName": "outgoing", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "signingSessionId", + "columnName": "signingSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "readAt", + "columnName": "readAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "rumorId" + ] + }, + "indices": [ + { + "name": "index_GroupInboxMessage_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxMessage_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupInboxMessage_conversationId", + "unique": false, + "columnNames": [ + "conversationId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxMessage_conversationId` ON `${TABLE_NAME}` (`conversationId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupInboxPublication", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`eventId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `eventJson` TEXT NOT NULL, `relays` TEXT NOT NULL, `signingSessionId` TEXT, `recipientPublicKey` TEXT, `attempts` INTEGER NOT NULL, `nextAttemptAt` INTEGER, `publishedAt` INTEGER, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`eventId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "eventId", + "columnName": "eventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "eventJson", + "columnName": "eventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relays", + "columnName": "relays", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signingSessionId", + "columnName": "signingSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "recipientPublicKey", + "columnName": "recipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "attempts", + "columnName": "attempts", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nextAttemptAt", + "columnName": "nextAttemptAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "publishedAt", + "columnName": "publishedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "eventId" + ] + }, + "indices": [ + { + "name": "index_GroupInboxPublication_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxPublication_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupInboxPublication_signingSessionId", + "unique": false, + "columnNames": [ + "signingSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxPublication_signingSessionId` ON `${TABLE_NAME}` (`signingSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupInboxWrap", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `wrapJson` TEXT NOT NULL, `wrapCreatedAt` INTEGER NOT NULL, `openedGeneration` INTEGER, `receivedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapJson", + "columnName": "wrapJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "wrapCreatedAt", + "columnName": "wrapCreatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "openedGeneration", + "columnName": "openedGeneration", + "affinity": "INTEGER" + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GroupInboxWrap_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupInboxWrap_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupKeyState", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `thresholdPublicKey` TEXT NOT NULL, `derivationPath` TEXT NOT NULL, `announcedBy` TEXT NOT NULL, `announcedAt` INTEGER NOT NULL, `parentChatRoomId` TEXT, `birthCertificateJson` TEXT, `generation` INTEGER, `publicSharesHash` TEXT, `memberBindings` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thresholdPublicKey", + "columnName": "thresholdPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcedBy", + "columnName": "announcedBy", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcedAt", + "columnName": "announcedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "birthCertificateJson", + "columnName": "birthCertificateJson", + "affinity": "TEXT" + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER" + }, + { + "fieldPath": "publicSharesHash", + "columnName": "publicSharesHash", + "affinity": "TEXT" + }, + { + "fieldPath": "memberBindings", + "columnName": "memberBindings", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId" + ] + }, + "indices": [ + { + "name": "index_GroupKeyState_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupKeyState_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupSignedEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `derivationPath` TEXT, `frostSigningSessionId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT" + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GroupSignedEvent_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupSignedEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_GroupSignedEvent_frostSigningSessionId", + "unique": false, + "columnNames": [ + "frostSigningSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_frostSigningSessionId` ON `${TABLE_NAME}` (`frostSigningSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InboxKey", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `generation` INTEGER NOT NULL, `publicKey` TEXT NOT NULL, `secretKey` TEXT, `recoveryData` TEXT, `ceremonyId` TEXT NOT NULL, `state` TEXT NOT NULL, `announcementEventId` TEXT, `createdAt` INTEGER NOT NULL, `announcedAt` INTEGER, `wipedAt` INTEGER, PRIMARY KEY(`chatRoomId`, `userPublicKey`, `generation`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "secretKey", + "columnName": "secretKey", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "ceremonyId", + "columnName": "ceremonyId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcementEventId", + "columnName": "announcementEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "announcedAt", + "columnName": "announcedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "wipedAt", + "columnName": "wipedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "userPublicKey", + "generation" + ] + }, + "indices": [ + { + "name": "index_InboxKey_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_InboxKey_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InboxKeyCeremony", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `participantPublicKeys` TEXT NOT NULL, `stage` TEXT NOT NULL, `hostPublicKey` TEXT, `round1Random` TEXT, `round2AuxRandom` TEXT, `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": "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, '446fdb6f17eaa57c1f2b06b4af19aa7d')" + ] + } +} \ 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 4bb0e818..f89482b7 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -700,14 +700,13 @@ Open for %1$d days Shorter Longer - You will coordinate its key ceremony, and every group that accepts discloses its admins to you. - This group discloses its %1$d admins and its threshold of %2$d to you + Proposing shows this group's admins to the admins of every group named here, and each group that accepts shows its own. Once every group has accepted, every admin of every group can join the key ceremony. + This group shows its %1$d admins and its threshold of %2$d to the groups it names Only one of the group's admins can propose a confederation This group cannot take part: it needs at least as many admins as its threshold, and a threshold of two or more Propose confederation Couldn't propose the confederation Confederation proposal - Coordinated by %1$s Open until %1$s Accepted Declined @@ -718,19 +717,17 @@ Reason (optional) Waiting for the group to sign its answer Open the signing session - Accepting discloses this group's admins and threshold to the coordinator, sealed so that only they can read them. + Accepting shows this group's admins and threshold to the admins of every group the proposal names. This device does not hold that proposal Couldn't ask the group to answer Every group accepted. %1$d admins across %2$d groups would hold the confederation's key. - Open the key ceremony - Couldn't open the key ceremony + Couldn't join the key ceremony Join the key ceremony Joining gives you a share of the confederation's key for each group you are an admin of. Everything after joining runs by itself. Abandon the key ceremony This device holds no key ceremony for this proposal Host keys Contributions - Contributions combined by the coordinator Authorizations Shares stored Waiting on %1$s 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 6885736e..712ff818 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt @@ -2,6 +2,7 @@ package mobi.giza.compose.database import androidx.room3.ColumnTypeConverters import androidx.room3.AutoMigration +import mobi.giza.compose.database.migrations.ConfederationSupergroupMigration import androidx.room3.ConstructedBy import androidx.room3.Database import androidx.room3.RoomDatabase @@ -222,7 +223,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) UnsignedNostrEvent::class, Zap::class ], - version = 47, + version = 48, autoMigrations = [ // v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can // generate the migration itself — nothing existing changes shape. @@ -506,6 +507,12 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) // Phase 4): GroupEcdhRound, GroupEcdhPartial, GroupConversationKey, GroupDmWrap, // GroupDmMessage and GroupDmOutbound. New tables only, so Room generates it. AutoMigration(from = 46, to = 47), + // v48 moves the confederation's statements into the groups' inboxes + // (docs/confederation-without-coordinator.md): ConfederationEvent gains the seal that + // carried a statement and the inbox that opened it; ConfederationSigning trades the seal + // secret and the carried public proposal for the statement and its invitation; version 1 + // statements, never in a release, are dropped. See ConfederationSupergroupMigration. + AutoMigration(from = 47, to = 48, spec = ConfederationSupergroupMigration::class), ] ) @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 f2466cec..4cc4f94f 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 @@ -20,10 +20,10 @@ interface ConfederationCeremonyDao { fun observeCeremony(id: String): Flow /** The newest ceremony for a proposal on this device: one per proposal is what runs. */ - @Query("SELECT * FROM ConfederationCeremony WHERE proposalId = :proposalId ORDER BY createdAt DESC LIMIT 1") + @Query("SELECT * FROM ConfederationCeremony WHERE proposalId = :proposalId ORDER BY attempt DESC, createdAt DESC LIMIT 1") suspend fun getLatestForProposal(proposalId: HexKey): ConfederationCeremony? - @Query("SELECT * FROM ConfederationCeremony WHERE proposalId = :proposalId ORDER BY createdAt DESC LIMIT 1") + @Query("SELECT * FROM ConfederationCeremony WHERE proposalId = :proposalId ORDER BY attempt DESC, createdAt DESC LIMIT 1") fun observeLatestForProposal(proposalId: HexKey): Flow @Query("SELECT * FROM ConfederationCeremony WHERE userPublicKey = :userPublicKey AND stage NOT IN ('COMPLETE', 'FAILED')") diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GiftWrapPayloadDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GiftWrapPayloadDao.kt index 8f1202c4..127e3f0f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GiftWrapPayloadDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GiftWrapPayloadDao.kt @@ -50,6 +50,15 @@ interface GiftWrapPayloadDao { ) suspend fun getByChatRoomAndKinds(chatRoomId: String, kinds: List): List + /** + * Every payload of [kinds], in whichever room it was filed: a confederation's ceremony looks + * here for what was sent to it before its owner joined, since a sender whose statements differ + * from this device's names other people, and so another room + * (docs/confederation-without-coordinator.md, D3 and D8). + */ + @Query("SELECT * FROM GiftWrapPayload WHERE kind IN (:kinds) ORDER BY createdAt ASC") + suspend fun getByKinds(kinds: List): List + @Upsert suspend fun upsert(giftWrapPayload: GiftWrapPayload) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/migrations/ConfederationSupergroupMigration.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/migrations/ConfederationSupergroupMigration.kt new file mode 100644 index 00000000..3e7a0c32 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/migrations/ConfederationSupergroupMigration.kt @@ -0,0 +1,41 @@ +package mobi.giza.compose.database.migrations + +import androidx.room3.DeleteColumn +import androidx.room3.RenameColumn +import androidx.room3.migration.AutoMigrationSpec +import androidx.sqlite.SQLiteConnection +import androidx.sqlite.execSQL + +/** + * Schema 48: the confederation's statements move from public events to rumors between the groups' + * inboxes (docs/confederation-without-coordinator.md, D12 and Phase 2). + * + * `ConfederationSigning` stops keeping a seal secret and the carried public proposal, and keeps the + * statement and the invitation that carried the proposal instead. Every version 1 statement (kinds + * 9430 to 9433) is dropped, with the sessions that were signing them: nothing reads a public + * statement any more, and nothing about them was ever in a release, since the feature has been off + * there. A confederation's charter (9434) is kept, as it is still public. + * + * The key ceremony loses its coordinator (D8): `ConfederationCeremony.coordinatorPublicKey` goes, + * the opening it sent becomes the basis each device builds for itself (`openingJson` is renamed + * `basisJson`), and a ceremony gains its attempt, its attestation and this person's seed. Every + * ceremony, and everything a ceremony formed, is dropped with the statements it was built from: + * a basis in the old shape no longer reads, and none of it was ever in a release either. + */ +@DeleteColumn(tableName = "ConfederationSigning", columnName = "sealSecret") +@DeleteColumn(tableName = "ConfederationSigning", columnName = "proposalJson") +@DeleteColumn(tableName = "ConfederationCeremony", columnName = "coordinatorPublicKey") +@RenameColumn(tableName = "ConfederationCeremony", fromColumnName = "openingJson", toColumnName = "basisJson") +class ConfederationSupergroupMigration : AutoMigrationSpec { + override suspend fun onPostMigrate(connection: SQLiteConnection) { + connection.execSQL("DELETE FROM ConfederationSigningMessage") + connection.execSQL("DELETE FROM ConfederationSigningAttempt") + connection.execSQL("DELETE FROM ConfederationMember") + connection.execSQL("DELETE FROM Confederation") + connection.execSQL("DELETE FROM ConfederationCeremonyMessage") + connection.execSQL("DELETE FROM ConfederationCeremony") + connection.execSQL("DELETE FROM ConfederationEvent WHERE kind IN (9430, 9431, 9432, 9433)") + connection.execSQL("DELETE FROM ConfederationInvitee WHERE proposalId NOT IN (SELECT id FROM ConfederationEvent)") + connection.execSQL("DELETE FROM ConfederationSigning") + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ConfederationCeremony.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ConfederationCeremony.kt index fd086dfc..0478add7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ConfederationCeremony.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ConfederationCeremony.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.database.model +import androidx.room3.ColumnInfo import androidx.room3.Entity import androidx.room3.ForeignKey import androidx.room3.Index @@ -10,7 +11,8 @@ import kotlin.time.Clock import kotlin.time.Instant /** - * One device's part in a confederation's key ceremony (docs/confederation.md, Phase 11). + * One device's part in a confederation's key ceremony (docs/confederation.md, Phase 11), made when + * its owner joins (docs/confederation-without-coordinator.md, D8). * * Inputs, never protocol state, as `DkgSession` keeps them: every step of the DKG is a pure * function of what is stored here and in [ConfederationCeremonyMessage], so a device that dies @@ -33,10 +35,20 @@ data class ConfederationCeremony( /** The NIP-17 room the ceremony runs in, over every admin of every group. */ val chatRoomId: String, val proposalId: HexKey, - val coordinatorPublicKey: HexKey, val userPublicKey: HexKey, - /** The coordinator's 30380, as sent: the roster's plan is rebuilt from it on every step. */ - val openingJson: String, + /** + * What the ceremony is built from on this device: the proposal and every acceptance, as its + * inboxes opened them (`ConfederationRitualEvents.Basis`). The roster's plan is rebuilt from it + * on every step. Nobody sent it: there is no coordinator (docs/confederation-without-coordinator.md, D8). + */ + val basisJson: String, + /** Which try at this roster it is: a failed or abandoned one is tried again as the next (D10). */ + @ColumnInfo(defaultValue = "1") + val attempt: Int = 1, + /** The roster's attestation, as this device built it: what every 30381 has to match (D3). */ + val attestationRef: HexKey? = null, + /** This person's part of the session seed, sent in its 30381 (D9). Fresh per attempt. */ + val seedContribution: HexKey? = null, val stage: ConfederationCeremonyStage = ConfederationCeremonyStage.WAITING_TO_JOIN, /** When this device's owner joined: the only thing they are asked. */ val approvedAt: Instant? = null, 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 1d4527d2..ddaded3b 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 @@ -10,10 +10,16 @@ import kotlin.time.Clock import kotlin.time.Instant /** - * A confederation event this device holds: a proposal, or an answer to one - * (docs/confederation.md, Phase 4). Signed by a group's key and verified before it is filed. + * 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). * - * One table for all four kinds, because the only question asked of them is "what has been said + * 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 + * verified as one. + * + * One table for every kind, because the only question asked of them is "what has been said * about this proposal", and a proposal's state is computed from the answer to it rather than * stored (D8). * @@ -27,21 +33,29 @@ data class ConfederationEvent( @PrimaryKey val id: HexKey, val kind: Kind, - /** The group that signed it. */ + /** The group that said it: the rumor's author, which its seal's signature vouches for. */ val pubKey: HexKey, /** The proposal it is about: its own id, for a proposal. */ val proposalId: HexKey, val eventCreatedAt: Long, + /** The rumor, for a statement; the signed event, for a charter. */ val eventJson: String, val receivedAt: Instant = Clock.System.now(), /** - * The signing session this device coordinated to make it, if it did: this device is the - * one that sends it to relays (D9). Null for everything heard from a relay or signed by - * another member's session. + * A charter this device's confederation signing proposed: this device is the one that sends + * it to relays. Statements are owed through the inbox's publications instead. */ val ownSessionId: String? = null, /** When a relay first accepted it from this device. Null while it is still owed. */ val publishedAt: Instant? = null, + /** + * The signed seal that carried a statement to this device, opened with [inboxRoomId]'s inbox + * key. Null for a charter, and for a statement this device's own group signed, which the + * signing session itself vouches for. + */ + val sealJson: String? = null, + /** Which of this device's groups' inboxes opened it, or signed it. Null for a charter. */ + val inboxRoomId: String? = null, ) { fun toEvent(): Event = Event.fromJson(eventJson) } @@ -57,13 +71,13 @@ data class ConfederationInvitee( ) /** - * What a device needs to remember about a signing session over a confederation event, past - * the moment its proposal arrived (docs/confederation.md, Phases 3 and 4). + * What a device needs to remember about a signing session over a confederation statement, past + * the moment its proposal arrived (docs/confederation-without-coordinator.md, D6). * - * - [sealSecret]: the ephemeral secret an acceptance is sealed under. The proposer's device - * needs it to resend the proposal; every signer's, to check the seal again at approval. - * - [proposalJson]: the 9430 an answer answers, carried on the signing proposal, so a signer - * does not depend on having heard it from a relay. + * - [rumorJson]: the statement the seals carry, in the clear inside the room's encryption, so + * every member sees what the group is being asked to say. + * - [invitationJson]: for an answer, the signed seal that brought the proposal to this group, so + * a signer does not depend on its own inbox having opened it. * - [refusal]: why this device declined, said in the decline it publishes. */ @Entity( @@ -79,8 +93,8 @@ data class ConfederationInvitee( data class ConfederationSigning( @PrimaryKey val sessionId: String, - val sealSecret: String? = null, - val proposalJson: String? = null, + val rumorJson: String? = null, + val invitationJson: String? = null, val refusal: String? = null, val createdAt: Instant = Clock.System.now(), ) 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 e188f111..af3bcb5e 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 @@ -30,7 +30,9 @@ import mobi.giza.compose.managers.RoomAdmins import mobi.giza.compose.nostr.confederation.ConfederationKinds import mobi.giza.compose.nostr.confederation.ConfederationStatus import mobi.giza.compose.managers.ConfederationManager -import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent +import mobi.giza.compose.nostr.confederation.ConfederationStatements +import mobi.giza.compose.managers.ConfederationRefusal +import mobi.giza.compose.extensions.toHex import mobi.giza.compose.repository.ConfederationRepository class DatabaseConfederationRepository( @@ -46,18 +48,11 @@ class DatabaseConfederationRepository( database.confederationCeremonyDao().observeMessages(sessionId) override fun ceremonyPlan(ceremony: ConfederationCeremony): ConfederationRosterBuilder.Plan? = - ConfederationRitualEvents.Opening.decode(ceremony.openingJson) - ?.let { ConfederationRitualManager.planFrom(it) as? Either.Right } - ?.value + ConfederationRitualManager.planOf(ceremony) - override suspend fun openCeremony(proposalId: HexKey): ConfederationCeremony { - val secret = activeIdentity.value?.nostrPrivateKey ?: throw IllegalStateException("This identity cannot sign") - return ConfederationRitualManager.open(database, proposalId, secret) - } - - override suspend fun joinCeremony(sessionId: String) { - val secret = activeIdentity.value?.nostrPrivateKey ?: return - ConfederationRitualManager.join(database, sessionId, secret.value.toByteArray()) + override suspend fun joinCeremony(proposalId: HexKey): ConfederationCeremony { + val secret = activeIdentity.value?.nostrPrivateKey ?: throw IllegalStateException("This identity cannot take part") + return ConfederationRitualManager.join(database, proposalId, secret.publicKey().xOnly().value.toHex(), secret.value.toByteArray()) } override suspend fun abandonCeremony(sessionId: String) = ConfederationRitualManager.abandon(database, sessionId) @@ -81,10 +76,8 @@ class DatabaseConfederationRepository( override fun observeConfederationsOf(groupPublicKey: HexKey): Flow> = database.confederationCeremonyDao().observeConfederationsOf(groupPublicKey) - override suspend fun outcome(proposalId: HexKey): ConfederationManager.Outcome? { - val secret = activeIdentity.value?.nostrPrivateKey ?: return null - return ConfederationManager.outcome(database, proposalId, secret) - } + override suspend fun outcome(proposalId: HexKey): ConfederationManager.Outcome? = + ConfederationManager.outcome(database, proposalId) override suspend fun record(event: Event): Boolean = ConfederationManager.record(database, event) @@ -94,26 +87,12 @@ class DatabaseConfederationRepository( override suspend fun markPublished(eventId: HexKey, at: Instant) = database.confederationDao().markPublished(eventId, at) - override fun observeOpenProposalIds(): Flow> = - database.confederationDao().observeProposals() - .map { rows -> - val now = Clock.System.now().epochSeconds - rows.mapNotNull { ConfederationProposalEvent.parse(it.toEvent()) } - .filterNot { it.isExpiredAt(now) } - .map { it.id } - .sorted() - } - .distinctUntilChanged() - - override suspend fun relayHintsFor(proposalId: HexKey): List = - ConfederationManager.proposal(database, proposalId)?.groups?.mapNotNull { it.relayHint }?.distinct().orEmpty() - override fun observeStatusesNaming(groupPublicKey: HexKey): Flow> = database.confederationDao().observeEventsNaming(groupPublicKey).map { rows -> val now = Clock.System.now().epochSeconds rows.groupBy { it.proposalId }.values.mapNotNull { events -> val proposal = events.firstOrNull { it.kind == ConfederationKinds.PROPOSAL && it.id == it.proposalId } - ?.let { ConfederationProposalEvent.parse(it.toEvent()) } ?: return@mapNotNull null + ?.let { ConfederationStatements.parseProposal(it.toEvent()) } ?: return@mapNotNull null ConfederationManager.statusOf(proposal, events, now) }.sortedWith(compareByDescending { it.proposal.createdAt }.thenBy { it.proposal.id }) } @@ -121,7 +100,7 @@ class DatabaseConfederationRepository( override fun observeStatus(proposalId: HexKey): Flow = database.confederationDao().observeEventsForProposal(proposalId).map { rows -> val proposal = rows.firstOrNull { it.kind == ConfederationKinds.PROPOSAL && it.id == proposalId } - ?.let { ConfederationProposalEvent.parse(it.toEvent()) } ?: return@map null + ?.let { ConfederationStatements.parseProposal(it.toEvent()) } ?: return@map null ConfederationManager.statusOf(proposal, rows) } @@ -137,7 +116,7 @@ class DatabaseConfederationRepository( override suspend fun proposeConfederation( localChatRoom: LocalChatRoom, userPublicKey: HexKey, - invitees: List, + invitees: List, threshold: Int, name: String, expiresAt: Long, @@ -154,17 +133,14 @@ class DatabaseConfederationRepository( override suspend fun proposeWithdrawal(localChatRoom: LocalChatRoom, userPublicKey: HexKey, proposalId: HexKey) = ConfederationManager.proposeWithdrawal(database, localChatRoom, userPublicKey, proposalId) + /** A session still signing a statement about [proposalId] in [chatRoomId]: its statement rides beside it. */ override fun observePendingAnswer(chatRoomId: String, proposalId: HexKey): Flow = database.frostSigningSessionDao().observeSessionsForChatRoom(chatRoomId).map { sessions -> sessions.firstOrNull { local -> local.session.stage != FrostSigningStage.COMPLETE && local.session.stage != FrostSigningStage.FAILED && - local.items.any { item -> - Event.fromJsonOrNull(item.unsignedEventJson)?.let { event -> - event.kind in ConfederationKinds.ALL && - (event.id == proposalId || event.tags.any { it.size > 1 && it[0] == "e" && it[1] == proposalId }) - } == true - } + ConfederationRefusal.Carried.from(database.confederationDao().getSigning(local.session.id)).rumor + ?.let { ConfederationStatements.proposalIdOf(it) } == proposalId }?.session } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationFollowThrough.kt index 4ad19f89..c39a835e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationFollowThrough.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationFollowThrough.kt @@ -3,7 +3,6 @@ package mobi.giza.compose.managers import co.touchlab.kermit.Logger import com.vitorpamplona.quartz.nip01Core.core.toHexKey import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair -import fr.acinq.bitcoin.utils.Either import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.conflate @@ -11,12 +10,14 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.Confederation -import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder import mobi.giza.compose.repository.ChatRepository /** - * The confederation's room, made by the coordinator's device once the key exists - * (docs/confederation.md, Phase 13), in the shape of `CeremonyFollowThrough`. + * The confederation's room, made once the key exists by the device of the first of its people + * (docs/confederation.md, Phase 13, and docs/confederation-without-coordinator.md, D11), in the + * shape of `CeremonyFollowThrough`. * * The room is an ordinary keyed Marmot room: its id is derived from the confederation's key the way * every keyed room's is (D10), its routing address is random, and every role holder is a member and @@ -48,7 +49,12 @@ object ConfederationFollowThrough { } } - /** Makes [confederation]'s room if this device coordinated it and the room is not here yet. */ + /** + * Makes [confederation]'s room if this device's owner is the one who makes it and the room is + * not here yet: the first of the roster's people, sorted bytewise + * (docs/confederation-without-coordinator.md, D11). Nobody coordinated the ceremony, so the + * order is the only thing that can say who. + */ suspend fun takeNextStep( database: GizaDatabase, chatRepository: ChatRepository, @@ -58,12 +64,16 @@ object ConfederationFollowThrough { ): MarmotGroupCreation.Outcome? = mutex.withLock { if (database.chatRoomDao().findChatRoomById(confederation.id) != null) return@withLock null val ceremony = database.confederationCeremonyDao().getCeremony(confederation.ceremonyId) ?: return@withLock null - if (ceremony.coordinatorPublicKey != keyPair.pubKey.toHexKey()) return@withLock null + val plan = ConfederationRitualManager.planOf(ceremony) ?: return@withLock null + if (creatorOf(plan) != keyPair.pubKey.toHexKey()) return@withLock null createRoom(database, chatRepository, confederation, keyPair, keyPackageLookupTimeout) } + /** Who makes the room for [plan]'s confederation: the first of its people, sorted bytewise (D11). */ + fun creatorOf(plan: ConfederationRosterBuilder.Plan): HexKey = plan.people.min() + /** - * Creates [confederation]'s room. Any role holder may -- the coordinator's device does it on its + * Creates [confederation]'s room. Any role holder may -- [creatorOf]'s device does it on its * own -- and anybody else is refused: listing themselves as the creator would put a member into * a room the confederation never chose. */ @@ -79,8 +89,7 @@ object ConfederationFollowThrough { } val ceremony = database.confederationCeremonyDao().getCeremony(confederation.ceremonyId) ?: return MarmotGroupCreation.Outcome.Failed("This device holds no ceremony for this confederation.") - val plan = ConfederationRitualEvents.Opening.decode(ceremony.openingJson) - ?.let { ConfederationRitualManager.planFrom(it) as? Either.Right }?.value + val plan = ConfederationRitualManager.planOf(ceremony) ?: return MarmotGroupCreation.Outcome.Failed("This confederation's roster no longer reads.") val me = keyPair.pubKey.toHexKey() if (me !in plan.people) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationFormation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationFormation.kt index 8ca1980a..c1695832 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationFormation.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationFormation.kt @@ -66,7 +66,7 @@ object ConfederationFormation { if (database.chatRoomDao().findChatRoomById(group) == null) return@forEach database.chatMessageDao().upsert( ChatMessage( - senderPublicKey = ceremony.coordinatorPublicKey, + senderPublicKey = plan.proposal.proposingGroup, isUserMessage = false, giftWrapPayloadId = null, marmotGroupEventId = null, 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 8ff6ad23..31a4b377 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt @@ -1,116 +1,141 @@ package mobi.giza.compose.managers import co.touchlab.kermit.Logger +import com.vitorpamplona.crypto.random.RandomInstance import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.vitorpamplona.crypto.random.RandomInstance +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.verify 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.extensions.toNpub -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import kotlin.time.Instant import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.InboxKeyState import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.extensions.toNpub import mobi.giza.compose.nostr.confederation.ConfederationAdminList import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent import mobi.giza.compose.nostr.confederation.ConfederationKinds -import mobi.giza.compose.nostr.confederation.ConfederationProposalAcceptanceEvent -import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent -import mobi.giza.compose.nostr.confederation.ConfederationProposalRejectionEvent -import mobi.giza.compose.nostr.confederation.ConfederationProposalWithdrawalEvent -import mobi.giza.compose.nostr.confederation.ConfederationSeal import mobi.giza.compose.nostr.confederation.ConfederationProposalState -import fr.acinq.bitcoin.PrivateKey +import mobi.giza.compose.nostr.confederation.ConfederationStatements import mobi.giza.compose.nostr.confederation.ConfederationStatus +import mobi.giza.compose.nostr.frost.FrostSigningEvents import mobi.giza.compose.nostr.frost.GroupKeyStateEvent +import mobi.giza.compose.nostr.inbox.InboxReplyManifest +import mobi.giza.compose.nostr.inbox.InboxSeal /** - * The confederation's events on this device: filing them, and reading a proposal's state back - * (docs/confederation.md). + * The confederation's statements on this device: proposing them, filing them, and reading a + * proposal's state back (docs/confederation.md, Part A, as + * docs/confederation-without-coordinator.md moved it into the groups' inboxes). + * + * A statement is a rumor a group seals once to every group its proposal names, its own included, + * from its inbox key, and signs through its quorum (D1, D6). Every admin of every group named + * therefore holds every statement, and every one of their devices computes the same state, with + * nobody coordinating. */ object ConfederationManager { private val logger = Logger.withTag("ConfederationManager") /** - * Files [event] if it is a well-formed confederation event that its author's key signed. - * Returns whether it was new. - * - * The author is a group's npub, which is also its room id, so "did this group sign it" is - * [GroupKeyStateEvent.isSignedByRoom] with the event's own author -- a plain nostr signature - * check, since a FROST signature is an ordinary BIP 340 one. + * Files [event] if it is a confederation's charter (9434) that its author's key signed: the one + * confederation event still heard on relays. Returns whether it was new. A statement is never + * filed this way: it arrives through an inbox, as [recordStatement]. */ suspend fun record(database: GizaDatabase, event: Event): Boolean { - if (!ConfederationKinds.isConfederationKind(event.kind)) return false + if (event.kind != ConfederationKinds.CHARTER) return false if (!GroupKeyStateEvent.isSignedByRoom(event, event.pubKey)) { - logger.w("Confederation event ${event.id.take(8)} does not verify as its author's; dropping") + logger.w("Charter ${event.id.take(8)} does not verify as its author's; dropping") return false } - - val (proposalId, invitees) = when (event.kind) { - ConfederationKinds.PROPOSAL -> ConfederationProposalEvent.parse(event) - ?.let { it.id to it.groupPublicKeys } - ConfederationKinds.ACCEPTANCE -> ConfederationProposalAcceptanceEvent.parse(event) - ?.let { it.proposalId to emptyList() } - ConfederationKinds.REJECTION -> ConfederationProposalRejectionEvent.parse(event) - ?.let { it.proposalId to emptyList() } - ConfederationKinds.WITHDRAWAL -> ConfederationProposalWithdrawalEvent.parse(event) - ?.let { it.proposalId to emptyList() } - // Filed under its own id, and under every group it names, so each member group finds it. - ConfederationKinds.CHARTER -> ConfederationCharterEvent.parse(event) - ?.let { it.id to it.groups } - else -> null - } ?: run { - logger.w("Confederation event ${event.id.take(8)} of kind ${event.kind} is not well formed; dropping") + val charter = ConfederationCharterEvent.parse(event) ?: run { + logger.w("Charter ${event.id.take(8)} is not well formed; dropping") return false } - val filed = database.confederationDao().record( ConfederationEvent( id = event.id, kind = event.kind, pubKey = event.pubKey, - proposalId = proposalId, + proposalId = charter.id, eventCreatedAt = event.createdAt, eventJson = event.toJson(), ), - invitees = invitees, + invitees = charter.groups, ) - // Once per event, by construction: the row above is written once. An answer filed - // before its proposal had nothing to name, so the proposal writes its lines now -- - // relays deliver in any order, and a proposal and its proposer's acceptance share a - // second, so which comes first is down to their ids. - if (filed) runCatching { - announce(database, event, proposalId) - if (event.kind == ConfederationKinds.PROPOSAL) { - database.confederationDao().getEventsForProposal(proposalId) - .filter { it.kind in ConfederationKinds.ANSWERS } - .forEach { announce(database, it.toEvent(), proposalId) } - } - }.onFailure { logger.w(throwable = it) { "Filed ${event.id.take(8)} but could not write its line" } } + if (filed) runCatching { announceCharter(database, event) } + .onFailure { logger.w(throwable = it) { "Filed ${event.id.take(8)} but could not write its line" } } return filed } /** - * A system line in every room on this device that [event] concerns: each group its - * proposal names (docs/confederation.md, Phase 6). An answer whose proposal this device does - * not hold yet gets its line when the proposal is filed. + * Files [rumor], a statement 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 an + * unsigned rumor the group's word (D3). Callers have opened it already; this checks again, + * since nothing else stands between a forged statement and the table. */ - private suspend fun announce(database: GizaDatabase, event: Event, proposalId: HexKey) { - if (event.kind == ConfederationKinds.CHARTER) return announceCharter(database, event) + suspend fun recordStatement(database: GizaDatabase, rumor: Event, seal: Event?, inboxRoomId: String?): Boolean { + if (!ConfederationStatements.isStatementKind(rumor.kind)) return false + if (seal != null && (!seal.verify() || !seal.pubKey.equals(rumor.pubKey, ignoreCase = true))) { + logger.w("Statement ${rumor.id.take(8)} came in a seal that is not its author's; dropping") + return false + } + val (proposalId, invitees) = when (rumor.kind) { + ConfederationKinds.PROPOSAL -> ConfederationStatements.parseProposal(rumor)?.let { it.id to it.groupPublicKeys } + else -> ConfederationStatements.parseAnswer(rumor)?.let { it.proposalId to emptyList() } + } ?: run { + logger.w("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 = proposalId, + eventCreatedAt = rumor.createdAt, + eventJson = InboxSeal.rumorJson(rumor), + sealJson = seal?.toJson(), + inboxRoomId = inboxRoomId, + ), + invitees = invitees, + ) + // Once per statement, by construction: the row above is written once. An answer filed + // before its proposal had nothing to name, so the proposal writes its lines now: wraps + // arrive in any order. + if (filed) runCatching { + announce(database, rumor, proposalId) + if (rumor.kind == ConfederationKinds.PROPOSAL) { + database.confederationDao().getEventsForProposal(proposalId) + .filter { it.kind in ConfederationKinds.ANSWERS } + .forEach { announce(database, it.toEvent(), proposalId) } + } + }.onFailure { logger.w(throwable = it) { "Filed ${rumor.id.take(8)} but could not write its line" } } + return filed + } + + /** + * A system line in every room on this device that [statement] concerns: each group its + * proposal names. An answer whose proposal this device does not hold yet gets its line when + * the proposal is filed. Written by each device for itself, sending nothing. + */ + private suspend fun announce(database: GizaDatabase, statement: Event, proposalId: HexKey) { val proposal = proposal(database, proposalId) ?: return val rooms = proposal.groupPublicKeys.mapNotNull { database.chatRoomDao().findChatRoomById(it) } if (rooms.isEmpty()) return rooms.forEach { room -> val roomId = room.chatRoom.id - val who = nameOf(database, event.pubKey, roomId) - val (type, content) = when (event.kind) { + val who = nameOf(database, statement.pubKey, roomId) + val (type, content) = when (statement.kind) { ConfederationKinds.PROPOSAL -> - ChatMessage.TYPE_CONFEDERATION_PROPOSED to if (event.pubKey == roomId) { + ChatMessage.TYPE_CONFEDERATION_PROPOSED to if (statement.pubKey == roomId) { "This group proposed a confederation, ${proposal.name}, of ${proposal.groups.size} groups" } else { "$who invited this group to a confederation, ${proposal.name}" @@ -125,7 +150,7 @@ object ConfederationManager { } database.chatMessageDao().upsert( ChatMessage( - senderPublicKey = event.pubKey, + senderPublicKey = statement.pubKey, isUserMessage = false, giftWrapPayloadId = null, marmotGroupEventId = null, @@ -133,15 +158,15 @@ object ConfederationManager { chatRoomId = roomId, content = content, messageType = type, - createdAt = Instant.fromEpochSeconds(event.createdAt), + createdAt = Instant.fromEpochSeconds(statement.createdAt), ) ) } } /** - * A line in each member group's room this device holds: the one way a group's members who are - * not admins hear that their group is part of a confederation. A claim by the confederation's + * A line in each member group's room this device holds: how a group's members who are not + * admins hear that their group is part of a confederation. A claim by the confederation's * key, which the line says. */ private suspend fun announceCharter(database: GizaDatabase, event: Event) { @@ -175,23 +200,21 @@ object ConfederationManager { } /** - * The group signed [signedEvents] in [session]: file the confederation's among them, as every - * device that completes the session does, and on the device that coordinated it, mark them - * owed to relays (D9). A confederation event exists only to be read on relays, so the - * quorum's approval of one is the decision to send it. + * The group signed [signedEvents] in [session]: if they were the seals of a statement, file + * the statement, as every device that completes the session does. The device that proposed it + * wraps and sends the seals, as the inbox does a reply's (`InboxReplies.onSigned`). */ suspend fun onSigned(database: GizaDatabase, session: FrostSigningSession, signedEvents: List) { - signedEvents.filter { ConfederationKinds.isConfederationKind(it.kind) }.forEach { signed -> - if (!record(database, signed) && database.confederationDao().getEvent(signed.id) == null) return@forEach - if (session.isCoordinator()) database.confederationDao().markOwn(signed.id, session.id) - } + 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 + recordStatement(database, rumor, seal = null, inboxRoomId = session.chatRoomId) } /** The proposal [proposalId], if this device holds it. */ - suspend fun proposal(database: GizaDatabase, proposalId: HexKey): ConfederationProposalEvent.Proposal? = + suspend fun proposal(database: GizaDatabase, proposalId: HexKey): ConfederationStatements.Proposal? = database.confederationDao().getEvent(proposalId) ?.takeIf { it.kind == ConfederationKinds.PROPOSAL } - ?.let { ConfederationProposalEvent.parse(it.toEvent()) } + ?.let { ConfederationStatements.parseProposal(it.toEvent()) } /** Where [proposalId] stands on this device, or null if this device does not hold it. */ suspend fun status( @@ -201,12 +224,12 @@ object ConfederationManager { ): ConfederationStatus? { val events = database.confederationDao().getEventsForProposal(proposalId) val proposal = events.firstOrNull { it.id == proposalId && it.kind == ConfederationKinds.PROPOSAL } - ?.let { ConfederationProposalEvent.parse(it.toEvent()) } ?: return null + ?.let { ConfederationStatements.parseProposal(it.toEvent()) } ?: return null return statusOf(proposal, events, now) } fun statusOf( - proposal: ConfederationProposalEvent.Proposal, + proposal: ConfederationStatements.Proposal, events: List, now: Long = Clock.System.now().epochSeconds, ): ConfederationStatus = ConfederationStatus.of( @@ -216,20 +239,20 @@ object ConfederationManager { ) /** - * What this group would disclose in an acceptance of [proposalId], read off this device's - * own view of it: the room's live admins and the threshold its key signs with. Null when - * this device cannot say -- no admin policy, no key -- or the group could not take part as - * it stands (fewer admins than its threshold, a threshold of one). + * The admin list this group would carry in a statement about [proposalId] (null: its own + * proposal), read off this device's own view of it: the room's live admins and the threshold + * its key signs with. Null when this device cannot say -- no admin policy, no key -- or the + * group could not take part as it stands. * * The same function on the proposer's device and every signer's, so the list each of them - * seals comes out the same when they see the same group (docs/confederation.md, D5). + * builds comes out the same when they see the same group. */ - suspend fun adminListFor(database: GizaDatabase, chatRoomId: String, proposalId: HexKey): ConfederationAdminList? = + suspend fun adminListFor(database: GizaDatabase, chatRoomId: String, proposalId: HexKey?): ConfederationAdminList? = disclosureFor(database, chatRoomId)?.listFor(proposalId) /** The admins and threshold [adminListFor] reads, before there is a proposal id to bind them to. */ class Disclosure(val group: HexKey, val admins: Set, val threshold: Int) { - fun listFor(proposalId: HexKey): ConfederationAdminList? = ConfederationAdminList.of(proposalId, group, threshold, admins) + fun listFor(proposalId: HexKey?): ConfederationAdminList? = ConfederationAdminList.ofV2(proposalId, group, threshold, admins) /** Whether upstream's roster would take this group as it stands: `2 <= t_g <= n_g`. */ val canTakePart: Boolean @@ -243,18 +266,24 @@ object ConfederationManager { return Disclosure(chatRoomId, admins, threshold) } + /** The inbox key [roomId] has announced and this device holds: what its statements are sealed from (D5). */ + suspend fun announcedInboxKey(database: GizaDatabase, roomId: HexKey, userPublicKey: HexKey) = + database.inboxKeyDao().getKeys(roomId, userPublicKey).firstOrNull { it.state == InboxKeyState.ANNOUNCED && it.secretKey != null } + + /** Why [group] cannot be sent a statement from this device, or null when it can: it has to have announced an inbox (D5). */ + suspend fun inboxProblem(database: GizaDatabase, group: HexKey): String? = + if (InboxReplies.hasAnnouncedKey(database, group)) null else "${nameOf(database, group)} has announced no inbox" + /** - * Proposes, in [localChatRoom], that its group sign a proposal for a confederation of - * [invitees] together with its own acceptance of it, in one session (D3). [userPublicKey] - * is the coordinator, and has to be one of the group's admins (D4). - * - * The group itself is put first on the invitation if [invitees] leave it out. + * Proposes, in [localChatRoom], that its group propose a confederation of itself and [invitees] + * (D2, D4). The proposal carries this group's own admins, so it is also its acceptance. + * [userPublicKey] only proposes the signing session, and has to be one of the group's admins. */ suspend fun proposeConfederation( database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, - invitees: List, + invitees: List, threshold: Int, name: String, expiresAt: Long, @@ -263,38 +292,29 @@ object ConfederationManager { val group = localChatRoom.chatRoom.id val admins = RoomAdmins.of(database, group)?.admins ?: throw IllegalStateException("This device cannot read the group's admins") - check(userPublicKey in admins) { "Only one of the group's admins can coordinate a confederation" } - - val groups = (listOf(ConfederationProposalEvent.Invitee(group)) + invitees) - .distinctBy { it.groupPublicKey } - val tags = ConfederationProposalEvent.assembleTags( - groups = groups, - coordinator = userPublicKey, + check(userPublicKey in admins) { "Only one of the group's admins can propose a confederation" } + val disclosure = disclosureFor(database, group) + ?: throw IllegalStateException("This device cannot read the group's admins and threshold") + val own = disclosure.listFor(null) + ?: throw IllegalStateException(CANNOT_TAKE_PART) + val others = invitees.filter { it != group }.distinct() + check(others.size + 1 <= ConfederationKinds.MAX_SUPERGROUP_GROUPS) { + "A confederation proposed between inboxes can name at most ${ConfederationKinds.MAX_SUPERGROUP_GROUPS} groups" + } + val rumor = ConfederationStatements.proposal( + group = group, + others = others, threshold = threshold, name = name, nonce = RandomInstance.bytes(32).toHex(), expiresAt = expiresAt, + admins = own, + createdAt = createdAt, ) - val secret = RandomInstance.bytes(32) - val carried = ConfederationRefusal.Carried(sealSecret = secret.toHex(), proposalJson = null) - val disclosure = disclosureFor(database, group) - ?: throw IllegalStateException("This device cannot read the group's admins and threshold") - - val session = FrostSigningManager.proposeSigningBatch( - database = database, - localChatRoom = localChatRoom, - userPublicKey = userPublicKey, - lead = EventTemplate(createdAt, ConfederationKinds.PROPOSAL, tags, ConfederationProposalEvent.content(name, groups.size)), - dependents = { lead -> - listOf(acceptanceTemplate(disclosure, lead.id, null, group, userPublicKey, secret, createdAt)) - }, - proposalTags = carried.toTags(), - ) - ConfederationRefusal.remember(database, session.id, carried, null) - return session + return proposeStatement(database, localChatRoom, userPublicKey, rumor, others, invitation = null) } - /** Proposes that this group accept [proposalId], disclosing its admins to the coordinator (D5). */ + /** Proposes that this group accept [proposalId], showing its admins to every group it names (D4). */ suspend fun proposeAcceptance( database: GizaDatabase, localChatRoom: LocalChatRoom, @@ -302,16 +322,11 @@ object ConfederationManager { proposalId: HexKey, createdAt: Long = Clock.System.now().epochSeconds, ): FrostSigningSession { - val (event, proposal) = heldProposal(database, proposalId) - val secret = RandomInstance.bytes(32) - val carried = ConfederationRefusal.Carried(sealSecret = secret.toHex(), proposalJson = event.toJson()) - val disclosure = disclosureFor(database, localChatRoom.chatRoom.id) - ?: throw IllegalStateException("This device cannot read the group's admins and threshold") - val template = acceptanceTemplate( - disclosure, proposal.id, proposal.relayHintFor(proposal.proposingGroup), - proposal.proposingGroup, proposal.coordinator, secret, createdAt, - ) - return proposeAnswer(database, localChatRoom, userPublicKey, template, carried) + val group = localChatRoom.chatRoom.id + val (proposal, invitation) = heldProposal(database, proposalId, group) + val list = adminListFor(database, group, proposal.id) ?: throw IllegalStateException(CANNOT_TAKE_PART) + val rumor = ConfederationStatements.acceptance(group, proposal, list, createdAt) + return proposeStatement(database, localChatRoom, userPublicKey, rumor, proposal.othersThan(group), invitation) } /** Proposes that this group reject [proposalId], saying [reason] if it gives one. */ @@ -323,13 +338,10 @@ object ConfederationManager { reason: String = "", createdAt: Long = Clock.System.now().epochSeconds, ): FrostSigningSession { - val (event, proposal) = heldProposal(database, proposalId) - val template = EventTemplate( - createdAt, ConfederationKinds.REJECTION, - ConfederationProposalRejectionEvent.assembleTags(proposal.id, proposal.relayHintFor(proposal.proposingGroup), proposal.proposingGroup), - reason, - ) - return proposeAnswer(database, localChatRoom, userPublicKey, template, ConfederationRefusal.Carried(null, event.toJson())) + val group = localChatRoom.chatRoom.id + val (proposal, invitation) = heldProposal(database, proposalId, group) + val rumor = ConfederationStatements.rejection(group, proposal, reason, createdAt) + return proposeStatement(database, localChatRoom, userPublicKey, rumor, proposal.othersThan(group), invitation) } /** Proposes that this group, which made [proposalId], take it back. */ @@ -341,104 +353,121 @@ object ConfederationManager { reason: String = "", createdAt: Long = Clock.System.now().epochSeconds, ): FrostSigningSession { - val (event, proposal) = heldProposal(database, proposalId) - val template = EventTemplate( - createdAt, ConfederationKinds.WITHDRAWAL, - ConfederationProposalWithdrawalEvent.assembleTags(proposal.id, proposal.relayHintFor(proposal.proposingGroup), proposal.groupPublicKeys), - reason, - ) - return proposeAnswer(database, localChatRoom, userPublicKey, template, ConfederationRefusal.Carried(null, event.toJson())) + val group = localChatRoom.chatRoom.id + val (proposal, invitation) = heldProposal(database, proposalId, group) + val rumor = ConfederationStatements.withdrawal(group, proposal, reason, createdAt) + return proposeStatement(database, localChatRoom, userPublicKey, rumor, proposal.othersThan(group), invitation) } - private suspend fun proposeAnswer( + private const val CANNOT_TAKE_PART = + "This group cannot take part as it stands: it needs at least as many admins as its threshold, and a threshold of two or more" + + /** + * Proposes that the group of [localChatRoom] sign [rumor], sealed once to each of [recipients] + * 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( database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, - template: EventTemplate, - carried: ConfederationRefusal.Carried, + rumor: Event, + recipients: List, + invitation: String?, ): FrostSigningSession { + val group = localChatRoom.chatRoom.id + val key = announcedInboxKey(database, group, userPublicKey) + ?: throw IllegalStateException("Set up the group's inbox first: its statements are sent from it") + val resolved = recipients.sorted().map { recipient -> + InboxReplies.recipientOf(database, recipient).takeIf { it.announcement != null } + ?: throw IllegalStateException(inboxProblem(database, recipient) ?: "A group has announced no inbox") + } + val secret = key.secretKey!!.hexToByteArray() + val built = InboxReplies.sealRumor(group, rumor, resolved, secret, key.generation) + return proposeSealed(database, localChatRoom, userPublicKey, rumor, built, secret, invitation) + } + + /** + * Proposes [built], the seals of [rumor], for the group's quorum to sign, with the manifest + * sealed from [inboxSecret] and the statement and [invitation] beside them. Separate from + * [proposeStatement] so a test can hand in seals with one thing wrong with them. + */ + internal suspend fun proposeSealed( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + rumor: Event, + built: InboxReplies.Built, + inboxSecret: ByteArray, + invitation: String?, + ): 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 + + 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" + } + val session = FrostSigningManager.proposeSigningBatch( database = database, localChatRoom = localChatRoom, userPublicKey = userPublicKey, - events = listOf(template), - proposalTags = carried.toTags(), + events = built.seals, + proposalTags = arrayOf(InboxReplyManifest.tag(sealed)) + carried.toTags(), ) ConfederationRefusal.remember(database, session.id, carried, null) + InboxRefusal.remember(database, session.id, group, refusal = null, manifest = sealed) + logger.i("Proposed a confederation statement of kind ${rumor.kind} to ${built.seals.size - 1} group(s) as session ${session.id.take(8)}") return session } - private suspend fun heldProposal(database: GizaDatabase, proposalId: HexKey): Pair { - val event = database.confederationDao().getEvent(proposalId) - ?.takeIf { it.kind == ConfederationKinds.PROPOSAL }?.toEvent() + /** + * The proposal [proposalId] and the seal that carried it to [group], from this device's store. + * The seal is null for a proposal this group made: its own signing session vouches for it. + */ + private suspend fun heldProposal(database: GizaDatabase, proposalId: HexKey, group: HexKey): Pair { + val row = database.confederationDao().getEvent(proposalId)?.takeIf { it.kind == ConfederationKinds.PROPOSAL } ?: throw IllegalStateException("This device does not hold that proposal") - val proposal = ConfederationProposalEvent.parse(event) + val proposal = ConfederationStatements.parseProposal(row.toEvent()) ?: throw IllegalStateException("That proposal is not well formed") - return event to proposal - } - - private fun acceptanceTemplate( - disclosure: Disclosure, - proposalId: HexKey, - relayHint: String?, - proposingGroup: HexKey, - coordinator: HexKey, - secret: ByteArray, - createdAt: Long, - ): EventTemplate { - val adminList = disclosure.listFor(proposalId) - ?: throw IllegalStateException("This group cannot take part as it stands: it needs at least as many admins as its threshold, and a threshold of two or more") - val sealed = ConfederationSeal.seal(secret, coordinator, adminList) - return EventTemplate( - createdAt, ConfederationKinds.ACCEPTANCE, - ConfederationProposalAcceptanceEvent.assembleTags(proposalId, relayHint, proposingGroup, coordinator, sealed.ephemeralPublicKey), - sealed.content, - ) + check(proposal.lists(group)) { "That proposal does not name this group" } + return proposal to row.sealJson } /** - * What the coordinator's device can say once every group has accepted (docs/confederation.md, - * Phase 8): each group's admins and threshold, opened from its acceptance with the - * coordinator's own key, and what stands between them and a key ceremony. + * What every admin's device can say once every group has accepted + * (docs/confederation-without-coordinator.md, D7): each group's admins and threshold, read from + * its statement, and what stands between them and a key ceremony. * * Stores nothing: every input is already on file, so it is read again each time. */ data class Outcome( val status: ConfederationStatus, - /** Each group's opened admin list, or null where its acceptance does not open to a list for it. */ - val adminLists: Map, + val adminLists: Map, /** Every admin across every group, counted once per group they sit in: upstream's roles. */ val roleCount: Int, /** Admins who sit in more than one of the groups, with those groups. Allowed; each needs a host key per group. */ val overlaps: Map>, /** What has to be put right before a ceremony could start. */ val problems: List, - /** What the coordinator should know but that stops nothing. */ + /** What a member should know but that stops nothing. */ val notes: List, ) { val ready: Boolean get() = status.state == ConfederationProposalState.ACCEPTED && problems.isEmpty() } - suspend fun outcome(database: GizaDatabase, proposalId: HexKey, coordinatorSecret: PrivateKey): Outcome? { + suspend fun outcome(database: GizaDatabase, proposalId: HexKey): Outcome? { val status = status(database, proposalId) ?: return null val proposal = status.proposal - if (coordinatorSecret.publicKey().xOnly().value.toHex() != proposal.coordinator) return null - - val secret = coordinatorSecret.value.toByteArray() - val adminLists = proposal.groupPublicKeys.associateWith { group -> - status.acceptances[group]?.let { acceptance -> - ConfederationSeal.open(ConfederationSeal.conversationKey(secret, acceptance.ephemeralPublicKey), acceptance.content) - ?.takeIf { it.proposalId == proposal.id && it.group == group } - } - } + val adminLists = status.adminLists val problems = mutableListOf() val notes = mutableListOf() if (status.state != ConfederationProposalState.ACCEPTED) problems += "Not every group has accepted" - adminLists.filter { (group, list) -> status.acceptances[group] != null && list == null }.keys.forEach { group -> - problems += "${nameOf(database, group)}'s acceptance does not open to its admins" - } - val roleCount = adminLists.values.filterNotNull().sumOf { it.admins.size } + val roleCount = adminLists.values.sumOf { it.admins.size } if (roleCount > ConfederationKinds.MAX_ROLES) { problems += "$roleCount admins in all, more than the ${ConfederationKinds.MAX_ROLES} one confederation can hold" } @@ -447,11 +476,11 @@ object ConfederationManager { } proposal.groupPublicKeys.forEach { group -> if (database.profileDao().getProfileByPublicKey(group)?.isResolved() != true) { - problems += "No public profile found for ${nameOf(database, group)} on this device" + notes += "No public profile found for ${nameOf(database, group)} on this device" } } val overlaps = adminLists.entries - .flatMap { (group, list) -> list?.admins.orEmpty().map { it to group } } + .flatMap { (group, list) -> list.admins.map { it to group } } .groupBy({ it.first }, { it.second }) .filterValues { it.size > 1 } overlaps.forEach { (admin, groups) -> 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 9dad53ee..9878b90a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationPublisher.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationPublisher.kt @@ -21,8 +21,10 @@ import mobi.giza.compose.nostr.Relays import mobi.giza.compose.repository.ConfederationRepository /** - * Sends the confederation events this device signed for to relays, and keeps trying until one - * takes each (docs/confederation.md, D9). + * Sends the charters this device's confederation signing proposed to relays, and keeps trying + * until one takes each (docs/confederation.md, Phase 15). A group's statements about a + * confederation are not sent here: they go to the other groups' inboxes, owed by the inbox's + * publisher (docs/confederation-without-coordinator.md, D12). * * Not through the `BroadcastNostrEventRequest` queue: that hangs off a `NostrEvent` row, and a * row for a group's event would put it in the home feed and make the group a `Profile` @@ -54,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 } + repository.relayHintsFor(event.proposalId)) + val targets = Relays.eventPublishRelaySet.map { it.url } .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 34491e82..177a5ed5 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRefusal.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRefusal.kt @@ -4,142 +4,159 @@ import co.touchlab.kermit.Logger import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.verify import kotlin.time.Clock import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.ConfederationSigning import mobi.giza.compose.nostr.confederation.ConfederationKinds -import mobi.giza.compose.nostr.confederation.ConfederationProposalAcceptanceEvent -import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent -import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent.Proposal -import mobi.giza.compose.nostr.confederation.ConfederationProposalRejectionEvent import mobi.giza.compose.nostr.confederation.ConfederationProposalState -import mobi.giza.compose.nostr.confederation.ConfederationProposalWithdrawalEvent -import mobi.giza.compose.nostr.confederation.ConfederationSeal -import mobi.giza.compose.nostr.confederation.tags.ConfederationCarriedProposalTag -import mobi.giza.compose.nostr.confederation.tags.ConfederationSealTag -import mobi.giza.compose.nostr.frost.GroupKeyStateEvent +import mobi.giza.compose.nostr.confederation.ConfederationStatements +import mobi.giza.compose.nostr.confederation.ConfederationStatements.Proposal +import mobi.giza.compose.nostr.inbox.InboxSeal /** * What a member's device refuses to sign for its group about a confederation, out loud - * (docs/confederation.md, D6). + * (docs/confederation.md, D6, and docs/confederation-without-coordinator.md, D6). * - * Giza has no allowlist: a kind nothing refuses reaches the approval prompt. So these kinds get - * their refusals beside `WalletRefusal`, `GroupStatementRefusal` and the governance check, run - * when a proposal arrives and again when the member approves -- a group's admins can change in - * between, and the seal has to hold the admins the group has when it signs. + * A group says something about a confederation by sealing a statement once to every group the + * proposal names, its own included, from its inbox key, and having its quorum sign the seals. The + * statement rides the signing proposal in the clear ([Carried.rumorJson]), so every member sees + * what the group is being asked to say; the manifest that says which seal is whose is the inbox's. * - * What is refused is what is wrong: a shape this device does not sign, a coordinator who is not - * the one proposing, an admin list that is not this group's. What a device merely cannot see -- - * a listed group's profile it cannot find right now -- is a warning on the approval screen, for - * the member to weigh. + * A signer reads what it signs. It declines unless it holds the group's inbox key, every seal holds + * the carried statement byte for byte, each to the inbox key the group it names announced, and the + * statement is one this group can make: its own admins, a proposal this device can read, a group + * that has not answered yet. Giza no longer signs a confederation's statement as a public event, + * so a batch holding one is declined too. + * + * What a device merely cannot see -- a listed group's profile it cannot find right now -- is a + * warning on the approval screen, for the member to weigh. */ object ConfederationRefusal { private val logger = Logger.withTag("ConfederationRefusal") - const val SHAPE = "Declined a confederation event in a form this device does not sign" + const val SHAPE = "Declined a confederation statement in a form this device does not sign" + const val PUBLIC = "Declined: Giza says what it says about a confederation to the groups, not to relays" + const val CANNOT_READ = "Declined: this device can't read what the group would be sending" + const val SEALS = "Declined: the sealed copies don't all hold the statement, to the groups it names" + const val NO_INBOX = "Declined: a group the proposal names has announced no inbox to send to" + const val TIME = "Declined: the statement is not dated now" const val NOT_LISTED = "Declined: the proposal does not name this group" - const val COORDINATOR = "Declined: the coordinator must be the member who proposed it" - const val COORDINATOR_NOT_ADMIN = "Declined: the coordinator is not one of this group's admins" const val EXPIRY = "Declined: the proposal has expired, or stays open longer than 30 days" + const val TOO_MANY = "Declined: more groups than one confederation's statements can carry" const val UNKNOWN_PROPOSAL = "Declined: this device has not seen the proposal being answered" const val CLOSED = "Declined: the proposal is no longer open" const val ANSWERED = "Declined: this group has already answered the proposal" const val NO_ADMINS = "Declined: this device cannot read the group's admins to check them" - const val SEAL = "Declined: the sealed admin list is not this group's admins" + const val ADMINS = "Declined: the admin list is not this group's admins" const val NOT_PROPOSER = "Declined: only the group that proposed it can withdraw it" + const val RUMOR_TAG = "confederation_rumor" + const val INVITATION_TAG = "confederation_invitation" + /** Leeway on the 30-day ceiling, for a proposer whose clock runs ahead of this one's. */ private const val CLOCK_SLACK_SECONDS = 60L * 60 - /** What the FROST proposal carries beside the events: the seal's secret, and the proposal answered. */ - data class Carried(val sealSecret: String?, val proposalJson: String?) { + /** How far a statement's own date may be from this device's clock. */ + private const val STATEMENT_SLACK_SECONDS = 10L * 60 + + /** + * What the signing proposal carries beside the seals: the statement, and for an answer the + * signed seal that brought the proposal to this group. + */ + data class Carried(val rumorJson: String?, val invitationJson: String?) { fun toTags(): Array> = listOfNotNull( - sealSecret?.let(ConfederationSealTag::assemble), - proposalJson?.let(ConfederationCarriedProposalTag::assemble), + rumorJson?.let { arrayOf(RUMOR_TAG, it) }, + invitationJson?.let { arrayOf(INVITATION_TAG, it) }, ).toTypedArray() - companion object { - fun from(tags: Array>) = Carried( - sealSecret = ConfederationSealTag.valueIn(tags), - proposalJson = ConfederationCarriedProposalTag.valueIn(tags), - ) + val rumor: Event? get() = rumorJson?.let { Event.fromJsonOrNull(it) } - fun from(signing: ConfederationSigning?) = Carried(signing?.sealSecret, signing?.proposalJson) + companion object { + private fun single(tags: Array>, name: String): String? = + tags.filter { it.size >= 2 && it[0] == name }.singleOrNull()?.get(1)?.ifBlank { null } + + fun from(tags: Array>) = Carried(single(tags, RUMOR_TAG), single(tags, INVITATION_TAG)) + + fun from(signing: ConfederationSigning?) = Carried(signing?.rumorJson, signing?.invitationJson) } } - fun involves(events: List): Boolean = events.any { ConfederationKinds.isConfederationKind(it.kind) } + /** 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) } /** - * Why this device declines to sign [events] for the room [chatRoomId], or null if it may be - * put to its member. [proposer] is the member who opened the signing session. + * Why this device, as [userPublicKey], declines to sign [events] for the room [chatRoomId], or + * null if it may be put to its member. [manifest] is the inbox manifest the proposal carried. */ suspend fun of( database: GizaDatabase, chatRoomId: String, - proposer: HexKey, + userPublicKey: HexKey, events: List, carried: Carried, + manifest: String?, now: Long = Clock.System.now().epochSeconds, ): String? { - if (!involves(events)) return null - if (!events.all { ConfederationKinds.isConfederationKind(it.kind) }) return SHAPE + 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 (!rumor.pubKey.equals(chatRoomId, ignoreCase = true)) return NOT_LISTED - val kinds = events.map { it.kind } - return when (kinds) { - listOf(ConfederationKinds.PROPOSAL, ConfederationKinds.ACCEPTANCE) -> { - val proposal = ConfederationProposalEvent.parse(events[0]) ?: return SHAPE - proposalRefusal(database, chatRoomId, proposer, proposal, now) - ?: acceptanceRefusal(database, chatRoomId, proposal, events[1], carried) + val read = when (val result = InboxRefusal.readSealed(database, chatRoomId, userPublicKey, events, manifest, ConfederationStatements::isStatementKind)) { + is InboxRefusal.Read.Refused -> return if (result.reason == InboxRefusal.REPLY_NO_KEY) CANNOT_READ else SEALS + is InboxRefusal.Read.Ok -> result.reply + } + if (read.rumor.id != rumor.id) return SEALS + // 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 + + return when (rumor.kind) { + ConfederationKinds.PROPOSAL -> { + val proposal = ConfederationStatements.parseProposal(rumor) ?: return SHAPE + proposalRefusal(database, chatRoomId, proposal, now) } - - listOf(ConfederationKinds.ACCEPTANCE) -> { - val proposal = answered(database, carried) ?: return UNKNOWN_PROPOSAL - answerRefusal(database, chatRoomId, proposal, now) - ?: acceptanceRefusal(database, chatRoomId, proposal, events[0], carried) + else -> { + val answer = ConfederationStatements.parseAnswer(rumor) ?: return SHAPE + val proposal = proposalFor(database, chatRoomId, userPublicKey, answer.proposalId, carried) ?: return UNKNOWN_PROPOSAL + if (!answer.answers(proposal)) return SHAPE + when (rumor.kind) { + ConfederationKinds.WITHDRAWAL -> { + if (proposal.proposingGroup != chatRoomId) return NOT_PROPOSER + val state = ConfederationManager.status(database, proposal.id, now)?.state + if (state != null && state != ConfederationProposalState.OPEN) return CLOSED + null + } + else -> answerRefusal(database, chatRoomId, proposal, now) ?: if (answer.isAcceptance) { + val expected = ConfederationManager.adminListFor(database, chatRoomId, proposal.id) ?: return NO_ADMINS + if (expected.encode() != rumor.content) ADMINS.also { logger.w("Acceptance ${rumor.id.take(8)} does not list the ${expected.admins.size} admins this device sees") } else null + } else { + null + } + } } - - listOf(ConfederationKinds.REJECTION) -> { - val proposal = answered(database, carried) ?: return UNKNOWN_PROPOSAL - val rejection = ConfederationProposalRejectionEvent.parse(events[0]) ?: return SHAPE - if (rejection.proposalId != proposal.id) return SHAPE - answerRefusal(database, chatRoomId, proposal, now) - } - - listOf(ConfederationKinds.WITHDRAWAL) -> { - val proposal = answered(database, carried) ?: return UNKNOWN_PROPOSAL - val withdrawal = ConfederationProposalWithdrawalEvent.parse(events[0]) ?: return SHAPE - if (withdrawal.proposalId != proposal.id) return SHAPE - if (proposal.proposingGroup != chatRoomId) return NOT_PROPOSER - val state = ConfederationManager.status(database, proposal.id, now)?.state - if (state != null && state != ConfederationProposalState.OPEN) return CLOSED - null - } - - else -> SHAPE } } - /** The rules for a proposal this group makes (D3, D4, D6). */ - private suspend fun proposalRefusal( - database: GizaDatabase, - chatRoomId: String, - proposer: HexKey, - proposal: Proposal, - now: Long, - ): String? { - if (proposal.proposingGroup != chatRoomId || !proposal.lists(chatRoomId)) return NOT_LISTED - if (proposal.coordinator != proposer) return COORDINATOR - val admins = RoomAdmins.of(database, chatRoomId)?.admins ?: return NO_ADMINS - if (proposal.coordinator !in admins) return COORDINATOR_NOT_ADMIN + /** The rules for a proposal this group makes (D6, step 4). */ + private suspend fun proposalRefusal(database: GizaDatabase, chatRoomId: String, proposal: Proposal, now: Long): String? { + if (proposal.proposingGroup != chatRoomId) return NOT_LISTED + if (proposal.groups.size > ConfederationKinds.MAX_SUPERGROUP_GROUPS) return TOO_MANY if (proposal.expiresAt <= now) return EXPIRY if (proposal.expiresAt > now + ConfederationKinds.MAX_EXPIRY_SECONDS + CLOCK_SLACK_SECONDS) return EXPIRY + val expected = ConfederationManager.adminListFor(database, chatRoomId, null) ?: return NO_ADMINS + val carried = proposal.proposerAdmins + if (expected.group != carried.group || expected.threshold != carried.threshold || expected.admins != carried.admins) return ADMINS return null } /** The rules for any answer this group gives to someone's proposal. */ private suspend fun answerRefusal(database: GizaDatabase, chatRoomId: String, proposal: Proposal, now: Long): String? { if (!proposal.lists(chatRoomId)) return NOT_LISTED + if (proposal.proposingGroup == chatRoomId) return ANSWERED if (proposal.isExpiredAt(now)) return EXPIRY val status = ConfederationManager.status(database, proposal.id, now) if (status != null) { @@ -149,84 +166,61 @@ object ConfederationRefusal { return null } - /** The seal: the acceptance has to hold, byte for byte, the admins this device sees (D5). */ - private suspend fun acceptanceRefusal( - database: GizaDatabase, - chatRoomId: String, - proposal: Proposal, - event: Event, - carried: Carried, - ): String? { - val acceptance = ConfederationProposalAcceptanceEvent.parse(event) ?: return SHAPE - if (acceptance.group != chatRoomId) return NOT_LISTED - if (!ConfederationProposalAcceptanceEvent.answers(acceptance, proposal)) return SHAPE - val secret = carried.sealSecret?.takeIf(ConfederationKinds::isHex32) ?: return SEAL - val expected = ConfederationManager.adminListFor(database, chatRoomId, proposal.id) ?: return NO_ADMINS - val reproduces = ConfederationSeal.reproduces( - ephemeralSecret = secret.hexToByteArray(), - coordinator = proposal.coordinator, - expected = expected, - content = acceptance.content, - ephemeralPublicKey = acceptance.ephemeralPublicKey, - ) - if (!reproduces) { - logger.w("Acceptance ${event.id.take(8)} does not seal the ${expected.admins.size} admins this device sees") - return SEAL - } - return null - } - /** - * The proposal an answer answers: carried on the signing proposal and verified as its - * author's, or already on file. A carried copy that verifies is filed, as a relay's would be. + * The proposal 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 answered(database: GizaDatabase, carried: Carried): Proposal? { - val carriedEvent = carried.proposalJson?.let { Event.fromJsonOrNull(it) } - if (carriedEvent != null && GroupKeyStateEvent.isSignedByRoom(carriedEvent, carriedEvent.pubKey)) { - ConfederationManager.record(database, carriedEvent) - return ConfederationProposalEvent.parse(carriedEvent) - } - return null + private suspend fun proposalFor(database: GizaDatabase, roomId: HexKey, userPublicKey: HexKey, proposalId: HexKey, carried: Carried): Proposal? { + ConfederationManager.proposal(database, proposalId)?.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 proposal = ConfederationStatements.parseProposal(opened.rumor)?.takeIf { it.id == proposalId && it.lists(roomId) } ?: return null + ConfederationManager.recordStatement(database, opened.rumor, seal, roomId) + return proposal } /** - * What a member should read before approving a session over a confederation event, beside - * its summary (D6): who it names, what an acceptance discloses, and -- as warnings rather - * than refusals -- each listed group whose public profile this device cannot find. + * What a member should read before approving a session over a statement, beside its summary: + * who it names, what an acceptance shows and to whom, and -- as warnings rather than refusals + * -- each listed group whose public profile this device cannot find. */ suspend fun notes(database: GizaDatabase, chatRoomId: String, sessionId: String, events: List): List { - if (!involves(events)) return emptyList() val carried = Carried.from(database.confederationDao().getSigning(sessionId)) - val proposal = events.firstOrNull { it.kind == ConfederationKinds.PROPOSAL }?.let(ConfederationProposalEvent::parse) - ?: carried.proposalJson?.let { Event.fromJsonOrNull(it) }?.let(ConfederationProposalEvent::parse) + if (!involves(events, carried)) return emptyList() + val rumor = carried.rumor ?: return emptyList() + val proposal = ConfederationStatements.parseProposal(rumor) + ?: ConfederationStatements.parseAnswer(rumor)?.let { ConfederationManager.proposal(database, it.proposalId) } ?: return emptyList() val names = proposal.groupPublicKeys.map { ConfederationManager.nameOf(database, it, chatRoomId) } val notes = mutableListOf( "Groups: ${names.joinToString()}", "${proposal.threshold} of ${proposal.groups.size} groups must take part to sign", - "Coordinated by ${ConfederationManager.nameOf(database, proposal.coordinator)}", ) - if (events.any { it.kind == ConfederationKinds.ACCEPTANCE }) { - ConfederationManager.adminListFor(database, chatRoomId, proposal.id)?.let { list -> - notes += "Discloses this group's ${list.admins.size} admins and its threshold of ${list.threshold} " + - "to the coordinator, sealed so that only they can read them" + if (rumor.kind == ConfederationKinds.PROPOSAL || rumor.kind == ConfederationKinds.ACCEPTANCE) { + ConfederationManager.adminListFor(database, chatRoomId, null)?.let { list -> + val others = proposal.othersThan(chatRoomId).map { ConfederationManager.nameOf(database, it) } + notes += "Shows this group's ${list.admins.size} admins and its threshold of ${list.threshold} " + + "to the admins of ${others.joinToString()}" } } proposal.groupPublicKeys.filter { it != chatRoomId }.forEach { group -> val found = database.profileDao().getProfileByPublicKey(group)?.isResolved() == true if (!found) notes += "No public profile found for ${ConfederationManager.nameOf(database, group)} on this device yet" } + if (proposal.expiresAt - Clock.System.now().epochSeconds < 24 * 60 * 60) notes += "The proposal expires within a day" return notes } - /** Keeps what a session over a confederation event must remember past its proposal (Phase 4's table). */ + /** Keeps what a session over a statement must remember past its proposal. */ suspend fun remember(database: GizaDatabase, sessionId: String, carried: Carried, refusal: String?) { database.confederationDao().upsertSigning( ConfederationSigning( sessionId = sessionId, - sealSecret = carried.sealSecret, - proposalJson = carried.proposalJson, + rumorJson = carried.rumorJson, + invitationJson = carried.invitationJson, refusal = refusal, ) ) @@ -236,6 +230,10 @@ object ConfederationRefusal { suspend fun reasonFor(database: GizaDatabase, sessionId: String): String? = database.confederationDao().getSigning(sessionId)?.refusal + /** Whether [sessionId] is a session over a confederation statement. */ + suspend fun isStatementSession(database: GizaDatabase, sessionId: String): Boolean = + database.confederationDao().getSigning(sessionId)?.rumorJson != null + /** The tags a resent proposal has to carry again, so a member who missed it can check it. */ suspend fun carriedTagsFor(database: GizaDatabase, sessionId: String): Array> = database.confederationDao().getSigning(sessionId)?.let { Carried.from(it).toTags() } ?: emptyArray() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt index acaf91a0..a40a6014 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt @@ -10,14 +10,12 @@ import fr.acinq.bitcoin.ByteVector import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.ByteVector64 import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.PrivateKey import fr.acinq.bitcoin.PublicKey import fr.acinq.bitcoin.crypto.confederation.ConfederationBroadcast import fr.acinq.bitcoin.crypto.confederation.ConfederationCiphertexts import fr.acinq.bitcoin.crypto.confederation.ConfederationDealerRecord import fr.acinq.bitcoin.crypto.confederation.ConfederationDkg import fr.acinq.bitcoin.crypto.confederation.ConfederationDkgDealing -import fr.acinq.bitcoin.crypto.confederation.ConfederationEvidenceList import fr.acinq.bitcoin.crypto.confederation.ConfederationFault import fr.acinq.bitcoin.crypto.confederation.ConfederationKeyState import fr.acinq.bitcoin.crypto.confederation.ConfederationRoleId @@ -38,34 +36,36 @@ 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.ConfederationAdminList -import mobi.giza.compose.nostr.confederation.ConfederationProposalAcceptanceEvent -import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent +import mobi.giza.compose.nostr.confederation.ConfederationAttestation import mobi.giza.compose.nostr.confederation.ConfederationProposalState import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents -import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents.Opening +import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents.Basis import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder.Plan -import mobi.giza.compose.nostr.confederation.ConfederationSeal +import mobi.giza.compose.nostr.confederation.ConfederationStatements import mobi.giza.compose.nostr.confederation.ConfederationStatus -import mobi.giza.compose.nostr.frost.GroupKeyStateEvent /** * Runs a confederation's key ceremony across devices, one person per device (docs/confederation.md, - * Phase 11), over upstream's `ConfederationDkg`. + * Phase 11), over upstream's `ConfederationDkg`, with nobody coordinating it + * (docs/confederation-without-coordinator.md, D8 to D10). * * The shape is `ChillDkgRitualManager`'s and for its reasons. The ceremony runs in a NIP-17 room - * over every admin of every group, on gift-wrapped rumors. Every step is a pure function of what + * over every admin of every group, on gift-wrapped rumors, and every step is a pure function of what * this device has stored, so [advance] decides what to do next from which messages exist, never * from the stage, and a device that dies between rounds picks up on the next message or the next * [resumeRunning]. Joining is the only thing a member is asked; the rounds after it run by * themselves (docs/automatic-key-ceremony.md). * - * What is new is what a participant checks before it will join at all. The coordinator could - * otherwise put a role of its own choosing into another group's segment, so every device rebuilds - * the roster from what the groups signed, opened with the keys the coordinator discloses (D7), and - * checks its own groups' segments against the admins it sees in them now. The coordinator's copy - * of the roster then has to match byte for byte, and every key state is derived by each role - * itself, never accepted from the coordinator. + * What a coordinator did is done on every device: + * + * - **The opening** is the basis each device builds from the statements its groups' inboxes opened. + * The ceremony's id, its room and its roster follow from it, the same on every device holding + * the same statements. A device that holds different ones builds a different attestation, which + * every 30381 carries, and the ceremony ends naming the group whose statement differs (D3). + * - **The session seed** is derived from every person's contribution in their 30381 (D9). + * - **The broadcast** is computed by every device from the dealings it holds; it takes no secret. + * Each 30384 carries its hash, so two devices that were dealt different things find out by name. * * WARNING: upstream's confederation module is experimental and unaudited. This runs behind * `ExperimentalFeatures.confederation`, off in release. @@ -75,238 +75,36 @@ object ConfederationRitualManager { const val ABANDONED = "Abandoned by a participant" - // ---- opening, on the coordinator's device --------------------------------------------- + // ---- what a ceremony is built from ------------------------------------------------------ /** - * Opens the key ceremony for [proposalId] once every group has accepted it: decrypts the - * acceptances with the coordinator's own key, checks the roster can be built, makes the room - * and sends the opening. Opening is the coordinator's own join. Returns the ceremony already - * running for this proposal, if there is one. + * The basis for [proposalId] from what this device holds: the proposal and every other group's + * acceptance, once every group has accepted. Left, with a reason, before that. */ - suspend fun open(database: GizaDatabase, proposalId: HexKey, coordinatorSecret: PrivateKey): ConfederationCeremony { - val coordinator = coordinatorSecret.publicKey().xOnly().value.toHex() - database.confederationCeremonyDao().getLatestForProposal(proposalId) - ?.takeIf { it.isRunning || it.stage == ConfederationCeremonyStage.COMPLETE } - ?.let { return it } - - val outcome = ConfederationManager.outcome(database, proposalId, coordinatorSecret) - ?: throw IllegalStateException("Only the coordinator can open the key ceremony") - check(outcome.ready) { outcome.problems.joinToString("; ").ifBlank { "The proposal is not ready to form" } } - - val status = outcome.status - val proposalEvent = database.confederationDao().getEvent(proposalId)!!.toEvent() - val acceptanceEvents = status.proposal.groupPublicKeys.map { group -> - database.confederationDao().getEvent(status.acceptances.getValue(group).id)!!.toEvent() - } - val keys = status.acceptances.values.associate { acceptance -> - acceptance.id to ConfederationSeal.conversationKey(coordinatorSecret.value.toByteArray(), acceptance.ephemeralPublicKey).toHex() - } - val opening = Opening( - proposalJson = proposalEvent.toJson(), - acceptanceJsons = acceptanceEvents.map { it.toJson() }, - conversationKeys = keys, - sessionSeed = RandomInstance.bytes(32).toHex(), - ) - val plan = planFrom(opening).let { - when (it) { - is Either.Right -> it.value - is Either.Left -> throw IllegalStateException(it.value) - } - } - - ensureProfiles(database, plan.people) - val room = database.nostrNip17Dao().createNip17ChatRoom( - userPublicKey = coordinator, - participantPublicKeys = plan.people, - subject = status.proposal.name, - ) ?: throw IllegalStateException("Could not make the ceremony's room") - - val ceremony = newCeremony( - sessionId = RandomInstance.bytes(32).toHex(), - chatRoomId = room.chatRoom.id, - proposalId = proposalId, - coordinator = coordinator, - user = coordinator, - opening = opening, - plan = plan, - ).copy(approvedAt = Clock.System.now()) - database.confederationCeremonyDao().upsert(ceremony) - announce(database, ceremony, ChatMessage.TYPE_CONFEDERATION_CEREMONY_STARTED, "The confederation's key ceremony started") - - broadcast(database, room, ceremony, plan, ConfederationRitualEvents.OPENING, opening.encode(), proposalTag = true) - advance(database, room, ceremony.id, coordinatorSecret.value.toByteArray()) - return database.confederationCeremonyDao().getCeremony(ceremony.id)!! - } - - // ---- inbound --------------------------------------------------------------------------- - - /** - * Feeds one inbound ceremony message in and moves the ceremony as far as it will go. Safe to - * call twice with the same message. - */ - suspend fun process( - database: GizaDatabase, - localChatRoom: LocalChatRoom, - innerEvent: Event, - userPublicKey: HexKey, - nostrPrivateKey: ByteArray, - ) { - val sessionId = ConfederationRitualEvents.parseSessionId(innerEvent.tags) ?: run { - logger.w("Ceremony message ${innerEvent.id.take(8)} names no session; dropping") - return - } - val ceremony = if (innerEvent.kind == ConfederationRitualEvents.OPENING) { - acceptOpening(database, localChatRoom, innerEvent, sessionId, userPublicKey) - } else { - // A message routinely arrives before the opening it belongs to. The gift wrap is - // stored by the inbound path, and the opening replays it. - database.confederationCeremonyDao().getCeremony(sessionId) - } ?: return - if (!ceremony.isRunning) return - - if (!record(database, ceremony, innerEvent)) return - advance(database, localChatRoom, ceremony.id, nostrPrivateKey) - } - - /** - * Files the coordinator's opening, after every check a participant makes before it would join - * (docs/confederation.md, Phase 11). A device whose owner is not in the roster drops it. One - * that finds the opening wrong files the ceremony as failed and says why to everybody, so - * nobody joins a ceremony one of them has found a fault in. - */ - private suspend fun acceptOpening( - database: GizaDatabase, - localChatRoom: LocalChatRoom, - innerEvent: Event, - sessionId: String, - userPublicKey: HexKey, - ): ConfederationCeremony? { - database.confederationCeremonyDao().getCeremony(sessionId)?.let { return it } - - val opening = Opening.decode(innerEvent.content) ?: run { - logger.w("Ceremony $sessionId: an opening that does not decode; dropping") - return null - } - val proposal = Event.fromJsonOrNull(opening.proposalJson)?.let(ConfederationProposalEvent::parse) ?: run { - logger.w("Ceremony $sessionId: an opening without a readable proposal; dropping") - return null - } - val planOrReason = eligibility(database, opening, innerEvent.pubKey, localChatRoom) - val plan = (planOrReason as? Either.Right)?.value - if (plan != null && userPublicKey !in plan.people) { - logger.i("Ceremony $sessionId does not include this device's owner; dropping") - return null - } - - val ceremony = newCeremony( - sessionId = sessionId, - chatRoomId = localChatRoom.chatRoom.id, - proposalId = proposal.id, - coordinator = innerEvent.pubKey, - user = userPublicKey, - opening = opening, - plan = plan, - ) - database.confederationCeremonyDao().upsert(ceremony) - - when (planOrReason) { - is Either.Left -> { - logger.w("Ceremony $sessionId refused: ${planOrReason.value}") - failOut(database, localChatRoom, ceremony, planOrReason.value, culprit = innerEvent.pubKey) - return null - } - is Either.Right -> { - announce( - database, ceremony, ChatMessage.TYPE_CONFEDERATION_CEREMONY_STARTED, - "The confederation's key ceremony started. Join it to hold a share of its key", - ) - replayStoredMessages(database, ceremony) - return database.confederationCeremonyDao().getCeremony(sessionId) - } - } - } - - /** - * Everything a participant checks before it would join, as a reason or the roster's plan: - * - * - the proposal and every acceptance are what their groups signed, and the proposal is - * accepted by every group it names, in time, with nothing on this device rejecting it; - * - the sender is the proposal's coordinator; - * - every acceptance opens with the key disclosed for it, to that group's answer (D7); - * - the roster can be planned from them; - * - the room is exactly the people the roster names; - * - each group this device is in still has the admins and threshold it accepted with. - */ - internal suspend fun eligibility( - database: GizaDatabase, - opening: Opening, - sender: HexKey, - localChatRoom: LocalChatRoom, - ): Either { - val proposalEvent = Event.fromJsonOrNull(opening.proposalJson) - ?.takeIf { GroupKeyStateEvent.isSignedByRoom(it, it.pubKey) } - ?: return Either.Left("The proposal in the opening is not one its group signed") - val proposal = ConfederationProposalEvent.parse(proposalEvent) - ?: return Either.Left("The proposal in the opening cannot be read") - if (sender != proposal.coordinator) return Either.Left("The ceremony was opened by someone other than the proposal's coordinator") - - val acceptanceEvents = opening.acceptanceJsons.mapNotNull { json -> - Event.fromJsonOrNull(json)?.takeIf { GroupKeyStateEvent.isSignedByRoom(it, it.pubKey) } - } - if (acceptanceEvents.size != opening.acceptanceJsons.size) return Either.Left("An acceptance in the opening is not one its group signed") - - val status = ConfederationStatus.of(proposal, acceptanceEvents, Clock.System.now().epochSeconds) + suspend fun basisFor(database: GizaDatabase, proposalId: HexKey): Either { + val status = ConfederationManager.status(database, proposalId) + ?: return Either.Left("This device does not hold the proposal") if (status.state != ConfederationProposalState.ACCEPTED) return Either.Left("Not every group has accepted the proposal") - val heldHere = ConfederationManager.status(database, proposal.id)?.state - if (heldHere == ConfederationProposalState.REJECTED || heldHere == ConfederationProposalState.WITHDRAWN) { - return Either.Left("This device holds a rejection or a withdrawal of the proposal") + val proposalRow = database.confederationDao().getEvent(proposalId) ?: return Either.Left("This device does not hold the proposal") + val acceptances = status.proposal.othersThan(status.proposal.proposingGroup).sorted().map { group -> + val answer = status.acceptances[group] ?: return Either.Left("No acceptance from ${ConfederationManager.nameOf(database, group)}") + database.confederationDao().getEvent(answer.id)?.eventJson ?: return Either.Left("No acceptance from ${ConfederationManager.nameOf(database, group)}") } - // Filed as a relay's copies would be: they are the groups' own signed statements. - ConfederationManager.record(database, proposalEvent) - acceptanceEvents.forEach { ConfederationManager.record(database, it) } - - val plan = when (val planned = planFrom(opening)) { - is Either.Left -> return Either.Left(planned.value) - is Either.Right -> planned.value - } - - val room = localChatRoom.localParticipants.map { it.participant.participantPublicKey }.toSet() + - localChatRoom.chatRoom.userPublicKey - if (room != plan.people.toSet()) return Either.Left("The ceremony's room is not exactly the confederation's admins") - - // The admins on their own, so a member who holds no share -- and so cannot read the - // threshold the group signs with -- still checks who its group put forward. The - // threshold is compared wherever this device can read it. - plan.groups.forEach { group -> - if (database.chatRoomDao().findChatRoomById(group) == null) return@forEach - val sealed = plan.adminLists.getValue(group) - val admins = RoomAdmins.of(database, group)?.admins ?: return@forEach - val threshold = FrostSigningManager.completedKey(database, group)?.threshold - if (admins.map { it.lowercase() }.sorted() != sealed.admins || (threshold != null && threshold != sealed.threshold)) { - return Either.Left("The admins of ${ConfederationManager.nameOf(database, group)} have changed since it accepted") - } - } - return Either.Right(plan) + return Either.Right(Basis(proposalRow.eventJson, acceptances)) } - /** The roster's plan from an opening alone: each acceptance opened with the key disclosed for it. */ - internal fun planFrom(opening: Opening): Either { - val proposal = Event.fromJsonOrNull(opening.proposalJson)?.let(ConfederationProposalEvent::parse) - ?: return Either.Left("The proposal in the opening cannot be read") - val lists = mutableMapOf() - val ids = mutableMapOf() - opening.acceptanceJsons.forEach { json -> - val acceptance = Event.fromJsonOrNull(json)?.let(ConfederationProposalAcceptanceEvent::parse) - ?: return Either.Left("An acceptance in the opening cannot be read") - val key = opening.conversationKeys[acceptance.id] - ?: return Either.Left("No key was disclosed for one group's acceptance") - val list = runCatching { ConfederationSeal.open(key.hexBytes(), acceptance.content) }.getOrNull() - ?: return Either.Left("The key disclosed for one group's acceptance does not open it") - if (list.group != acceptance.group || list.proposalId != proposal.id) { - return Either.Left("One group's acceptance opens to another group's or another proposal's admins") - } - lists[acceptance.group] = list - ids[acceptance.group] = acceptance.id + /** The roster's plan from a basis alone: the proposal's own admins and each acceptance's. */ + fun planFrom(basis: Basis): Either { + val proposal = Event.fromJsonOrNull(basis.proposalJson)?.let(ConfederationStatements::parseProposal) + ?: return Either.Left("The proposal cannot be read") + val lists = mutableMapOf(proposal.proposingGroup to proposal.proposerAdmins) + val ids = mutableMapOf(proposal.proposingGroup to proposal.id) + basis.acceptanceJsons.forEach { json -> + val answer = Event.fromJsonOrNull(json)?.let(ConfederationStatements::parseAnswer) + ?.takeIf { it.isAcceptance && it.answers(proposal) } + ?: return Either.Left("An acceptance cannot be read, or does not answer the proposal") + lists[answer.group] = answer.admins!! + ids[answer.group] = answer.id } return when (val planned = ConfederationRosterBuilder.plan(proposal, lists, ids)) { is Either.Left -> Either.Left(planned.value.reason) @@ -314,23 +112,105 @@ object ConfederationRitualManager { } } - private fun newCeremony( - sessionId: String, - chatRoomId: String, - proposalId: HexKey, - coordinator: HexKey, - user: HexKey, - opening: Opening, - plan: Plan?, - ): ConfederationCeremony { - val groups = plan?.seatsOf(user)?.map { it.group }.orEmpty() + /** The plan [ceremony] runs over, or null if its basis no longer reads. */ + fun planOf(ceremony: ConfederationCeremony): Plan? = + Basis.decode(ceremony.basisJson)?.let { planFrom(it) as? Either.Right }?.value + + /** + * Everything a person checks before they would join, as a reason or the roster's plan: the + * basis plans, the statements are accepted in time and nothing this device holds rejects or + * withdraws them, [userPublicKey] holds a role, and each group this device is in still has the + * admins and threshold it accepted with. + */ + internal suspend fun eligibility(database: GizaDatabase, basis: Basis, userPublicKey: HexKey): Either { + val plan = when (val planned = planFrom(basis)) { + is Either.Left -> return Either.Left(planned.value) + is Either.Right -> planned.value + } + if (userPublicKey !in plan.people) return Either.Left("This device's owner holds no role in the confederation") + val held = ConfederationManager.status(database, plan.proposal.id)?.state + if (held != ConfederationProposalState.ACCEPTED) return Either.Left("Not every group has accepted the proposal") + + // The admins on their own, so a member who holds no share -- and so cannot read the + // threshold the group signs with -- still checks who its group put forward. The + // threshold is compared wherever this device can read it. + plan.groups.forEach { group -> + if (database.chatRoomDao().findChatRoomById(group) == null) return@forEach + val listed = plan.adminLists.getValue(group) + val admins = RoomAdmins.of(database, group)?.admins ?: return@forEach + val threshold = FrostSigningManager.completedKey(database, group)?.threshold + if (admins.map { it.lowercase() }.sorted() != listed.admins || (threshold != null && threshold != listed.threshold)) { + return Either.Left("The admins of ${ConfederationManager.nameOf(database, group)} have changed since it accepted") + } + } + return Either.Right(plan) + } + + // ---- joining, and trying again ---------------------------------------------------------- + + /** Whether this ceremony is waiting on its member to join. */ + fun isAwaitingJoin(ceremony: ConfederationCeremony): Boolean = ceremony.isRunning && ceremony.approvedAt == null + + /** + * Joins the key ceremony for [proposalId] as [userPublicKey]: the one thing a member is asked, + * offered to every admin of every group once every group has accepted (D7). Makes the ceremony + * and its room here, sends this person's 30381, and replays what others sent first. + * + * After a failed or abandoned attempt it joins the next one: that is **Try again** (D10). A + * running or finished ceremony is returned as it is. Throws, with a reason a person can read, + * when this device cannot take part. + */ + suspend fun join(database: GizaDatabase, proposalId: HexKey, userPublicKey: HexKey, nostrPrivateKey: ByteArray): ConfederationCeremony { + val latest = database.confederationCeremonyDao().getLatestForProposal(proposalId)?.takeIf { it.userPublicKey == userPublicKey } + if (latest != null && latest.stage == ConfederationCeremonyStage.COMPLETE) return latest + if (latest != null && latest.isRunning) { + if (latest.approvedAt == null) update(database, latest) { it.copy(approvedAt = Clock.System.now()) } + database.chatRoomDao().findChatRoomById(latest.chatRoomId)?.let { advance(database, it, latest.id, nostrPrivateKey) } + return database.confederationCeremonyDao().getCeremony(latest.id)!! + } + + val basis = when (val built = basisFor(database, proposalId)) { + is Either.Left -> throw IllegalStateException(built.value) + is Either.Right -> built.value + } + val plan = when (val checked = eligibility(database, basis, userPublicKey)) { + is Either.Left -> throw IllegalStateException(checked.value) + is Either.Right -> checked.value + } + val attempt = (latest?.attempt ?: 0) + 1 + + ensureProfiles(database, plan.people) + // Every device makes the same room: its id is the set of its people (D8). + val room = database.nostrNip17Dao().createNip17ChatRoom( + userPublicKey = userPublicKey, + participantPublicKeys = plan.people.filter { it != userPublicKey }, + subject = plan.proposal.name, + ) ?: throw IllegalStateException("Could not make the ceremony's room") + + val ceremony = newCeremony(database, room.chatRoom.id, userPublicKey, basis, plan, attempt).copy(approvedAt = Clock.System.now()) + database.confederationCeremonyDao().upsert(ceremony) + announce( + database, ceremony, ChatMessage.TYPE_CONFEDERATION_CEREMONY_STARTED, + if (attempt == 1) "The confederation's key ceremony started" else "The confederation's key ceremony started again, as attempt $attempt", + ) + replayStoredMessages(database, ceremony) + database.confederationCeremonyDao().getCeremony(ceremony.id)?.takeIf { it.isRunning }?.let { + advance(database, room, it.id, nostrPrivateKey) + } + return database.confederationCeremonyDao().getCeremony(ceremony.id)!! + } + + private fun newCeremony(database: GizaDatabase, chatRoomId: String, user: HexKey, basis: Basis, plan: Plan, attempt: Int): ConfederationCeremony { + val groups = plan.seatsOf(user).map { it.group } return ConfederationCeremony( - id = sessionId, + id = ConfederationAttestation.ceremonyId(plan.proposal.id, attempt), chatRoomId = chatRoomId, - proposalId = proposalId, - coordinatorPublicKey = coordinator, + proposalId = plan.proposal.id, userPublicKey = user, - openingJson = opening.encode(), + basisJson = basis.encode(), + attempt = attempt, + attestationRef = plan.attestationRef.toByteArray().toHex(), + seedContribution = RandomInstance.bytes(32).toHex(), // Fresh per role, and persisted: the dealing is a pure function of the seed, which is // what lets a device that died before sending it send the same one. dealerSeeds = ConfederationRitualEvents.encodeByGroup(groups.associateWith { RandomInstance.bytes(32).toHex() }), @@ -338,67 +218,6 @@ object ConfederationRitualManager { ) } - /** - * Files one message. Returns false when it ended the ceremony. Per-person messages are taken - * only from a person the roster names, carrying a value for exactly the roles they hold; the - * broadcast only from the coordinator; a failure only from someone in the ceremony. - */ - private suspend fun record(database: GizaDatabase, ceremony: ConfederationCeremony, innerEvent: Event): Boolean { - if (innerEvent.kind == ConfederationRitualEvents.OPENING) return true - val plan = (planFrom(Opening.decode(ceremony.openingJson) ?: return true) as? Either.Right)?.value ?: return true - val sender = innerEvent.pubKey - - when (innerEvent.kind) { - in ConfederationRitualEvents.PER_PERSON -> { - val groups = plan.seatsOf(sender).map { it.group }.toSet() - if (groups.isEmpty()) { - logger.w("Ceremony ${ceremony.id}: kind ${innerEvent.kind} from ${sender.take(8)}, who holds no role; ignoring") - return true - } - val keys = if (innerEvent.kind == ConfederationRitualEvents.DEALINGS) { - ConfederationRitualEvents.decodeDealings(innerEvent.content)?.keys - } else { - ConfederationRitualEvents.decodeByGroup(innerEvent.content)?.keys - } - if (keys != groups) { - logger.w("Ceremony ${ceremony.id}: kind ${innerEvent.kind} from ${sender.take(8)} is not one value per role; ignoring") - return true - } - database.confederationCeremonyDao().insertMessage( - ConfederationCeremonyMessage(ceremony.id, sender, innerEvent.kind, innerEvent.content) - ) - } - - ConfederationRitualEvents.BROADCAST -> { - if (sender != ceremony.coordinatorPublicKey) return true - database.confederationCeremonyDao().insertMessage( - ConfederationCeremonyMessage(ceremony.id, sender, innerEvent.kind, innerEvent.content) - ) - } - - ConfederationRitualEvents.FAILURE -> { - if (sender !in plan.people) return true - fail(database, ceremony, "Ended by ${ConfederationManager.nameOf(database, sender)}: ${innerEvent.content}", sender) - return false - } - } - return true - } - - // ---- the member's say -------------------------------------------------------------------- - - /** Whether this ceremony is waiting on its member to join. */ - fun isAwaitingJoin(ceremony: ConfederationCeremony): Boolean = ceremony.isRunning && ceremony.approvedAt == null - - /** Joins: the one thing a member is asked. Everything after it runs by itself. */ - suspend fun join(database: GizaDatabase, sessionId: String, nostrPrivateKey: ByteArray) { - val ceremony = database.confederationCeremonyDao().getCeremony(sessionId) ?: return - if (!isAwaitingJoin(ceremony)) return - update(database, ceremony) { it.copy(approvedAt = Clock.System.now()) } - val room = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return - advance(database, room, sessionId, nostrPrivateKey) - } - /** Ends a running ceremony for everybody, as any participant may. */ suspend fun abandon(database: GizaDatabase, sessionId: String) { val ceremony = database.confederationCeremonyDao().getCeremony(sessionId)?.takeIf { it.isRunning } ?: return @@ -417,6 +236,85 @@ object ConfederationRitualManager { return running.size } + // ---- inbound --------------------------------------------------------------------------- + + /** + * Feeds one inbound ceremony message in and moves the ceremony as far as it will go. Safe to + * call twice with the same message. A message for a ceremony this device has not joined is + * left where the inbound path stored it, and replayed when its owner joins. + */ + suspend fun process( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + innerEvent: Event, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + ) { + val sessionId = ConfederationRitualEvents.parseSessionId(innerEvent.tags) ?: run { + logger.w("Ceremony message ${innerEvent.id.take(8)} names no session; dropping") + return + } + val ceremony = database.confederationCeremonyDao().getCeremony(sessionId)?.takeIf { it.userPublicKey == userPublicKey } + ?: return + if (!ceremony.isRunning) return + if (!record(database, localChatRoom, ceremony, innerEvent)) return + advance(database, localChatRoom, ceremony.id, nostrPrivateKey) + } + + /** + * Files one message. Returns false when it ended the ceremony. Per-person messages are taken + * only from a person the roster names, carrying a value for exactly the roles they hold; a + * failure only from someone in the ceremony. + */ + private suspend fun record(database: GizaDatabase, room: LocalChatRoom, ceremony: ConfederationCeremony, innerEvent: Event): Boolean { + val plan = planOf(ceremony) ?: return true + val sender = innerEvent.pubKey + + when (innerEvent.kind) { + in ConfederationRitualEvents.PER_PERSON -> { + val groups = plan.seatsOf(sender).map { it.group }.toSet() + if (groups.isEmpty()) { + logger.w("Ceremony ${ceremony.id}: kind ${innerEvent.kind} from ${sender.take(8)}, who holds no role; ignoring") + return true + } + val keys = when (innerEvent.kind) { + ConfederationRitualEvents.HOST_KEYS -> { + val hostKeys = ConfederationRitualEvents.HostKeys.decode(innerEvent.content) ?: return true + if (hostKeys.attestation != ceremony.attestationRef) { + // D3: somebody built the roster from other statements than this device holds. + val differing = plan.acceptanceIds.filter { (group, id) -> hostKeys.statements[group] != id }.keys + val named = differing.map { ConfederationManager.nameOf(database, it) }.ifEmpty { listOf("one of the groups") } + failOut( + database, room, ceremony, + "${ConfederationManager.nameOf(database, sender)} holds a different statement from ${named.joinToString()} than this device does", + culprit = null, + ) + return false + } + hostKeys.keys.keys + } + ConfederationRitualEvents.DEALINGS -> ConfederationRitualEvents.decodeDealings(innerEvent.content)?.keys + ConfederationRitualEvents.AUTHORIZATIONS -> ConfederationRitualEvents.Authorizations.decode(innerEvent.content)?.values?.keys + else -> ConfederationRitualEvents.decodeByGroup(innerEvent.content)?.keys + } + if (keys != groups) { + logger.w("Ceremony ${ceremony.id}: kind ${innerEvent.kind} from ${sender.take(8)} is not one value per role; ignoring") + return true + } + database.confederationCeremonyDao().insertMessage( + ConfederationCeremonyMessage(ceremony.id, sender, innerEvent.kind, innerEvent.content) + ) + } + + ConfederationRitualEvents.FAILURE -> { + if (sender !in plan.people) return true + fail(database, ceremony, "Ended by ${ConfederationManager.nameOf(database, sender)}: ${innerEvent.content}", sender) + return false + } + } + return true + } + // ---- the rounds ---------------------------------------------------------------------------- /** @@ -428,30 +326,35 @@ object ConfederationRitualManager { var ceremony = database.confederationCeremonyDao().getCeremony(sessionId) ?: return if (!ceremony.isRunning || ceremony.approvedAt == null) return - val opening = Opening.decode(ceremony.openingJson) ?: return fail(database, ceremony, "The opening cannot be read", null) - val plan = when (val planned = planFrom(opening)) { - is Either.Left -> return failOut(database, localChatRoom, ceremony, planned.value, ceremony.coordinatorPublicKey) - is Either.Right -> planned.value - } + val plan = planOf(ceremony) ?: return fail(database, ceremony, "The statements it was built from no longer read", null) val me = ceremony.userPublicKey val seats = plan.seatsOf(me) val host = seats.associate { it.roleId to ConfederationRosterBuilder.hostSecretKey(nostrPrivateKey, it.group, plan.proposal.id) } - val sessionSeed = ByteVector32(opening.sessionSeed) - // 1. This person's host keys, one per role. + // 1. This person's host keys, one per role, with their part of the seed and the attestation. if (own(database, ceremony, ConfederationRitualEvents.HOST_KEYS) == null) { publishOwn( database, localChatRoom, ceremony, plan, ConfederationRitualEvents.HOST_KEYS, - ConfederationRitualEvents.encodeByGroup(seats.associate { it.group to host.getValue(it.roleId).publicKey().value.toHex() }), + ConfederationRitualEvents.HostKeys( + keys = seats.associate { it.group to host.getValue(it.roleId).publicKey().value.toHex() }, + seed = ceremony.seedContribution!!, + attestation = ceremony.attestationRef!!, + statements = plan.acceptanceIds, + ).encode(), ) } - val hostKeys = perRole(database, ceremony, plan, ConfederationRitualEvents.HOST_KEYS) { PublicKey(ByteVector(it)) } - ?: return moveTo(database, ceremony, ConfederationCeremonyStage.COLLECTING_HOST_KEYS) + val hostMessages = plan.people.associateWith { person -> + database.confederationCeremonyDao().getMessage(ceremony.id, person, ConfederationRitualEvents.HOST_KEYS) + ?.let { ConfederationRitualEvents.HostKeys.decode(it.payload) } + ?: return moveTo(database, ceremony, ConfederationCeremonyStage.COLLECTING_HOST_KEYS) + } + val hostKeys = plan.seats.associate { seat -> seat.roleId to PublicKey(ByteVector(hostMessages.getValue(seat.admin).keys.getValue(seat.group))) } val roster = when (val built = plan.roster(hostKeys)) { is Either.Left -> return failOut(database, localChatRoom, ceremony, "The roster cannot be built: ${built.value.message}", null) is Either.Right -> built.value } - val rosterHex = roster.data.toHex() + // D9: everybody's seed, in roster order, after every host key is in and before anybody deals. + val sessionSeed = ConfederationAttestation.sessionSeed(plan.attestationRef, ceremony.attempt, plan.people.map { hostMessages.getValue(it).seed }) // 2. This person's dealings. The seeds go once the dealings are stored. if (own(database, ceremony, ConfederationRitualEvents.DEALINGS) == null) { @@ -466,25 +369,14 @@ object ConfederationRitualManager { } if (ceremony.dealerSeeds != null) ceremony = update(database, ceremony) { it.copy(dealerSeeds = null) } - // 3. The coordinator combines everybody's dealings. - if (me == ceremony.coordinatorPublicKey && own(database, ceremony, ConfederationRitualEvents.BROADCAST) == null) { - val dealings = perRoleDealings(database, ceremony, plan) - ?: return moveTo(database, ceremony, ConfederationCeremonyStage.DEALING) - val step = ConfederationDkg.coordinatorStep1(roster, sessionSeed, dealings) - .rightOrFail { return failOut(database, localChatRoom, ceremony, "Combining the dealings failed: $it", null) } - step.fault?.let { return failOut(database, localChatRoom, ceremony, describe(database, plan, it), culpritOf(plan, it)) } - publishOwn( - database, localChatRoom, ceremony, plan, ConfederationRitualEvents.BROADCAST, - ConfederationRitualEvents.Broadcast(rosterHex, step.broadcast!!.data.toHex()).encode(), - ) - } - val sent = database.confederationCeremonyDao().getMessage(ceremony.id, ceremony.coordinatorPublicKey, ConfederationRitualEvents.BROADCAST) - ?.let { ConfederationRitualEvents.Broadcast.decode(it.payload) } + // 3. The broadcast, computed here from everybody's dealings: it needs no secret (D8). + val dealings = perRoleDealings(database, ceremony, plan) ?: return moveTo(database, ceremony, ConfederationCeremonyStage.DEALING) - if (sent.roster != rosterHex) { - return failOut(database, localChatRoom, ceremony, "The coordinator's roster is not the one this device built", ceremony.coordinatorPublicKey) - } - val broadcast = ConfederationBroadcast(ByteVector(sent.broadcast)) + val combined = ConfederationDkg.coordinatorStep1(roster, sessionSeed, dealings) + .rightOrFail { return failOut(database, localChatRoom, ceremony, "Combining the dealings failed: $it", null) } + combined.fault?.let { return failOut(database, localChatRoom, ceremony, describe(database, plan, it), culpritOf(plan, it)) } + val broadcast = ConfederationBroadcast(ByteVector(combined.broadcast!!.toByteArray())) + val broadcastHash = Crypto.sha256(broadcast.toByteArray()).toHex() val ownDealings = ConfederationRitualEvents.decodeDealings(own(database, ceremony, ConfederationRitualEvents.DEALINGS)!!.payload)!! val ownRecord = { group: HexKey -> ConfederationDealerRecord(ByteVector(ownDealings.getValue(group).record)) } @@ -507,13 +399,27 @@ object ConfederationRitualManager { confederationPublicKey = keyState!!.publicKey.value.toHex(), ) } - publishOwn(database, localChatRoom, ceremony, plan, ConfederationRitualEvents.AUTHORIZATIONS, ConfederationRitualEvents.encodeByGroup(authorizations)) + publishOwn( + database, localChatRoom, ceremony, plan, ConfederationRitualEvents.AUTHORIZATIONS, + ConfederationRitualEvents.Authorizations(authorizations, broadcastHash).encode(), + ) + } + val authorizationMessages = plan.people.associateWith { person -> + database.confederationCeremonyDao().getMessage(ceremony.id, person, ConfederationRitualEvents.AUTHORIZATIONS) + ?.let { ConfederationRitualEvents.Authorizations.decode(it.payload) } + ?: return moveTo(database, ceremony, ConfederationCeremonyStage.AUTHORIZING) + } + // Two devices dealt different things computed different broadcasts: say who, before a signature fails on it. + authorizationMessages.filterValues { it.broadcast != broadcastHash }.keys.takeIf { it.isNotEmpty() }?.let { others -> + val names = others.map { ConfederationManager.nameOf(database, it) } + return failOut(database, localChatRoom, ceremony, "${names.joinToString()} received different dealings than this device did", null) } val keyState = ConfederationKeyState.fromData(ByteVector(ceremony.keyState!!), roster) .rightOrFail { return failOut(database, localChatRoom, ceremony, "This device's key state no longer reads: $it", null) } val transitionHash = ByteVector32(ceremony.transitionHash!!) - val authorizations = perRole(database, ceremony, plan, ConfederationRitualEvents.AUTHORIZATIONS) { ByteVector64(it) } - ?: return moveTo(database, ceremony, ConfederationCeremonyStage.AUTHORIZING) + val authorizations = plan.seats.associate { seat -> + seat.roleId to ByteVector64(authorizationMessages.getValue(seat.admin).values.getValue(seat.group)) + } val authorizationList = ConfederationDkg.evidenceList(roster, authorizations) .rightOrFail { return failOut(database, localChatRoom, ceremony, "The authorizations cannot be listed: $it", null) } @@ -564,7 +470,11 @@ object ConfederationRitualManager { /** The roster a ceremony ran over, once every host key is in; null before. */ internal suspend fun rosterFor(database: GizaDatabase, ceremony: ConfederationCeremony, plan: Plan): ConfederationRoster? { - val hostKeys = perRole(database, ceremony, plan, ConfederationRitualEvents.HOST_KEYS) { PublicKey(ByteVector(it)) } ?: return null + val hostKeys = plan.seats.associate { seat -> + val message = database.confederationCeremonyDao().getMessage(ceremony.id, seat.admin, ConfederationRitualEvents.HOST_KEYS) + ?.let { ConfederationRitualEvents.HostKeys.decode(it.payload) } ?: return null + seat.roleId to PublicKey(ByteVector(message.keys[seat.group] ?: return null)) + } return (plan.roster(hostKeys) as? Either.Right)?.value } @@ -599,15 +509,19 @@ object ConfederationRitualManager { private fun culpritOf(plan: Plan, fault: ConfederationFault): HexKey? = fault.role?.let { plan.seatOf(it)?.admin } - /** A fault said as who and what, for the failure line and the decline everybody sees. */ + /** + * A fault said as who and what, for the failure line and the decline everybody sees. There is + * no coordinator to blame: what upstream calls the coordinator is this device, computing the + * broadcast from the dealings it was sent. + */ private suspend fun describe(database: GizaDatabase, plan: Plan, fault: ConfederationFault): String { val who = fault.role?.let(plan::seatOf)?.let { seat -> "${ConfederationManager.nameOf(database, seat.admin)} for ${ConfederationManager.nameOf(database, seat.group)}" } return when (fault.kind) { - ConfederationFault.Kind.COORDINATOR -> "The coordinator sent something no honest coordinator sends" + ConfederationFault.Kind.COORDINATOR -> "The dealings this device was sent do not combine; a participant sent something no honest participant sends" ConfederationFault.Kind.ROLE -> "${who ?: "A participant"} sent something no honest participant sends" - ConfederationFault.Kind.ROLE_OR_COORDINATOR -> "A share from ${who ?: "a participant"} did not decrypt; either they or the coordinator is at fault" + ConfederationFault.Kind.ROLE_OR_COORDINATOR -> "A share dealt by ${who ?: "a participant"} did not decrypt here" ConfederationFault.Kind.UNKNOWN -> "A message from ${who ?: "a participant"} does not verify" ConfederationFault.Kind.INVALID_CONFIGURATION -> "The roster and keys make no valid key; nobody is at fault" } @@ -635,8 +549,7 @@ object ConfederationRitualManager { /** Says the ceremony is over to everybody, then ends it here. */ private suspend fun failOut(database: GizaDatabase, localChatRoom: LocalChatRoom, ceremony: ConfederationCeremony, reason: String, culprit: HexKey?) { - val plan = (planFrom(Opening.decode(ceremony.openingJson) ?: return fail(database, ceremony, reason, culprit)) as? Either.Right)?.value - broadcast(database, localChatRoom, ceremony, plan, ConfederationRitualEvents.FAILURE, reason) + broadcast(database, localChatRoom, ceremony, planOf(ceremony), ConfederationRitualEvents.FAILURE, reason) fail(database, ceremony, reason, culprit) } @@ -661,13 +574,14 @@ object ConfederationRitualManager { plan: Plan?, kind: Kind, content: String, - proposalTag: Boolean = false, ) { val people = plan?.people ?: (localChatRoom.localParticipants.map { it.participant.participantPublicKey } + localChatRoom.chatRoom.userPublicKey) - val tags = people.filter { it != ceremony.userPublicKey }.sorted().map { arrayOf("p", it) }.toTypedArray() + - arrayOf(ConfederationRitualEvents.sessionTag(ceremony.id)) + - (if (proposalTag) arrayOf(arrayOf(ConfederationRitualEvents.PROPOSAL_TAG, ceremony.proposalId)) else emptyArray()) + val tags = people.filter { it != ceremony.userPublicKey }.sorted().map { arrayOf("p", it) }.toTypedArray() + arrayOf( + ConfederationRitualEvents.sessionTag(ceremony.id), + arrayOf(ConfederationRitualEvents.PROPOSAL_TAG, ceremony.proposalId), + arrayOf(ConfederationRitualEvents.ATTEMPT_TAG, ceremony.attempt.toString()), + ) val createdAt = Clock.System.now().epochSeconds val id = EventHasher.hashId(pubKey = ceremony.userPublicKey, createdAt = createdAt, kind = kind, tags = tags, content = content) database.giftWrapPayloadDao().upsert( @@ -683,14 +597,16 @@ object ConfederationRitualManager { ) } - /** Feeds in what arrived before the opening did: the inbound path stores every gift wrap first. */ + /** Feeds in what arrived before this device's owner joined: the inbound path stores every gift wrap first. */ private suspend fun replayStoredMessages(database: GizaDatabase, ceremony: ConfederationCeremony) { + val room = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return database.giftWrapPayloadDao() - .getByChatRoomAndKinds(ceremony.chatRoomId, (ConfederationRitualEvents.ALL - ConfederationRitualEvents.OPENING).toList()) - .filter { ConfederationRitualEvents.parseSessionId(it.tags) == ceremony.id } + .getByKinds(ConfederationRitualEvents.ALL.toList()) + .filter { it.publicKey != ceremony.userPublicKey && ConfederationRitualEvents.parseSessionId(it.tags) == ceremony.id } + .sortedBy { it.createdAt } .forEach { stored -> val event = Event(stored.id, stored.publicKey, stored.createdAt.epochSeconds, stored.kind, stored.tags, stored.content, "") - if (!record(database, database.confederationCeremonyDao().getCeremony(ceremony.id) ?: return, event)) return + if (!record(database, room, database.confederationCeremonyDao().getCeremony(ceremony.id) ?: return, event)) return } } @@ -698,7 +614,7 @@ object ConfederationRitualManager { private suspend fun announce(database: GizaDatabase, ceremony: ConfederationCeremony, type: String, content: String) { database.chatMessageDao().upsert( ChatMessage( - senderPublicKey = ceremony.coordinatorPublicKey, + senderPublicKey = ceremony.userPublicKey, isUserMessage = false, giftWrapPayloadId = null, marmotGroupEventId = null, @@ -729,6 +645,4 @@ object ConfederationRitualManager { ) } } - - private fun String.hexBytes(): ByteArray = ByteVector(this).toByteArray() } 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 8ce1580a..6c8f592f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationSigningManager.kt @@ -98,8 +98,7 @@ object ConfederationSigningManager { val confederation = database.confederationCeremonyDao().getConfederation(confederationId) ?.takeIf(ConfederationFormation::verifies) ?: return null val ceremony = database.confederationCeremonyDao().getCeremony(confederation.ceremonyId) ?: return null - val plan = ConfederationRitualEvents.Opening.decode(ceremony.openingJson) - ?.let { ConfederationRitualManager.planFrom(it) as? Either.Right }?.value ?: return null + val plan = ConfederationRitualManager.planOf(ceremony) ?: return null val roster = (ConfederationRoster.fromData(ByteVector(confederation.roster)) as? Either.Right)?.value ?: return null val keyState = (ConfederationKeyState.fromData(ByteVector(confederation.keyState), roster) as? Either.Right)?.value ?: return null val derived = SharedKeyDerivation.derive("02${confederation.publicKey}") diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt index d1534267..4fba3a0e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt @@ -321,8 +321,8 @@ object FrostSigningManager { key: DkgSession? = null, /** * Tags the proposal rumor carries beside the events, for what a signer needs to check - * them and the signed events must not show: a confederation acceptance's seal secret - * (docs/confederation.md, D5). Inside the group's encryption like the rest of it. + * them and the signed events must not show: a confederation statement and the inbox manifest + * (docs/confederation-without-coordinator.md, D6). Inside the group's encryption like the rest of it. */ proposalTags: Array> = emptyArray() ): FrostSigningSession { @@ -731,17 +731,16 @@ object FrostSigningManager { } } - // A confederation event this device can check and finds wrong -- a coordinator who - // is not the proposer, a sealed admin list that is not this group's -- is declined - // before anybody is asked. What it carries to be checked with is kept either way, - // since approval checks again. docs/confederation.md, D6. - val confederation = if (ConfederationRefusal.involves(unsignedEvents)) { - ConfederationRefusal.Carried.from(innerEvent.tags) - } else { - null - } + // A confederation's statement this device can check and finds wrong -- seals that do + // not all hold it, an admin list that is not this group's, a proposal already answered + // -- is declined before anybody is asked. What it carries to be checked with is kept + // either way, since approval checks again. + // docs/confederation-without-coordinator.md, D6. + val inboxManifest = InboxReplyManifest.sealedIn(innerEvent.tags) + val confederation = ConfederationRefusal.Carried.from(innerEvent.tags) + .takeIf { ConfederationRefusal.involves(unsignedEvents, it) } confederation?.let { carried -> - ConfederationRefusal.of(database, localChatRoom.chatRoom.id, innerEvent.pubKey, unsignedEvents, carried) + ConfederationRefusal.of(database, localChatRoom.chatRoom.id, userPublicKey, unsignedEvents, carried, inboxManifest) }?.let { why -> logger.w("Signing proposal $sessionId: $why") val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0, participantCount = n) @@ -757,9 +756,9 @@ object FrostSigningManager { // of one since replaced, or relays a stranger could not reach, is declined before // anybody is asked. docs/group-inbox.md, D5. // A reply from the group's inbox carries its manifest beside the seals (D11), kept so - // approval can read the reply again and the signed seals can be sent. - val inboxManifest = InboxReplyManifest.sealedIn(innerEvent.tags) - if (InboxRefusal.involves(unsignedEvents)) { + // approval can read the reply again and the signed seals can be sent. A confederation's + // statement carries one too, and is the confederation's refusal's to read, above. + if (confederation == null && InboxRefusal.involves(unsignedEvents)) { InboxRefusal.of(database, localChatRoom, userPublicKey, unsignedEvents, inboxManifest)?.let { why -> logger.w("Signing proposal $sessionId: $why") val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0, participantCount = n) @@ -1122,6 +1121,7 @@ object FrostSigningManager { if (session.subject != FrostSigningSubject.EVENTS) return null val events = items.mapNotNull { Event.fromJsonOrNull(it.unsignedEventJson) } if (!InboxRefusal.involves(events)) return null + if (ConfederationRefusal.isStatementSession(database, session.id)) return null return InboxRefusal.of(database, localChatRoom, session.userPublicKey, events, database.groupInboxDao().getSigning(session.id)?.manifest) } @@ -1159,13 +1159,15 @@ object FrostSigningManager { ): String? { if (session.subject != FrostSigningSubject.EVENTS) return null val events = items.mapNotNull { Event.fromJsonOrNull(it.unsignedEventJson) } - if (!ConfederationRefusal.involves(events)) return null + val carried = ConfederationRefusal.Carried.from(database.confederationDao().getSigning(session.id)) + if (!ConfederationRefusal.involves(events, carried)) return null return ConfederationRefusal.of( database = database, chatRoomId = localChatRoom.chatRoom.id, - proposer = session.coordinatorPublicKey, + userPublicKey = session.userPublicKey, events = events, - carried = ConfederationRefusal.Carried.from(database.confederationDao().getSigning(session.id)), + carried = carried, + manifest = database.groupInboxDao().getSigning(session.id)?.manifest, ) } 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 bfa4ff26..4c98e0b8 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupInboxManager.kt @@ -10,6 +10,7 @@ import mobi.giza.compose.database.model.ChatMessage import mobi.giza.compose.database.model.GroupInboxMessage import mobi.giza.compose.database.model.GroupInboxWrap import mobi.giza.compose.database.model.InboxKey +import mobi.giza.compose.nostr.confederation.ConfederationStatements import mobi.giza.compose.nostr.inbox.InboxAnnouncement import mobi.giza.compose.nostr.inbox.InboxConversation import mobi.giza.compose.nostr.inbox.InboxSeal @@ -85,6 +86,13 @@ object GroupInboxManager { return null } val rumor = opened.rumor + // A confederation's statement, from one group to the others it names: the confederation's + // to file, not a conversation in the inbox (docs/confederation-without-coordinator.md, D7). + if (ConfederationStatements.isStatementKind(rumor.kind)) { + ConfederationManager.recordStatement(database, rumor, opened.seal, roomId) + database.groupInboxDao().markOpened(wrap.id, key.generation) + return null + } val participants = InboxConversation.participantsOf(rumor, roomId) val message = GroupInboxMessage( chatRoomId = roomId, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt index 1a41d77f..a85174d8 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxRefusal.kt @@ -130,12 +130,29 @@ object InboxRefusal { return null } - private sealed interface Read { + internal sealed interface Read { data class Ok(val reply: ReadReply) : Read data class Refused(val reason: String) : Read } - private suspend fun readReply(database: GizaDatabase, roomId: HexKey, userPublicKey: HexKey, events: List, manifest: String?): Read { + private suspend fun readReply(database: GizaDatabase, roomId: HexKey, userPublicKey: HexKey, events: List, manifest: String?): Read = + readSealed(database, roomId, userPublicKey, events, manifest) { it == 14 } + + /** + * D12's reading of a batch of seals, for any rumor kind [acceptsKind] takes: the manifest + * opened with a key this device holds, every seal sealed from that generation to the key its + * recipient announced (or their identity), all of them holding one rumor, written by the group + * to exactly the people the manifest names. A reply is a kind 14; a confederation's statement + * is one of its own kinds (docs/confederation-without-coordinator.md, D6). + */ + internal suspend fun readSealed( + database: GizaDatabase, + roomId: HexKey, + userPublicKey: HexKey, + events: List, + manifest: String?, + acceptsKind: (Int) -> Boolean, + ): Read { val sealed = manifest ?: return Read.Refused(REPLY_UNREADABLE) val keys = database.inboxKeyDao().getKeys(roomId, userPublicKey).filter { it.secretKey != null } val (key, opened) = keys.firstNotNullOfOrNull { k -> @@ -167,7 +184,7 @@ object InboxRefusal { } if (rumors.map { it.id }.distinct().size != 1) return Read.Refused(REPLY_MISMATCH) val rumor = rumors.first() - if (rumor.kind != 14) return Read.Refused(REPLY_UNREADABLE) + if (!acceptsKind(rumor.kind)) return Read.Refused(REPLY_UNREADABLE) val named = rumor.tags.filter { it.size >= 2 && it[0] == "p" }.map { it[1].lowercase() }.distinct().sorted() val manifestRecipients = opened.seals.filterIndexed { index, _ -> index != opened.groupCopy }.map { it.recipient.lowercase() }.distinct().sorted() if (named != manifestRecipients || opened.seals.size != manifestRecipients.size + 1) return Read.Refused(REPLY_MISMATCH) 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 11de5328..3de1086f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/InboxReplies.kt @@ -17,6 +17,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.ConfederationStatements import mobi.giza.compose.nostr.inbox.InboxAnnouncement import mobi.giza.compose.nostr.inbox.InboxConversation import mobi.giza.compose.nostr.inbox.InboxReplyManifest @@ -64,9 +65,25 @@ object InboxReplies { replyTo?.let { add(arrayOf("e", it, "", "reply")) } }.toTypedArray() val rumor = RumorAssembler.assembleRumor(pubKey = roomId, ev = EventTemplate(now, 14, tags, text)) + return sealRumor(roomId, rumor, ordered, inboxSecret, generation, sealTime) + } + /** + * [rumor], from the group of [roomId], sealed once to each of [recipients] and once to the + * group itself, from the inbox key [inboxSecret] of [generation]: a reply's seals, or a + * confederation statement's (docs/confederation-without-coordinator.md, D1). The group's + * copy is last, and the recipients are in the order given. + */ + fun sealRumor( + roomId: HexKey, + rumor: Event, + recipients: List, + inboxSecret: ByteArray, + generation: Int, + sealTime: () -> Long = { TimeUtils.randomWithTwoDays() }, + ): Built { val inboxKey = InboxWire.publicKeyOf(inboxSecret) - val entries = ordered.map { InboxReplyManifest.Entry(it.publicKey, it.encryptionKey, it.announcement?.toJson()) } + + val entries = recipients.map { InboxReplyManifest.Entry(it.publicKey, it.encryptionKey, it.announcement?.toJson()) } + InboxReplyManifest.Entry(roomId, inboxKey, null) val seals = entries.map { InboxSeal.template(rumor, inboxSecret, it.key, sealTime()) } return Built(rumor, seals, InboxReplyManifest(generation, entries, groupCopy = entries.lastIndex)) @@ -196,6 +213,9 @@ object InboxReplies { // The group's copy, filed now so the reply is in the conversation before it comes back. val copy = ordered[manifest.groupCopy] ?: return val rumor = InboxSeal.rumorInside(copy.content, InboxReplyManifest.selfConversationKey(key.secretKey!!.hexToByteArray()), roomId) ?: return + // 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 val participants = InboxConversation.participantsOf(rumor, roomId) database.groupInboxDao().insertMessage( GroupInboxMessage( 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 65f820a6..056ebe2a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/LiveSubscriptionManager.kt @@ -228,19 +228,14 @@ class LiveSubscriptionManager( .sorted() /** - * What the confederation subscription asks for: every confederation event that names one - * of our keyed rooms -- a proposal inviting it, an answer addressed to it -- and every - * answer to a proposal still open on this device, whoever it is addressed to, so a - * proposal's progress is seen by every group on it (docs/confederation.md, Phase 5). - * - * Signed by groups and public, so nothing here is ours to decrypt and nothing is - * p-tagged to a person. + * What the confederation subscription asks for: every charter that names one of our keyed + * rooms (docs/confederation.md, Phase 15). It is the one confederation event still + * 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, openProposalIds: List): List = + internal fun confederationFilters(roomIds: List): List = roomIds.chunked(MAX_CONFEDERATION_IDS).map { chunk -> - Filter(kinds = ConfederationKinds.ALL.toList(), tags = mapOf("p" to chunk), limit = INITIAL_GROUP_HISTORY_LIMIT) - } + openProposalIds.chunked(MAX_CONFEDERATION_IDS).map { chunk -> - Filter(kinds = ConfederationKinds.ANSWERS.toList(), tags = mapOf("e" to chunk), limit = INITIAL_GROUP_HISTORY_LIMIT) + Filter(kinds = listOf(ConfederationKinds.CHARTER), tags = mapOf("p" to chunk), limit = INITIAL_GROUP_HISTORY_LIMIT) } /** @@ -422,15 +417,13 @@ class LiveSubscriptionManager( /** * Keeps one subscription per public relay open on [confederationFilters], re-sent whenever - * the rooms or the open proposals change. Events go to [repository], never to the + * the rooms change. Events go to [repository], never to the * `NostrEvent` table (docs/confederation.md, Phase 5). */ @OptIn(FlowPreview::class) private suspend fun followConfederations(publicKey: HexKey, keyPair: KeyPair, repository: ConfederationRepository) { - combine( - chatRepository.observeChatRoomListByPublicKey(publicKey).map(::confederationRoomIdsFrom).distinctUntilChanged(), - repository.observeOpenProposalIds(), - ) { roomIds, proposalIds -> confederationFilters(roomIds, proposalIds) } + chatRepository.observeChatRoomListByPublicKey(publicKey).map(::confederationRoomIdsFrom).distinctUntilChanged() + .map(::confederationFilters) .distinctUntilChanged() .debounce(GROUP_CHANGE_DEBOUNCE) .collectLatest { filters -> diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationAnswerEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationAnswerEvents.kt deleted file mode 100644 index 624a5282..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationAnswerEvents.kt +++ /dev/null @@ -1,166 +0,0 @@ -package mobi.giza.compose.nostr.confederation - -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.Kind -import mobi.giza.compose.nostr.confederation.tags.ConfederationEphemeralKeyTag - -/** - * The `e` tag every answer carries: the proposal it answers, by event id. An id rather than an - * address because the proposal is a regular event (D1): the thing a group agreed to cannot be - * replaced under it. - */ -internal object ConfederationProposalReference { - const val TAG_NAME = "e" - - fun assemble(proposalId: HexKey, relayHint: String?): Array = - arrayOf(TAG_NAME, proposalId, relayHint.orEmpty()) - - /** The one proposal [tags] answer, or null when they name none or more than one. */ - fun parse(tags: Array>): HexKey? = - tags.filter { it.size >= 2 && it[0] == TAG_NAME }.singleOrNull()?.get(1) - ?.takeIf(ConfederationKinds::isHex32) - - /** The `p` tags of [tags] that carry no `group` marker: who the answer is addressed to. */ - fun addressees(tags: Array>): List = - tags.filter { it.size >= 2 && it[0] == "p" && (it.size < 4 || it[3] != "group") }.map { it[1] } -} - -/** - * A group accepting a confederation proposal, and disclosing to its coordinator, sealed, the - * admins it would take part with (docs/confederation.md, D5). - * - * ``` - * kind: 9431 - * pubkey: - * content: - * tags: - * ["e", , ] - * ["p", ] - * ["p", ] - * ["epk", ] - * ["alt", ...] - * ``` - * - * Whether the content holds the right list is not something a reader outside the group can - * check, and [parse] does not try: that is checked by the group's own signers before it exists, - * and by the coordinator when they open it. - */ -object ConfederationProposalAcceptanceEvent { - val KIND: Kind = ConfederationKinds.ACCEPTANCE - const val ALT = "An acceptance of a confederation proposal" - - data class Acceptance( - val id: HexKey, - val group: HexKey, - val createdAt: Long, - val proposalId: HexKey, - val addressees: List, - val ephemeralPublicKey: HexKey, - val content: String, - ) - - fun assembleTags( - proposalId: HexKey, - relayHint: String?, - proposingGroup: HexKey, - coordinator: HexKey, - ephemeralPublicKey: HexKey, - ): Array> = arrayOf( - ConfederationProposalReference.assemble(proposalId, relayHint), - arrayOf("p", proposingGroup), - arrayOf("p", coordinator), - ConfederationEphemeralKeyTag.assemble(ephemeralPublicKey), - arrayOf(ConfederationProposalEvent.ALT_TAG, ALT), - ) - - fun parse(event: Event): Acceptance? = runCatching { - if (event.kind != KIND) return null - if (!ConfederationKinds.isPublicKey(event.pubKey)) return null - val proposalId = ConfederationProposalReference.parse(event.tags) ?: return null - val epk = ConfederationEphemeralKeyTag.valueIn(event.tags) - ?.takeIf(ConfederationKinds::isPublicKey) ?: return null - if (event.content.isBlank()) return null - Acceptance( - id = event.id, - group = event.pubKey, - createdAt = event.createdAt, - proposalId = proposalId, - addressees = ConfederationProposalReference.addressees(event.tags), - ephemeralPublicKey = epk, - content = event.content, - ) - }.getOrNull() - - /** Whether [acceptance] is addressed the way an answer to [proposal] must be. */ - fun answers(acceptance: Acceptance, proposal: ConfederationProposalEvent.Proposal): Boolean = - acceptance.proposalId == proposal.id && - proposal.lists(acceptance.group) && - proposal.proposingGroup in acceptance.addressees && - proposal.coordinator in acceptance.addressees -} - -/** - * A group declining a confederation proposal. Public, unencrypted, and final: one rejection ends - * the proposal for every group (docs/confederation.md, D8). - * - * ``` - * kind: 9432 - * pubkey: - * content: - * tags: ["e", , ], ["p", ], ["alt", ...] - * ``` - */ -object ConfederationProposalRejectionEvent { - val KIND: Kind = ConfederationKinds.REJECTION - const val ALT = "A rejection of a confederation proposal" - - data class Rejection( - val id: HexKey, - val group: HexKey, - val createdAt: Long, - val proposalId: HexKey, - val reason: String, - ) - - fun assembleTags(proposalId: HexKey, relayHint: String?, proposingGroup: HexKey): Array> = arrayOf( - ConfederationProposalReference.assemble(proposalId, relayHint), - arrayOf("p", proposingGroup), - arrayOf(ConfederationProposalEvent.ALT_TAG, ALT), - ) - - fun parse(event: Event): Rejection? = runCatching { - if (event.kind != KIND) return null - if (!ConfederationKinds.isPublicKey(event.pubKey)) return null - val proposalId = ConfederationProposalReference.parse(event.tags) ?: return null - Rejection(event.id, event.pubKey, event.createdAt, proposalId, event.content) - }.getOrNull() -} - -/** - * The proposing group taking its proposal back before every group has accepted it - * (docs/confederation.md, Phase 8). Same shape as a rejection; only the proposing group's counts. - */ -object ConfederationProposalWithdrawalEvent { - val KIND: Kind = ConfederationKinds.WITHDRAWAL - const val ALT = "A withdrawal of a confederation proposal" - - data class Withdrawal( - val id: HexKey, - val group: HexKey, - val createdAt: Long, - val proposalId: HexKey, - val reason: String, - ) - - fun assembleTags(proposalId: HexKey, relayHint: String?, groups: List): Array> = arrayOf( - ConfederationProposalReference.assemble(proposalId, relayHint), - ) + groups.map { arrayOf("p", it) } + arrayOf(arrayOf(ConfederationProposalEvent.ALT_TAG, ALT)) - - fun parse(event: Event): Withdrawal? = runCatching { - if (event.kind != KIND) return null - if (!ConfederationKinds.isPublicKey(event.pubKey)) return null - val proposalId = ConfederationProposalReference.parse(event.tags) ?: return null - Withdrawal(event.id, event.pubKey, event.createdAt, proposalId, event.content) - }.getOrNull() -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationAttestation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationAttestation.kt index 1cfd37e9..de11718d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationAttestation.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationAttestation.kt @@ -13,12 +13,15 @@ import mobi.giza.compose.extensions.toHex * ``` * attestation_ref = TaggedHash(ATTESTATION_TAG, proposal id ‖ each group's acceptance id, in groupId order) * the proposal's own id standing for the proposing group's acceptance - * ceremony id = TaggedHash(CEREMONY_TAG, attestation_ref ‖ attempt as u32) + * ceremony id = TaggedHash(CEREMONY_TAG, proposal id ‖ attempt as u32) * session seed = TaggedHash(SEED_TAG, attestation_ref ‖ attempt as u32 ‖ every person's seed, in roster order) * ``` * * Two devices holding the same statements compute the same three values; a group that told two - * groups different things gives them different ones, which is how that is caught (D3). + * groups different things gives them different attestations, which is how that is caught (D3). + * The ceremony's id is the one value not made from the statements, on purpose: two devices that + * hold different ones still meet in the same ceremony, where the first message names the + * difference, rather than each waiting in a ceremony of its own for people who never come. * * The tags are hash inputs, spelled the house way for protocol tags (CLAUDE.md), and new: version * 1 of the attestation hashed public event ids, and these are rumor ids. @@ -38,9 +41,9 @@ object ConfederationAttestation { ATTESTATION_TAG, ) - /** The id of attempt [attempt] at the ceremony over [attestationRef]: the same on every device. */ - fun ceremonyId(attestationRef: ByteVector32, attempt: Int): HexKey = - Crypto.taggedHash(attestationRef.toByteArray() + u32(attempt), CEREMONY_TAG).toByteArray().toHex() + /** The id of attempt [attempt] at the ceremony for [proposalId]: the same on every device. */ + fun ceremonyId(proposalId: HexKey, attempt: Int): HexKey = + Crypto.taggedHash(proposalId.hexToByteArray() + u32(attempt), CEREMONY_TAG).toByteArray().toHex() /** * The session seed of attempt [attempt]: fresh as long as one person's [contributions] was, 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 ee5fc770..c8f6ac95 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 @@ -21,20 +21,22 @@ import mobi.giza.compose.nostr.confederation.tags.ConfederationGroupTag * * The one public statement that the confederation exists, and the only way a group's members * who are not its admins hear of it: the `p` tags reach every member group's devices through the - * same relay filter that brings them proposals. What it proves is that whoever holds the + * relay filter that listens for it. What it proves is that whoever holds the * confederation's key named these groups -- a reader cannot check the roster behind the key, any * more than it can tell a group's key from a person's. */ object ConfederationCharterEvent { val KIND: Kind = ConfederationKinds.CHARTER const val ALT = "A confederation of nostr groups, naming its member groups" + 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) fun assembleTags(name: String, groups: List): Array> = ( groups.sorted().map { ConfederationGroupTag.assemble(it, null) } + listOf( - arrayOf(ConfederationProposalEvent.NAME_TAG, name), - arrayOf(ConfederationProposalEvent.ALT_TAG, ALT), + arrayOf(NAME_TAG, name), + arrayOf(ALT_TAG, ALT), ) ).toTypedArray() @@ -45,7 +47,7 @@ object ConfederationCharterEvent { val groups = event.tags.mapNotNull(ConfederationGroupTag::parse).map { it.groupPublicKey } if (groups.size !in ConfederationKinds.MIN_GROUPS..ConfederationKinds.MAX_GROUPS) return null if (groups.any { !ConfederationKinds.isPublicKey(it) } || groups.toSet().size != groups.size) return null - val name = ConfederationProposalEvent.single(event.tags, ConfederationProposalEvent.NAME_TAG)?.takeIf { it.isNotBlank() } ?: return null + 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) }.getOrNull() } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProposalEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProposalEvent.kt deleted file mode 100644 index d6519742..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationProposalEvent.kt +++ /dev/null @@ -1,136 +0,0 @@ -package mobi.giza.compose.nostr.confederation - -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.Kind -import mobi.giza.compose.nostr.confederation.tags.ConfederationCoordinatorTag -import mobi.giza.compose.nostr.confederation.tags.ConfederationGroupTag -import mobi.giza.compose.nostr.confederation.tags.ConfederationThresholdTag - -/** - * A group proposing that it and the groups it names form a confederation - * (docs/confederation.md). - * - * ``` - * kind: 9430 - * pubkey: set by the signing session - * content: a sentence for clients that know nothing of this kind - * tags: - * ["p", , , "group"] one per group, the proposer's included - * ["coordinator", ] - * ["threshold", ""] - * ["name", ] - * ["nonce", <32 random bytes>] two otherwise identical proposals differ - * ["expiration", ""] NIP-40 - * ["alt", ...] NIP-31 - * ``` - * - * Never signed alone. The proposing group signs it in one session with its own acceptance, - * which e-tags it (D3), so a proposal never exists without its proposer having committed to its - * own admins. - * - * [parse] is all or nothing. A proposal with one field missing or malformed is not a weaker - * proposal -- every device has to derive the same roster from it later, and a field one reader - * skips and another reads is a roster two devices disagree on. - */ -object ConfederationProposalEvent { - val KIND: Kind = ConfederationKinds.PROPOSAL - - const val NAME_TAG = "name" - const val NONCE_TAG = "nonce" - const val EXPIRATION_TAG = "expiration" - const val ALT_TAG = "alt" - const val ALT = "A proposal to form a confederation of nostr groups" - - /** One group on the invitation: its npub as hex, and where its profile was found. */ - data class Invitee(val groupPublicKey: HexKey, val relayHint: String? = null) - - /** A proposal as [parse] reads it. [groups] are in the order the tags give them. */ - data class Proposal( - val id: HexKey, - val proposingGroup: HexKey, - val createdAt: Long, - val groups: List, - val coordinator: HexKey, - val threshold: Int, - val name: String, - val nonce: HexKey, - val expiresAt: Long, - ) { - val groupPublicKeys: List get() = groups.map { it.groupPublicKey } - - fun lists(groupPublicKey: HexKey): Boolean = groups.any { it.groupPublicKey == groupPublicKey } - - fun relayHintFor(groupPublicKey: HexKey): String? = - groups.firstOrNull { it.groupPublicKey == groupPublicKey }?.relayHint - - fun isExpiredAt(epochSeconds: Long): Boolean = epochSeconds > expiresAt - } - - fun assembleTags( - groups: List, - coordinator: HexKey, - threshold: Int, - name: String, - nonce: HexKey, - expiresAt: Long, - ): Array> = ( - groups.map { ConfederationGroupTag.assemble(it.groupPublicKey, it.relayHint) } + - listOf( - ConfederationCoordinatorTag.assemble(coordinator), - ConfederationThresholdTag.assemble(threshold.toString()), - arrayOf(NAME_TAG, name), - arrayOf(NONCE_TAG, nonce), - arrayOf(EXPIRATION_TAG, expiresAt.toString()), - arrayOf(ALT_TAG, ALT), - ) - ).toTypedArray() - - /** What a client that does not know this kind shows. Unverified, and never read back. */ - fun content(name: String, groupCount: Int): String = - "A proposal to form a confederation, $name, of $groupCount groups" - - /** - * The proposal in [event], or null if it is not a well-formed one. Checks only what the - * event says about itself: whether the groups agree to it is [ConfederationStatus]'s, and - * whether a device should sign it is `ConfederationRefusal`'s. - */ - fun parse(event: Event): Proposal? = runCatching { - if (event.kind != KIND) return null - if (!ConfederationKinds.isPublicKey(event.pubKey)) return null - - val groups = event.tags.mapNotNull(ConfederationGroupTag::parse) - .map { Invitee(it.groupPublicKey, it.relayHint) } - if (groups.size !in ConfederationKinds.MIN_GROUPS..ConfederationKinds.MAX_GROUPS) return null - if (groups.any { !ConfederationKinds.isPublicKey(it.groupPublicKey) }) return null - if (groups.map { it.groupPublicKey }.toSet().size != groups.size) return null - if (groups.none { it.groupPublicKey == event.pubKey }) return null - - val coordinator = ConfederationCoordinatorTag.valueIn(event.tags) - ?.takeIf(ConfederationKinds::isPublicKey) ?: return null - val thresholdText = ConfederationThresholdTag.valueIn(event.tags) ?: return null - val threshold = thresholdText.toIntOrNull()?.takeIf { it.toString() == thresholdText } ?: return null - if (threshold !in ConfederationKinds.MIN_GROUPS..groups.size) return null - - val name = single(event.tags, NAME_TAG)?.takeIf { it.isNotBlank() } ?: return null - val nonce = single(event.tags, NONCE_TAG)?.takeIf(ConfederationKinds::isHex32) ?: return null - val expiresAt = single(event.tags, EXPIRATION_TAG)?.toLongOrNull() ?: return null - if (expiresAt <= event.createdAt) return null - - Proposal( - id = event.id, - proposingGroup = event.pubKey, - createdAt = event.createdAt, - groups = groups, - coordinator = coordinator, - threshold = threshold, - name = name, - nonce = nonce, - expiresAt = expiresAt, - ) - }.getOrNull() - - /** The value of the one tag named [name], or null if there is none or more than one. */ - internal 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/ConfederationRitualEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationRitualEvents.kt index 434e57d2..695df578 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationRitualEvents.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationRitualEvents.kt @@ -10,39 +10,42 @@ import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put /** - * The confederation's key ceremony on the wire (docs/confederation.md, Phase 11): rumors in the - * NIP-17 room the coordinator opens over every admin of every group, gift-wrapped per member - * like the group's own ChillDKG ceremony (docs/shared-key-ceremony.md). + * The confederation's key ceremony on the wire (docs/confederation.md, Phase 11, as + * docs/confederation-without-coordinator.md, D8, took its coordinator out): rumors in the NIP-17 + * room over every admin of every group, gift-wrapped per member like the group's own ChillDKG + * ceremony (docs/shared-key-ceremony.md). Nobody opens it and nobody relays it: every device + * builds the same room and the same roster from the statements it holds. * * A person who is an admin of two groups holds two roles and sends one message per step, * carrying a value for each of their roles keyed by group. Every receiver checks the sender is * that group's admin in the roster before it reads a value. * - * | kind | from | carries | - * |-------|-------------|----------------------------------------------------------------------| - * | 30380 | coordinator | the opening: the 9430, every 9431, D7's conversation keys, the seed | - * | 30381 | each person | a host public key per role | - * | 30382 | each person | a dealer record and ciphertext vector per role | - * | 30383 | coordinator | the roster as the coordinator built it, and the broadcast | - * | 30384 | each person | an authorization of the genesis per role | - * | 30385 | each person | an acknowledgment per role: its share can be recovered from storage | - * | 30387 | anyone | failure or abandonment, with a reason | + * | kind | from | carries | + * |-------|-------------|----------------------------------------------------------------------------------| + * | 30381 | each person | a host public key per role, a seed contribution, and the attestation it built | + * | 30382 | each person | a dealer record and ciphertext vector per role | + * | 30384 | each person | an authorization of the genesis per role, and the hash of the broadcast it made | + * | 30385 | each person | an acknowledgment per role: its share can be recovered from storage | + * | 30387 | anyone | failure or abandonment, with a reason | * - * There is no certificate message. Every device assembles the certified genesis itself from - * the authorizations and acknowledgments it already holds: it needs no secret to do it, and a - * device that builds its own cannot be handed someone else's. 30386 is left unused for that - * reason, and 30388 for the investigation a decryption fault would start, which is not built. + * 30380 (a coordinator's opening) and 30383 (a coordinator's broadcast) are not sent any more: + * every device builds the opening from what its groups' inboxes hold, and computes the + * broadcast from the dealings, which needs no secret. 30386 is unused, since every device + * assembles the certified genesis itself, and 30388 for the investigation a decryption fault + * would start, which is not built. + * + * Every message names the ceremony (its id, derived from the statements and the attempt), the + * proposal and the attempt, so a device that does not hold every statement yet keeps it until it + * does. */ object ConfederationRitualEvents { - const val OPENING: Kind = 30380 const val HOST_KEYS: Kind = 30381 const val DEALINGS: Kind = 30382 - const val BROADCAST: Kind = 30383 const val AUTHORIZATIONS: Kind = 30384 const val ACKNOWLEDGMENTS: Kind = 30385 const val FAILURE: Kind = 30387 - val ALL: Set = setOf(OPENING, HOST_KEYS, DEALINGS, BROADCAST, AUTHORIZATIONS, ACKNOWLEDGMENTS, FAILURE) + val ALL: Set = setOf(HOST_KEYS, DEALINGS, AUTHORIZATIONS, ACKNOWLEDGMENTS, FAILURE) /** The messages each person sends once, one value per role. */ val PER_PERSON: Set = setOf(HOST_KEYS, DEALINGS, AUTHORIZATIONS, ACKNOWLEDGMENTS) @@ -51,48 +54,100 @@ object ConfederationRitualEvents { const val SESSION_TAG = "confederation_ceremony" const val PROPOSAL_TAG = "confederation_proposal_id" + const val ATTEMPT_TAG = "confederation_attempt" fun sessionTag(sessionId: String): Array = arrayOf(SESSION_TAG, sessionId) fun parseSessionId(tags: Array>): String? = tags.firstOrNull { it.size >= 2 && it[0] == SESSION_TAG }?.get(1)?.takeIf(ConfederationKinds::isHex32) + fun parseProposalId(tags: Array>): String? = + tags.firstOrNull { it.size >= 2 && it[0] == PROPOSAL_TAG }?.get(1)?.takeIf(ConfederationKinds::isHex32) + + fun parseAttempt(tags: Array>): Int? = + tags.firstOrNull { it.size >= 2 && it[0] == ATTEMPT_TAG }?.get(1)?.toIntOrNull()?.takeIf { it >= 1 } + private val json = Json { ignoreUnknownKeys = false } /** - * What the coordinator opens the ceremony with: the signed proposal and acceptances, a key that - * opens each acceptance (D7), and the session seed every role's steps take. + * What a ceremony is built from, on one device: the proposal and every other group's acceptance, + * as the statements this device's inboxes opened (D8). Kept on the ceremony, since every step + * rebuilds the roster's plan from it. */ - data class Opening( - val proposalJson: String, - val acceptanceJsons: List, - /** By acceptance event id: the NIP-44 conversation key that opens it, and nothing else. */ - val conversationKeys: Map, - val sessionSeed: HexKey, - ) { + data class Basis(val proposalJson: String, val acceptanceJsons: List) { fun encode(): String = buildJsonObject { - put("v", 1) + put("v", 2) put("proposal", proposalJson) put("acceptances", JsonArray(acceptanceJsons.map(::JsonPrimitive))) - put("keys", JsonObject(conversationKeys.toSortedMap().mapValues { JsonPrimitive(it.value) })) - put("seed", sessionSeed) }.toString() companion object { - fun decode(content: String): Opening? = runCatching { + fun decode(content: String): Basis? = runCatching { val obj = json.parseToJsonElement(content) as JsonObject - require((obj["v"] as JsonPrimitive).content == "1") - Opening( + require((obj["v"] as JsonPrimitive).content == "2") + Basis( proposalJson = (obj["proposal"] as JsonPrimitive).content, acceptanceJsons = (obj["acceptances"] as JsonArray).map { (it as JsonPrimitive).content }, - conversationKeys = (obj["keys"] as JsonObject).mapValues { (it.value as JsonPrimitive).content }, - sessionSeed = (obj["seed"] as JsonPrimitive).content.also { require(ConfederationKinds.isHex32(it)) }, ) }.getOrNull() } } - /** One value per role, keyed by the role's group: a host key, an authorization, an acknowledgment. */ + /** + * One person's 30381: a host key per role, keyed by group; their contribution to the session + * seed (D9); and the attestation they built, with the statement each group's admins came from, + * so a device that built another names the group whose statement differs (D3). + */ + data class HostKeys( + val keys: Map, + val seed: HexKey, + val attestation: HexKey, + val statements: Map, + ) { + fun encode(): String = buildJsonObject { + put("keys", JsonObject(keys.toSortedMap().mapValues { JsonPrimitive(it.value) })) + put("seed", seed) + put("attestation", attestation) + put("statements", JsonObject(statements.toSortedMap().mapValues { JsonPrimitive(it.value) })) + }.toString() + + companion object { + fun decode(content: String): HostKeys? = runCatching { + val obj = json.parseToJsonElement(content) as JsonObject + require(obj.keys == setOf("keys", "seed", "attestation", "statements")) + HostKeys( + keys = (obj["keys"] as JsonObject).mapValues { (it.value as JsonPrimitive).content }, + seed = (obj["seed"] as JsonPrimitive).content.also { require(ConfederationKinds.isHex32(it)) }, + attestation = (obj["attestation"] as JsonPrimitive).content.also { require(ConfederationKinds.isHex32(it)) }, + statements = (obj["statements"] as JsonObject).mapValues { (it.value as JsonPrimitive).content }, + ) + }.getOrNull() + } + } + + /** + * One person's 30384: an authorization per role, keyed by group, and the hash of the broadcast + * their device computed, so two devices that were dealt different things find out by name (D8). + */ + data class Authorizations(val values: Map, val broadcast: HexKey) { + fun encode(): String = buildJsonObject { + put("authorizations", JsonObject(values.toSortedMap().mapValues { JsonPrimitive(it.value) })) + put("broadcast", broadcast) + }.toString() + + companion object { + fun decode(content: String): Authorizations? = runCatching { + val obj = json.parseToJsonElement(content) as JsonObject + require(obj.keys == setOf("authorizations", "broadcast")) + Authorizations( + values = (obj["authorizations"] as JsonObject).mapValues { (it.value as JsonPrimitive).content }, + broadcast = (obj["broadcast"] as JsonPrimitive).content.also { require(ConfederationKinds.isHex32(it)) }, + ) + }.getOrNull() + } + } + + /** One value per role, keyed by the role's group: an acknowledgment, or a recovery package. */ fun encodeByGroup(values: Map): String = JsonObject(values.toSortedMap().mapValues { JsonPrimitive(it.value) }).toString() @@ -118,19 +173,4 @@ object ConfederationRitualEvents { Dealing((obj["record"] as JsonPrimitive).content, (obj["ciphertexts"] as JsonPrimitive).content) } }.getOrNull() - - /** The coordinator's broadcast, with the roster it was made over so every device can compare its own. */ - data class Broadcast(val roster: String, val broadcast: String) { - fun encode(): String = buildJsonObject { - put("roster", roster) - put("broadcast", broadcast) - }.toString() - - companion object { - fun decode(content: String): Broadcast? = runCatching { - val obj = json.parseToJsonElement(content) as JsonObject - Broadcast((obj["roster"] as JsonPrimitive).content, (obj["broadcast"] as JsonPrimitive).content) - }.getOrNull() - } - } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationRosterBuilder.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationRosterBuilder.kt index cbbc2c7c..532b5e0a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationRosterBuilder.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationRosterBuilder.kt @@ -13,7 +13,8 @@ import fr.acinq.bitcoin.utils.Either /** * The confederation's roster (upstream's RPD), derived the same way on every device from what the - * groups signed in Part A (docs/confederation.md, Phase 10). + * groups said to each other in their inboxes (docs/confederation.md, Phase 10, and + * docs/confederation-without-coordinator.md, D8). * * A roster is hashed into every step of the DKG, so two devices that order it differently do not * get a weaker key -- they get no key, the same rule ChillDKG's host-key ordering follows @@ -24,11 +25,12 @@ import fr.acinq.bitcoin.utils.Either * outer threshold = the proposal's T * groups = the proposal's group npubs, sorted bytewise; groupId = index * share_epoch = 1 - * threshold = the group's sealed threshold - * roles = the group's sealed admins, sorted bytewise; adminId = index + * threshold = the group's threshold, from its acceptance (the proposer's, from its proposal) + * roles = the group's admins, the same way, sorted bytewise; adminId = index * entity_id = the admin's nostr pubkey * host key = this role's, from the ceremony - * attestation_ref = TaggedHash(ATTESTATION_TAG, proposal id ‖ acceptance ids in groupId order) + * attestation_ref = ConfederationAttestation.attestationRef: the proposal's id, then each group's + * acceptance id in groupId order, the proposal's own id for the proposer * ``` * * Upstream offers no builder, only [ConfederationRoster.fromData] over canonical bytes, so this @@ -37,7 +39,6 @@ import fr.acinq.bitcoin.utils.Either */ object ConfederationRosterBuilder { /** Protocol tags, spelled the house way: hash inputs, not brand strings. */ - const val ATTESTATION_TAG = "mantra/confederation/attestation/v1" const val HOST_KEY_TAG = "mantra/confederation/host-key/v1" private val MAGIC = "CRPD".encodeToByteArray() @@ -49,10 +50,10 @@ object ConfederationRosterBuilder { /** * Everything about the roster but the host keys, which only the ceremony brings. Built by - * [plan] from the proposal and the opened acceptances, by every participant on their own. + * [plan] from the proposal and the acceptances, by every participant on their own. */ class Plan internal constructor( - val proposal: ConfederationProposalEvent.Proposal, + val proposal: ConfederationStatements.Proposal, /** The groups in roster order: sorted bytewise, so groupId is the index. */ val groups: List, val adminLists: Map, @@ -115,16 +116,16 @@ object ConfederationRosterBuilder { ) } - /** Why a roster cannot be planned: something the coordinator or a group got wrong. */ + /** Why a roster cannot be planned: something a group got wrong. */ class Refused(val reason: String) /** - * The roster's plan from [proposal], each group's opened [adminLists] and the ids of the - * [acceptanceIds] they came from. Refused rather than repaired: every participant runs this + * The roster's plan from [proposal], each group's [adminLists] and the ids of the + * [acceptanceIds] they came from (the proposal's own, for the proposer). Refused rather than repaired: every participant runs this * on their own, and one that quietly fixed something would disagree with one that did not. */ fun plan( - proposal: ConfederationProposalEvent.Proposal, + proposal: ConfederationStatements.Proposal, adminLists: Map, acceptanceIds: Map, ): Either { @@ -147,18 +148,11 @@ object ConfederationRosterBuilder { groups = groups, adminLists = adminLists, acceptanceIds = acceptanceIds.filterKeys { it in groups }, - attestationRef = attestationRef(proposal.id, groups.map { acceptanceIds.getValue(it) }), + attestationRef = ConfederationAttestation.attestationRef(proposal.id, groups.map { acceptanceIds.getValue(it) }), ) ) } - /** What the roster says it was made from: the proposal and every acceptance, in groupId order. */ - fun attestationRef(proposalId: HexKey, acceptanceIdsInGroupOrder: List): ByteVector32 = - Crypto.taggedHash( - (listOf(proposalId) + acceptanceIdsInGroupOrder).fold(ByteArray(0)) { acc, id -> acc + id.hexToByteArray() }, - ATTESTATION_TAG, - ) - /** * The host secret key for one role: derived from the member's own nostr secret, so a role's * recovery package reopens from that member's backup and nobody else's, as a ChillDKG share diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationSeal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationSeal.kt deleted file mode 100644 index 4b9b0cc6..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationSeal.kt +++ /dev/null @@ -1,77 +0,0 @@ -package mobi.giza.compose.nostr.confederation - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip44Encryption.Nip44v2 -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.PrivateKey -import mobi.giza.compose.extensions.toHex - -/** - * Sealing a group's admin list so that only the coordinator can read it, and so that every member - * of the group can check the seal holds what the group agreed to (docs/confederation.md, D5). - * - * Nobody holds a group's secret key, so the seal cannot be NIP-44 *from* the group. It is from an - * ephemeral secret `e` that the member proposing the acceptance chooses and hands to the group - * inside its own encryption ([mobi.giza.compose.nostr.confederation.tags.ConfederationSealTag]). - * With `e` fixed, and the nonce derived from it, NIP-44 v2 is a function: the same list seals to - * the same bytes on every device, and a member who sees a different admin list in the group - * gets different bytes and declines. - * - * The coordinator opens it with `ECDH(coordinator secret, E)`. Any member of the group could - * too, since they were given `e` -- and they already know the list. Nobody else can. - */ -object ConfederationSeal { - /** A protocol tag, spelled the house way: a hash input, not a brand. */ - const val NONCE_TAG = "mantra/confederation/seal-nonce/v1" - - private val nip44 = Nip44v2() - - data class Sealed(val content: String, val ephemeralPublicKey: HexKey) - - /** `E = e·G`, x-only, as it goes in the acceptance's `epk` tag. */ - fun ephemeralPublicKey(ephemeralSecret: ByteArray): HexKey = - PrivateKey(ephemeralSecret).publicKey().xOnly().value.toHex() - - /** The NIP-44 nonce: bound to `e` and to the proposal, so one `e` never seals twice under one nonce for two proposals. */ - fun nonce(ephemeralSecret: ByteArray, proposalId: HexKey): ByteArray = - Crypto.taggedHash(ephemeralSecret + proposalId.hexToByteArray(), NONCE_TAG).toByteArray() - - fun seal(ephemeralSecret: ByteArray, coordinator: HexKey, adminList: ConfederationAdminList): Sealed { - val conversationKey = nip44.computeConversationKey(ephemeralSecret, coordinator.hexToByteArray()) - val content = nip44.encryptWithNonce( - adminList.encode(), - conversationKey, - nonce(ephemeralSecret, adminList.proposalId), - ).encodePayload() - return Sealed(content = content, ephemeralPublicKey = ephemeralPublicKey(ephemeralSecret)) - } - - /** - * Whether [content] and [ephemeralPublicKey] are exactly what sealing [expected] to - * [coordinator] under [ephemeralSecret] gives. What every signer of an acceptance checks. - */ - fun reproduces( - ephemeralSecret: ByteArray, - coordinator: HexKey, - expected: ConfederationAdminList, - content: String, - ephemeralPublicKey: HexKey, - ): Boolean = runCatching { - val sealed = seal(ephemeralSecret, coordinator, expected) - sealed.content == content && sealed.ephemeralPublicKey == ephemeralPublicKey - }.getOrDefault(false) - - /** - * The conversation key one acceptance was sealed under, as the coordinator computes it. It - * opens that acceptance and nothing else, which is why the coordinator can hand it to the - * ceremony's participants (D7). - */ - fun conversationKey(coordinatorSecret: ByteArray, ephemeralPublicKey: HexKey): ByteArray = - nip44.computeConversationKey(coordinatorSecret, ephemeralPublicKey.hexToByteArray()) - - /** The admin list sealed in [content], or null if [conversationKey] does not open it or it is not one. */ - fun open(conversationKey: ByteArray, content: String): ConfederationAdminList? = runCatching { - ConfederationAdminList.decode(nip44.decrypt(content, conversationKey)) - }.getOrNull() -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationStatements.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationStatements.kt index 170e63fc..26677d0e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationStatements.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationStatements.kt @@ -128,8 +128,9 @@ object ConfederationStatements { fun rejection(group: HexKey, proposal: Proposal, reason: String, createdAt: Long): Event = answer(group, ConfederationKinds.REJECTION, proposal, reason, createdAt) - fun withdrawal(proposal: Proposal, reason: String, createdAt: Long): Event = - answer(proposal.proposingGroup, ConfederationKinds.WITHDRAWAL, proposal, reason, createdAt) + /** [group] taking [proposal] back: only the proposing group's counts, and only its signers sign one. */ + fun withdrawal(group: HexKey, proposal: Proposal, reason: String, createdAt: Long): Event = + answer(group, ConfederationKinds.WITHDRAWAL, proposal, reason, createdAt) private fun answer(group: HexKey, kind: Kind, proposal: Proposal, content: String, createdAt: Long): Event { val tags = proposal.othersThan(group).map { arrayOf("p", it) } + listOf(arrayOf("e", proposal.id)) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationStatus.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationStatus.kt index 242fb74b..75d816d9 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationStatus.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/ConfederationStatus.kt @@ -2,41 +2,43 @@ package mobi.giza.compose.nostr.confederation import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey -import mobi.giza.compose.nostr.confederation.ConfederationProposalAcceptanceEvent.Acceptance -import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent.Proposal +import mobi.giza.compose.nostr.confederation.ConfederationStatements.Answer +import mobi.giza.compose.nostr.confederation.ConfederationStatements.Proposal /** Where a proposal stands (docs/confederation.md, D8). Part B adds the ceremony's states. */ enum class ConfederationProposalState { OPEN, ACCEPTED, REJECTED, EXPIRED, WITHDRAWN } -/** One group's answer to a proposal, as far as the events a device holds say. */ +/** One group's answer to a proposal, as far as the statements a device holds say. */ enum class ConfederationAnswer { WAITING, ACCEPTED, REJECTED } /** - * A proposal's state, computed from the events a device holds -- never stored, so every device - * holding the same events agrees (D8). + * A proposal's state, computed from the statements a device holds -- never stored, so every + * device holding the same statements agrees (docs/confederation.md, D8). * * The rules, in the order they are applied: * - * 1. Only answers that reference the proposal by id, come from a group it lists, and are - * addressed as [ConfederationProposalAcceptanceEvent.answers] requires are counted. A - * withdrawal counts only from the proposing group. - * 2. An answer counts only if it was made by the proposal's expiry -- its own `created_at` -- - * so whether a proposal was accepted in time is a fact about the events, not about when this - * device heard of them. - * 3. Any rejection: **REJECTED**. A group with both an acceptance and a rejection has rejected: + * 1. The proposing group has accepted by proposing: a proposal carries its proposer's admins + * (docs/confederation-without-coordinator.md, D4). + * 2. Only answers that name the proposal, come from a group it lists, and are addressed to every + * other group it lists ([Answer.answers]) are counted. A withdrawal counts only from the + * proposing group. + * 3. An answer counts only if it was made by the proposal's expiry -- its own `created_at`, which + * the group's quorum signed the seal around -- so whether a proposal was accepted in time is a + * fact about the statements, not about when this device heard of them. + * 4. Any rejection: **REJECTED**. A group with both an acceptance and a rejection has rejected: * answers are final, and of two contradictory ones the safe one wins. - * 4. A withdrawal: **WITHDRAWN**. - * 5. Every listed group accepted: **ACCEPTED**. - * 6. Past the expiry: **EXPIRED**. Otherwise **OPEN**. + * 5. A withdrawal: **WITHDRAWN**. + * 6. Every listed group accepted: **ACCEPTED**. + * 7. Past the expiry: **EXPIRED**. Otherwise **OPEN**. * - * Signatures are not checked here. Every event reaching this was checked when it was stored. + * Seals are not checked here. Every statement reaching this was checked when it was filed. */ data class ConfederationStatus( val proposal: Proposal, val state: ConfederationProposalState, val answers: Map, - /** Each accepting group's acceptance: the earliest, ties broken by id, if it gave more than one. */ - val acceptances: Map, + /** Each accepting group other than the proposer's: the earliest acceptance, ties broken by id. */ + val acceptances: Map, ) { val waitingOn: List get() = proposal.groupPublicKeys.filter { answers[it] == ConfederationAnswer.WAITING } @@ -45,27 +47,39 @@ data class ConfederationStatus( fun hasAnswered(group: HexKey): Boolean = answerOf(group) != ConfederationAnswer.WAITING + /** Every accepting group's admins: the proposer's from its proposal, the others' from their acceptances. */ + val adminLists: Map + get() = buildMap { + if (answerOf(proposal.proposingGroup) == ConfederationAnswer.ACCEPTED) put(proposal.proposingGroup, proposal.proposerAdmins) + acceptances.forEach { (group, answer) -> answer.admins?.let { put(group, it) } } + } + + /** The statement each accepting group's admins came from: the proposal itself, for the proposer. */ + val acceptanceIds: Map + get() = buildMap { + if (answerOf(proposal.proposingGroup) == ConfederationAnswer.ACCEPTED) put(proposal.proposingGroup, proposal.id) + acceptances.forEach { (group, answer) -> put(group, answer.id) } + } + companion object { - fun of(proposal: Proposal, events: Collection, now: Long): ConfederationStatus { - val inTime = events.filter { it.createdAt <= proposal.expiresAt } + /** [proposal]'s state from the answer rumors [statements] a device holds; anything else among them is ignored. */ + fun of(proposal: Proposal, statements: Collection, now: Long): ConfederationStatus { + val inTime = statements.filter { it.createdAt <= proposal.expiresAt } + .mapNotNull(ConfederationStatements::parseAnswer) + .filter { it.answers(proposal) } - val acceptances = inTime.mapNotNull(ConfederationProposalAcceptanceEvent::parse) - .filter { ConfederationProposalAcceptanceEvent.answers(it, proposal) } + val acceptances = inTime.filter { it.isAcceptance && it.group != proposal.proposingGroup } .groupBy { it.group } - .mapValues { (_, all) -> all.minWith(compareBy { it.createdAt }.thenBy { it.id }) } + .mapValues { (_, all) -> all.minWith(compareBy { it.createdAt }.thenBy { it.id }) } - val rejecting = inTime.mapNotNull(ConfederationProposalRejectionEvent::parse) - .filter { it.proposalId == proposal.id && proposal.lists(it.group) } - .map { it.group } - .toSet() + val rejecting = inTime.filter { it.kind == ConfederationKinds.REJECTION }.map { it.group }.toSet() - val withdrawn = inTime.mapNotNull(ConfederationProposalWithdrawalEvent::parse) - .any { it.proposalId == proposal.id && it.group == proposal.proposingGroup } + val withdrawn = inTime.any { it.kind == ConfederationKinds.WITHDRAWAL && it.group == proposal.proposingGroup } val answers = proposal.groupPublicKeys.associateWith { group -> when { group in rejecting -> ConfederationAnswer.REJECTED - group in acceptances -> ConfederationAnswer.ACCEPTED + group == proposal.proposingGroup || group in acceptances -> ConfederationAnswer.ACCEPTED else -> ConfederationAnswer.WAITING } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/tags/ConfederationCarriedProposalTag.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/tags/ConfederationCarriedProposalTag.kt deleted file mode 100644 index 90b3fd61..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/tags/ConfederationCarriedProposalTag.kt +++ /dev/null @@ -1,34 +0,0 @@ -package mobi.giza.compose.nostr.confederation.tags - -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.utils.ensure - -/** - * The signed proposal a group is being asked to answer, riding the FROST signing proposal for - * the answer (docs/confederation.md, Phase 3). - * - * A signer checks an answer against the proposal it answers, and could otherwise do that only - * if its relays had already delivered the proposal. Carrying it removes that dependence. It is - * a signed event, so carrying it costs no trust: the signer verifies it against its author like - * any copy from a relay, and files it as one. - */ -class ConfederationCarriedProposalTag( - val proposalJson: String, -) { - fun toTagArray() = assemble(proposalJson) - - companion object { - const val TAG_NAME = "confederation_proposal" - - fun parse(tag: Array): ConfederationCarriedProposalTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - return ConfederationCarriedProposalTag(tag[1].ifBlank { return null }) - } - - fun assemble(proposalJson: String): Array = arrayOf(TAG_NAME, proposalJson) - - /** The first such tag's value among [tags], or null. */ - fun valueIn(tags: Array>): String? = tags.firstNotNullOfOrNull(::parse)?.proposalJson - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/tags/ConfederationCoordinatorTag.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/tags/ConfederationCoordinatorTag.kt deleted file mode 100644 index bb5ceae8..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/tags/ConfederationCoordinatorTag.kt +++ /dev/null @@ -1,33 +0,0 @@ -package mobi.giza.compose.nostr.confederation.tags - -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.utils.ensure - -/** - * The member who proposed a confederation, and who will coordinate its key ceremony. - * - * A person's pubkey, not a group's. Every signer checks it is the signing session's proposer - * and one of the proposing group's current admins (docs/confederation.md, D4), so a member can - * neither volunteer somebody else nor be volunteered. It is also the only key the acceptances' - * sealed admin lists open with (D5). - */ -class ConfederationCoordinatorTag( - val coordinatorPublicKey: String, -) { - fun toTagArray() = assemble(coordinatorPublicKey) - - companion object { - const val TAG_NAME = "coordinator" - - fun parse(tag: Array): ConfederationCoordinatorTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - return ConfederationCoordinatorTag(tag[1].ifBlank { return null }) - } - - fun assemble(coordinatorPublicKey: String): Array = arrayOf(TAG_NAME, coordinatorPublicKey) - - /** The first such tag's value among [tags], or null. */ - fun valueIn(tags: Array>): String? = tags.firstNotNullOfOrNull(::parse)?.coordinatorPublicKey - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/tags/ConfederationEphemeralKeyTag.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/tags/ConfederationEphemeralKeyTag.kt deleted file mode 100644 index f411ca03..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/tags/ConfederationEphemeralKeyTag.kt +++ /dev/null @@ -1,33 +0,0 @@ -package mobi.giza.compose.nostr.confederation.tags - -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.utils.ensure - -/** - * The ephemeral public key `E = e·G` an acceptance's admin list is sealed under - * (docs/confederation.md, D5). - * - * Nobody holds a group's secret key, so the seal cannot be from the group: it is from `e`, which - * the acceptance's proposer chose and every signer was given inside the group's encryption. The - * coordinator opens the seal with `ECDH(coordinator secret, E)`. - */ -class ConfederationEphemeralKeyTag( - val ephemeralPublicKey: String, -) { - fun toTagArray() = assemble(ephemeralPublicKey) - - companion object { - const val TAG_NAME = "epk" - - fun parse(tag: Array): ConfederationEphemeralKeyTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - return ConfederationEphemeralKeyTag(tag[1].ifBlank { return null }) - } - - fun assemble(ephemeralPublicKey: String): Array = arrayOf(TAG_NAME, ephemeralPublicKey) - - /** The first such tag's value among [tags], or null. */ - fun valueIn(tags: Array>): String? = tags.firstNotNullOfOrNull(::parse)?.ephemeralPublicKey - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/tags/ConfederationSealTag.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/tags/ConfederationSealTag.kt deleted file mode 100644 index f74e2c71..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/confederation/tags/ConfederationSealTag.kt +++ /dev/null @@ -1,34 +0,0 @@ -package mobi.giza.compose.nostr.confederation.tags - -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.utils.ensure - -/** - * The ephemeral secret `e` behind an acceptance's seal, riding the FROST signing proposal that - * asks the group to sign the acceptance (docs/confederation.md, D5). - * - * That proposal is a rumor inside the group's own encryption -- an MLS message, or gift wraps to - * each member -- so only the group's members ever see `e`. Each of them reseals the admin list - * they see in the group with it and checks the result is the acceptance's content byte for - * byte. It never goes on the signed acceptance itself, which is public. - */ -class ConfederationSealTag( - val ephemeralSecret: String, -) { - fun toTagArray() = assemble(ephemeralSecret) - - companion object { - const val TAG_NAME = "confederation_seal" - - fun parse(tag: Array): ConfederationSealTag? { - ensure(tag.has(1)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - return ConfederationSealTag(tag[1].ifBlank { return null }) - } - - fun assemble(ephemeralSecret: String): Array = arrayOf(TAG_NAME, ephemeralSecret) - - /** The first such tag's value among [tags], or null. */ - fun valueIn(tags: Array>): String? = tags.firstNotNullOfOrNull(::parse)?.ephemeralSecret - } -} 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 b7abbc20..3c23f294 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt @@ -15,7 +15,6 @@ import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder 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.ConfederationProposalEvent import mobi.giza.compose.nostr.confederation.ConfederationStatus /** @@ -23,27 +22,21 @@ import mobi.giza.compose.nostr.confederation.ConfederationStatus * (docs/confederation.md). */ interface ConfederationRepository { - /** Files [event] if it is a confederation event its author signed. Whether it was new. */ + /** Files [event] if it is a confederation's charter its author signed: the one confederation event heard on relays. Whether it was new. */ suspend fun record(event: Event): Boolean - /** Events this device signed for and still owes to relays (D9). */ + /** Charters this device's confederation signing proposed and still owes to relays. */ fun observeUnpublished(): Flow> suspend fun markPublished(eventId: HexKey, at: Instant) - /** The proposals not yet past their expiry, by id: what the relay filter asks for answers to. */ - fun observeOpenProposalIds(): Flow> - - /** Where to send an event about [proposalId]: the relays the proposal hints at for its groups. */ - suspend fun relayHintsFor(proposalId: HexKey): List - /** Every proposal naming the group [groupPublicKey], newest first, with where each stands. */ fun observeStatusesNaming(groupPublicKey: HexKey): Flow> /** Where [proposalId] stands, as it changes. Null while this device does not hold it. */ fun observeStatus(proposalId: HexKey): Flow - /** Whether [userPublicKey] is one of [chatRoomId]'s current admins, and so may coordinate (D4). */ + /** Whether [userPublicKey] is one of [chatRoomId]'s current admins, and so may propose its statements. */ suspend fun isAdmin(chatRoomId: String, userPublicKey: HexKey): Boolean /** What an acceptance by [chatRoomId] would disclose, read as its signers will read it. Null when it could not take part. */ @@ -55,7 +48,7 @@ interface ConfederationRepository { suspend fun proposeConfederation( localChatRoom: LocalChatRoom, userPublicKey: HexKey, - invitees: List, + invitees: List, threshold: Int, name: String, expiresAt: Long, @@ -67,7 +60,7 @@ interface ConfederationRepository { suspend fun proposeWithdrawal(localChatRoom: LocalChatRoom, userPublicKey: HexKey, proposalId: HexKey): FrostSigningSession - /** What the coordinator's device can say once every group has accepted, or null on any other device. */ + /** What every admin's device can say once every group has accepted (docs/confederation-without-coordinator.md, D7). */ suspend fun outcome(proposalId: HexKey): ConfederationManager.Outcome? /** A signing session this room has open over an answer to [proposalId], if any: one at a time. */ @@ -78,13 +71,15 @@ interface ConfederationRepository { fun observeCeremonyMessages(sessionId: String): Flow> - /** The roster's plan a ceremony runs over, or null if its opening no longer reads. */ + /** The roster's plan a ceremony runs over, or null if its basis no longer reads. */ fun ceremonyPlan(ceremony: ConfederationCeremony): ConfederationRosterBuilder.Plan? - /** Opens the key ceremony, on the coordinator's device, once every group has accepted. */ - suspend fun openCeremony(proposalId: HexKey): ConfederationCeremony - - suspend fun joinCeremony(sessionId: String) + /** + * Joins the key ceremony for [proposalId], once every group has accepted: what every admin of + * every group is offered, nobody opening it first. After a failed attempt it joins the next + * (docs/confederation-without-coordinator.md, D8 and D10). + */ + suspend fun joinCeremony(proposalId: HexKey): ConfederationCeremony suspend fun abandonCeremony(sessionId: String) @@ -109,8 +104,6 @@ interface ConfederationRepository { override suspend fun record(event: Event): Boolean = false override fun observeUnpublished(): Flow> = flowOf(emptyList()) override suspend fun markPublished(eventId: HexKey, at: Instant) = Unit - override fun observeOpenProposalIds(): Flow> = flowOf(emptyList()) - override suspend fun relayHintsFor(proposalId: HexKey): List = emptyList() override fun observeStatusesNaming(groupPublicKey: HexKey): Flow> = flowOf(emptyList()) override fun observeStatus(proposalId: HexKey): Flow = flowOf(null) override suspend fun isAdmin(chatRoomId: String, userPublicKey: HexKey): Boolean = false @@ -119,7 +112,7 @@ interface ConfederationRepository { override suspend fun proposeConfederation( localChatRoom: LocalChatRoom, userPublicKey: HexKey, - invitees: List, + invitees: List, threshold: Int, name: String, expiresAt: Long, @@ -135,9 +128,8 @@ interface ConfederationRepository { override fun observeCeremony(proposalId: HexKey): Flow = flowOf(null) override fun observeCeremonyMessages(sessionId: String): Flow> = flowOf(emptyList()) override fun ceremonyPlan(ceremony: ConfederationCeremony): ConfederationRosterBuilder.Plan? = null - override suspend fun openCeremony(proposalId: HexKey): ConfederationCeremony = + override suspend fun joinCeremony(proposalId: HexKey): ConfederationCeremony = throw UnsupportedOperationException("No confederation here") - override suspend fun joinCeremony(sessionId: String) = Unit override suspend fun abandonCeremony(sessionId: String) = Unit override fun observeConfederationsOf(groupPublicKey: HexKey): Flow> = flowOf(emptyList()) override fun observeSigningAttempt(attemptId: String): Flow = flowOf(null) 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 1eabdb19..10f1a59c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt @@ -6,7 +6,7 @@ import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import mobi.giza.compose.nostr.confederation.ConfederationCharterEvent import mobi.giza.compose.nostr.confederation.ConfederationKinds -import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent +import mobi.giza.compose.nostr.confederation.ConfederationStatements import mobi.giza.compose.managers.SharedKeyDerivation import mobi.giza.compose.managers.WalletRefusal import mobi.giza.compose.nostr.RetiredKinds @@ -143,10 +143,11 @@ object ProposedEvent { TextNoteEvent.KIND -> Summary(label = "Post", detail = event.content) // The confederation's (docs/confederation.md): what the group would be joining, - // with whom and on what terms, rather than a number and a ciphertext. An - // acceptance's content is sealed to the coordinator, so its summary says what - // the seal discloses instead of showing it. - ConfederationKinds.PROPOSAL -> ConfederationProposalEvent.parse(event)?.let { proposal -> + // with whom and on what terms, rather than a number. Giza says these to the other + // groups' inboxes, sealed, and declines them as public events + // (docs/confederation-without-coordinator.md, D6); a peer that proposes one still + // reads as what it is. + ConfederationKinds.PROPOSAL -> ConfederationStatements.parseProposal(event)?.let { proposal -> Summary( label = "A confederation, ${proposal.name}", detail = "Proposed with ${proposal.groups.size} groups · " + @@ -160,7 +161,7 @@ object ProposedEvent { ConfederationKinds.ACCEPTANCE -> Summary( label = "Accepting a confederation", - detail = "Discloses this group's admins and threshold to the coordinator", + detail = "Shows this group's admins and threshold to the other groups", ) ConfederationKinds.REJECTION -> Summary(label = "Declining a confederation", detail = event.content) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationProposalScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationProposalScreen.kt index 04bab0c4..cd656c1d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationProposalScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationProposalScreen.kt @@ -50,11 +50,10 @@ import mobi.giza.compose.resources.confederation_groups import mobi.giza.compose.resources.confederation_groups_to_act import mobi.giza.compose.resources.confederation_proposal import mobi.giza.compose.resources.confederation_proposed_by -import mobi.giza.compose.resources.coordinated_by import mobi.giza.compose.resources.every_group_accepted_admins_across_groups import mobi.giza.compose.resources.key_ceremony -import mobi.giza.compose.resources.open_the_key_ceremony -import mobi.giza.compose.resources.could_not_open_the_key_ceremony +import mobi.giza.compose.resources.join_the_key_ceremony +import mobi.giza.compose.resources.could_not_join_the_key_ceremony import mobi.giza.compose.resources.could_not_ask_the_group_to_answer import mobi.giza.compose.resources.open_the_signing_session import mobi.giza.compose.resources.open_until @@ -117,7 +116,7 @@ fun ConfederationProposalScreen( val notify = rememberNotifier(rememberCoroutineScope()) val couldNotAnswer = stringResource(Res.string.could_not_ask_the_group_to_answer) - val couldNotOpenCeremony = stringResource(Res.string.could_not_open_the_key_ceremony) + val couldNotJoinCeremony = stringResource(Res.string.could_not_join_the_key_ceremony) val identityCanSign = LocalCanSign.current val reasonField = rememberTextFieldState() val state by viewModel.uiState.collectAsState() @@ -158,7 +157,6 @@ fun ConfederationProposalScreen( Text(text = proposal.name, style = MaterialTheme.typography.headlineSmall) Text(text = stateLabel(current.status.state), style = MaterialTheme.typography.labelLarge) Text(text = stringResource(Res.string.confederation_proposed_by, nameOf(proposal.proposingGroup))) - Text(text = stringResource(Res.string.coordinated_by, nameOf(proposal.coordinator))) Text(text = stringResource(Res.string.confederation_groups_to_act, proposal.threshold, proposal.groups.size)) Text( text = stringResource(Res.string.open_until, Instant.fromEpochSeconds(proposal.expiresAt).toFormattedTimeAndDateString()), @@ -196,8 +194,9 @@ fun ConfederationProposalScreen( ) } - // The coordinator's end of Part A: each group's admins opened, and - // what stands between them and a key ceremony. docs/confederation.md, Phase 8. + // Once every group has accepted: what every admin's device can say about + // forming it, and the join each of them is offered, nobody opening it first. + // docs/confederation-without-coordinator.md, D7 and D8. current.outcome?.let { outcome -> HorizontalDivider() Text( @@ -210,17 +209,17 @@ fun ConfederationProposalScreen( outcome.notes.forEach { note -> Text(text = note, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } - if (outcome.ready && current.ceremony == null && identityCanSign) { + if (outcome.ready && current.holdsRole && current.ceremony == null && identityCanSign) { Button( modifier = Modifier.fillMaxWidth(), enabled = !current.isActing, onClick = { - viewModel.openCeremony( + viewModel.joinCeremony( onSuccess = { onNavigateToRoute(ConfederationRitualRoute(activeUserPublicKey, proposalId)) }, - onFailure = { notify(couldNotOpenCeremony) }, + onFailure = { notify(couldNotJoinCeremony) }, ) }, - ) { Text(stringResource(Res.string.open_the_key_ceremony)) } + ) { Text(stringResource(Res.string.join_the_key_ceremony)) } } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationRitualScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationRitualScreen.kt index ff1acfaf..b6cf7ee0 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationRitualScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationRitualScreen.kt @@ -34,7 +34,6 @@ import mobi.giza.compose.repository.ConfederationRepository import mobi.giza.compose.resources.Res import mobi.giza.compose.resources.abandon_the_key_ceremony import mobi.giza.compose.resources.ceremony_step_authorizations -import mobi.giza.compose.resources.ceremony_step_combined import mobi.giza.compose.resources.ceremony_step_contributions import mobi.giza.compose.resources.ceremony_step_done import mobi.giza.compose.resources.ceremony_step_host_keys @@ -183,7 +182,6 @@ private fun stepLabel(kind: StepKind): String = stringResource( when (kind) { StepKind.HOST_KEYS -> Res.string.ceremony_step_host_keys StepKind.CONTRIBUTIONS -> Res.string.ceremony_step_contributions - StepKind.COMBINED -> Res.string.ceremony_step_combined StepKind.AUTHORIZATIONS -> Res.string.ceremony_step_authorizations StepKind.SHARES_STORED -> Res.string.ceremony_step_shares_stored } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProposeConfederationScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProposeConfederationScreen.kt index ebeed1dd..cf01067f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProposeConfederationScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProposeConfederationScreen.kt @@ -70,7 +70,7 @@ import mobi.giza.compose.resources.that_is_not_an_npub import mobi.giza.compose.resources.this_group_cannot_take_part_in_a_confederation import mobi.giza.compose.resources.this_group_discloses_its_admins import mobi.giza.compose.resources.this_group_has_no_public_profile -import mobi.giza.compose.resources.you_will_coordinate_the_confederation +import mobi.giza.compose.resources.proposing_shows_admins_to_the_groups 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 @@ -183,7 +183,7 @@ fun ProposeConfederationScreen( verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), ) { Text( - text = stringResource(Res.string.you_will_coordinate_the_confederation), + text = stringResource(Res.string.proposing_shows_admins_to_the_groups), style = MaterialTheme.typography.bodyMedium, ) if (!current.isAdmin) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationProposalViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationProposalViewModel.kt index b65ac703..73b8a1e3 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationProposalViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationProposalViewModel.kt @@ -57,7 +57,7 @@ class ConfederationProposalViewModel( state.value = ConfederationProposalUIState.NotHeld return@collect } - val keys = status.proposal.groupPublicKeys + status.proposal.coordinator + val keys = status.proposal.groupPublicKeys val names = keys.associateWith { confederationRepository.nameOf(it, chatRoomId) } val acting = (state.value as? ConfederationProposalUIState.Loaded)?.isActing == true state.value = ConfederationProposalUIState.Loaded( @@ -72,6 +72,7 @@ class ConfederationProposalViewModel( } else { null }, + holdsRole = status.adminLists.values.any { activeUserPublicKey in it.admins }, ceremony = ceremony, ) } @@ -86,14 +87,17 @@ class ConfederationProposalViewModel( confederationRepository.proposeRejection(loaded.localChatRoom, activeUserPublicKey, proposalId, reason.trim()) } - /** Opens the key ceremony, on the coordinator's device. docs/confederation.md, Phase 11. */ - fun openCeremony(onSuccess: () -> Unit, onFailure: () -> Unit) { + /** + * Joins the key ceremony, as every admin of every group is offered once every group has + * accepted (docs/confederation-without-coordinator.md, D8). + */ + fun joinCeremony(onSuccess: () -> Unit, onFailure: () -> Unit) { val loaded = state.value as? ConfederationProposalUIState.Loaded ?: return if (loaded.isActing) return state.update { (it as? ConfederationProposalUIState.Loaded)?.copy(isActing = true) ?: it } viewModelScope.launch(Dispatchers.IO) { - val opened = runCatching { confederationRepository.openCeremony(proposalId) } - .onFailure { logger.e("Could not open the key ceremony for $proposalId", it) } + val opened = runCatching { confederationRepository.joinCeremony(proposalId) } + .onFailure { logger.e("Could not join the key ceremony for $proposalId", it) } .isSuccess state.update { (it as? ConfederationProposalUIState.Loaded)?.copy(isActing = false) ?: it } viewModelScope.launch(Dispatchers.Main) { if (opened) onSuccess() else onFailure() } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationRitualViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationRitualViewModel.kt index 3843a6e9..26472520 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationRitualViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationRitualViewModel.kt @@ -19,6 +19,7 @@ import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents +import mobi.giza.compose.database.model.ConfederationCeremony import mobi.giza.compose.repository.ConfederationRepository import mobi.giza.compose.ui.view.state.ConfederationRitualUIState import mobi.giza.compose.ui.view.state.ConfederationRitualUIState.Step @@ -60,7 +61,6 @@ class ConfederationRitualViewModel( val names = (plan.people + plan.groups).associateWith { confederationRepository.nameOf(it) } val sent = { kind: Int -> messages.filter { it.kind == kind }.map { it.senderPublicKey }.toSet() } val waiting = { kind: Int -> plan.people.filterNot { it in sent(kind) }.map { names.getValue(it) } } - val combined = messages.any { it.kind == ConfederationRitualEvents.BROADCAST } val acting = (state.value as? ConfederationRitualUIState.Loaded)?.isActing == true state.value = ConfederationRitualUIState.Loaded( ceremony = ceremony, @@ -73,7 +73,6 @@ class ConfederationRitualViewModel( steps = listOf( Step(StepKind.HOST_KEYS, waiting(ConfederationRitualEvents.HOST_KEYS)), Step(StepKind.CONTRIBUTIONS, waiting(ConfederationRitualEvents.DEALINGS)), - Step(StepKind.COMBINED, if (combined) emptyList() else listOf(names[ceremony.coordinatorPublicKey] ?: ceremony.coordinatorPublicKey.take(8))), Step(StepKind.AUTHORIZATIONS, waiting(ConfederationRitualEvents.AUTHORIZATIONS)), Step(StepKind.SHARES_STORED, waiting(ConfederationRitualEvents.ACKNOWLEDGMENTS)), ), @@ -84,16 +83,17 @@ class ConfederationRitualViewModel( } } - fun join() = act { confederationRepository.joinCeremony(it) } + /** Joins this attempt, or after a failed one joins the next: Try again (docs/confederation-without-coordinator.md, D10). */ + fun join() = act { confederationRepository.joinCeremony(it.proposalId) } - fun abandon() = act { confederationRepository.abandonCeremony(it) } + fun abandon() = act { confederationRepository.abandonCeremony(it.id) } - private fun act(action: suspend (String) -> Unit) { + private fun act(action: suspend (ConfederationCeremony) -> Unit) { val loaded = state.value as? ConfederationRitualUIState.Loaded ?: return if (loaded.isActing) return state.update { (it as? ConfederationRitualUIState.Loaded)?.copy(isActing = true) ?: it } viewModelScope.launch(Dispatchers.IO) { - runCatching { action(loaded.ceremony.id) }.onFailure { logger.e("Ceremony action failed", it) } + runCatching { action(loaded.ceremony) }.onFailure { logger.e("Ceremony action failed", it) } state.update { (it as? ConfederationRitualUIState.Loaded)?.copy(isActing = false) ?: it } } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModel.kt index 1fb5974c..85eca487 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModel.kt @@ -23,7 +23,6 @@ import mobi.giza.compose.database.model.Profile import mobi.giza.compose.identity.CredentialParser import mobi.giza.compose.nostr.DirectMessagePeerSync import mobi.giza.compose.nostr.confederation.ConfederationKinds -import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.ConfederationRepository import mobi.giza.compose.repository.NostrRepository @@ -143,7 +142,7 @@ class ProposeConfederationViewModel( confederationRepository.proposeConfederation( localChatRoom = form.localChatRoom, userPublicKey = activeUserPublicKey, - invitees = form.invitees.map { ConfederationProposalEvent.Invitee(it.publicKey) }, + invitees = form.invitees.map { it.publicKey }, threshold = form.threshold, name = name.trim(), expiresAt = Clock.System.now().epochSeconds + form.expiryDays * SECONDS_PER_DAY, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationProposalUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationProposalUIState.kt index 08d90fed..b62a9302 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationProposalUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationProposalUIState.kt @@ -11,15 +11,17 @@ sealed interface ConfederationProposalUIState { data class Loaded( val localChatRoom: LocalChatRoom, val status: ConfederationStatus, - /** How to name each group on it, and the coordinator. */ + /** How to name each group on it. */ val names: Map = emptyMap(), /** A signing session this group has open over an answer, if any: one at a time. */ val pendingSessionId: String? = null, /** Whether this device can put an answer to the group: an open room and a share. */ val canSign: Boolean = false, val isActing: Boolean = false, - /** On the coordinator's device once every group has accepted: what it can say about forming it. */ + /** Once every group has accepted, on every device: what it can say about forming it. */ val outcome: ConfederationManager.Outcome? = null, + /** Whether this device's owner is an admin of one of the groups, and so holds a role (D8). */ + val holdsRole: Boolean = false, /** The key ceremony this device holds for the proposal, once one is open. */ val ceremony: ConfederationCeremony? = null, ) : ConfederationProposalUIState { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationRitualUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationRitualUIState.kt index 2b3e7481..c870fd14 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationRitualUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationRitualUIState.kt @@ -18,7 +18,7 @@ sealed interface ConfederationRitualUIState { data class GroupRoles(val name: String, val threshold: Int, val admins: List) - enum class StepKind { HOST_KEYS, CONTRIBUTIONS, COMBINED, AUTHORIZATIONS, SHARES_STORED } + enum class StepKind { HOST_KEYS, CONTRIBUTIONS, AUTHORIZATIONS, SHARES_STORED } data class Step(val kind: StepKind, val waitingOn: List) 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 b8427194..471f36db 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt @@ -43,9 +43,10 @@ import mobi.giza.compose.repository.ConfederationRepository import mobi.giza.compose.repository.NostrRepository /** - * The confederation on the wire (docs/confederation.md, Phase 5): what the live subscription - * asks for, where what arrives goes, and the publisher that keeps at an owed event until a - * relay takes it. + * The confederation on the public wire (docs/confederation.md, Phase 5, narrowed by + * docs/confederation-without-coordinator.md, D12): the live subscription asks only for charters, + * what arrives goes to the confederation, and the publisher keeps at an owed charter until a relay + * takes it. A group's statements go between inboxes and are not here. */ @OptIn(ExperimentalCoroutinesApi::class) class ConfederationRelayTest { @@ -60,37 +61,44 @@ class ConfederationRelayTest { // --- the subscription @Test - fun `it asks every public relay for what names our rooms and what answers open proposals`() = runTest { + fun `it asks every public relay for the charters that name our rooms, and nothing else`() = runTest { ExperimentalFeatures.confederationOverride = true val transport = ConfederationLiveTransport() - val repository = FakeConfederationRepository(openIds = listOf("p1")) + val repository = FakeConfederationRepository() val running = start(transport, listOf(room("room-a"), room("dm", mlsGroupState = null)), repository) settle() val opened = transport.opened.filter { it.reqCommand.subId == CONFEDERATION_SUB_ID } assertEquals(Relays.eventPublishRelaySet.map { it.url }.toSet(), opened.map { it.relayUrl }.toSet()) val filters = opened.first().reqCommand.filters + assertEquals(1, filters.size, "no filter for a proposal's answers: they arrive in the inbox") assertEquals(mapOf("p" to listOf("room-a")), filters[0].tags, "a NIP-17 room is never named") - assertEquals(ConfederationKinds.ALL.toList(), filters[0].kinds) - assertEquals(mapOf("e" to listOf("p1")), filters[1].tags) - assertEquals(ConfederationKinds.ANSWERS.toList(), filters[1].kinds) + assertEquals(listOf(ConfederationKinds.CHARTER), filters[0].kinds) running.cancelAndJoin() } @Test - fun `a new proposal widens what it asks for`() = runTest { + fun `a new room widens what it asks for`() = runTest { ExperimentalFeatures.confederationOverride = true val transport = ConfederationLiveTransport() - val repository = FakeConfederationRepository(openIds = emptyList()) - val running = start(transport, listOf(room("room-a")), repository) + val rooms = MutableStateFlow(listOf(room("room-a"))) + val running = launch { + LiveSubscriptionManager( + relaysSocketManager = transport, + nostrRepository = ConfederationRecordingNostr(), + chatRepository = ConfederationRooms(rooms), + isForeground = MutableStateFlow(true), + confederationRepository = FakeConfederationRepository(), + ).observe(keyPair) + } settle() - repository.openIds.value = listOf("p2") + rooms.value = listOf(room("room-a"), room("room-b")) settle() val latest = transport.opened.last { it.reqCommand.subId == CONFEDERATION_SUB_ID } - assertEquals(mapOf("e" to listOf("p2")), latest.reqCommand.filters[1].tags) + assertEquals(mapOf("p" to listOf("room-a", "room-b")), latest.reqCommand.filters[0].tags) running.cancelAndJoin() } @@ -99,7 +107,7 @@ class ConfederationRelayTest { fun `what arrives is filed as the confederation's, never as a nostr event`() = runTest { ExperimentalFeatures.confederationOverride = true val transport = ConfederationLiveTransport() - val repository = FakeConfederationRepository(openIds = emptyList()) + val repository = FakeConfederationRepository() val nostr = ConfederationRecordingNostr() val running = start(transport, listOf(room("room-a")), repository, nostr) settle() @@ -120,7 +128,7 @@ class ConfederationRelayTest { fun `with the feature off it asks for nothing`() = runTest { ExperimentalFeatures.confederationOverride = false val transport = ConfederationLiveTransport() - val running = start(transport, listOf(room("room-a")), FakeConfederationRepository(openIds = listOf("p1"))) + val running = start(transport, listOf(room("room-a")), FakeConfederationRepository()) settle() assertTrue(transport.opened.none { it.reqCommand.subId == CONFEDERATION_SUB_ID }) @@ -131,8 +139,8 @@ class ConfederationRelayTest { // --- the publisher @Test - fun `an owed event goes to the publish set and the proposal's hints, and is marked once a relay takes it`() = runTest { - val repository = FakeConfederationRepository(openIds = emptyList(), hints = listOf("wss://hint.example")) + fun `an owed charter goes to the publish set, and is marked once a relay takes it`() = runTest { + val repository = FakeConfederationRepository() repository.owed.value = listOf(owed("ev-1")) val transport = ConfederationFakePublisher(accept = true) @@ -140,7 +148,6 @@ class ConfederationRelayTest { settle() val asked = transport.asked.single() - assertTrue("wss://hint.example" in asked.second) assertTrue(Relays.eventPublishRelaySet.map { it.url }.all { it in asked.second }) assertEquals(listOf("ev-1"), repository.published) @@ -149,7 +156,7 @@ class ConfederationRelayTest { @Test fun `an event no relay takes is tried again, later`() = runTest { - val repository = FakeConfederationRepository(openIds = emptyList()) + val repository = FakeConfederationRepository() repository.owed.value = listOf(owed("ev-1")) val transport = ConfederationFakePublisher(accept = false) @@ -196,13 +203,13 @@ class ConfederationRelayTest { private fun wire(id: String) = NostrEvent( id = id, pubKey = "a".repeat(64), createdAt = Instant.fromEpochSeconds(1_000), - kind = ConfederationKinds.PROPOSAL, tags = emptyArray(), content = "", sig = "", + kind = ConfederationKinds.CHARTER, tags = emptyArray(), content = "", sig = "", ) private fun owed(id: String) = ConfederationEvent( - id = id, kind = ConfederationKinds.ACCEPTANCE, pubKey = "a".repeat(64), proposalId = "p1", + id = id, kind = ConfederationKinds.CHARTER, pubKey = "a".repeat(64), proposalId = id, eventCreatedAt = 1_000, - eventJson = Event(id, "a".repeat(64), 1_000, ConfederationKinds.ACCEPTANCE, emptyArray(), "", "").toJson(), + eventJson = Event(id, "a".repeat(64), 1_000, ConfederationKinds.CHARTER, emptyArray(), "", "").toJson(), ownSessionId = "s1", ) } @@ -242,11 +249,7 @@ private class ConfederationFakePublisher(var accept: Boolean) : EventPublishTran } } -private class FakeConfederationRepository( - openIds: List, - private val hints: List = emptyList(), -) : ConfederationRepository by ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY { - val openIds = MutableStateFlow(openIds) +private class FakeConfederationRepository : ConfederationRepository by ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY { val owed = MutableStateFlow>(emptyList()) val recorded = mutableListOf() val published = mutableListOf() @@ -261,9 +264,6 @@ private class FakeConfederationRepository( published += eventId owed.value = owed.value.filterNot { it.id == eventId } } - - override fun observeOpenProposalIds(): Flow> = openIds - override suspend fun relayHintsFor(proposalId: HexKey): List = hints } private class ConfederationRooms(private val rooms: StateFlow>) : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationEventsTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationEventsTest.kt deleted file mode 100644 index a6f1fdd8..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationEventsTest.kt +++ /dev/null @@ -1,279 +0,0 @@ -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.core.hexToByteArray -import com.vitorpamplona.quartz.nip44Encryption.Nip44v2 -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 -import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent.Invitee - -/** The confederation's wire format, read and written (docs/confederation.md, Phase 2). */ -class ConfederationEventsTest { - private fun key(n: Int): PrivateKey = PrivateKey(ByteArray(32).also { it[31] = n.toByte(); it[0] = 0x11 }) - private fun npub(n: Int): HexKey = key(n).publicKey().xOnly().value.toHex() - - private val agora = npub(1) - private val polis = npub(2) - private val ekklesia = npub(3) - private val coordinator = key(9) - private val coordinatorPub = npub(9) - private val admins = listOf(npub(21), npub(22), npub(23)) - - private val createdAt = 1_790_000_000L - private val expiresAt = createdAt + ConfederationKinds.DEFAULT_EXPIRY_SECONDS - - private fun event(kind: Kind, author: HexKey, tags: Array>, content: String = "", id: String = "1".repeat(64), at: Long = createdAt) = - Event(id, author, at, kind, tags, content, "") - - private fun proposalTags( - groups: List = listOf(agora, polis, ekklesia), - threshold: Int = 2, - nonce: String = "ab".repeat(32), - ) = ConfederationProposalEvent.assembleTags( - groups = groups.map { Invitee(it, "wss://relay.example") }, - coordinator = coordinatorPub, - threshold = threshold, - name = "Atlas", - nonce = nonce, - expiresAt = expiresAt, - ) - - private val proposalEvent = event(ConfederationKinds.PROPOSAL, agora, proposalTags(), id = "a".repeat(64)) - private val proposal = assertNotNull(ConfederationProposalEvent.parse(proposalEvent)) - - // --- proposals - - @Test - fun `a proposal reads back what was written`() { - assertEquals(agora, proposal.proposingGroup) - assertEquals(listOf(agora, polis, ekklesia), proposal.groupPublicKeys) - assertEquals("wss://relay.example", proposal.relayHintFor(polis)) - assertEquals(coordinatorPub, proposal.coordinator) - assertEquals(2, proposal.threshold) - assertEquals("Atlas", proposal.name) - assertEquals(expiresAt, proposal.expiresAt) - } - - @Test - fun `a proposal its author is not on is not one`() { - assertNull(ConfederationProposalEvent.parse(event(ConfederationKinds.PROPOSAL, npub(4), proposalTags()))) - } - - @Test - fun `one group is not a confederation`() { - assertNull(ConfederationProposalEvent.parse(event(ConfederationKinds.PROPOSAL, agora, proposalTags(listOf(agora))))) - } - - @Test - fun `a group listed twice is refused`() { - assertNull(ConfederationProposalEvent.parse(event(ConfederationKinds.PROPOSAL, agora, proposalTags(listOf(agora, polis, polis))))) - } - - @Test - fun `the outer threshold is between two and the number of groups`() { - assertNull(ConfederationProposalEvent.parse(event(ConfederationKinds.PROPOSAL, agora, proposalTags(threshold = 1)))) - assertNull(ConfederationProposalEvent.parse(event(ConfederationKinds.PROPOSAL, agora, proposalTags(threshold = 4)))) - assertNotNull(ConfederationProposalEvent.parse(event(ConfederationKinds.PROPOSAL, agora, proposalTags(threshold = 3)))) - } - - @Test - fun `a threshold written oddly is refused rather than read`() { - val tags = proposalTags().map { if (it[0] == "threshold") arrayOf("threshold", "02") else it }.toTypedArray() - assertNull(ConfederationProposalEvent.parse(event(ConfederationKinds.PROPOSAL, agora, tags))) - } - - @Test - fun `a group that is not a key is refused`() { - val tags = proposalTags(listOf(agora, polis, "f".repeat(64))) - assertNull(ConfederationProposalEvent.parse(event(ConfederationKinds.PROPOSAL, agora, tags))) - } - - @Test - fun `a proposal that has expired before it was made is refused`() { - assertNull(ConfederationProposalEvent.parse(event(ConfederationKinds.PROPOSAL, agora, proposalTags(), at = expiresAt))) - } - - @Test - fun `two names is no name`() { - val tags = proposalTags() + arrayOf(arrayOf("name", "Other")) - assertNull(ConfederationProposalEvent.parse(event(ConfederationKinds.PROPOSAL, agora, tags))) - } - - // --- the admin list - - @Test - fun `an admin list is the same bytes in any order`() { - val one = ConfederationAdminList.of(proposal.id, polis, 2, admins)!! - val other = ConfederationAdminList.of(proposal.id, polis, 2, admins.reversed() + admins[0])!! - assertEquals(one.encode(), other.encode()) - assertEquals(one, ConfederationAdminList.decode(one.encode())) - } - - @Test - fun `an admin list decodes only from its own encoding`() { - val text = ConfederationAdminList.of(proposal.id, polis, 2, admins)!!.encode() - assertNull(ConfederationAdminList.decode(text.replace(",", ", "))) - assertNull(ConfederationAdminList.decode(text.replace("\"v\":1", "\"v\":3"))) - val unsorted = text.replace("${admins.sorted()[0]}\",\"${admins.sorted()[1]}", "${admins.sorted()[1]}\",\"${admins.sorted()[0]}") - assertNull(ConfederationAdminList.decode(unsorted)) - } - - @Test - fun `an admin list upstream would refuse is never made`() { - assertNull(ConfederationAdminList.of(proposal.id, polis, 1, admins), "t_g is at least two") - assertNull(ConfederationAdminList.of(proposal.id, polis, 4, admins), "and at most the admins there are") - } - - // --- the seal - - private val e = ByteArray(32) { 7 } - private val list = ConfederationAdminList.of(proposal.id, polis, 2, admins)!! - - @Test - fun `a seal reproduces from the same list and the same secret`() { - val sealed = ConfederationSeal.seal(e, coordinatorPub, list) - assertTrue(ConfederationSeal.reproduces(e, coordinatorPub, list, sealed.content, sealed.ephemeralPublicKey)) - } - - @Test - fun `a seal does not reproduce from any other list`() { - val sealed = ConfederationSeal.seal(e, coordinatorPub, list) - val others = listOf( - ConfederationAdminList.of(proposal.id, polis, 2, admins + npub(24)), - ConfederationAdminList.of(proposal.id, polis, 2, admins.drop(1)), - ConfederationAdminList.of(proposal.id, polis, 3, admins), - ConfederationAdminList.of("b".repeat(64), polis, 2, admins), - ) - others.forEach { other -> - assertFalse(ConfederationSeal.reproduces(e, coordinatorPub, other!!, sealed.content, sealed.ephemeralPublicKey), "$other") - } - assertFalse(ConfederationSeal.reproduces(e, npub(8), list, sealed.content, sealed.ephemeralPublicKey), "another coordinator") - assertFalse(ConfederationSeal.reproduces(ByteArray(32) { 8 }, coordinatorPub, list, sealed.content, sealed.ephemeralPublicKey), "another secret") - } - - @Test - fun `the coordinator opens it, and the conversation key opens it for anyone it is given to`() { - val sealed = ConfederationSeal.seal(e, coordinatorPub, list) - val conversationKey = ConfederationSeal.conversationKey(coordinator.value.toByteArray(), sealed.ephemeralPublicKey) - assertEquals(list, ConfederationSeal.open(conversationKey, sealed.content)) - // and quartz's own decrypt agrees, from the other side - assertEquals( - list.encode(), - Nip44v2().decrypt(sealed.content, coordinator.value.toByteArray(), sealed.ephemeralPublicKey.hexToByteArray()), - ) - } - - @Test - fun `nobody else opens it`() { - val sealed = ConfederationSeal.seal(e, coordinatorPub, list) - val wrong = ConfederationSeal.conversationKey(key(8).value.toByteArray(), sealed.ephemeralPublicKey) - assertNull(ConfederationSeal.open(wrong, sealed.content)) - } - - // --- answers and the state they add up to - - private var nextId = 0 - private fun accept(group: HexKey, at: Long = createdAt + 10): Event { - val sealed = ConfederationSeal.seal(e, coordinatorPub, ConfederationAdminList.of(proposal.id, group, 2, admins)!!) - return event( - ConfederationKinds.ACCEPTANCE, group, - ConfederationProposalAcceptanceEvent.assembleTags(proposal.id, null, agora, coordinatorPub, sealed.ephemeralPublicKey), - sealed.content, id = (++nextId).toString().padStart(64, '0'), at = at, - ) - } - - private fun reject(group: HexKey, at: Long = createdAt + 10) = event( - ConfederationKinds.REJECTION, group, - ConfederationProposalRejectionEvent.assembleTags(proposal.id, null, agora), "Not for us", - id = (++nextId).toString().padStart(64, '0'), at = at, - ) - - private fun withdraw(group: HexKey = agora) = event( - ConfederationKinds.WITHDRAWAL, group, - ConfederationProposalWithdrawalEvent.assembleTags(proposal.id, null, proposal.groupPublicKeys), "", - id = (++nextId).toString().padStart(64, '0'), at = createdAt + 20, - ) - - private fun status(vararg events: Event, now: Long = createdAt + 100) = - ConfederationStatus.of(proposal, events.toList(), now) - - @Test - fun `an acceptance reads back and answers its proposal`() { - val acceptance = assertNotNull(ConfederationProposalAcceptanceEvent.parse(accept(polis))) - assertEquals(polis, acceptance.group) - assertEquals(proposal.id, acceptance.proposalId) - assertTrue(ConfederationProposalAcceptanceEvent.answers(acceptance, proposal)) - } - - @Test - fun `nobody has answered`() { - val status = status() - assertEquals(ConfederationProposalState.OPEN, status.state) - assertEquals(listOf(agora, polis, ekklesia), status.waitingOn) - } - - @Test - fun `every group accepted`() { - val status = status(accept(agora), accept(polis), accept(ekklesia)) - assertEquals(ConfederationProposalState.ACCEPTED, status.state) - assertEquals(setOf(agora, polis, ekklesia), status.acceptances.keys) - } - - @Test - fun `one rejection ends it`() { - assertEquals(ConfederationProposalState.REJECTED, status(accept(agora), accept(polis), reject(ekklesia)).state) - } - - @Test - fun `a group that accepted and rejected has rejected`() { - val status = status(accept(agora), accept(polis), accept(ekklesia), reject(polis)) - assertEquals(ConfederationProposalState.REJECTED, status.state) - assertEquals(ConfederationAnswer.REJECTED, status.answerOf(polis)) - } - - @Test - fun `an answer from a group not on the proposal counts for nothing`() { - assertEquals(ConfederationProposalState.OPEN, status(accept(agora), reject(npub(4))).state) - } - - @Test - fun `an acceptance not addressed to the coordinator counts for nothing`() { - val stray = accept(polis).let { it.copy(tags = it.tags.filterNot { t -> t[0] == "p" && t[1] == coordinatorPub }.toTypedArray()) } - assertEquals(ConfederationAnswer.WAITING, status(stray).answerOf(polis)) - } - - @Test - fun `expired with nobody rejecting`() { - assertEquals(ConfederationProposalState.EXPIRED, status(accept(agora), now = expiresAt + 1).state) - } - - @Test - fun `accepted in time stays accepted after the expiry`() { - assertEquals( - ConfederationProposalState.ACCEPTED, - status(accept(agora), accept(polis), accept(ekklesia), now = expiresAt + 1).state, - ) - } - - @Test - fun `an acceptance made after the expiry counts for nothing`() { - val status = status(accept(agora), accept(polis), accept(ekklesia, at = expiresAt + 1), now = expiresAt + 2) - assertEquals(ConfederationProposalState.EXPIRED, status.state) - } - - @Test - fun `the proposing group withdraws, and nobody else can`() { - assertEquals(ConfederationProposalState.WITHDRAWN, status(accept(agora), withdraw()).state) - assertEquals(ConfederationProposalState.OPEN, status(accept(agora), withdraw(polis)).state) - } - - private fun Event.copy(tags: Array>) = Event(id, pubKey, createdAt, kind, tags, content, sig) -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationStatementsTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationStatementsTest.kt index 70fa8620..52e49cc2 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationStatementsTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationStatementsTest.kt @@ -113,7 +113,7 @@ class ConfederationStatementsTest { @Test fun `a withdrawal is the proposer's, to everybody`() { val proposal = proposal() - val answer = assertNotNull(ConfederationStatements.parseAnswer(ConfederationStatements.withdrawal(proposal, "", createdAt + 20))) + val answer = assertNotNull(ConfederationStatements.parseAnswer(ConfederationStatements.withdrawal(agora, proposal, "", createdAt + 20))) assertEquals(agora, answer.group) assertEquals(setOf(polis, ekklesia), answer.addressees.toSet()) } @@ -136,14 +136,13 @@ class ConfederationStatementsTest { assertEquals(ref, ConfederationAttestation.attestationRef("aa".repeat(32), ids)) assertNotEquals(ref, ConfederationAttestation.attestationRef("aa".repeat(32), listOf("11".repeat(32), "23".repeat(32)))) assertNotEquals(ref, ConfederationAttestation.attestationRef("aa".repeat(32), ids.reversed()), "groupId order matters") - assertNotEquals(ref, ConfederationRosterBuilder.attestationRef("aa".repeat(32), ids), "version 1 hashed public event ids") } @Test fun `the ceremony's id and seed change with the attempt, and the seed with any contribution`() { val ref = ConfederationAttestation.attestationRef("aa".repeat(32), listOf("11".repeat(32))) - assertNotEquals(ConfederationAttestation.ceremonyId(ref, 1), ConfederationAttestation.ceremonyId(ref, 2)) - assertEquals(ConfederationAttestation.ceremonyId(ref, 1), ConfederationAttestation.ceremonyId(ref, 1)) + assertNotEquals(ConfederationAttestation.ceremonyId("aa".repeat(32), 1), ConfederationAttestation.ceremonyId("aa".repeat(32), 2)) + assertEquals(ConfederationAttestation.ceremonyId("aa".repeat(32), 1), ConfederationAttestation.ceremonyId("aa".repeat(32), 1)) val seeds = listOf("01".repeat(32), "02".repeat(32)) val seed = ConfederationAttestation.sessionSeed(ref, 1, seeds) assertEquals(seed, ConfederationAttestation.sessionSeed(ref, 1, seeds)) diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationStatusTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationStatusTest.kt new file mode 100644 index 00000000..9ba804aa --- /dev/null +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationStatusTest.kt @@ -0,0 +1,122 @@ +package mobi.giza.compose.nostr.confederation + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.PrivateKey +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import mobi.giza.compose.extensions.toHex + +/** + * A proposal's state from the statements a device holds (docs/confederation.md, D8, as + * docs/confederation-without-coordinator.md has the statements): the proposer has accepted by + * proposing, and an answer counts only if it is addressed to every other group. + */ +class ConfederationStatusTest { + private fun npub(n: Int): HexKey = PrivateKey(ByteArray(32).also { it[0] = 0x11; 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 stranger = npub(4) + private val admins = listOf(npub(21), npub(22), npub(23)) + private val createdAt = 1_790_000_000L + private val expiresAt = createdAt + ConfederationKinds.DEFAULT_EXPIRY_SECONDS + + private val proposal = assertNotNull( + ConfederationStatements.parseProposal( + ConfederationStatements.proposal( + agora, listOf(polis, ekklesia), 2, "Atlas", "ab".repeat(32), expiresAt, + ConfederationAdminList.ofV2(null, agora, 2, admins)!!, createdAt, + ) + ) + ) + + private fun accept(group: HexKey, at: Long = createdAt + 10) = + ConfederationStatements.acceptance(group, proposal, ConfederationAdminList.ofV2(proposal.id, group, 2, admins)!!, at) + + private fun reject(group: HexKey, at: Long = createdAt + 10) = ConfederationStatements.rejection(group, proposal, "", at) + + private fun status(vararg statements: Event, now: Long = createdAt + 100) = ConfederationStatus.of(proposal, statements.toList(), now) + + @Test + fun `nobody has answered, and the proposer has accepted by proposing`() { + val status = status() + assertEquals(ConfederationProposalState.OPEN, status.state) + assertEquals(ConfederationAnswer.ACCEPTED, status.answerOf(agora)) + assertEquals(listOf(polis, ekklesia), status.waitingOn) + assertEquals(mapOf(agora to proposal.id), status.acceptanceIds) + } + + @Test + fun `every group accepted, each with its admins`() { + val polisAccepts = accept(polis) + val status = status(polisAccepts, accept(ekklesia)) + assertEquals(ConfederationProposalState.ACCEPTED, status.state) + assertEquals(setOf(agora, polis, ekklesia), status.adminLists.keys) + assertEquals(polisAccepts.id, status.acceptanceIds[polis]) + assertEquals(proposal.id, status.adminLists.getValue(agora).proposalId, "the proposer's list is bound to its proposal") + } + + @Test + fun `one rejection ends it`() { + assertEquals(ConfederationProposalState.REJECTED, status(accept(polis), reject(ekklesia)).state) + } + + @Test + fun `a group that accepted and rejected has rejected`() { + val status = status(accept(polis), reject(polis), accept(ekklesia)) + assertEquals(ConfederationProposalState.REJECTED, status.state) + assertEquals(ConfederationAnswer.REJECTED, status.answerOf(polis)) + assertNull(status.acceptances[polis]) + } + + @Test + fun `an answer from a group the proposal does not name counts for nothing`() { + val outsider = ConfederationStatements.rejection(stranger, proposal, "", createdAt + 10) + assertEquals(ConfederationProposalState.OPEN, status(outsider).state) + } + + @Test + fun `an answer that leaves a group out counts for nothing`() { + val whispered = ConfederationStatements.parseAnswer(accept(polis))!!.let { answer -> + val tags = arrayOf(arrayOf("p", agora), arrayOf("e", proposal.id)) + com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler.assembleRumor( + polis, + com.vitorpamplona.quartz.nip01Core.signers.EventTemplate(answer.createdAt, ConfederationKinds.ACCEPTANCE, tags, answer.admins!!.encode()), + ) + } + assertEquals(ConfederationAnswer.WAITING, status(whispered, accept(ekklesia)).answerOf(polis), "Ekklesia never heard it") + } + + @Test + fun `expired with nobody rejecting`() { + assertEquals(ConfederationProposalState.EXPIRED, status(accept(polis), now = expiresAt + 1).state) + } + + @Test + fun `accepted in time stays accepted after the expiry`() { + assertEquals(ConfederationProposalState.ACCEPTED, status(accept(polis), accept(ekklesia), now = expiresAt + 1000).state) + } + + @Test + fun `an acceptance made after the expiry counts for nothing`() { + assertEquals(ConfederationProposalState.EXPIRED, status(accept(polis), accept(ekklesia, at = expiresAt + 1), now = expiresAt + 10).state) + } + + @Test + fun `the proposing group withdraws, and nobody else can`() { + assertEquals(ConfederationProposalState.WITHDRAWN, status(ConfederationStatements.withdrawal(agora, proposal, "", createdAt + 20)).state) + val notTheirs = ConfederationStatements.withdrawal(polis, proposal, "", createdAt + 20) + assertEquals(ConfederationProposalState.OPEN, status(notTheirs).state) + } + + @Test + fun `an admin list upstream would refuse is never made`() { + assertNull(ConfederationAdminList.ofV2(null, agora, 1, admins), "a threshold of one") + assertNull(ConfederationAdminList.ofV2(null, agora, 4, admins), "more than its admins") + assertNull(ConfederationAdminList.ofV2(null, agora, 2, listOf("not a key", admins[0]))) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ConfederationSealPremiseJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ConfederationSealPremiseJvmTest.kt deleted file mode 100644 index 60ecedc6..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ConfederationSealPremiseJvmTest.kt +++ /dev/null @@ -1,46 +0,0 @@ -package mobi.giza.compose - -import com.vitorpamplona.quartz.nip44Encryption.Nip44v2 -import fr.acinq.bitcoin.PrivateKey -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotEquals - -/** - * The premise of docs/confederation.md's D5, against quartz's real NIP-44: two devices that - * hold the same ephemeral secret, nonce and plaintext produce the same payload, byte for - * byte, and the coordinator alone opens it with their own key. - */ -class ConfederationSealPremiseJvmTest { - private val ephemeral = PrivateKey.fromHex("11".repeat(32)) - private val coordinator = PrivateKey.fromHex("22".repeat(32)) - private val coordinatorPublic = coordinator.publicKey().xOnly().value.toByteArray() - private val nonce = ByteArray(32) { it.toByte() } - private val plaintext = """{"v":1,"admins":["aa","bb"]}""" - - private fun seal(nip44: Nip44v2, text: String = plaintext) = nip44.encryptWithNonce( - text, - nip44.getConversationKey(ephemeral.value.toByteArray(), coordinatorPublic), - nonce, - ).encodePayload() - - @Test - fun `two devices seal the same plaintext to the same bytes`() { - assertEquals(seal(Nip44v2()), seal(Nip44v2())) - } - - @Test - fun `another plaintext seals to other bytes`() { - assertNotEquals(seal(Nip44v2()), seal(Nip44v2(), """{"v":1,"admins":["aa"]}""")) - } - - @Test - fun `the coordinator opens it with their own key and the ephemeral public key`() { - val opened = Nip44v2().decrypt( - seal(Nip44v2()), - coordinator.value.toByteArray(), - ephemeral.publicKey().xOnly().value.toByteArray(), - ) - assertEquals(plaintext, opened) - } -} 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 7b71d74f..71343842 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 @@ -67,11 +67,12 @@ class ShippedProfileUpgradeJvmTest { * 10), 41 for governance proposals and 42 for what follows them * (docs/member-admin-promotion.md, Phases 5, 8 and 9), 43 for the confederation * (docs/confederation.md, Phase 4), 44 for its key ceremony (Phase 11), 45 for its signing - * (Phase 14), 46 for the group's inbox (docs/group-inbox.md, Phase 3) and 47 for a group's - * direct messages by threshold ECDH (docs/group-threshold-ecdh.md, Phase 4), so the upgrade - * crosses eleven generated migrations and the file has to come out at the last. + * (Phase 14), 46 for the group's inbox (docs/group-inbox.md, Phase 3), 47 for a group's + * direct messages by threshold ECDH (docs/group-threshold-ecdh.md, Phase 4) and 48 for the + * confederation's statements between inboxes (docs/confederation-without-coordinator.md), so + * the upgrade crosses twelve generated migrations and the file has to come out at the last. */ - private val current = 47 + private val current = 48 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/ConfederationCeremonyJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt index 0f59be2d..1ff1f44d 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt @@ -40,7 +40,6 @@ import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.builder.getRoomDatabase import mobi.giza.compose.database.model.ConfederationCeremony import mobi.giza.compose.database.model.ConfederationCeremonyStage -import mobi.giza.compose.database.model.GiftWrapPayload import mobi.giza.compose.database.model.NostrEvent import mobi.giza.compose.database.model.Profile import mobi.giza.compose.database.model.intermdiate.LocalChatRoom @@ -49,121 +48,56 @@ import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder /** - * A confederation's key ceremony across devices, one person to a device (docs/confederation.md, - * Phase 11): gift wraps ferried between devices, every round run by `ConfederationDkg` on the - * device of the role it belongs to, and at the end the same key on every device -- a key that - * signs as the confederation's room, once each device's recovery package is opened back into its - * share. + * A confederation's key ceremony across devices, one person to a device, with nobody coordinating + * it (docs/confederation.md, Phase 11, and docs/confederation-without-coordinator.md, Phase 7): + * every admin joins on their own once their device holds every group's statement, gift wraps are + * ferried between devices, every round is run by `ConfederationDkg` on the device of the role it + * belongs to -- the broadcast included -- and at the end the same key on every device, a key that + * signs as the confederation's room once each device's recovery package is opened into its share. */ class ConfederationCeremonyJvmTest { - private fun secret(n: Int) = PrivateKey(ByteArray(32).also { it[0] = 0x61; it[31] = n.toByte() }) - private fun npub(key: PrivateKey): HexKey = key.publicKey().xOnly().value.toHex() - - private val groupKeys = (1..3).map { secret(it) } - private val groups = groupKeys.map(::npub) - - private inner class Device(val secret: PrivateKey, val db: GizaDatabase) { - val person = npub(secret) - lateinit var room: LocalChatRoom - val received = mutableSetOf() - } - - private val devices = mutableMapOf() + private var people: ConfederationPeople? = null + private val network get() = people!! @AfterTest fun close() { - RoomAdmins.override = null - devices.values.forEach { it.db.close() } + people?.close() } - /** Sets up the three groups' admins, a device each, and the signed proposal with every acceptance. */ - private fun network(adminsByGroup: List>, coordinatorIndex: Int = adminsByGroup[0][0]): Pair = runBlocking { - val people = adminsByGroup.flatten().distinct().map(::secret) - val coordinator = npub(secret(coordinatorIndex)) - val now = Clock.System.now().epochSeconds - val proposal = ConfederationTestGroups.proposal(groupKeys[0], groups, coordinator, createdAt = now - 10, expiresAt = now + 1000) - val acceptances = groupKeys.mapIndexed { i, key -> - ConfederationTestGroups.acceptance(key, proposal, adminsByGroup[i].map { npub(secret(it)) }, threshold = 2) - } + private fun secret(n: Int) = network.secret(n) + private fun npub(n: Int) = network.npub(n) + private val groups get() = network.groups + private val devices get() = network.devices - people.forEach { key -> - val db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) - (people.map(::npub) + groups).forEach { member -> - val eventId = Crypto.sha256(member.encodeToByteArray()).toHex() - db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = member, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) - // Every profile resolved: D2's check at the coordinator is Part A's, not this test's. - db.profileDao().upsert(Profile(publicKey = member, nostrEventId = eventId, displayName = member.take(6), createdAt = Instant.fromEpochSeconds(1_790_000_000))) - } - devices[npub(key)] = Device(key, db) - } - - val host = devices.getValue(coordinator) - (listOf(proposal) + acceptances).forEach { ConfederationManager.record(host.db, it) } - host to proposal.id + private fun setUp( + adminsByGroup: List> = listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33)), + statementsFor: ((ConfederationPeople.Device) -> List>)? = null, + ) = runBlocking { + people = ConfederationPeople(adminsByGroup) + if (statementsFor == null) network.setUp() else network.setUp(statementsFor) } - /** The coordinator opens; every other device gets the room the opening's p-tags name. */ - private fun open(host: Device, proposalId: HexKey): ConfederationCeremony = runBlocking { - val ceremony = ConfederationRitualManager.open(host.db, proposalId, host.secret) - host.room = host.db.chatRoomDao().findChatRoomById(ceremony.chatRoomId)!! - devices.values.filter { it !== host }.forEach { device -> - device.room = device.db.nostrNip17Dao().createNip17ChatRoom( - userPublicKey = device.person, - participantPublicKeys = devices.keys.filter { it != device.person }, - subject = "Atlas", - )!! - assertEquals(ceremony.chatRoomId, device.room.chatRoom.id, "every device lands in the same room") - } - ceremony - } + private fun pump(tamper: (ConfederationPeople.Device, ConfederationPeople.Device, mobi.giza.compose.database.model.GiftWrapPayload) -> mobi.giza.compose.database.model.GiftWrapPayload? = { _, _, it -> it }) = + runBlocking { network.pump(tamper) } - /** Ferries every queued ceremony message to every device it is addressed to, until nothing moves. */ - private fun pump(tamper: (GiftWrapPayload) -> GiftWrapPayload = { it }) = runBlocking { - var moved = true - while (moved) { - moved = false - for (from in devices.values) for (to in devices.values) { - if (from === to) continue - from.db.giftWrapPayloadDao().getByChatRoomAndKinds(from.room.chatRoom.id, ConfederationRitualEvents.ALL.toList()) - .filter { it.publicKey == from.person } - .sortedBy { it.createdAt } - .forEach { original -> - if (!to.received.add(original.id)) return@forEach - moved = true - val queued = tamper(original) - to.db.giftWrapPayloadDao().upsert(queued.copy(chatRoomId = to.room.chatRoom.id)) - ConfederationRitualManager.process( - to.db, to.room, - Event(queued.id, queued.publicKey, queued.createdAt.epochSeconds, queued.kind, queued.tags, queued.content, ""), - to.person, to.secret.value.toByteArray(), - ) - } - } - } - } + private fun joinAll(except: Set = emptySet()) = runBlocking { network.joinAll(except) } - private fun joinAll(sessionId: String, except: Set = emptySet()) = runBlocking { - devices.values.filter { it.person !in except }.forEach { ConfederationRitualManager.join(it.db, sessionId, it.secret.value.toByteArray()) } - } - - private fun ceremonies(sessionId: String) = runBlocking { - devices.values.associate { it.person to it.db.confederationCeremonyDao().getCeremony(sessionId) } - } + private fun ceremonies() = runBlocking { network.ceremonies() } /** Every role's share, opened from the recovery package its device kept. */ - private fun shares(sessionId: String): Pair>> = runBlocking { - val any = devices.values.first().db.confederationCeremonyDao().getCeremony(sessionId)!! - val plan = (ConfederationRitualManager.planFrom(ConfederationRitualEvents.Opening.decode(any.openingJson)!!) as fr.acinq.bitcoin.utils.Either.Right).value + private fun shares(): Pair>> = runBlocking { + val any = ceremonies().values.first()!! + val plan = assertNotNull(ConfederationRitualManager.planOf(any)) val hostKeys = plan.seats.associate { seat -> - seat.roleId to ConfederationRosterBuilder.hostPublicKey(devices.getValue(seat.admin).secret.value.toByteArray(), seat.group, plan.proposal.id) + seat.roleId to ConfederationRosterBuilder.hostPublicKey(devices.getValue(seat.admin).nsec, seat.group, plan.proposal.id) } val roster: ConfederationRoster = plan.roster(hostKeys).right!! val keyState = ConfederationKeyState.fromData(ByteVector(any.keyState!!), roster).right!! keyState to plan.seats.associate { seat -> val device = devices.getValue(seat.admin) - val ceremony = device.db.confederationCeremonyDao().getCeremony(sessionId)!! + val ceremony = device.db.confederationCeremonyDao().getLatestForProposal(plan.proposal.id)!! val hex = ConfederationRitualEvents.decodeByGroup(ceremony.recoveryPackages!!)!!.getValue(seat.group) - val host = ConfederationRosterBuilder.hostSecretKey(device.secret.value.toByteArray(), seat.group, plan.proposal.id) + val host = ConfederationRosterBuilder.hostSecretKey(device.nsec, seat.group, plan.proposal.id) val recovery = ConfederationRecoveryPackage.fromData(ByteVector(hex), host).right!! seat.roleId to (recovery.open(host, keyState).right!! to host) } @@ -171,27 +105,27 @@ class ConfederationCeremonyJvmTest { @Test fun `three groups of three make one key, the same on every device, that signs as the room`() { - val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33))) - val agoraAdmin = devices.getValue(npub(secret(12))) + setUp() + val agoraAdmin = network.device(12) runBlocking { agoraAdmin.db.chatRoomDao().upsert( mobi.giza.compose.database.model.ChatRoom(id = groups[0], userPublicKey = agoraAdmin.person, subject = "#Agora", description = null, mlsGroupState = "00") ) } - val opened = open(host, proposalId) - pump() - joinAll(opened.id) + joinAll() pump() - val all = ceremonies(opened.id) + val all = ceremonies() all.forEach { (person, ceremony) -> assertEquals(ConfederationCeremonyStage.COMPLETE, ceremony?.stage, "${person.take(6)}: ${ceremony?.failureReason}") } + assertEquals(1, all.values.map { it!!.id }.toSet().size, "one ceremony id, derived on every device") + assertEquals(1, all.values.map { it!!.chatRoomId }.toSet().size, "one room, whoever made it") assertEquals(1, all.values.map { it!!.confederationPublicKey }.toSet().size, "one key, everywhere") assertEquals(1, all.values.map { it!!.genesis }.toSet().size, "one certified genesis, assembled on each device") all.values.forEach { assertNull(it!!.dealerSeeds, "dealer seeds erased once dealt") } // Phase 12: every device files the same confederation, certified, under the room its key derives. runBlocking { - val formed = devices.values.map { assertNotNull(it.db.confederationCeremonyDao().getConfederationForProposal(proposalId)) } + val formed = devices.values.map { assertNotNull(it.db.confederationCeremonyDao().getConfederationForProposal(network.proposalId)) } assertEquals(1, formed.map { it.id }.toSet().size) formed.forEach { assertTrue(ConfederationFormation.verifies(it)) } assertEquals(ConfederationFormation.roomIdOf(all.values.first()!!.confederationPublicKey!!), formed.first().id) @@ -203,7 +137,7 @@ class ConfederationCeremonyJvmTest { ) } - val (keyState, held) = shares(opened.id) + val (keyState, held) = shares() val threshold = "02" + keyState.publicKey.value.toHex() val derived = SharedKeyDerivation.derive(threshold) val selection = ConfederationSignerSelection(mapOf(0u to setOf(0u, 1u), 1u to setOf(0u, 2u))) @@ -218,165 +152,167 @@ class ConfederationCeremonyJvmTest { } @Test - fun `a person who is an admin of two groups takes part once, with two roles`() { - val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(11, 22, 23), listOf(31, 32, 33))) - val opened = open(host, proposalId) - assertEquals(8, devices.size) + fun `nobody opens it and nobody relays a broadcast, so no 30380 or 30383 is ever sent`() { + setUp() + joinAll() pump() - joinAll(opened.id) + runBlocking { + devices.values.forEach { device -> + val kinds = device.db.giftWrapPayloadDao().getByChatRoomAndKinds(device.room.chatRoom.id, listOf(30380, 30383)) + assertEquals(emptyList(), kinds.map { it.kind }, "on ${device.person.take(6)}") + } + } + ceremonies().values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) } + } + + @Test + fun `a person who is an admin of two groups takes part once, with two roles`() { + setUp(listOf(listOf(11, 12, 13), listOf(11, 22, 23), listOf(31, 32, 33))) + assertEquals(8, devices.size) + joinAll() pump() - ceremonies(opened.id).values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) } - val packages = ConfederationRitualEvents.decodeByGroup(ceremonies(opened.id).getValue(npub(secret(11)))!!.recoveryPackages!!)!! + ceremonies().values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) } + val packages = ConfederationRitualEvents.decodeByGroup(ceremonies().getValue(npub(11))!!.recoveryPackages!!)!! assertEquals(setOf(groups[0], groups[1]), packages.keys) } @Test - fun `nobody moves until they join, and an admin who never joins stalls it until somebody abandons`() { - val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33))) - val opened = open(host, proposalId) + fun `an admin who never joins stalls it until somebody abandons, and joining late ends it there too`() { + setUp() + val holdout = npub(33) + joinAll(except = setOf(holdout)) pump() - val holdout = npub(secret(33)) - ceremonies(opened.id).filterKeys { it != host.person }.values.forEach { assertTrue(ConfederationRitualManager.isAwaitingJoin(it!!)) } - - joinAll(opened.id, except = setOf(holdout)) - pump() - ceremonies(opened.id).filterKeys { it != holdout }.values.forEach { + ceremonies().filterKeys { it != holdout }.values.forEach { assertEquals(ConfederationCeremonyStage.COLLECTING_HOST_KEYS, it?.stage) } + assertNull(ceremonies()[holdout], "nothing is made on a device until its owner joins") - runBlocking { ConfederationRitualManager.abandon(devices.getValue(npub(secret(21))).db, opened.id) } + runBlocking { ConfederationRitualManager.abandon(network.device(21).db, ceremonies().getValue(npub(21))!!.id) } pump() - ceremonies(opened.id).values.forEach { assertEquals(ConfederationCeremonyStage.FAILED, it?.stage) } + ceremonies().filterKeys { it != holdout }.values.forEach { assertEquals(ConfederationCeremonyStage.FAILED, it?.stage) } + + runBlocking { network.join(network.device(33)) } + assertEquals(ConfederationCeremonyStage.FAILED, ceremonies()[holdout]?.stage, "the abandonment it missed is replayed") } @Test - fun `a key that does not open an acceptance is refused before anybody joins`() { - val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33))) - val opened = open(host, proposalId) - pump { payload -> - if (payload.kind != ConfederationRitualEvents.OPENING) return@pump payload - val opening = ConfederationRitualEvents.Opening.decode(payload.content)!! - val wrongKeys = opening.conversationKeys.mapValues { "11".repeat(32) } - payload.copy(content = opening.copy(conversationKeys = wrongKeys).encode()) - } - ceremonies(opened.id).filterKeys { it != host.person }.values.forEach { - assertNotNull(it) - assertEquals(ConfederationCeremonyStage.FAILED, it.stage) - assertTrue(it.failureReason!!.contains("does not open"), it.failureReason) - assertNull(it.approvedAt, "nobody was asked") - } - assertEquals(ConfederationCeremonyStage.FAILED, ceremonies(opened.id).getValue(host.person)?.stage, "the coordinator hears why") - } - - @Test - fun `a coordinator's roster that is not the one every device built ends it`() { - val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33))) - val opened = open(host, proposalId) + fun `an abandoned attempt is tried again as the next, with a new seed, and forms`() { + setUp() + joinAll() + runBlocking { ConfederationRitualManager.abandon(network.device(11).db, ceremonies().getValue(npub(11))!!.id) } pump() - joinAll(opened.id) - pump { payload -> - if (payload.kind != ConfederationRitualEvents.BROADCAST) return@pump payload - val sent = ConfederationRitualEvents.Broadcast.decode(payload.content)!! - payload.copy(content = sent.copy(roster = sent.roster.dropLast(2) + "00").encode()) - } - ceremonies(opened.id).filterKeys { it != host.person }.values.forEach { - assertEquals(ConfederationCeremonyStage.FAILED, it?.stage) + val first = ceremonies().values.map { it!! } + first.forEach { assertEquals(ConfederationCeremonyStage.FAILED, it.stage) } + + joinAll() + pump() + val second = ceremonies().values.map { it!! } + second.forEach { + assertEquals(2, it.attempt) + assertEquals(ConfederationCeremonyStage.COMPLETE, it.stage, it.failureReason) } + assertTrue(second.first().id != first.first().id, "another ceremony id for another attempt") } @Test - fun `a device whose group's admins changed since it accepted refuses to join`() { - val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33))) - // Device 22 holds Polis's room, and sees a fourth admin there now. - val polisMember = devices.getValue(npub(secret(22))) + fun `a group that told two groups different things is named at the first message`() { + // Ekklesia's quorum signs two acceptances; Polis's admins hold one, everybody else the other. + val polisAdmins = setOf(21, 22, 23) + setUp(statementsFor = { device -> + val sees = network.everyStatement() + if (device.person in polisAdmins.map(network::npub)) { + val other = ConfederationStatementFixture.acceptance( + network.groupKeys[2], network.proposal, listOf(31, 32, 33).map(network::npub), createdAt = network.acceptances[1].createdAt + 1, + ) + sees.filter { it.second.id != network.acceptances[1].id } + (network.groupKeys[2] to other) + } else { + sees + } + }) + joinAll() + pump() + val ended = ceremonies().values.filterNotNull() + assertTrue(ended.isNotEmpty()) + ended.forEach { assertEquals(ConfederationCeremonyStage.FAILED, it.stage) } + assertTrue(ended.any { it.failureReason!!.contains("different statement from Ekklesia") }, ended.map { it.failureReason }.toString()) + ended.forEach { assertNull(it.recoveryPackages) } + } + + @Test + fun `two devices that were dealt different things are named at the authorizations`() { + setUp() + joinAll() + val liar = npub(22) + pump { from, _, payload -> + if (from.person != liar || payload.kind != ConfederationRitualEvents.AUTHORIZATIONS) return@pump payload + val sent = ConfederationRitualEvents.Authorizations.decode(payload.content)!! + payload.copy(content = sent.copy(broadcast = "00".repeat(32)).encode()) + } + val others = ceremonies().filterKeys { it != liar }.values.map { it!! } + others.forEach { assertEquals(ConfederationCeremonyStage.FAILED, it.stage) } + assertTrue(others.any { it.failureReason!!.contains("received different dealings than this device did") }, others.map { it.failureReason }.toString()) + } + + @Test + fun `a device whose group's admins changed since it accepted cannot join`() { + setUp() + val polisMember = network.device(22) runBlocking { polisMember.db.chatRoomDao().upsert( mobi.giza.compose.database.model.ChatRoom(id = groups[1], userPublicKey = polisMember.person, subject = "#Polis", description = null, mlsGroupState = "00") ) - polisMember.db.dkgSessionDao().upsert( - mobi.giza.compose.database.model.DkgSession( - id = "k".repeat(64), chatRoomId = groups[1], coordinatorPublicKey = polisMember.person, userPublicKey = polisMember.person, - threshold = 2, participantCount = 4, stage = mobi.giza.compose.database.model.types.DkgRitualStage.COMPLETE, - hostPublicKey = "02".padEnd(66, '0'), round1Random = "1".repeat(64), round2AuxRandom = "2".repeat(64), - ) - ) } RoomAdmins.override = { id -> - if (id == groups[1]) RoomAdmins(setOf(21, 22, 23, 24).map { npub(secret(it)) }.toSet(), governed = false) else null + if (id == groups[1]) RoomAdmins(setOf(21, 22, 23, 24).map { npub(it) }.toSet(), governed = false) else null } - val opened = open(host, proposalId) - pump() - val refused = ceremonies(opened.id).getValue(polisMember.person) - assertEquals(ConfederationCeremonyStage.FAILED, refused?.stage, "refused") - assertTrue(refused!!.failureReason!!.contains("have changed since it accepted"), refused.failureReason) + val refused = kotlin.test.assertFailsWith { runBlocking { network.join(polisMember) } } + assertTrue(refused.message!!.contains("have changed since it accepted"), refused.message) } @Test - fun `messages that arrive before the opening are replayed when it comes`() { - val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33))) - val opened = open(host, proposalId) - val late = devices.getValue(npub(secret(32))) - // Everybody else hears the opening and joins; the late device hears nothing yet. - val others = devices.values.filter { it !== late } - runBlocking { - others.filter { it !== host }.forEach { to -> - host.db.giftWrapPayloadDao().getByChatRoomAndKinds(host.room.chatRoom.id, listOf(ConfederationRitualEvents.OPENING)).forEach { q -> - to.received += q.id - ConfederationRitualManager.process(to.db, to.room, Event(q.id, q.publicKey, q.createdAt.epochSeconds, q.kind, q.tags, q.content, ""), to.person, to.secret.value.toByteArray()) - } - } - } - joinAll(opened.id, except = setOf(late.person)) - // Then everything, the opening last of all for the late device. - pump { it } - runBlocking { ConfederationRitualManager.join(late.db, opened.id, late.secret.value.toByteArray()) } - pump() - ceremonies(opened.id).values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) } - } - - // ---- pinned before the coordinator goes (docs/confederation-without-coordinator.md, Phase 1) - - @Test - fun `today an opening sent by anyone but the coordinator is refused`() { - val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33))) - val opened = open(host, proposalId) - val impostor = npub(secret(21)) - pump { payload -> if (payload.kind == ConfederationRitualEvents.OPENING) payload.copy(publicKey = impostor) else payload } - ceremonies(opened.id).filterKeys { it != host.person && it != impostor }.values.forEach { - assertEquals(ConfederationCeremonyStage.FAILED, it?.stage) - assertTrue(it!!.failureReason!!.contains("someone other than the proposal's coordinator"), it.failureReason) - } + fun `a device that does not hold every acceptance yet cannot join`() { + val late = 32 + setUp(statementsFor = { device -> if (device.person == network.npub(late)) network.everyStatement().take(2) else network.everyStatement() }) + val refused = kotlin.test.assertFailsWith { runBlocking { network.join(network.device(late)) } } + assertTrue(refused.message!!.contains("Not every group has accepted"), refused.message) } @Test - fun `today every device waits on the coordinator's broadcast`() { - val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33))) - val opened = open(host, proposalId) + fun `messages that arrive before a member joins are replayed when they do`() { + setUp() + val late = npub(32) + joinAll(except = setOf(late)) pump() - joinAll(opened.id) - // The broadcast never arrives: it is turned into a kind nobody reads. - pump { payload -> if (payload.kind == ConfederationRitualEvents.BROADCAST) payload.copy(kind = 30386) else payload } - ceremonies(opened.id).filterKeys { it != host.person }.values.forEach { - assertEquals(ConfederationCeremonyStage.DEALING, it?.stage, "every dealing is in, and still nobody moves") + runBlocking { network.join(network.device(32)) } + pump() + ceremonies().values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) } + } + + @Test + fun `a message from someone outside the roster is not read`() { + setUp() + joinAll() + val outsider = ConfederationStatementFixture.npub(99) + pump { _, to, payload -> + if (to.person == npub(12) && payload.kind == ConfederationRitualEvents.FAILURE) payload.copy(publicKey = outsider) else payload } + ceremonies().values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) } } // ---- Phase 13: the confederation's room ---------------------------------------------- - private fun formed(): Pair { - val (host, proposalId) = network(listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33))) - val opened = open(host, proposalId) + private fun formed(): mobi.giza.compose.database.model.Confederation { + setUp() + joinAll() pump() - joinAll(opened.id) - pump() - return host to runBlocking { assertNotNull(host.db.confederationCeremonyDao().getConfederationForProposal(proposalId)) } + return runBlocking { assertNotNull(network.device(11).db.confederationCeremonyDao().getConfederationForProposal(network.proposalId)) } } /** Every member's key package on [device], as it would have synced them, but for [except]. */ - private fun keyPackagesOn(device: Device, except: Set = emptySet()) = runBlocking { + private fun keyPackagesOn(device: ConfederationPeople.Device, except: Set = emptySet()) = runBlocking { devices.values.filter { it !== device && it.person !in except }.forEach { peer -> - val bundle = CurrentProfileGroupFactory.createKeyPackage(NostrSignerInternal(KeyPair(privKey = peer.secret.value.toByteArray()))) + val bundle = CurrentProfileGroupFactory.createKeyPackage(NostrSignerInternal(KeyPair(privKey = peer.nsec))) device.db.marmotKeyPackageDao().upsert( MarmotKeyPackage( id = peer.person.take(60) + "0000", @@ -388,15 +324,23 @@ class ConfederationCeremonyJvmTest { } } - private fun repository(device: Device) = DatabaseChatRepository(device.db, CoroutineScope(Dispatchers.IO)) + private fun repository(device: ConfederationPeople.Device) = DatabaseChatRepository(device.db, CoroutineScope(Dispatchers.IO)) + + /** The person whose device makes the room: the first of the roster's people, sorted (D11). */ + private fun creator(confederation: mobi.giza.compose.database.model.Confederation): ConfederationPeople.Device = runBlocking { + val ceremony = network.device(11).db.confederationCeremonyDao().getCeremony(confederation.ceremonyId)!! + devices.getValue(ConfederationFollowThrough.creatorOf(ConfederationRitualManager.planOf(ceremony)!!)) + } @Test - fun `the coordinator's device makes the room the key derives, with every role holder its admin`() { - val (host, confederation) = formed() + fun `the first person's device makes the room the key derives, with every role holder its admin`() { + val confederation = formed() + val host = creator(confederation) + val confederationHere = runBlocking { host.db.confederationCeremonyDao().getConfederation(confederation.id)!! } keyPackagesOn(host) val outcome = runBlocking { - ConfederationFollowThrough.takeNextStep(host.db, repository(host), confederation, KeyPair(privKey = host.secret.value.toByteArray()), keyPackageLookupTimeout = 2_000L) + ConfederationFollowThrough.takeNextStep(host.db, repository(host), confederationHere, KeyPair(privKey = host.nsec), keyPackageLookupTimeout = 2_000L) } val created = assertIs(outcome) assertEquals(confederation.id, created.room.chatRoom.id, "the room is the one the confederation's key derives") @@ -410,17 +354,17 @@ class ConfederationCeremonyJvmTest { @Test fun `a member's key package missing holds the room back, and nobody else's device makes it`() { - val (host, confederation) = formed() - val missing = npub(secret(23)) + val confederation = formed() + val host = creator(confederation) + val missing = devices.keys.first { it != host.person } keyPackagesOn(host, except = setOf(missing)) - val hostKeys = KeyPair(privKey = host.secret.value.toByteArray()) - val blocked = runBlocking { ConfederationFollowThrough.takeNextStep(host.db, repository(host), confederation, hostKeys, keyPackageLookupTimeout = 500L) } + val blocked = runBlocking { ConfederationFollowThrough.takeNextStep(host.db, repository(host), confederation, KeyPair(privKey = host.nsec), keyPackageLookupTimeout = 500L) } assertEquals(listOf(missing), assertIs(blocked).missing) - val member = devices.getValue(npub(secret(22))) + val member = devices.values.first { it !== host } val memberCopy = runBlocking { assertNotNull(member.db.confederationCeremonyDao().getConfederation(confederation.id)) } - assertNull(runBlocking { ConfederationFollowThrough.takeNextStep(member.db, repository(member), memberCopy, KeyPair(privKey = member.secret.value.toByteArray())) }) + assertNull(runBlocking { ConfederationFollowThrough.takeNextStep(member.db, repository(member), memberCopy, KeyPair(privKey = member.nsec)) }) val outsider = runBlocking { ConfederationFollowThrough.createRoom(host.db, repository(host), confederation, KeyPair(), keyPackageLookupTimeout = 500L) } assertIs(outsider) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationDeclineJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationDeclineJvmTest.kt index 3f282bb3..a030e72f 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationDeclineJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationDeclineJvmTest.kt @@ -2,8 +2,8 @@ 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.signers.EventTemplate -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test @@ -14,269 +14,225 @@ import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock import kotlinx.coroutines.runBlocking -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.managers.ConfederationTestGroups.key -import mobi.giza.compose.managers.ConfederationTestGroups.npub +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.nostr.confederation.ConfederationAdminList import mobi.giza.compose.nostr.confederation.ConfederationKinds -import mobi.giza.compose.nostr.confederation.ConfederationProposalAcceptanceEvent -import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent -import mobi.giza.compose.nostr.confederation.ConfederationSeal -import mobi.giza.compose.extensions.toHex -import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent.Invitee -import mobi.giza.compose.nostr.confederation.tags.ConfederationCarriedProposalTag -import mobi.giza.compose.nostr.confederation.tags.ConfederationSealTag +import mobi.giza.compose.nostr.confederation.ConfederationStatements import mobi.giza.compose.nostr.frost.FrostSigningEvents -import mobi.giza.compose.text.ProposedEvent +import mobi.giza.compose.nostr.inbox.InboxReplyManifest +import mobi.giza.compose.nostr.inbox.InboxSeal +import mobi.giza.compose.nostr.inbox.InboxWire /** - * What a member's device does with a proposal to sign one of the confederation's events - * (docs/confederation.md, Phase 3): a right one is put to the member, a wrong one is declined - * out loud with its reason, and approval checks again. + * What a member's device does with a proposal to sign one of its group's statements about a + * confederation (docs/confederation-without-coordinator.md, D6, Phase 4): a right one is put to the + * member, a wrong one is declined out loud with its reason, and approval checks again. * - * Each proposal is a real one, made on Alice's device and handed to Bob's through the inbound - * path. Who a device sees as the group's admins is [RoomAdmins.override], per device, since the - * harness's room has no MLS state. + * Each proposal is a real one, made on one admin's device and handed to the next through the + * group's room, its seals sealed to the other groups' real inbox keys. */ class ConfederationDeclineJvmTest { - private val names = listOf(npub(31), npub(32), npub(33)) - private val harness = SigningProposalHarness(names = names) - private val alice = harness.members[0] - private val bob = harness.members[1] - private val carol = harness.members[2] - - private val polis = key(2) - private val ekklesia = key(3) - - /** Who the device being opened sees as the group's admins. */ - private var admins: Set = harness.members.toSet() - - @BeforeTest - fun seeAdmins() { - RoomAdmins.override = { id -> if (id == harness.roomId) RoomAdmins(admins, governed = false) else null } - } - - @AfterTest - fun close() { - RoomAdmins.override = null - harness.close() - } - + private val network = ConfederationTestGroups() + private val agora = network.groups[0] + private val polis = network.groups[1] + private val ekklesia = network.groups[2] private val now get() = Clock.System.now().epochSeconds - private fun deliver(sent: SigningProposalHarness.Sent, to: HexKey, prepare: suspend (GizaDatabase) -> Unit = {}) = - runBlocking { harness.deliver(sent, to, prepare) } + @BeforeTest + fun setUp() = runBlocking { network.setUp() } - private fun proposeHere(proposer: HexKey = alice, prepare: suspend (GizaDatabase) -> Unit = {}) = runBlocking { - harness.propose(proposer, prepare) { db, room -> - ConfederationManager.proposeConfederation( - db, room, proposer, - invitees = listOf(Invitee(npub(2)), Invitee(npub(3))), - threshold = 2, - name = "Atlas", - expiresAt = now + ConfederationKinds.DEFAULT_EXPIRY_SECONDS, - ) - } + @AfterTest + fun close() = network.close() + + private val proposer get() = agora.devices[0] + private val signer get() = agora.devices[1] + + private suspend fun proposeAtlas(createdAt: Long = now, expiresAt: Long = now + ConfederationKinds.DEFAULT_EXPIRY_SECONDS): FrostSigningSession { + val session = ConfederationManager.proposeConfederation( + proposer.db, proposer.room(), proposer.publicKey, + invitees = listOf(polis.roomId, ekklesia.roomId), threshold = 2, name = "Atlas", + expiresAt = expiresAt, createdAt = createdAt, + ) + agora.harness.pump() + return session } - private fun session(sent: SigningProposalHarness.Sent) = runBlocking { - assertNotNull(harness.db.frostSigningSessionDao().getSessionById(sent.session.id)) + private suspend fun at(device: GroupInboxHarness.Device, sessionId: String) = + assertNotNull(device.db.frostSigningSessionDao().getSessionById(sessionId), "the session reached ${device.name}") + + 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 = at(device, sessionId) + assertNull(session.signDeclinedAt, "not declined: ${ConfederationRefusal.reasonFor(device.db, sessionId)}") + assertTrue(FrostSigningManager.isAwaitingApproval(session, device.db.frostSigningSessionDao().getItems(sessionId))) } - private fun assertAsked(sent: SigningProposalHarness.Sent) = runBlocking { - val session = session(sent) - assertNull(session.signDeclinedAt, "not declined") - assertTrue(FrostSigningManager.isAwaitingApproval(session, harness.db.frostSigningSessionDao().getItems(session.id))) - assertEquals(emptyList(), harness.queued(FrostSigningEvents.DECLINE)) - } - - private fun assertDeclined(sent: SigningProposalHarness.Sent, reason: String) = runBlocking { - val session = session(sent) + private suspend fun assertDeclined(device: GroupInboxHarness.Device, roomId: HexKey, sessionId: String, reason: String) { + val session = at(device, sessionId) assertNotNull(session.signDeclinedAt, "declined, and filed so the decline goes out") assertNull(session.signApprovedAt) - assertEquals(listOf(reason), harness.queued(FrostSigningEvents.DECLINE).map { it.content }, "said out loud, with its reason") - assertEquals(emptyList(), harness.queued(FrostSigningEvents.NONCE)) + assertEquals(listOf(reason), declines(device, roomId), "said out loud, with its reason") } - // --- a proposal, with the proposer's own acceptance + // --- a proposal @Test - fun `a proposal sealed with the group's own admins is put to the member`() { - val sent = proposeHere() - deliver(sent, bob) - assertAsked(sent) - - val proposal = runBlocking { harness.db.frostSigningSessionDao().getItems(sent.session.id) } - .first().let { Event.fromJson(it.unsignedEventJson) } - assertEquals("A confederation, Atlas", ProposedEvent.summarize(proposal).label) - assertEquals(alice, ConfederationProposalEvent.parse(proposal)?.coordinator) + fun `a proposal with the group's own admins is put to the member, who reads it`() = runBlocking { + val session = proposeAtlas() + 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.any { it.startsWith("Groups: This group, Polis, Ekklesia") }, "$notes") + assertTrue(notes.any { it.contains("to the admins of Polis, Ekklesia") }, "$notes") } @Test - fun `a member who is not an admin cannot coordinate`() { - admins = setOf(bob, carol) - assertFailsWith { proposeHere() } - } - - @Test - fun `a coordinator the group does not have as an admin is declined`() { - val sent = proposeHere() - admins = setOf(bob, carol) - deliver(sent, bob) - assertDeclined(sent, ConfederationRefusal.COORDINATOR_NOT_ADMIN) - } - - @Test - fun `a seal over admins this device does not see is declined`() { - admins = harness.members.toSet() + npub(40) - val sent = proposeHere() - admins = harness.members.toSet() - deliver(sent, bob) - assertDeclined(sent, ConfederationRefusal.SEAL) - } - - @Test - fun `a proposal that leaves out the seal's secret is declined`() { - val sent = proposeHere().let { it.copy(tags = it.tags.filterNot { t -> t[0] == ConfederationSealTag.TAG_NAME }.toTypedArray()) } - deliver(sent, bob) - assertDeclined(sent, ConfederationRefusal.SEAL) + fun `a member who is not an admin cannot propose`() = runBlocking { + agora.harness.admins = agora.members.drop(1).toSet() + assertFailsWith { proposeAtlas() } } @Test fun `admins who change before approval make approval a decline`() = runBlocking { - val sent = proposeHere() - deliver(sent, bob) - assertAsked(sent) + val session = proposeAtlas() + assertAsked(signer, session.id) - admins = setOf(alice, bob) - FrostSigningManager.approve(harness.db, harness.room, sent.session.id) - assertDeclined(sent, ConfederationRefusal.SEAL) - } - - /** A batch built by hand, so one thing about it can be wrong: [coordinator] names someone else. */ - private fun batch(coordinator: HexKey, withAcceptance: Boolean = true) = runBlocking { - harness.propose(alice) { db, room -> - val disclosure = assertNotNull(ConfederationManager.disclosureFor(db, room.chatRoom.id)) - val secret = ByteArray(32) { 9 } - FrostSigningManager.proposeSigningBatch( - db, room, alice, - lead = EventTemplate( - now, ConfederationKinds.PROPOSAL, - ConfederationProposalEvent.assembleTags( - listOf(Invitee(room.chatRoom.id), Invitee(npub(2))), coordinator, 2, "Atlas", "ab".repeat(32), - now + 1000, - ), - "", - ), - dependents = { lead -> - if (!withAcceptance) return@proposeSigningBatch emptyList() - val sealed = ConfederationSeal.seal(secret, coordinator, disclosure.listFor(lead.id)!!) - listOf( - EventTemplate( - now, ConfederationKinds.ACCEPTANCE, - ConfederationProposalAcceptanceEvent.assembleTags(lead.id, null, room.chatRoom.id, coordinator, sealed.ephemeralPublicKey), - sealed.content, - ) - ) - }, - proposalTags = ConfederationRefusal.Carried(secret.toHex(), null).toTags(), - ) - } + agora.harness.admins = agora.members.take(2).toSet() + FrostSigningManager.approve(signer.db, signer.room(), session.id) + assertDeclined(signer, agora.roomId, session.id, ConfederationRefusal.ADMINS) } @Test - fun `a coordinator who is not the proposer is declined`() { - val sent = batch(coordinator = carol) - deliver(sent, bob) - assertDeclined(sent, ConfederationRefusal.COORDINATOR) + fun `an expired proposal is declined`() = runBlocking { + val session = proposeAtlas(createdAt = now - 100, expiresAt = now - 50) + assertDeclined(signer, agora.roomId, session.id, ConfederationRefusal.EXPIRY) } - @Test - fun `the same batch naming its proposer is put to the member`() { - val sent = batch(coordinator = alice) - deliver(sent, bob) - assertAsked(sent) + /** A statement's seals built by hand, so one thing about them can be wrong. */ + private suspend fun proposeBuilt( + rumor: Event, + recipients: suspend () -> List = { listOf(polis.roomId, ekklesia.roomId).sorted().map { InboxReplies.recipientOf(proposer.db, it) } }, + tamper: (InboxReplies.Built, ByteArray) -> InboxReplies.Built = { built, _ -> built }, + ): FrostSigningSession { + val key = assertNotNull(ConfederationManager.announcedInboxKey(proposer.db, agora.roomId, proposer.publicKey)) + val secret = key.secretKey!!.hexToByteArray() + val built = tamper(InboxReplies.sealRumor(agora.roomId, rumor, recipients(), secret, key.generation), secret) + val session = ConfederationManager.proposeSealed(proposer.db, proposer.room(), proposer.publicKey, rumor, built, secret, null) + agora.harness.pump() + return session } - @Test - fun `a proposal without its proposer's acceptance is declined`() { - val sent = batch(coordinator = alice, withAcceptance = false) - deliver(sent, bob) - assertDeclined(sent, ConfederationRefusal.SHAPE) - } - - @Test - fun `a confederation event batched with anything else is declined`() { - val sent = runBlocking { - harness.propose(alice) { db, room -> - FrostSigningManager.proposeSigningBatch( - db, room, alice, - events = listOf( - EventTemplate(now, TextNoteEvent.KIND, arrayOf(), "hello"), - EventTemplate(now, ConfederationKinds.REJECTION, arrayOf(arrayOf("e", "a".repeat(64))), ""), - ), - ) - } - } - deliver(sent, bob) - assertDeclined(sent, ConfederationRefusal.SHAPE) - } - - // --- answering another group's proposal - - private fun inviting(expiresAt: Long = now + 1000) = ConfederationTestGroups.proposal( - polis, listOf(npub(2), harness.roomId, npub(3)), coordinator = npub(9), - createdAt = now - 10, expiresAt = expiresAt, + private fun rumor(admins: Collection = agora.members) = ConfederationStatements.proposal( + agora.roomId, listOf(polis.roomId, ekklesia.roomId), 2, "Atlas", "ab".repeat(32), now + 1000, + ConfederationAdminList.ofV2(null, agora.roomId, 2, admins)!!, now, ) - private fun answer(proposal: Event, how: suspend (GizaDatabase, mobi.giza.compose.database.model.intermdiate.LocalChatRoom) -> mobi.giza.compose.database.model.FrostSigningSession) = - runBlocking { harness.propose(alice, prepare = { ConfederationManager.record(it, proposal) }, propose = how) } - @Test - fun `an acceptance is put to the member, with the proposal it answers carried`() { - val proposal = inviting() - val sent = answer(proposal) { db, room -> ConfederationManager.proposeAcceptance(db, room, alice, proposal.id) } - deliver(sent, bob) - assertAsked(sent) - runBlocking { assertNotNull(harness.db.confederationDao().getEvent(proposal.id), "the carried proposal is filed") } + fun `an admin list that is not this group's is declined`() = runBlocking { + val stranger = ConfederationStatementFixture.npub(77) + val session = proposeBuilt(rumor(agora.members + stranger)) + assertDeclined(signer, agora.roomId, session.id, ConfederationRefusal.ADMINS) } @Test - fun `an answer to a proposal this device has not seen is declined`() { - val proposal = inviting() - val sent = answer(proposal) { db, room -> ConfederationManager.proposeRejection(db, room, alice, proposal.id) } - .let { it.copy(tags = it.tags.filterNot { t -> t[0] == ConfederationCarriedProposalTag.TAG_NAME }.toTypedArray()) } - deliver(sent, bob) - assertDeclined(sent, ConfederationRefusal.UNKNOWN_PROPOSAL) + fun `seals that do not all hold the statement are declined`() = runBlocking { + val other = rumor().let { ConfederationStatements.proposal(agora.roomId, listOf(polis.roomId, ekklesia.roomId), 2, "Another", "cd".repeat(32), now + 1000, ConfederationAdminList.ofV2(null, agora.roomId, 2, agora.members)!!, now) } + val session = proposeBuilt(rumor()) { built, secret -> + // Ekklesia's copy says something else. + val index = built.manifest.seals.indexOfFirst { it.recipient == ekklesia.roomId } + val swapped = InboxSeal.template(other, secret, built.manifest.seals[index].key, built.seals[index].createdAt) + built.copy(seals = built.seals.toMutableList().also { it[index] = swapped }) + } + assertDeclined(signer, agora.roomId, session.id, ConfederationRefusal.SEALS) } @Test - fun `an answer to a proposal another group has rejected is declined`() { - val proposal = inviting() - val sent = answer(proposal) { db, room -> ConfederationManager.proposeAcceptance(db, room, alice, proposal.id) } - deliver(sent, bob, prepare = { ConfederationManager.record(it, ConfederationTestGroups.rejection(ekklesia, proposal)) }) - assertDeclined(sent, ConfederationRefusal.CLOSED) + fun `a seal to a key the group did not announce is declined`() = runBlocking { + val session = proposeBuilt(rumor(), recipients = { + listOf(polis.roomId, ekklesia.roomId).sorted().map { group -> + val real = InboxReplies.recipientOf(proposer.db, group) + if (group == polis.roomId) real.copy(encryptionKey = InboxWire.publicKeyOf(ByteArray(32) { 7 })) else real + } + }) + assertDeclined(signer, agora.roomId, session.id, ConfederationRefusal.SEALS) } @Test - fun `an answer to an expired proposal is declined`() { - val proposal = inviting(expiresAt = now - 1) - val sent = answer(proposal) { db, room -> ConfederationManager.proposeRejection(db, room, alice, proposal.id) } - deliver(sent, bob) - assertDeclined(sent, ConfederationRefusal.EXPIRY) + fun `a share-holder without the inbox key cannot read it, and says so`() = runBlocking { + signer.db.inboxKeyDao().wipeKeys(agora.roomId, signer.publicKey, Clock.System.now()) + val session = proposeAtlas() + assertDeclined(signer, agora.roomId, session.id, ConfederationRefusal.CANNOT_READ) } @Test - fun `only the proposing group can withdraw`() { - val proposal = inviting() - val sent = answer(proposal) { db, room -> ConfederationManager.proposeWithdrawal(db, room, alice, proposal.id) } - deliver(sent, bob) - assertDeclined(sent, ConfederationRefusal.NOT_PROPOSER) + fun `a statement as a public event is declined`() = runBlocking { + val session = FrostSigningManager.proposeSigningBatch( + proposer.db, proposer.room(), proposer.publicKey, + events = listOf(EventTemplate(now, ConfederationKinds.PROPOSAL, rumor().tags, rumor().content)), + ) + agora.harness.pump() + assertDeclined(signer, agora.roomId, session.id, ConfederationRefusal.PUBLIC) } @Test - fun `a resent proposal carries its seal again`() = runBlocking { - val sent = proposeHere() - val tags = ConfederationRefusal.carriedTagsFor(harness.db, sent.session.id) - assertEquals(1, tags.count { it[0] == ConfederationSealTag.TAG_NAME }) + fun `a resent proposal carries its statement and its manifest again`() = runBlocking { + val session = proposeAtlas() + val tags = ConfederationRefusal.carriedTagsFor(proposer.db, session.id) + InboxRefusal.carriedTagsFor(proposer.db, session.id) + assertEquals(1, tags.count { it[0] == ConfederationRefusal.RUMOR_TAG }) + assertEquals(1, tags.count { it[0] == InboxReplyManifest.TAG_NAME }) + } + + // --- answers + + private suspend fun atlas(): HexKey { + network.signed(agora) { proposeAtlas().id } + return agora.devices[0].db.confederationDao().getProposals().single().id + } + + private suspend fun answerOn(group: ConfederationTestGroups.Group, propose: suspend (GroupInboxHarness.Device) -> FrostSigningSession): String { + val session = propose(group.devices[0]) + group.harness.pump() + return session.id + } + + @Test + fun `an acceptance is put to the member`() = runBlocking { + val proposalId = atlas() + val sessionId = answerOn(polis) { ConfederationManager.proposeAcceptance(it.db, it.room(), it.publicKey, proposalId) } + assertAsked(polis.devices[1], sessionId) + } + + @Test + fun `a second answer from the same group is declined`() = runBlocking { + val proposalId = atlas() + network.signed(polis) { ConfederationManager.proposeAcceptance(it.db, it.room(), it.publicKey, proposalId).id } + val sessionId = answerOn(polis) { ConfederationManager.proposeRejection(it.db, it.room(), it.publicKey, proposalId) } + assertDeclined(polis.devices[1], polis.roomId, sessionId, ConfederationRefusal.ANSWERED) + } + + @Test + fun `an answer to a proposal another group has rejected is declined`() = runBlocking { + val proposalId = atlas() + network.signed(polis) { ConfederationManager.proposeRejection(it.db, it.room(), it.publicKey, proposalId).id } + val sessionId = answerOn(ekklesia) { ConfederationManager.proposeAcceptance(it.db, it.room(), it.publicKey, proposalId) } + assertDeclined(ekklesia.devices[1], ekklesia.roomId, sessionId, ConfederationRefusal.CLOSED) + } + + @Test + fun `only the proposing group can withdraw`() = runBlocking { + val proposalId = atlas() + val sessionId = answerOn(polis) { ConfederationManager.proposeWithdrawal(it.db, it.room(), it.publicKey, proposalId) } + assertDeclined(polis.devices[1], polis.roomId, sessionId, ConfederationRefusal.NOT_PROPOSER) + } + + @Test + fun `the proposing group withdraws, and every group hears it`() = runBlocking { + val proposalId = atlas() + network.signed(agora) { ConfederationManager.proposeWithdrawal(it.db, it.room(), it.publicKey, proposalId).id } + network.everyDevice.forEach { + assertEquals(mobi.giza.compose.nostr.confederation.ConfederationProposalState.WITHDRAWN, ConfederationManager.status(it.db, proposalId)?.state) + } } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationNetworkJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationNetworkJvmTest.kt index 84029bd8..e5f8b947 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationNetworkJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationNetworkJvmTest.kt @@ -1,261 +1,156 @@ package mobi.giza.compose.managers -import androidx.room3.Room -import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.KeyMaterial import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertNotNull import kotlin.test.assertTrue 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.DkgParticipantMessage -import mobi.giza.compose.database.model.DkgSession -import mobi.giza.compose.database.model.MarmotInnerEvent -import mobi.giza.compose.database.model.NostrEvent -import mobi.giza.compose.database.model.Profile -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.database.model.types.DkgRitualStage -import mobi.giza.compose.database.model.types.FrostSigningStage -import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.confederation.ConfederationKinds -import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent.Invitee import mobi.giza.compose.nostr.confederation.ConfederationProposalState -import mobi.giza.compose.nostr.confederation.ConfederationSeal -import mobi.giza.compose.nostr.dkg.DkgRitualEvents -import mobi.giza.compose.nostr.frost.FrostSigningEvents import kotlin.time.Clock /** - * Three groups agreeing, or not, to form a confederation, end to end (docs/confederation.md, - * Phase 7): real FROST signatures by each group's quorum, every device's own refusals, and the - * relays stood in for by copying each signed event to every device. Afterwards every device on - * every group computes the same state, and the coordinator opens each acceptance to the admins - * that group has. + * Three groups agreeing, or not, to form a confederation, end to end, with nobody coordinating it + * (docs/confederation-without-coordinator.md, Phases 3 to 5): each group's statement signed by its + * quorum and sealed to every group's inbox, every device's own refusals, and the relays stood in + * for by handing every wrap to every device. Afterwards every admin's device in every group holds + * the same statements, computes the same state, and reads every group's admins. */ class ConfederationNetworkJvmTest { - private fun key(group: Int, member: Int) = PrivateKey(ByteArray(32).also { it[0] = 0x41; it[30] = group.toByte(); it[31] = member.toByte() }) - - private inner class Group(val index: Int, val name: String) { - val secrets = (1..3).map { key(index, it) } - val members = secrets.map { it.publicKey().xOnly().value.toHex() } - val material: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey(ByteVector32(("c0" + index.toString().padStart(2, '0')).padEnd(62, '0') + "a1")), - nParticipants = 3, - threshold = 2, - ) - val thresholdPublicKey = material.thresholdPublicKey.value.toHex() - val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) - val ceremonyId = "ceremony$index".padEnd(64, '0') - val hostKeys = (0..2).map { "2${('a' + it)}$index".padEnd(66, '0') } - lateinit var devices: List - } - - private inner class Device(val group: Group, val signerIndex: Int, val db: GizaDatabase, val room: LocalChatRoom) { - val publicKey get() = group.members[signerIndex] - val received = mutableSetOf() - } - - private val groups = listOf(Group(1, "Agora"), Group(2, "Polis"), Group(3, "Ekklesia")) - private val agora = groups[0] - private val polis = groups[1] - private val ekklesia = groups[2] - private val everyDevice get() = groups.flatMap { it.devices } + private val network = ConfederationTestGroups() + private val agora = network.groups[0] + private val polis = network.groups[1] + private val ekklesia = network.groups[2] @BeforeTest - fun network() = runBlocking { - RoomAdmins.override = { id -> groups.firstOrNull { it.roomId == id }?.let { RoomAdmins(it.members.toSet(), governed = false) } } - groups.forEach { group -> group.devices = (0..2).map { device(group, it) } } - } + fun setUp() = runBlocking { network.setUp() } @AfterTest - fun close() { - RoomAdmins.override = null - groups.forEach { g -> if (g.isInitialised()) g.devices.forEach { it.db.close() } } - } - - private fun Group.isInitialised() = runCatching { devices }.isSuccess - - private suspend fun device(group: Group, signerIndex: Int): Device { - val db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) - val owner = group.members[signerIndex] - group.members.forEach { member -> - val eventId = "e$member".take(64) - db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = member, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) - db.profileDao().upsert(Profile(publicKey = member, nostrEventId = eventId)) - } - val chatRoom = ChatRoom( - id = group.roomId, userPublicKey = owner, subject = "#${group.name}", - description = SharedKeyDerivation.describe("Admins of the group."), mlsGroupState = "00", - ) - db.chatRoomDao().upsert(chatRoom) - db.dkgSessionDao().upsert( - DkgSession( - id = group.ceremonyId, chatRoomId = group.roomId, coordinatorPublicKey = group.members[0], userPublicKey = owner, - threshold = 2, participantCount = 3, stage = DkgRitualStage.COMPLETE, hostPublicKey = group.hostKeys[signerIndex], - round1Random = "1".repeat(64), round2AuxRandom = "2".repeat(64), thresholdPublicKey = group.thresholdPublicKey, - secretShare = group.material.secretShares[signerIndex].value.toHex(), - publicShares = group.material.publicShares.joinToString(",") { it.value.toHex() }, - ) - ) - group.members.forEachIndexed { i, member -> - db.dkgSessionDao().upsert(DkgParticipantMessage(sessionId = group.ceremonyId, participantPublicKey = member, kind = DkgRitualEvents.HOST_KEY, payload = group.hostKeys[i])) - } - return Device(group, signerIndex, db, LocalChatRoom(chatRoom = chatRoom)) - } - - /** Ferries a group's signing messages between its devices until nothing moves. */ - private suspend fun pump(group: Group) { - var moved = true - while (moved) { - moved = false - for (from in group.devices) for (to in group.devices) { - if (from === to) continue - from.db.marmotInnerEventDao().getByChatRoomAndKinds(group.roomId, FrostSigningEvents.ALL.toList()) - .filter { it.publicKey == from.publicKey } - .sortedWith(compareBy({ it.createdAt }, { it.kind })) - .forEach { queued -> - if (!to.received.add(queued.id)) return@forEach - moved = true - to.db.marmotInnerEventDao().upsert( - MarmotInnerEvent( - id = queued.id, publicKey = queued.publicKey, kind = queued.kind, createdAt = queued.createdAt, - tags = queued.tags, content = queued.content, chatRoomId = group.roomId, - ) - ) - FrostSigningManager.processSigningPayload( - database = to.db, localChatRoom = to.room, - innerEvent = Event(queued.id, queued.publicKey, queued.createdAt.epochSeconds, queued.kind, queued.tags, queued.content, ""), - userPublicKey = to.publicKey, - ) - } - } - } - } - - /** The relays: every event a coordinating device owes goes to every device, and is marked sent. */ - private suspend fun relay() { - everyDevice.forEach { from -> - from.db.confederationDao().observeUnpublished().first().forEach { owed -> - everyDevice.forEach { to -> ConfederationManager.record(to.db, owed.toEvent()) } - from.db.confederationDao().markPublished(owed.id, Clock.System.now()) - } - } - } - - /** [group]'s first member proposes with [propose]; its second approves; the quorum signs; the relays carry it. */ - private suspend fun signed(group: Group, propose: suspend (Device) -> String) { - val sessionId = propose(group.devices[0]) - pump(group) - val second = group.devices[1] - FrostSigningManager.approve(second.db, second.room, sessionId) - pump(group) - group.devices.forEach { device -> - assertEquals(FrostSigningStage.COMPLETE, device.db.frostSigningSessionDao().getSessionById(sessionId)?.stage, "${group.name} signed on device ${device.signerIndex}") - } - relay() - } + fun close() = network.close() private suspend fun proposeAtlas(): HexKey { - signed(agora) { device -> + network.signed(agora) { device -> ConfederationManager.proposeConfederation( - device.db, device.room, device.publicKey, - invitees = listOf(Invitee(polis.roomId), Invitee(ekklesia.roomId)), + device.db, device.room(), device.publicKey, + invitees = listOf(polis.roomId, ekklesia.roomId), threshold = 2, name = "Atlas", expiresAt = Clock.System.now().epochSeconds + ConfederationKinds.DEFAULT_EXPIRY_SECONDS, ).id } - return everyDevice.first().db.confederationDao().getProposals().single().id + return network.everyDevice.first().db.confederationDao().getProposals().single().id } - private suspend fun states(proposalId: HexKey) = everyDevice.map { ConfederationManager.status(it.db, proposalId)?.state }.toSet() + private suspend fun states(proposalId: HexKey) = network.everyDevice.map { ConfederationManager.status(it.db, proposalId)?.state }.toSet() + + @Test + fun `the proposal reaches every admin of every group, and nothing is sent bare`() = runBlocking { + val proposalId = proposeAtlas() + assertEquals(setOf(ConfederationProposalState.OPEN), states(proposalId)) + network.everyDevice.forEach { device -> + val row = assertNotNull(device.db.confederationDao().getEvent(proposalId), "on ${device.name}") + assertEquals("", com.vitorpamplona.quartz.nip01Core.core.Event.fromJson(row.eventJson).sig, "a rumor, never a public event") + assertEquals(emptyList(), device.db.confederationDao().observeUnpublished().first(), "nothing owed to public relays") + } + // Nobody's inbox shows it as a conversation. + network.everyDevice.forEach { assertEquals(emptyList(), it.db.groupInboxDao().getMessages(it.harness().roomId)) } + } + + private fun GroupInboxHarness.Device.harness() = network.groups.first { g -> g.devices.contains(this) }.harness @Test fun `one group declining ends it for every device on every group`() = runBlocking { val proposalId = proposeAtlas() - assertEquals(setOf(ConfederationProposalState.OPEN), states(proposalId)) - - signed(polis) { ConfederationManager.proposeAcceptance(it.db, it.room, it.publicKey, proposalId).id } - signed(ekklesia) { ConfederationManager.proposeRejection(it.db, it.room, it.publicKey, proposalId, "Not this year").id } + network.signed(polis) { ConfederationManager.proposeAcceptance(it.db, it.room(), it.publicKey, proposalId).id } + network.signed(ekklesia) { ConfederationManager.proposeRejection(it.db, it.room(), it.publicKey, proposalId, "Not this year").id } assertEquals(setOf(ConfederationProposalState.REJECTED), states(proposalId)) } @Test - fun `every group accepting is seen by every device, and the coordinator opens each group's admins`() = runBlocking { + fun `every group accepting is seen by every device, and every admin reads every group's admins`() = runBlocking { val proposalId = proposeAtlas() - signed(polis) { ConfederationManager.proposeAcceptance(it.db, it.room, it.publicKey, proposalId).id } - signed(ekklesia) { ConfederationManager.proposeAcceptance(it.db, it.room, it.publicKey, proposalId).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 } assertEquals(setOf(ConfederationProposalState.ACCEPTED), states(proposalId)) - - val coordinator = agora.devices[0] - val status = assertNotNull(ConfederationManager.status(coordinator.db, proposalId)) - groups.forEach { group -> - val acceptance = assertNotNull(status.acceptances[group.roomId], "${group.name} accepted") - val conversationKey = ConfederationSeal.conversationKey(agora.secrets[0].value.toByteArray(), acceptance.ephemeralPublicKey) - val list = assertNotNull(ConfederationSeal.open(conversationKey, acceptance.content), "the coordinator opens ${group.name}'s") - assertEquals(group.members.sorted(), list.admins) - assertEquals(2, list.threshold) - assertEquals(group.roomId, list.group) + network.everyDevice.forEach { device -> + val lists = assertNotNull(ConfederationManager.status(device.db, proposalId)).adminLists + network.groups.forEach { group -> + val list = assertNotNull(lists[group.roomId], "${device.name} reads ${group.name}'s") + assertEquals(group.members.sorted(), list.admins) + assertEquals(2, list.threshold) + } } } @Test fun `each group's room has a line for the proposal and for every answer`() = runBlocking { val proposalId = proposeAtlas() - signed(polis) { ConfederationManager.proposeAcceptance(it.db, it.room, it.publicKey, proposalId).id } + network.signed(polis) { ConfederationManager.proposeAcceptance(it.db, it.room(), it.publicKey, proposalId).id } val lines = ekklesia.devices[2].db.chatMessageDao().getChatMessagesByChatRoomId(ekklesia.roomId) .map { it.chatMessage.messageType } .filter { it in ChatMessage.CONFEDERATION_TYPES } - // Agora's proposal, Agora's own acceptance signed with it, and Polis's acceptance. - assertEquals( - listOf(ChatMessage.TYPE_CONFEDERATION_PROPOSED, ChatMessage.TYPE_CONFEDERATION_ACCEPTED, ChatMessage.TYPE_CONFEDERATION_ACCEPTED).sorted(), - lines.sorted(), - ) + // Agora's proposal, which is its acceptance too, and Polis's acceptance. + assertEquals(listOf(ChatMessage.TYPE_CONFEDERATION_ACCEPTED, ChatMessage.TYPE_CONFEDERATION_PROPOSED).sorted(), lines.sorted()) } @Test - fun `the coordinator's device says what forming it would take, and nobody else's says anything`() = runBlocking { + fun `every admin's device says what forming it would take, not one coordinator's`() = runBlocking { val proposalId = proposeAtlas() - signed(polis) { ConfederationManager.proposeAcceptance(it.db, it.room, it.publicKey, proposalId).id } - signed(ekklesia) { ConfederationManager.proposeAcceptance(it.db, it.room, it.publicKey, proposalId).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 } - val coordinator = agora.devices[0] - // D2 at the coordinator: each group's profile has come back from the relays. - groups.forEach { group -> - val eventId = "f${group.index}".padEnd(64, '0') - coordinator.db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = group.roomId, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) - coordinator.db.profileDao().upsert(Profile(publicKey = group.roomId, nostrEventId = eventId, displayName = group.name, createdAt = kotlin.time.Instant.fromEpochSeconds(1_790_000_000))) + network.everyDevice.forEach { device -> + val outcome = assertNotNull(ConfederationManager.outcome(device.db, proposalId), "on ${device.name}") + assertTrue(outcome.ready, "${outcome.problems}") + assertEquals(9, outcome.roleCount) + assertEquals(emptyMap(), outcome.overlaps) } - - val outcome = assertNotNull(ConfederationManager.outcome(coordinator.db, proposalId, agora.secrets[0])) - assertTrue(outcome.ready, "${outcome.problems}") - assertEquals(9, outcome.roleCount) - assertEquals(emptyMap(), outcome.overlaps) - - assertEquals(null, ConfederationManager.outcome(polis.devices[0].db, proposalId, polis.secrets[0]), "only the coordinator's key opens them") } @Test - fun `a group without a public profile at the coordinator is named as what stands in the way`() = runBlocking { - val proposalId = proposeAtlas() - signed(polis) { ConfederationManager.proposeAcceptance(it.db, it.room, it.publicKey, proposalId).id } - signed(ekklesia) { ConfederationManager.proposeAcceptance(it.db, it.room, it.publicKey, proposalId).id } + fun `a device that missed the proposal answers from the invitation its signing proposal carries`() = runBlocking { + // Polis's second admin never hears the proposal. + val forgetful = polis.devices[1] + network.signed(agora, except = setOf(forgetful)) { device -> + ConfederationManager.proposeConfederation( + device.db, device.room(), device.publicKey, + invitees = 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 + assertEquals(null, ConfederationManager.proposal(forgetful.db, proposalId)) - val outcome = assertNotNull(ConfederationManager.outcome(agora.devices[0].db, proposalId, agora.secrets[0])) - assertEquals(false, outcome.ready) - assertEquals(3, outcome.problems.count { it.startsWith("No public profile found") }) + // It is Polis's approver all the same: the acceptance's signing proposal carries the invitation. + network.signed(polis) { ConfederationManager.proposeAcceptance(it.db, it.room(), it.publicKey, proposalId).id } + assertNotNull(ConfederationManager.proposal(forgetful.db, proposalId), "filed from the carried invitation") + } + + @Test + fun `a group that has announced no inbox cannot be invited`() = runBlocking { + val withoutInbox = ConfederationTestGroups(names = listOf("Stoa", "Lyceum"), keySeries = 1) + try { + withoutInbox.setUp(withoutInbox = setOf("Lyceum")) + val stoa = withoutInbox.groups[0] + val device = stoa.devices[0] + val failure = assertFailsWith { + ConfederationManager.proposeConfederation( + device.db, device.room(), device.publicKey, + invitees = listOf(withoutInbox.groups[1].roomId), threshold = 2, name = "Atlas", + expiresAt = Clock.System.now().epochSeconds + ConfederationKinds.DEFAULT_EXPIRY_SECONDS, + ) + } + assertTrue(failure.message!!.contains("has announced no inbox"), failure.message) + } finally { + withoutInbox.close() + } } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationPeople.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationPeople.kt new file mode 100644 index 00000000..b315fefc --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationPeople.kt @@ -0,0 +1,133 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PrivateKey +import kotlin.time.Clock +import kotlin.time.Instant +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ConfederationCeremony +import mobi.giza.compose.database.model.GiftWrapPayload +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.ConfederationRitualEvents + +/** + * Every admin of every group a confederation names, one person to a device, each holding every + * group's statement as their inboxes would have opened them, for the key ceremony + * (docs/confederation-without-coordinator.md, D8). The statements come from + * [ConfederationStatementFixture]; the inboxes themselves are [ConfederationTestGroups]'s business. + * + * Each device makes the ceremony's NIP-17 room up front, as the inbound path would on the first + * message, and [pump] ferries gift wraps between them, stored first. + */ +class ConfederationPeople( + /** Each group's admins, by the number [secret] makes a person's key from. A number in two groups is one person. */ + val adminsByGroup: List>, + tag: Int = 0x61, + val names: List = listOf("Agora", "Polis", "Ekklesia").take(adminsByGroup.size), +) { + private val tagByte = tag.toByte() + fun secret(n: Int) = PrivateKey(ByteArray(32).also { it[0] = tagByte; it[31] = n.toByte() }) + fun npub(n: Int): HexKey = npub(secret(n)) + fun npub(key: PrivateKey): HexKey = key.publicKey().xOnly().value.toHex() + + val groupKeys = adminsByGroup.indices.map { secret(it + 1) } + val groups = groupKeys.map(::npub) + + inner class Device(val secret: PrivateKey, val db: GizaDatabase) { + val person = npub(secret) + lateinit var room: LocalChatRoom + val received = mutableSetOf() + val nsec: ByteArray get() = secret.value.toByteArray() + } + + val devices = linkedMapOf() + lateinit var proposal: Event + lateinit var acceptances: List + val proposalId: HexKey get() = proposal.id + + fun device(n: Int): Device = devices.getValue(npub(n)) + + /** + * The statements, and a device per person holding them. [statementsFor] chooses which a device + * holds; every one, by default. + */ + suspend fun setUp(statementsFor: (Device) -> List> = { everyStatement() }) { + val now = Clock.System.now().epochSeconds + proposal = ConfederationStatementFixture.proposal( + groupKeys[0], groups, adminsByGroup[0].map(::npub), createdAt = now - 10, expiresAt = now + 1000, + ) + acceptances = groupKeys.drop(1).mapIndexed { i, key -> + ConfederationStatementFixture.acceptance(key, proposal, adminsByGroup[i + 1].map(::npub), createdAt = now - 5) + } + val people = adminsByGroup.flatten().distinct() + people.map(::secret).forEach { key -> + val db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + (people.map(::npub)).forEach { member -> profile(db, member, member.take(6)) } + groups.forEachIndexed { i, group -> profile(db, group, names[i]) } + val device = Device(key, db) + devices[device.person] = device + statementsFor(device).forEach { (by, rumor) -> ConfederationStatementFixture.file(db, by, rumor) } + device.room = db.nostrNip17Dao().createNip17ChatRoom(device.person, people.map(::npub).filter { it != device.person }, "Atlas")!! + } + } + + fun everyStatement(): List> = listOf(groupKeys[0] to proposal) + groupKeys.drop(1).zip(acceptances) + + private suspend fun profile(db: GizaDatabase, key: HexKey, name: String) { + val eventId = Crypto.sha256(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 = name, createdAt = Instant.fromEpochSeconds(1_790_000_000))) + } + + /** + * Ferries every queued ceremony message to every other device, until nothing moves. [tamper] + * may change or drop (null) what one device receives from another. + */ + suspend fun pump(tamper: (from: Device, to: Device, payload: GiftWrapPayload) -> GiftWrapPayload? = { _, _, it -> it }) { + var moved = true + while (moved) { + moved = false + for (from in devices.values) for (to in devices.values) { + if (from === to) continue + from.db.giftWrapPayloadDao().getByChatRoomAndKinds(from.room.chatRoom.id, ConfederationRitualEvents.ALL.toList()) + .filter { it.publicKey == from.person } + .sortedBy { it.createdAt } + .forEach { original -> + if (!to.received.add(original.id)) return@forEach + moved = true + val queued = tamper(from, to, original) ?: return@forEach + to.db.giftWrapPayloadDao().upsert(queued.copy(chatRoomId = to.room.chatRoom.id)) + ConfederationRitualManager.process( + to.db, to.room, + Event(queued.id, queued.publicKey, queued.createdAt.epochSeconds, queued.kind, queued.tags, queued.content, ""), + to.person, to.nsec, + ) + } + } + } + } + + /** Every device but [except] joins: what each admin is offered, nobody opening it first. */ + suspend fun joinAll(except: Set = emptySet()) { + devices.values.filter { it.person !in except }.forEach { join(it) } + } + + suspend fun join(device: Device): ConfederationCeremony = + ConfederationRitualManager.join(device.db, proposalId, device.person, device.nsec) + + /** Each device's latest ceremony for the proposal, or null where its owner never joined. */ + suspend fun ceremonies(): Map = + devices.values.associate { it.person to it.db.confederationCeremonyDao().getLatestForProposal(proposalId) } + + fun close() { + RoomAdmins.override = null + devices.values.forEach { it.db.close() } + } +} 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 85d50e9a..4a1acab3 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationSigningJvmTest.kt @@ -44,14 +44,15 @@ class ConfederationSigningJvmTest { private fun secret(n: Int) = PrivateKey(ByteArray(32).also { it[0] = 0x71; it[31] = n.toByte() }) private fun npub(key: PrivateKey): HexKey = key.publicKey().xOnly().value.toHex() - private val groupKeys = (1..3).map { secret(it) } - private val groups = groupKeys.map(::npub) private val people = listOf(11, 12, 13, 21, 22, 23, 31, 32, 33) private val admins = listOf(listOf(11, 12, 13), listOf(21, 22, 23), listOf(31, 32, 33)) + private val network = ConfederationPeople(admins, tag = 0x71) + private val groups get() = network.groups - private inner class Device(val secret: PrivateKey, val db: GizaDatabase) { - val person = npub(secret) - lateinit var ceremonyRoom: LocalChatRoom + private inner class Device(val ceremonyDevice: ConfederationPeople.Device) { + val secret get() = ceremonyDevice.secret + val db get() = ceremonyDevice.db + val person get() = ceremonyDevice.person lateinit var room: LocalChatRoom val received = mutableSetOf() val nsec get() = secret.value.toByteArray() @@ -63,33 +64,13 @@ class ConfederationSigningJvmTest { @BeforeTest fun formed() = runBlocking { - val coordinator = npub(secret(11)) - val now = Clock.System.now().epochSeconds - val proposal = ConfederationTestGroups.proposal(groupKeys[0], groups, coordinator, createdAt = now - 10, expiresAt = now + 1000) - val acceptances = groupKeys.mapIndexed { i, key -> ConfederationTestGroups.acceptance(key, proposal, admins[i].map { npub(secret(it)) }) } - - people.map(::secret).forEach { key -> - val db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) - (people.map { npub(secret(it)) } + groups).forEach { member -> - val eventId = Crypto.sha256(member.encodeToByteArray()).toHex() - db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = member, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) - db.profileDao().upsert(Profile(publicKey = member, nostrEventId = eventId, displayName = member.take(6), createdAt = Instant.fromEpochSeconds(1_790_000_000))) - } - devices[npub(key)] = Device(key, db) - } - proposer = devices.getValue(coordinator) - (listOf(proposal) + acceptances).forEach { ConfederationManager.record(proposer.db, it) } - - // Part B, across the devices: the ceremony, every device joining. - val ceremony = ConfederationRitualManager.open(proposer.db, proposal.id, proposer.secret) - proposer.ceremonyRoom = proposer.db.chatRoomDao().findChatRoomById(ceremony.chatRoomId)!! - devices.values.filter { it !== proposer }.forEach { d -> - d.ceremonyRoom = d.db.nostrNip17Dao().createNip17ChatRoom(d.person, devices.keys.filter { it != d.person }, "Atlas")!! - } - pumpCeremony() - devices.values.forEach { ConfederationRitualManager.join(it.db, ceremony.id, it.nsec) } - pumpCeremony() - confederation = assertNotNull(proposer.db.confederationCeremonyDao().getConfederationForProposal(proposal.id)) + // Part B, across the devices: every admin holding every statement, and every one of them joining. + network.setUp() + network.devices.values.forEach { devices[it.person] = Device(it) } + proposer = devices.getValue(npub(secret(11))) + network.joinAll() + network.pump() + confederation = assertNotNull(proposer.db.confederationCeremonyDao().getConfederationForProposal(network.proposalId)) // The confederation's room on every device. Its MLS state is not this test's business; a // room with group state is what makes signing travel as a group event. @@ -102,25 +83,7 @@ class ConfederationSigningJvmTest { @AfterTest fun close() { ConfederationSigningManager.forgetSignersForTest() - devices.values.forEach { it.db.close() } - } - - private suspend fun pumpCeremony() { - var moved = true - while (moved) { - moved = false - for (from in devices.values) for (to in devices.values) { - if (from === to) continue - from.db.giftWrapPayloadDao().getByChatRoomAndKinds(from.ceremonyRoom.chatRoom.id, ConfederationRitualEvents.ALL.toList()) - .filter { it.publicKey == from.person }.sortedBy { it.createdAt } - .forEach { q -> - if (!to.received.add(q.id)) return@forEach - moved = true - to.db.giftWrapPayloadDao().upsert(q.copy(chatRoomId = to.ceremonyRoom.chatRoom.id)) - ConfederationRitualManager.process(to.db, to.ceremonyRoom, Event(q.id, q.publicKey, q.createdAt.epochSeconds, q.kind, q.tags, q.content, ""), to.person, to.nsec) - } - } - } + network.close() } /** Ferries the room's signing messages between devices until nothing moves; [hold] keeps some back. */ diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStatementFixture.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStatementFixture.kt new file mode 100644 index 00000000..bb15c333 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStatementFixture.kt @@ -0,0 +1,72 @@ +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 fr.acinq.bitcoin.PrivateKey +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.confederation.ConfederationAdminList +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationStatements + +/** + * Statements groups send each other, without a network to send them on + * (docs/confederation-without-coordinator.md): each group a single key standing in for its quorum, + * and each statement filed as an inbox would file it, beside a seal that key signed. A FROST + * signature is an ordinary BIP 340 one, so a reader cannot tell the difference -- which is why + * docs/confederation.md says a group cannot be told from a person. + */ +object ConfederationStatementFixture { + fun key(n: Int): PrivateKey = PrivateKey(ByteArray(32).also { it[0] = 0x21; it[31] = n.toByte() }) + fun npub(n: Int): HexKey = npub(key(n)) + fun npub(key: PrivateKey): HexKey = key.publicKey().xOnly().value.toHex() + + const val CREATED_AT = 1_790_000_000L + + fun proposal( + by: PrivateKey, + groups: List, + admins: List, + threshold: Int = 2, + innerThreshold: Int = 2, + name: String = "Atlas", + createdAt: Long = CREATED_AT, + expiresAt: Long = createdAt + ConfederationKinds.DEFAULT_EXPIRY_SECONDS, + ): Event { + val group = npub(by) + return ConfederationStatements.proposal( + group, groups, threshold, name, "cd".repeat(32), expiresAt, + ConfederationAdminList.ofV2(null, group, innerThreshold, admins)!!, createdAt, + ) + } + + fun parsed(proposal: Event): ConfederationStatements.Proposal = ConfederationStatements.parseProposal(proposal)!! + + fun acceptance(by: PrivateKey, proposal: Event, admins: List, threshold: Int = 2, createdAt: Long = proposal.createdAt + 10): Event { + val p = parsed(proposal) + val group = npub(by) + return ConfederationStatements.acceptance(group, p, ConfederationAdminList.ofV2(p.id, group, threshold, admins)!!, createdAt) + } + + fun rejection(by: PrivateKey, proposal: Event, createdAt: Long = proposal.createdAt + 10): Event = + ConfederationStatements.rejection(npub(by), parsed(proposal), "Not for us", createdAt) + + fun withdrawal(proposal: Event, createdAt: Long = proposal.createdAt + 20): Event = + ConfederationStatements.withdrawal(parsed(proposal).proposingGroup, parsed(proposal), "", createdAt) + + /** A seal [by] signed around [rumor]: what makes a rumor the group's word. Its content is not read by the store. */ + fun seal(by: PrivateKey, rumor: Event): Event { + val pubKey = npub(by) + val tags = arrayOf(arrayOf("n", "ab".repeat(32))) + val content = "sealed:${rumor.id}" + val id = EventHasher.hashId(pubKey, rumor.createdAt - 60, 13, tags, content) + return Event(id, pubKey, rumor.createdAt - 60, 13, tags, content, Nip01Crypto.sign(id.hexToByteArray(), by.value.toByteArray()).toHex()) + } + + /** Files [rumor] on [db] as [by]'s inbox would, opened in the room [inboxRoomId]. */ + suspend fun file(db: GizaDatabase, by: PrivateKey, rumor: Event, inboxRoomId: String? = null): Boolean = + ConfederationManager.recordStatement(db, rumor, seal(by, rumor), inboxRoomId) +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt index 6758ebdf..8939ed3b 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt @@ -18,112 +18,88 @@ import mobi.giza.compose.database.model.FrostSigningSession import mobi.giza.compose.database.model.NostrEvent import mobi.giza.compose.database.model.Profile import mobi.giza.compose.database.model.types.FrostSigningSubject -import mobi.giza.compose.managers.ConfederationTestGroups.key -import mobi.giza.compose.managers.ConfederationTestGroups.npub import mobi.giza.compose.nostr.confederation.ConfederationProposalState -/** Filing the confederation's events, and reading a proposal's state back (docs/confederation.md, Phase 4). */ +/** + * Filing the confederation's statements, and reading a proposal's state back + * (docs/confederation.md, Phase 4, with docs/confederation-without-coordinator.md's statements). + */ class ConfederationStorageJvmTest { private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) @AfterTest fun close() = db.close() + private fun key(n: Int) = ConfederationStatementFixture.key(n) + private fun npub(n: Int) = ConfederationStatementFixture.npub(n) + private val agora = key(1) private val polis = key(2) private val ekklesia = key(3) private val groups = listOf(npub(1), npub(2), npub(3)) - private val coordinator = npub(9) private val admins = listOf(npub(21), npub(22), npub(23)) - private val proposal = ConfederationTestGroups.proposal(agora, groups, coordinator) + private val proposal = ConfederationStatementFixture.proposal(agora, groups, admins) + + private suspend fun file(by: fr.acinq.bitcoin.PrivateKey, rumor: Event) = ConfederationStatementFixture.file(db, by, rumor) @Test - fun `a proposal is filed once, under every group it names`() = runBlocking { - assertTrue(ConfederationManager.record(db, proposal)) - assertFalse(ConfederationManager.record(db, proposal), "a relay's second copy is the same event") + fun `a proposal is filed once, under every group it names, beside its seal`() = runBlocking { + assertTrue(file(agora, proposal)) + assertFalse(file(agora, proposal), "a second wrap of it is the same statement") groups.forEach { group -> assertEquals(listOf(proposal.id), db.confederationDao().getProposalsNaming(group).map { it.id }) } assertEquals(emptyList(), db.confederationDao().getProposalsNaming(npub(4))) + assertTrue(db.confederationDao().getEvent(proposal.id)!!.sealJson!!.isNotEmpty()) } @Test - fun `an event that does not verify as its author's is not filed`() = runBlocking { - val forged = Event(proposal.id, npub(2), proposal.createdAt, proposal.kind, proposal.tags, proposal.content, proposal.sig) - assertFalse(ConfederationManager.record(db, forged)) - val tampered = Event(proposal.id, proposal.pubKey, proposal.createdAt, proposal.kind, proposal.tags, proposal.content + ".", proposal.sig) - assertFalse(ConfederationManager.record(db, tampered)) + fun `a statement in a seal that is not its author's is not filed`() = runBlocking { + assertFalse(ConfederationManager.recordStatement(db, proposal, ConfederationStatementFixture.seal(polis, proposal), null), "Polis's seal") + val seal = ConfederationStatementFixture.seal(agora, proposal) + val tampered = Event(seal.id, seal.pubKey, seal.createdAt, seal.kind, seal.tags, seal.content + ".", seal.sig) + assertFalse(ConfederationManager.recordStatement(db, proposal, tampered, null), "a seal that does not verify") assertNull(db.confederationDao().getEvent(proposal.id)) } @Test - fun `a signed event that is not well formed is not filed`() = runBlocking { - val oneGroup = ConfederationTestGroups.proposal(agora, listOf(npub(1)), coordinator) - assertFalse(ConfederationManager.record(db, oneGroup)) + fun `a statement that is not well formed is not filed, nor a public one`() = runBlocking { + val oneGroup = ConfederationStatementFixture.proposal(agora, listOf(npub(1)), admins) + assertFalse(file(agora, oneGroup)) + assertFalse(ConfederationManager.record(db, proposal), "statements never come in as public events") } @Test fun `the state is read from what is filed`() = runBlocking { - ConfederationManager.record(db, proposal) - val now = ConfederationTestGroups.CREATED_AT + 100 + file(agora, proposal) + val now = ConfederationStatementFixture.CREATED_AT + 100 assertEquals(ConfederationProposalState.OPEN, ConfederationManager.status(db, proposal.id, now)?.state) - ConfederationManager.record(db, ConfederationTestGroups.acceptance(agora, proposal, admins)) - ConfederationManager.record(db, ConfederationTestGroups.acceptance(polis, proposal, admins)) + file(polis, ConfederationStatementFixture.acceptance(polis, proposal, admins)) assertEquals(listOf(npub(3)), ConfederationManager.status(db, proposal.id, now)?.waitingOn) - ConfederationManager.record(db, ConfederationTestGroups.acceptance(ekklesia, proposal, admins)) + file(ekklesia, ConfederationStatementFixture.acceptance(ekklesia, proposal, admins)) assertEquals(ConfederationProposalState.ACCEPTED, ConfederationManager.status(db, proposal.id, now)?.state) - assertEquals(4, db.confederationDao().observeEventsForProposal(proposal.id).first().size) + assertEquals(3, db.confederationDao().observeEventsForProposal(proposal.id).first().size) } @Test fun `an answer that arrives before its proposal waits for it`() = runBlocking { - assertTrue(ConfederationManager.record(db, ConfederationTestGroups.rejection(polis, proposal))) + assertTrue(file(polis, ConfederationStatementFixture.rejection(polis, proposal))) assertNull(ConfederationManager.status(db, proposal.id), "nothing to answer yet") - ConfederationManager.record(db, proposal) + file(agora, proposal) assertEquals(ConfederationProposalState.REJECTED, ConfederationManager.status(db, proposal.id)?.state) } - private fun session(coordinator: String, user: String) = FrostSigningSession( - id = "s".repeat(64), - chatRoomId = npub(1), - coordinatorPublicKey = coordinator, - userPublicKey = user, - dkgSessionId = "k".repeat(64), - threshold = 2, - participantCount = 3, - signerId = 1, - derivationPath = null, - subject = FrostSigningSubject.EVENTS, - ) - - @Test - fun `what the group signed is filed, and owed to relays by the device that proposed it`() = runBlocking { - ConfederationManager.onSigned(db, session(coordinator = coordinator, user = coordinator), listOf(proposal)) - val owed = db.confederationDao().observeUnpublished().first() - assertEquals(listOf(proposal.id), owed.map { it.id }) - assertEquals("s".repeat(64), owed.single().ownSessionId) - - db.confederationDao().markPublished(proposal.id, kotlin.time.Clock.System.now()) - assertEquals(emptyList(), db.confederationDao().observeUnpublished().first()) - } - - @Test - fun `on a device that only signed, it is filed and owed to nobody`() = runBlocking { - ConfederationManager.onSigned(db, session(coordinator = coordinator, user = npub(10)), listOf(proposal)) - assertEquals(proposal.id, db.confederationDao().getEvent(proposal.id)?.id) - assertEquals(emptyList(), db.confederationDao().observeUnpublished().first()) - } - private suspend fun room(group: String) { val eventId = "e".repeat(64) - db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = coordinator, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) - db.profileDao().upsert(Profile(publicKey = coordinator, nostrEventId = eventId)) - db.chatRoomDao().upsert(ChatRoom(id = group, userPublicKey = coordinator, subject = "#Polis", description = null, mlsGroupState = "state")) + val owner = npub(9) + db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = owner, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = owner, nostrEventId = eventId)) + db.chatRoomDao().upsert(ChatRoom(id = group, userPublicKey = owner, subject = "#Polis", description = null, mlsGroupState = "state")) } private suspend fun lines(group: String) = db.chatMessageDao().getChatMessagesByChatRoomId(group) @@ -134,9 +110,9 @@ class ConfederationStorageJvmTest { @Test fun `an invitation and its answers are lines in the invited room, once each`() = runBlocking { room(npub(2)) - ConfederationManager.record(db, proposal) - ConfederationManager.record(db, proposal) - ConfederationManager.record(db, ConfederationTestGroups.acceptance(polis, proposal, admins)) + file(agora, proposal) + file(agora, proposal) + file(polis, ConfederationStatementFixture.acceptance(polis, proposal, admins)) val written = lines(npub(2)) assertEquals( @@ -151,17 +127,17 @@ class ConfederationStorageJvmTest { @Test fun `a room the proposal does not name gets no line`() = runBlocking { room(npub(4)) - ConfederationManager.record(db, proposal) + file(agora, proposal) assertEquals(emptyList(), lines(npub(4))) } @Test fun `an answer filed before its proposal gets its line when the proposal comes`() = runBlocking { room(npub(2)) - ConfederationManager.record(db, ConfederationTestGroups.acceptance(agora, proposal, admins)) + file(ekklesia, ConfederationStatementFixture.acceptance(ekklesia, proposal, admins)) assertEquals(emptyList(), lines(npub(2))) - ConfederationManager.record(db, proposal) + file(agora, proposal) assertEquals( listOf(ChatMessage.TYPE_CONFEDERATION_PROPOSED, ChatMessage.TYPE_CONFEDERATION_ACCEPTED), lines(npub(2)).map { it.messageType }, @@ -169,15 +145,13 @@ class ConfederationStorageJvmTest { } @Test - fun `an admin of two groups is counted twice, and said so`() = runBlocking { + fun `an admin of two groups is counted twice, and said so, on any device`() = runBlocking { val shared = npub(21) - listOf(proposal, - ConfederationTestGroups.acceptance(agora, proposal, admins), - ConfederationTestGroups.acceptance(polis, proposal, listOf(shared, npub(31), npub(32))), - ConfederationTestGroups.acceptance(ekklesia, proposal, listOf(npub(41), npub(42), npub(43))), - ).forEach { ConfederationManager.record(db, it) } + file(agora, proposal) + file(polis, ConfederationStatementFixture.acceptance(polis, proposal, listOf(shared, npub(31), npub(32)))) + file(ekklesia, ConfederationStatementFixture.acceptance(ekklesia, proposal, listOf(npub(41), npub(42), npub(43)))) - val outcome = kotlin.test.assertNotNull(ConfederationManager.outcome(db, proposal.id, key(9))) + val outcome = kotlin.test.assertNotNull(ConfederationManager.outcome(db, proposal.id)) assertEquals(9, outcome.roleCount) assertEquals(listOf(npub(1), npub(2)), outcome.overlaps[shared]) assertTrue(outcome.notes.any { it.contains("would hold a key for each") }) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationTestGroups.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationTestGroups.kt index 2c6759f2..7b2ae81b 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationTestGroups.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationTestGroups.kt @@ -2,84 +2,140 @@ 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.Kind -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto -import fr.acinq.bitcoin.PrivateKey -import mobi.giza.compose.extensions.toHex -import mobi.giza.compose.nostr.confederation.ConfederationAdminList -import mobi.giza.compose.nostr.confederation.ConfederationKinds -import mobi.giza.compose.nostr.confederation.ConfederationProposalAcceptanceEvent -import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent -import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent.Invitee -import mobi.giza.compose.nostr.confederation.ConfederationProposalRejectionEvent -import mobi.giza.compose.nostr.confederation.ConfederationProposalWithdrawalEvent -import mobi.giza.compose.nostr.confederation.ConfederationSeal +import kotlinx.coroutines.flow.first +import kotlin.time.Clock +import kotlin.time.Instant +import mobi.giza.compose.ExperimentalFeatures +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.model.types.FrostSigningStage +import mobi.giza.compose.nostr.inbox.InboxAnnouncement +import kotlin.test.assertEquals /** - * Groups that sign confederation events with a single key standing in for a quorum. A FROST - * signature is an ordinary BIP 340 one, so a reader cannot tell the difference -- which is the - * point of the tests that use these, and also why docs/confederation.md says a group cannot be - * told from a person. + * Several keyed groups, a device per member, each with an inbox its admins hold + * (docs/group-inbox.md), for a confederation proposed between them + * (docs/confederation-without-coordinator.md). + * + * Each group is a [GroupInboxHarness] with its own signing key: real FROST signatures by each + * group's quorum, real inbox ceremonies, and the relays stood in for twice over -- every group's + * signed 10044 and kind 0 reach every device as the profile sync would bring them, and every wrap a + * device owes is handed by [deliver] to every device, which keeps what its inbox opens. */ -object ConfederationTestGroups { - fun key(n: Int): PrivateKey = PrivateKey(ByteArray(32).also { it[0] = 0x21; it[31] = n.toByte() }) - fun npub(n: Int): HexKey = key(n).publicKey().xOnly().value.toHex() - - const val CREATED_AT = 1_790_000_000L - val EXPIRES_AT = CREATED_AT + ConfederationKinds.DEFAULT_EXPIRY_SECONDS - - fun signed(by: PrivateKey, kind: Kind, tags: Array>, content: String = "", createdAt: Long = CREATED_AT): Event { - val pubKey = by.publicKey().xOnly().value.toHex() - val id = EventHasher.hashId(pubKey = pubKey, createdAt = createdAt, kind = kind, tags = tags, content = content) - val sig = Nip01Crypto.sign(data = id.hexToByteArray(), privKey = by.value.toByteArray()).toHex() - return Event(id, pubKey, createdAt, kind, tags, content, sig) +class ConfederationTestGroups( + names: List = listOf("Agora", "Polis", "Ekklesia"), + /** How many admins each group has: every one of them holds a share and the inbox key. */ + admins: Int = 3, + threshold: Int = 2, + /** Picks the groups' signing keys: two sets of groups in one test need different ones. */ + keySeries: Int = 0, +) { + inner class Group(val index: Int, val name: String, val memberNames: List, val harness: GroupInboxHarness) { + val roomId: HexKey get() = harness.roomId + lateinit var devices: List + val members: List get() = harness.signers } - fun proposal( - by: PrivateKey, - groups: List, - coordinator: HexKey, - threshold: Int = 2, - name: String = "Atlas", - createdAt: Long = CREATED_AT, - expiresAt: Long = createdAt + ConfederationKinds.DEFAULT_EXPIRY_SECONDS, - ): Event = - signed( - by, ConfederationKinds.PROPOSAL, - ConfederationProposalEvent.assembleTags( - groups = groups.map { Invitee(it, "wss://relay.example") }, - coordinator = coordinator, - threshold = threshold, - name = name, - nonce = "cd".repeat(32), - expiresAt = expiresAt, - ), - ConfederationProposalEvent.content(name, groups.size), - createdAt = createdAt, + val groups: List = names.mapIndexed { i, name -> + val memberNames = (1..admins).map { "${name.lowercase()}-$it" } + val harness = GroupInboxHarness( + names = memberNames, + threshold = threshold, + dealerSecret = ("c" + keySeries + (i + 1).toString().padStart(2, '0')).padEnd(62, '0') + "a1", + subject = "#$name", ) + Group(i, name, memberNames, harness) + } - fun acceptance(by: PrivateKey, proposal: Event, admins: List, threshold: Int = 2, secret: ByteArray = ByteArray(32) { 5 }): Event { - val parsed = ConfederationProposalEvent.parse(proposal)!! - val group = by.publicKey().xOnly().value.toHex() - val sealed = ConfederationSeal.seal(secret, parsed.coordinator, ConfederationAdminList.of(parsed.id, group, threshold, admins)!!) - return signed( - by, ConfederationKinds.ACCEPTANCE, - ConfederationProposalAcceptanceEvent.assembleTags(parsed.id, null, parsed.proposingGroup, parsed.coordinator, sealed.ephemeralPublicKey), - sealed.content, createdAt = proposal.createdAt + 10, + val everyDevice get() = groups.flatMap { it.devices } + + init { + ExperimentalFeatures.confederationOverride = true + } + + fun close() { + groups.forEach { it.harness.close() } + RoomAdmins.override = null + ExperimentalFeatures.confederationOverride = null + } + + /** + * Makes every group's devices, runs every group's inbox ceremony and announcement, and hands + * each group's signed 10044 and kind 0 to every device. Groups in [withoutInbox] stay without one. + */ + suspend fun setUp(withoutInbox: Set = emptySet()) { + groups.forEach { group -> group.devices = group.memberNames.map { group.harness.device(it) } } + groups.filter { it.name !in withoutInbox }.forEach { group -> + val first = group.devices[0] + InboxKeyRitualManager.propose(first.db, first.room(), first.publicKey, first.secret) + group.harness.pump() + val announcement = first.db.frostSigningSessionDao().getSessionsForChatRoom(group.roomId).single() + FrostSigningManager.approve(group.devices[1].db, group.devices[1].room(), announcement.id) + group.harness.pump() + } + groups.forEach { group -> + val signed = group.devices[0].db.groupSignedEventDao().getByChatRoomId(group.roomId) + .filter { it.kind == InboxAnnouncement.KEY_KIND || it.kind == InboxAnnouncement.RELAYS_KIND } + .map { it.toEvent() } + everyDevice.forEach { device -> + signed.forEach { heard(device, it) } + val eventId = "f${group.index}".padEnd(64, '0') + device.db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = group.roomId, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + device.db.profileDao().upsert( + Profile(publicKey = group.roomId, nostrEventId = eventId, displayName = group.name, createdAt = Instant.fromEpochSeconds(1_790_000_000)) + ) + } + } + } + + /** [event], as a relay would bring it to [device]. */ + suspend fun heard(device: GroupInboxHarness.Device, event: Event) { + device.db.nostrEventDao().upsert( + NostrEvent( + id = event.id, pubKey = event.pubKey, kind = event.kind, tags = event.tags, content = event.content, + sig = event.sig, createdAt = Instant.fromEpochSeconds(event.createdAt), + ) ) } - fun rejection(by: PrivateKey, proposal: Event): Event = signed( - by, ConfederationKinds.REJECTION, - ConfederationProposalRejectionEvent.assembleTags(proposal.id, null, proposal.pubKey), "Not for us", - createdAt = proposal.createdAt + 10, - ) + /** + * The relays between inboxes: every wrap a device owes goes to every device, which files what + * its inbox keys open, and is marked sent. Returns how many wraps moved. + */ + suspend fun deliver(except: Set = emptySet()): Int { + var moved = 0 + everyDevice.forEach { from -> + from.db.groupInboxDao().observeUnpublished().first().forEach { owed -> + val wrap = Event.fromJson(owed.eventJson) + everyDevice.filter { it !in except }.forEach { to -> GroupInboxManager.receive(to.db, wrap, to.publicKey) } + from.db.groupInboxDao().markPublished(owed.eventId, Clock.System.now()) + moved++ + } + } + return moved + } - fun withdrawal(by: PrivateKey, proposal: Event): Event = signed( - by, ConfederationKinds.WITHDRAWAL, - ConfederationProposalWithdrawalEvent.assembleTags(proposal.id, null, ConfederationProposalEvent.parse(proposal)!!.groupPublicKeys), "", - createdAt = proposal.createdAt + 20, - ) + /** + * [group]'s first device proposes with [propose]; its second approves; the quorum signs; the + * statement's wraps are delivered. Returns the signing session's id. + */ + suspend fun signed( + group: Group, + except: Set = emptySet(), + propose: suspend (GroupInboxHarness.Device) -> String, + ): String { + val sessionId = propose(group.devices[0]) + group.harness.pump() + val second = group.devices[1] + FrostSigningManager.approve(second.db, second.room(), sessionId) + group.harness.pump() + group.devices.forEach { device -> + assertEquals( + FrostSigningStage.COMPLETE, device.db.frostSigningSessionDao().getSessionById(sessionId)?.stage, + "${group.name} signed on ${device.name}", + ) + } + deliver(except) + return sessionId + } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationWithoutCoordinatorPremiseJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationWithoutCoordinatorPremiseJvmTest.kt index 5f17417f..fb7f03f3 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationWithoutCoordinatorPremiseJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationWithoutCoordinatorPremiseJvmTest.kt @@ -142,7 +142,7 @@ class ConfederationWithoutCoordinatorPremiseJvmTest { // ---- check 5: one group writing to another, as the inbox has it today ------------------ @Test - fun `a seal from one group's inbox key to another's is filed today as an inbox message`() = runBlocking { + fun `a seal from one group's inbox key to another's is filed as the confederation's, not the inbox's`() = runBlocking { val b = GroupInboxHarness().also { harness = it } val devices = listOf("alice", "bob", "carol").map { b.device(it) } val alice = devices[0] @@ -158,15 +158,19 @@ class ConfederationWithoutCoordinatorPremiseJvmTest { val aGroup: HexKey = InboxWire.publicKeyOf(aSigner) val aInbox = ByteArray(32).also { it[0] = 0x62; it[31] = 1 } val now = kotlin.time.Clock.System.now().epochSeconds - val rumor = RumorAssembler.assembleRumor( - aGroup, - EventTemplate(now, ConfederationKinds.PROPOSAL, arrayOf(arrayOf("p", b.roomId)), "{\"v\":2}"), + val admins = (1..2).map { InboxWire.publicKeyOf(ByteArray(32).also { b -> b[0] = 0x63; b[31] = it.toByte() }) } + val rumor = mobi.giza.compose.nostr.confederation.ConfederationStatements.proposal( + aGroup, listOf(b.roomId), 2, "Atlas", "ab".repeat(32), now + 1000, + mobi.giza.compose.nostr.confederation.ConfederationAdminList.ofV2(null, aGroup, 2, admins)!!, now, ) val seal = signed(aSigner, InboxSeal.template(rumor, aInbox, bInbox, now - 60)) val wrap = InboxWrap.wrap(seal, b.roomId, bInbox) - val filed = assertNotNull(GroupInboxManager.receive(alice.db, wrap, alice.publicKey), "B's admin opens A's seal with the n tag") - assertEquals(aGroup, filed.senderPublicKey, "and the seal is A's") - assertEquals(ConfederationKinds.PROPOSAL, filed.kind, "filed as an inbox message of a kind the inbox cannot show (Phase 5 flips this)") + // Phase 5 flipped this: until then it was filed as an inbox message of a kind the inbox cannot show. + assertEquals(null, GroupInboxManager.receive(alice.db, wrap, alice.publicKey), "not an inbox message") + assertEquals(emptyList(), alice.db.groupInboxDao().getMessages(b.roomId)) + val filed = assertNotNull(alice.db.confederationDao().getEvent(rumor.id), "B's admin opened A's seal with its n tag and filed the statement") + assertEquals(aGroup, filed.pubKey, "as A's") + assertEquals(b.roomId, filed.inboxRoomId) } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxHarness.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxHarness.kt index 6dc7963d..8181f4bc 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxHarness.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxHarness.kt @@ -42,6 +42,10 @@ class GroupInboxHarness( /** Members of the room who are not admins and hold no share. */ watchers: List = emptyList(), val threshold: Int = 2, + /** The group's signing key, as a trusted dealer's: different groups in one test need different ones. */ + dealerSecret: String = "1c0ffee0000000000000000000000000000000000000000000000000000000a1", + /** The room's name on every device. */ + val subject: String = "#Ekklesia", ) { val secrets: Map = (names + watchers).associateWith { Crypto.sha256("giza inbox $it".encodeToByteArray()) } val keyOf: Map = secrets.mapValues { KeyPair(it.value).pubKey.toHexKey() } @@ -49,7 +53,7 @@ class GroupInboxHarness( val everyone: List = (names + watchers).map { keyOf.getValue(it) } val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey(ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1")), + thresholdSecretKey = PrivateKey(ByteVector32(dealerSecret)), nParticipants = names.size, threshold = threshold, ) @@ -66,7 +70,9 @@ class GroupInboxHarness( init { ExperimentalFeatures.groupInboxOverride = true - RoomAdmins.override = { id -> if (id == roomId) RoomAdmins(admins, governed = false) else null } + // Beside any other harness's room: several groups can share one test. + val previous = RoomAdmins.override + RoomAdmins.override = { id -> if (id == roomId) RoomAdmins(admins, governed = false) else previous?.invoke(id) } } fun close() { @@ -102,7 +108,7 @@ class GroupInboxHarness( ChatRoom( id = roomId, userPublicKey = publicKey, - subject = "#Ekklesia", + subject = subject, description = SharedKeyDerivation.describe("Admins of the group."), mlsGroupState = "00", ) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationRosterBuilderJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationRosterBuilderJvmTest.kt index 24f23d7d..1a167b5c 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationRosterBuilderJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/nostr/confederation/ConfederationRosterBuilderJvmTest.kt @@ -16,7 +16,6 @@ import kotlin.test.assertTrue import mobi.giza.compose.ConfederationFixture import mobi.giza.compose.extensions.toHex import mobi.giza.compose.managers.SharedKeyDerivation -import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent.Invitee /** * The roster every participant derives on its own (docs/confederation.md, Phase 10): it parses as @@ -28,10 +27,7 @@ class ConfederationRosterBuilderJvmTest { private fun npub(n: Int): HexKey = secret(n).publicKey().xOnly().value.toHex() private val groups = listOf(npub(1), npub(2), npub(3)) - private val proposal = ConfederationProposalEvent.Proposal( - id = "a1".repeat(32), proposingGroup = groups[0], createdAt = 1, coordinator = npub(11), - groups = groups.map { Invitee(it) }, threshold = 2, name = "Atlas", nonce = "00".repeat(32), expiresAt = 2, - ) + private val proposalId = "a1".repeat(32) /** Admins by group: three each, the person 11 in both of the first two groups. */ private val admins = mapOf( @@ -40,7 +36,12 @@ class ConfederationRosterBuilderJvmTest { groups[2] to listOf(31, 32, 33), ) - private val lists = admins.mapValues { (group, people) -> ConfederationAdminList.of(proposal.id, group, 2, people.map(::npub))!! } + private val lists = admins.mapValues { (group, people) -> ConfederationAdminList.ofV2(proposalId, group, 2, people.map(::npub))!! } + + private val proposal = ConfederationStatements.Proposal( + id = proposalId, proposingGroup = groups[0], createdAt = 1, groups = groups, threshold = 2, + name = "Atlas", nonce = "00".repeat(32), expiresAt = 2, proposerAdmins = lists.getValue(groups[0]), + ) private val acceptanceIds = groups.withIndex().associate { (i, g) -> g to (i + 1).toString().repeat(64).take(64) } private val plan = ConfederationRosterBuilder.plan(proposal, lists, acceptanceIds).right!! diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt index 93b244b6..fac4bd01 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt @@ -14,7 +14,8 @@ import androidx.compose.ui.test.runDesktopComposeUiTest import kotlin.test.Test import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent +import mobi.giza.compose.nostr.confederation.ConfederationStatements +import mobi.giza.compose.nostr.confederation.ConfederationAdminList import mobi.giza.compose.nostr.confederation.ConfederationStatus import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.ConfederationRepository @@ -36,15 +37,21 @@ import mobi.giza.compose.ui.view.state.ProposeConfederationUIState.Lookup /** The confederation's two screens as a member first meets them (docs/confederation.md, Phase 6). */ @OptIn(ExperimentalTestApi::class) class ConfederationScreensJvmTest { - private val roomId = "d4c3b2a1".repeat(8) - private val polis = "a1b2c3d4".repeat(8) + private val roomId = mobi.giza.compose.managers.ConfederationStatementFixture.npub(1) + private val polis = mobi.giza.compose.managers.ConfederationStatementFixture.npub(2) + + private fun proposal(expiresAt: Long) = ConfederationStatements.Proposal( + id = "p".padEnd(64, '0'), proposingGroup = polis, createdAt = 1, groups = listOf(polis, roomId), + threshold = 2, name = "Atlas", nonce = "0".repeat(64), expiresAt = expiresAt, + proposerAdmins = ConfederationAdminList.ofV2(null, polis, 2, listOf(polis, roomId))!!.boundTo("p".padEnd(64, '0')), + ) private val localChatRoom = LocalChatRoom( chatRoom = ChatRoom(id = roomId, userPublicKey = "a".repeat(64), subject = "#Agora", description = null, mlsGroupState = "state") ) @Test - fun `the form says who coordinates, what is disclosed, and waits for a name`() = render( + fun `the form says what is shown to whom, and waits for a name`() = render( propose = ProposeConfederationUIState.Loaded( localChatRoom = localChatRoom, ownGroup = GroupLookup(roomId, Lookup.Found("Agora", null)), @@ -55,8 +62,9 @@ class ConfederationScreensJvmTest { canSign = true, ) ) { - onNodeWithText("You will coordinate its key ceremony", substring = true).assertIsDisplayed() - onNodeWithText("This group discloses its 3 admins and its threshold of 2 to you").assertIsDisplayed() + onNodeWithText("Proposing shows this group's admins to the admins of every group named here", substring = true).assertIsDisplayed() + onAllNodesWithText("coordinate", substring = true).assertCountEquals(0) + onNodeWithText("This group shows its 3 admins and its threshold of 2 to the groups it names").assertIsDisplayed() onNodeWithText("Agora").assertIsDisplayed() onNodeWithText("Polis").assertIsDisplayed() onNodeWithText("2 of 2 groups must take part for the confederation to sign").assertIsDisplayed() @@ -85,11 +93,7 @@ class ConfederationScreensJvmTest { proposals = listOf( ConfederationsUIState.Item( status = ConfederationStatus.of( - ConfederationProposalEvent.Proposal( - id = "p".padEnd(64, '0'), proposingGroup = polis, createdAt = 1, coordinator = polis, - groups = listOf(ConfederationProposalEvent.Invitee(polis), ConfederationProposalEvent.Invitee(roomId)), - threshold = 2, name = "Atlas", nonce = "0".repeat(64), expiresAt = Long.MAX_VALUE, - ), + proposal(expiresAt = Long.MAX_VALUE), emptyList(), now = 2, ), proposerName = "Polis", @@ -100,7 +104,7 @@ class ConfederationScreensJvmTest { onNodeWithText("Atlas").assertIsDisplayed() onNodeWithText("Open").assertIsDisplayed() onNodeWithText("Proposed by Polis").assertIsDisplayed() - onNodeWithText("Waiting on 2 of 2 groups").assertIsDisplayed() + onNodeWithText("Waiting on 1 of 2 groups").assertIsDisplayed() } @Test @@ -154,11 +158,7 @@ class ConfederationScreensJvmTest { } private fun status(answers: List = emptyList()) = ConfederationStatus.of( - ConfederationProposalEvent.Proposal( - id = "p".padEnd(64, '0'), proposingGroup = polis, createdAt = 1, coordinator = polis, - groups = listOf(ConfederationProposalEvent.Invitee(polis), ConfederationProposalEvent.Invitee(roomId)), - threshold = 2, name = "Atlas", nonce = "0".repeat(64), expiresAt = 4_000_000_000, - ), + proposal(expiresAt = 4_000_000_000), answers, now = 2, ) @@ -167,8 +167,8 @@ class ConfederationScreensJvmTest { ConfederationProposalUIState.Loaded(localChatRoom = localChatRoom, status = status(), names = mapOf(polis to "Polis", roomId to "This group"), canSign = true) ) { onNodeWithText("Atlas").assertIsDisplayed() - onNodeWithText("Coordinated by Polis").assertIsDisplayed() - onNodeWithText("Accepting discloses this group's admins", substring = true).assertIsDisplayed() + onAllNodesWithText("Coordinated by", substring = true).assertCountEquals(0) + onNodeWithText("Accepting shows this group's admins and threshold to the admins of every group", substring = true).assertIsDisplayed() onNodeWithText("Propose accepting").assertIsDisplayed() onNodeWithText("Propose declining").assertIsDisplayed() } @@ -213,8 +213,8 @@ class ConfederationScreensJvmTest { } private fun ceremony(stage: ConfederationCeremonyStage, approved: Boolean, failure: String? = null) = ConfederationCeremony( - id = "s".repeat(64), chatRoomId = roomId, proposalId = "p".padEnd(64, '0'), coordinatorPublicKey = polis, - userPublicKey = "a".repeat(64), openingJson = "{}", stage = stage, + id = "s".repeat(64), chatRoomId = roomId, proposalId = "p".padEnd(64, '0'), + userPublicKey = "a".repeat(64), basisJson = "{}", stage = stage, approvedAt = if (approved) kotlin.time.Instant.fromEpochSeconds(1) else null, failureReason = failure, ) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModelJvmTest.kt index 92a5b5d5..e82925e9 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModelJvmTest.kt @@ -33,7 +33,6 @@ import mobi.giza.compose.database.model.types.FrostSigningSubject import mobi.giza.compose.extensions.toHex import mobi.giza.compose.extensions.toNpub import mobi.giza.compose.managers.ConfederationManager -import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent import mobi.giza.compose.nostr.confederation.ConfederationStatus import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.ConfederationRepository @@ -88,7 +87,7 @@ class ProposeConfederationViewModelJvmTest { override suspend fun canSign(chatRoomId: String): Boolean = true } - private var proposed: List? = null + private var proposed: List? = null private var proposedThreshold: Int? = null private var admins = setOf(me, npub(10), npub(11)) @@ -97,7 +96,7 @@ class ProposeConfederationViewModelJvmTest { override suspend fun disclosure(chatRoomId: String) = ConfederationManager.Disclosure(chatRoomId, admins, 2) override suspend fun nameOf(groupPublicKey: HexKey, inRoom: String?) = groupPublicKey.take(8) override suspend fun proposeConfederation( - localChatRoom: LocalChatRoom, userPublicKey: HexKey, invitees: List, + localChatRoom: LocalChatRoom, userPublicKey: HexKey, invitees: List, threshold: Int, name: String, expiresAt: Long, ): FrostSigningSession { proposed = invitees @@ -219,7 +218,7 @@ class ProposeConfederationViewModelJvmTest { vm.propose("Atlas", onSuccess = { session = it }, onFailure = {}) eventually { session != null } - assertEquals(listOf(polis, ekklesia), proposed?.map { it.groupPublicKey }) + assertEquals(listOf(polis, ekklesia), proposed) assertEquals(3, proposedThreshold) } } diff --git a/docs/confederation-without-coordinator.md b/docs/confederation-without-coordinator.md index fb2b1d87..a7e702e7 100644 --- a/docs/confederation-without-coordinator.md +++ b/docs/confederation-without-coordinator.md @@ -637,6 +637,43 @@ dealer who sent different dealings to two people fails at the 30384, naming them abandon, then **Try again** reaching a key in attempt 2 with a different seed; admins changed; a restart mid-round. The Phase 1 pins on the opening and the broadcast flip. +**Phases 3, 4, 5 and 7 built, in one commit**, with schema 48 from Phase 2. They could not be split: +a statement is an unsigned rumor, so a coordinator's opening that carried statements would have held +nothing a participant could check, and the ceremony had to stop being opened in the same change that +stopped Part A being public. Where the build chose differently from the phases above: + +| what the plan said | what it turned out to be | +|---|---| +| D8: ceremony id from `attestation_ref` and the attempt | **from the proposal's id and the attempt.** Built as planned, a group that told two groups different things gave their admins different ceremony ids, so each side waited in a ceremony of its own for people who never came, and the attestation check in the 30381 never ran. With the id from the proposal, every device meets in one ceremony and the first message names the group | +| D8: the room every device derives | as planned; and a device replays a ceremony's waiting messages from **any** room (`GiftWrapPayloadDao.getByKinds`), since a sender whose statements differ names other people, and so another room | +| Phase 7: `planFor(proposalId)` | `basisFor`, `planFrom(basis)` and `planOf(ceremony)`. The basis (the proposal and every acceptance, as rumors) is kept on the ceremony as `basisJson`, the renamed `openingJson` | +| Phase 7: `join` makes the room if it is not here | and the ceremony row itself: nothing is made on a device until its owner joins. Messages that came before are replayed; a missed abandonment ends a late joiner's attempt at once | +| D10: **Try again** | `join` after a failed or abandoned attempt joins the next one, so the screen needs no second button | +| Phase 2: `ConfederationEvent` loses `publishedAt` and `ownSessionId` | kept: the charter is still owed to public relays by `ConfederationPublisher`. A statement's wraps are owed through `GroupInboxPublication`, by `InboxReplies.onSigned` as for a reply | +| Phase 2: a manual migration | an `AutoMigration(47, 48)` with a spec: `@DeleteColumn` and `@RenameColumn`, and `onPostMigrate` dropping version 1's statements and every ceremony and confederation built on them | +| Phase 3: `InboxMessages.build` | `InboxReplies.sealRumor`, which `InboxReplies.build` now calls; and `InboxRefusal.readSealed`, the reply's checks for any rumor kind, which the confederation's refusal calls | +| D6: a statement's `confederation_invitation` | the seal that brought the proposal to this group, from the store; none for the proposing group's own statements | +| D6: a 9433 withdrawal | built with any group as its author, so a group that tries to withdraw another's proposal is declined by its own signers (`NOT_PROPOSER`) rather than refused by the builder | +| Phase 8: Phase 13's room | made, for now, by the first of the roster's people, sorted (`ConfederationFollowThrough.creatorOf`). The fallback and the tie are Phase 8 | +| outcome: a group with no profile on this device stops the ceremony | a note, not a problem: every device computes it now, and a lookup that has not come back on one device would have stopped only that device's join | + +Tests, all passing: `ConfederationNetworkJvmTest` 7/7 on a harness of three groups of three, each +with a real inbox ceremony (`ConfederationTestGroups`, now a harness, over a `GroupInboxHarness` that +takes its dealer key and room name); `ConfederationDeclineJvmTest` 15/15 on the same; +`ConfederationCeremonyJvmTest` 13/13 and `ConfederationSigningJvmTest` 7/7 on `ConfederationPeople` +(every admin of every group with every statement filed beside its seal, from +`ConfederationStatementFixture`); `ConfederationStorageJvmTest` 9/9; `ConfederationStatusTest` 11/11 +in place of the version 1 `ConfederationEventsTest`; `ConfederationRelayTest` 6/6, now only charters. +`ConfederationSealPremiseJvmTest` went with the seal. **Not tested:** a member who is not an admin +filing nothing from the supergroup is the inbox's own test (`GroupInboxReadJvmTest`), not repeated +here; and a restart mid-round is covered only by every step being a function of stored messages, +as before. + +Full `jvmTest` 1,776, all passing; `m3Audit`, `brandAudit` and `walletAudit` at their budgets; +`compileDebugKotlinAndroid` builds. One earlier run of the suite ended in a segfault inside the +bundled SQLite driver, during an `UnsignedNostrEvent` upsert on a background coroutine -- code this +change does not touch, and it did not happen again. + ### Phase 8: the room (D11) - `ConfederationFollowThrough.takeNextStep` creates the room on the device whose owner is first in the